diff --git a/.cargo/config.toml b/.cargo/config.toml index be5e9d63f5b..a10f60e0f68 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -3,8 +3,8 @@ xtask = "run --package esp-devtool --" update-metadata = "run --quiet --manifest-path ./esp-metadata/Cargo.toml -- generate" xclean = "xtask clean" xdoc = "run --package esp-devtool --features=deploy-docs,preview-docs --" -xfmt = "xtask fmt-packages" -qa = "xtask run example qa-test" +xfmt = "xtask fmt" +qa = "xtask run qa" xcheck = "run --quiet --package esp-devtool --features=semver-checks --" xrelease = "run --package esp-devtool --features=release -- release" xrel-check = "run --package esp-devtool --features=rel-check -- rel-check" diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 4ccde9add06..0140e4965ac 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -5,7 +5,7 @@ To help us review it efficiently, please ensure you've gone through the followin ### Submission Checklist 📝 - [ ] I have updated existing examples or added new ones (if applicable). -- [ ] I have used `cargo xtask fmt-packages` command to ensure that all changed code is formatted correctly. +- [ ] I have used `cargo xtask fmt` command to ensure that all changed code is formatted correctly. - [ ] I have added changelog entries and/or migration guide notes in the sections below, or I will ask a maintainer to add the `skip-changelog` or `manual-changelog` label as appropriate. - [ ] My changes are in accordance to the [esp-rs developer guidelines](https://github.com/esp-rs/esp-hal/blob/main/documentation/DEVELOPER-GUIDELINES.md) diff --git a/.github/actions/build-tests/action.yml b/.github/actions/build-tests/action.yml deleted file mode 100644 index 2ca8bbe7731..00000000000 --- a/.github/actions/build-tests/action.yml +++ /dev/null @@ -1,137 +0,0 @@ -name: Build HIL tests (composite) -description: Checkout, install toolchains, build tests for a SoC, upload artifact -inputs: - event_name: - description: github.event_name - required: true - - repository: - description: owner/repo for workflow_dispatch - required: true - - branch: - description: branch/tag to checkout if no SHA - required: true - - soc: - description: SoC (e.g. esp32c3) - required: true - - rust_target: - description: rust target triple - required: true - - tests: - description: Optional comma-separated test names - required: false - default: "" - - package: - description: '"hil-test", "hil-test-radio", or "all"' - required: false - default: "all" - -runs: - using: composite - steps: - - uses: actions/checkout@v6 - if: ${{ inputs.event_name == 'merge_group' }} - - uses: actions/checkout@v6 - if: ${{ inputs.event_name == 'workflow_dispatch' }} - with: - repository: ${{ inputs.repository }} - ref: ${{ inputs.branch }} - - - if: ${{ !contains(fromJson('["esp32","esp32s2","esp32s3"]'), inputs.soc) }} - uses: dtolnay/rust-toolchain@v1 - with: - target: ${{ inputs.rust_target }} - toolchain: stable - components: rust-src - - - if: ${{ !contains(fromJson('["esp32","esp32s2","esp32s3"]'), inputs.soc) }} - name: Install nightly Rust toolchain - uses: dtolnay/rust-toolchain@v1 - with: - target: ${{ inputs.rust_target }} - toolchain: nightly - components: rust-src - - - if: ${{ contains(fromJson('["esp32","esp32s2","esp32s3"]'), inputs.soc) }} - uses: esp-rs/xtensa-toolchain@v1.6 - with: - buildtargets: ${{ inputs.soc }} - default: true - version: 1.97.0.0 - - - name: Check if chip is supported by this ref's xtask - id: chip - shell: bash - run: | - if cargo xtask build tests ${{ inputs.soc }} --help >/dev/null 2>&1; then - echo "supported=true" >> $GITHUB_OUTPUT - else - echo "supported=false" >> $GITHUB_OUTPUT - echo "Skipping ${{ inputs.soc }}: this ref's xtask does not support it." - fi - - - name: Build tests - if: ${{ steps.chip.outputs.supported == 'true' }} - shell: bash - env: - CARGO_TARGET_DIR: ${{ github.workspace }}/target - run: | - build_package() { - local pkg=$1 - if [ -n "${{ inputs.tests }}" ]; then - cargo xtask build tests ${{ inputs.soc }} $pkg --tests "${{ inputs.tests }}" - else - cargo xtask build tests ${{ inputs.soc }} $pkg - fi - - # Always separate artifacts by package so upload paths are consistent - # for full and selected-test builds. - local src="${{ github.workspace }}/target/tests/${{ inputs.soc }}" - local dst="${src}/${pkg}" - mkdir -p "$dst" - find "$src" -maxdepth 1 -type f -exec mv {} "$dst/" \; - } - - if [ "${{ inputs.package }}" = "all" ]; then - build_package hil-test - build_package hil-test-radio - else - build_package "${{ inputs.package }}" - fi - - - uses: actions/upload-artifact@v6 - if: ${{ steps.chip.outputs.supported == 'true' && inputs.tests == '' && (inputs.package == 'all' || inputs.package == 'hil-test') }} - with: - name: tests-${{ inputs.soc }}-hil-test - path: ${{ github.workspace }}/target/tests/${{ inputs.soc }}/hil-test - if-no-files-found: error - overwrite: true - - - uses: actions/upload-artifact@v6 - if: ${{ steps.chip.outputs.supported == 'true' && inputs.tests == '' && (inputs.package == 'all' || inputs.package == 'hil-test-radio') && hashFiles(format('{0}/target/tests/{1}/hil-test-radio/**', github.workspace, inputs.soc)) != '' }} - with: - name: tests-${{ inputs.soc }}-hil-test-radio - path: ${{ github.workspace }}/target/tests/${{ inputs.soc }}/hil-test-radio - if-no-files-found: error - overwrite: true - - - uses: actions/upload-artifact@v6 - if: ${{ steps.chip.outputs.supported == 'true' && inputs.tests != '' && (inputs.package == 'all' || inputs.package == 'hil-test') }} - with: - name: tests-${{ inputs.soc }}-hil-test - path: ${{ github.workspace }}/target/tests/${{ inputs.soc }}/hil-test - if-no-files-found: ignore - overwrite: true - - - uses: actions/upload-artifact@v6 - if: ${{ steps.chip.outputs.supported == 'true' && inputs.tests != '' && (inputs.package == 'all' || inputs.package == 'hil-test-radio') }} - with: - name: tests-${{ inputs.soc }}-hil-test-radio - path: ${{ github.workspace }}/target/tests/${{ inputs.soc }}/hil-test-radio - if-no-files-found: ignore - overwrite: true diff --git a/.github/actions/measure-binary-size/action.yml b/.github/actions/measure-binary-size/action.yml new file mode 100644 index 00000000000..e4fd5fe523f --- /dev/null +++ b/.github/actions/measure-binary-size/action.yml @@ -0,0 +1,84 @@ +name: Measure binary size +description: >- + Build examples for one chip at two commits and record the size of every + section that ends up in the image, for `.github/scripts/binary-size.js` to + compare. Uploads the sizes as the `sizes-` artifact. + +inputs: + soc: + description: Chip to build for, as in chips.json. + required: true + examples: + description: Space-separated examples to build. + required: true + package: + description: Optional package the examples belong to (e.g. "qa"). + required: false + default: "" + base: + description: Commit to compare against. + required: true + head: + description: Commit to measure. + required: true + between: + description: >- + Space-separated commits between base and head. Examples that grew past + the `MAX_*` limits are also built at each of them. + required: false + default: "" + has-cached: + description: >- + When "true", download the `sizes-cached` artifact produced by `prepare` + so commits already stored in `app-metrics` are not rebuilt. + required: false + default: "false" + +runs: + using: composite + steps: + - name: Resolve Rust target + id: target + shell: bash + env: + SOC: ${{ inputs.soc }} + run: | + ENTRY=$(jq -c --arg s "$SOC" '.[] | select(.soc == $s)' .github/chips.json) + echo "rust-target=$(echo "$ENTRY" | jq -r '."rust-target"')" >> "$GITHUB_OUTPUT" + echo "arch=$(echo "$ENTRY" | jq -r '.arch')" >> "$GITHUB_OUTPUT" + + - uses: ./.github/actions/setup-toolchains + with: + xtensa: ${{ steps.target.outputs.arch == 'xtensa' }} + xtensa-buildtargets: ${{ inputs.soc }} + xtensa-default: "true" + riscv: ${{ steps.target.outputs.arch == 'riscv' }} + riscv-targets: ${{ steps.target.outputs.rust-target }} + + - if: inputs.has-cached == 'true' + uses: actions/download-artifact@v4 + continue-on-error: true + with: + name: sizes-cached + path: sizes + + - name: Measure ${{ inputs.soc }} + uses: actions/github-script@v8 + env: + SOC: ${{ inputs.soc }} + TARGET: ${{ steps.target.outputs.rust-target }} + EXAMPLES: ${{ inputs.examples }} + PACKAGE: ${{ inputs.package }} + BASE: ${{ inputs.base }} + HEAD: ${{ inputs.head }} + BETWEEN: ${{ inputs.between }} + with: + script: | + const { measure } = require('./.github/scripts/binary-size.js'); + await measure({ core, exec }); + + - uses: actions/upload-artifact@v6 + with: + name: sizes-${{ inputs.soc }} + path: sizes/${{ inputs.soc }}.txt + if-no-files-found: ignore diff --git a/.github/actions/setup-nightly/action.yml b/.github/actions/setup-nightly/action.yml index 8cbe49e9d26..ff45fdf1db9 100644 --- a/.github/actions/setup-nightly/action.yml +++ b/.github/actions/setup-nightly/action.yml @@ -3,7 +3,9 @@ description: Install the repo-wide pinned Rust nightly toolchain, with an option inputs: targets: - description: Comma-separated list of target triples to install. + description: >- + Comma-separated list of target triples to install, or "all" for every RISC-V + triple in chips.json. required: false default: "" components: @@ -24,10 +26,25 @@ runs: shell: bash run: echo "nightly=nightly" >> "$GITHUB_OUTPUT" + - id: targets + shell: bash + run: | + if [ '${{ inputs.targets }}' = all ]; then + # Order-preserving dedupe, so the triple list reads the same as + # chips.json rather than being alphabetised. + VALUE=$(jq -r ' + [.[] | select(.arch == "riscv") | ."rust-target"] + | reduce .[] as $t ([]; if index($t) then . else . + [$t] end) + | join(",")' .github/chips.json) + else + VALUE='${{ inputs.targets }}' + fi + echo "value=$VALUE" >> "$GITHUB_OUTPUT" + - uses: dtolnay/rust-toolchain@v1 with: toolchain: ${{ steps.version.outputs.nightly }} - targets: ${{ inputs.targets }} + targets: ${{ steps.targets.outputs.value }} components: ${{ inputs.components }} # xtask docs/doc-tests call `cargo +nightly`; make that name resolve to the pin. diff --git a/.github/actions/setup-toolchains/action.yml b/.github/actions/setup-toolchains/action.yml new file mode 100644 index 00000000000..d3437f7caf3 --- /dev/null +++ b/.github/actions/setup-toolchains/action.yml @@ -0,0 +1,126 @@ +name: Setup toolchains +description: >- + Install the repo-wide pinned Rust toolchains for Xtensa and/or RISC-V targets. + +inputs: + channel: + description: 'Which pin to install: "current" or "msrv".' + required: false + default: current + current-xtensa-version: + description: Xtensa Rust release for the "current" channel. + required: false + default: "1.99.0.0" + xtensa: + description: When "true", install the Xtensa toolchain. + required: false + default: "false" + xtensa-buildtargets: + description: Comma-separated SoCs to build the Xtensa toolchain for. Defaults to every Xtensa chip in chips.json. + required: false + default: "" + xtensa-default: + description: When "true", make the Xtensa toolchain the rustup default. + required: false + default: "false" + riscv: + description: When "true", install the RISC-V toolchain. + required: false + default: "false" + riscv-targets: + description: '"all" for every RISC-V triple in chips.json, "none" for a host-only toolchain, or an explicit comma-separated list.' + required: false + default: all + riscv-extra-targets: + description: Comma-separated extra triples to append to the RISC-V toolchain. + required: false + default: "" + riscv-components: + description: >- + Comma-separated components for the RISC-V toolchain. + required: false + default: rust-src + +outputs: + xtensa-version: + description: The Xtensa toolchain version for the selected channel. + value: ${{ steps.pins.outputs.xtensa-version }} + riscv-toolchain: + description: The rustup channel used for the RISC-V toolchain. + value: ${{ steps.pins.outputs.riscv-toolchain }} + +runs: + using: composite + steps: + # Pins for the two channels CI exercises. api-baseline-generation.yml pins + # the current Xtensa version inline as well, since it runs against trees + # that may not contain this action. + - id: pins + shell: bash + run: | + case '${{ inputs.channel }}' in + current) + echo "xtensa-version=${{ inputs.current-xtensa-version }}" >> "$GITHUB_OUTPUT" + echo "riscv-toolchain=stable" >> "$GITHUB_OUTPUT" + ;; + msrv) + # The first `rust-version` in the file is the one in `[package]`. + MSRV=$(sed -n 's/^rust-version[[:space:]]*=[[:space:]]*"\([^"]*\)".*/\1/p' esp-hal/Cargo.toml | head -n1) + if [ -z "$MSRV" ]; then + echo "::error::Could not read rust-version from esp-hal/Cargo.toml" + exit 1 + fi + echo "Resolved MSRV: $MSRV" + # espup resolves this three-component prefix to the newest 1.x.y.* release. + echo "xtensa-version=$MSRV" >> "$GITHUB_OUTPUT" + echo "riscv-toolchain=$MSRV" >> "$GITHUB_OUTPUT" + ;; + *) + echo "::error::Unknown channel '${{ inputs.channel }}'; expected 'current' or 'msrv'" + exit 1 + ;; + esac + + # Chip-derived defaults, so adding a chip to chips.json does not require + # touching any workflow. + - id: chips + shell: bash + run: | + BUILDTARGETS='${{ inputs.xtensa-buildtargets }}' + if [ -z "$BUILDTARGETS" ]; then + BUILDTARGETS=$(jq -r '[.[] | select(.arch == "xtensa") | .soc] | join(",")' .github/chips.json) + fi + echo "buildtargets=$BUILDTARGETS" >> "$GITHUB_OUTPUT" + + case '${{ inputs.riscv-targets }}' in + all) + # Order-preserving dedupe, so the triple list reads the same as + # chips.json rather than being alphabetised. + TARGETS=$(jq -r ' + [.[] | select(.arch == "riscv") | ."rust-target"] + | reduce .[] as $t ([]; if index($t) then . else . + [$t] end) + | join(",")' .github/chips.json) + ;; + none) TARGETS="" ;; + *) TARGETS='${{ inputs.riscv-targets }}' ;; + esac + + EXTRA='${{ inputs.riscv-extra-targets }}' + if [ -n "$EXTRA" ]; then + TARGETS="${TARGETS:+$TARGETS,}$EXTRA" + fi + echo "targets=$TARGETS" >> "$GITHUB_OUTPUT" + + - if: inputs.xtensa == 'true' + uses: esp-rs/xtensa-toolchain@v1.6 + with: + buildtargets: ${{ steps.chips.outputs.buildtargets }} + default: ${{ inputs.xtensa-default }} + version: ${{ steps.pins.outputs.xtensa-version }} + + - if: inputs.riscv == 'true' + uses: dtolnay/rust-toolchain@v1 + with: + toolchain: ${{ steps.pins.outputs.riscv-toolchain }} + targets: ${{ steps.chips.outputs.targets }} + components: ${{ inputs.riscv-components }} diff --git a/.github/actions/upload-metrics/action.yml b/.github/actions/upload-metrics/action.yml new file mode 100644 index 00000000000..cacfe9bdb34 --- /dev/null +++ b/.github/actions/upload-metrics/action.yml @@ -0,0 +1,89 @@ +name: Upload metrics to S3 +description: >- + Validate and upload a metrics JSON artifact to the Espressif App Metrics S3 + storage using `esp-metrics-cli`. Must run on a Brno self-hosted runner with + access to the internal S3 endpoint. + +inputs: + artifact: + description: Artifact containing the metrics JSON file. + required: false + default: binary-size-metrics + metrics-file: + description: Path to the metrics JSON file inside the artifact. + required: false + default: binary_size_metrics.json + definitions: + description: Path to the YAML schema definition file. + required: false + default: .github/ci/metrics/binary_size_schema.yaml + commit-sha: + description: Commit SHA the metrics belong to. + required: true + branch-name: + description: Branch name for bucket routing ("main" routes to long-term). + required: false + default: ${{ github.ref_name }} + s3-server: + description: S3 endpoint URL. + required: true + long-term-bucket: + description: S3 bucket for default/release branches. + required: false + default: longterm + short-term-bucket: + description: S3 bucket for other branches. + required: false + default: idf-artifacts + s3-access-key: + description: S3 access key. + required: true + s3-secret-key: + description: S3 secret key. + required: true + +runs: + using: composite + steps: + - name: Clean previous metrics workspace + shell: bash + run: rm -rf .metrics-venv metrics + + - uses: actions/download-artifact@v4 + with: + name: ${{ inputs.artifact }} + path: metrics + + - name: Set up Python + id: setup-python + uses: actions/setup-python@v7 + with: + python-version: "3.14" + + - name: Validate and upload metrics + shell: bash + env: + ESP_METRICS_S3_SERVER: ${{ inputs.s3-server }} + ESP_METRICS_S3_ACCESS_KEY: ${{ inputs.s3-access-key }} + ESP_METRICS_S3_SECRET_KEY: ${{ inputs.s3-secret-key }} + ESP_METRICS_S3_LONG_TERM_BUCKET: ${{ inputs.long-term-bucket }} + ESP_METRICS_S3_SHORT_TERM_BUCKET: ${{ inputs.short-term-bucket }} + ESP_METRICS_PROJECT_URL: ${{ github.server_url }}/${{ github.repository }} + ESP_METRICS_PROJECT_ID: ${{ github.repository_id }} + ESP_METRICS_COMMIT_SHA: ${{ inputs.commit-sha }} + ESP_METRICS_BRANCH_NAME: ${{ inputs.branch-name }} + DEFINITIONS: ${{ inputs.definitions }} + METRICS_FILE: metrics/${{ inputs.metrics-file }} + PYTHON: ${{ steps.setup-python.outputs.python-path }} + run: | + set -euo pipefail + trap 'rm -rf .metrics-venv metrics' EXIT + + echo "Using interpreter: $PYTHON" + "$PYTHON" -V + + "$PYTHON" -m venv .metrics-venv + .metrics-venv/bin/python -m pip install --upgrade pip + .metrics-venv/bin/pip install --no-cache-dir esp-metrics-cli + .metrics-venv/bin/esp-metrics-cli validate -d "$DEFINITIONS" -i "$METRICS_FILE" --verbose + .metrics-venv/bin/esp-metrics-cli upload -d "$DEFINITIONS" -i "$METRICS_FILE" --verbose diff --git a/.github/chips.json b/.github/chips.json new file mode 100644 index 00000000000..6b821c7233f --- /dev/null +++ b/.github/chips.json @@ -0,0 +1,14 @@ +[ + { "soc": "esp32", "arch": "xtensa", "rust-target": "xtensa-esp32-none-elf", "ci-toolchain": "esp", "hil-runner": "esp32-jtag" }, + { "soc": "esp32s2", "arch": "xtensa", "rust-target": "xtensa-esp32s2-none-elf", "ci-toolchain": "esp", "hil-runner": "esp32s2-jtag" }, + { "soc": "esp32s3", "arch": "xtensa", "rust-target": "xtensa-esp32s3-none-elf", "ci-toolchain": "esp", "quick": true, "hil-runner": "esp32s3-usb", "hil-radio-runner": "esp32s3-radio" }, + { "soc": "esp32c2", "arch": "riscv", "rust-target": "riscv32imc-unknown-none-elf", "ci-toolchain": "esp", "hil-runner": "esp32c2-jtag" }, + { "soc": "esp32c3", "arch": "riscv", "rust-target": "riscv32imc-unknown-none-elf", "ci-toolchain": "esp", "hil-runner": "esp32c3-usb" }, + { "soc": "esp32c5", "arch": "riscv", "rust-target": "riscv32imac-unknown-none-elf", "ci-toolchain": "stable", "hil-runner": "esp32c5-usb" }, + { "soc": "esp32c6", "arch": "riscv", "rust-target": "riscv32imac-unknown-none-elf", "ci-toolchain": "stable", "quick": true, "hil-runner": "esp32c6-usb", "hil-radio-runner": "esp32c6-radio" }, + { "soc": "esp32c61", "arch": "riscv", "rust-target": "riscv32imac-unknown-none-elf", "ci-toolchain": "stable", "hil-runner": "esp32c61-usb" }, + { "soc": "esp32h2", "arch": "riscv", "rust-target": "riscv32imac-unknown-none-elf", "ci-toolchain": "stable", "hil-runner": "esp32h2-usb" }, + { "soc": "esp32h4", "arch": "riscv", "rust-target": "riscv32imafc-unknown-none-elf", "ci-toolchain": "stable", "hil-runner": "esp32h4-usb" }, + { "soc": "esp32p4", "arch": "riscv", "rust-target": "riscv32imafc-unknown-none-elf", "ci-toolchain": "stable", "hil-runner": "esp32p4" }, + { "soc": "esp32s31", "arch": "riscv", "rust-target": "riscv32imafc-unknown-none-elf", "ci-toolchain": "stable", "hil-runner": "esp32s31-jtag" } +] diff --git a/.github/ci/metrics/binary_size_schema.yaml b/.github/ci/metrics/binary_size_schema.yaml new file mode 100644 index 00000000000..61f9466cbaa --- /dev/null +++ b/.github/ci/metrics/binary_size_schema.yaml @@ -0,0 +1,89 @@ +title: esp-hal Binary Size Metrics +type: object +properties: + binary_size: + type: object + title: Binary Size Totals + description: Total flash and bss sizes per chip and example. + properties: + data: + type: array + minItems: 1 + items: + type: object + properties: + chip: + type: string + title: Chip + description: Target SoC identifier (InfluxDB tag). + example: + type: string + title: Example + description: Example binary name (InfluxDB tag). + flash: + type: integer + title: Flash size + description: Total flash usage in bytes. + unit: bytes + bss: + type: integer + title: BSS size + description: Total bss usage in bytes. + unit: bytes + required: + - chip + - example + - flash + - bss + additionalProperties: false + required: + - data + additionalProperties: false + + binary_size_sections: + type: object + title: Binary Size Sections + description: Per-ELF-section size breakdown per chip and example. + properties: + data: + type: array + minItems: 1 + items: + type: object + properties: + chip: + type: string + title: Chip + description: Target SoC identifier (InfluxDB tag). + example: + type: string + title: Example + description: Example binary name (InfluxDB tag). + section: + type: string + title: ELF section + description: ELF section name, e.g. .text, .rodata, .bss (InfluxDB tag). + kind: + type: string + title: Memory kind + description: Memory region kind, flash or bss (InfluxDB tag). + bytes: + type: integer + title: Section size + description: Section size in bytes. + unit: bytes + required: + - chip + - example + - section + - kind + - bytes + additionalProperties: false + required: + - data + additionalProperties: false + +required: + - binary_size + - binary_size_sections +additionalProperties: false diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md deleted file mode 100644 index c3cd4b29b7b..00000000000 --- a/.github/copilot-instructions.md +++ /dev/null @@ -1,132 +0,0 @@ -# esp-hal agent instructions - -Bare-metal `no_std` Rust HAL for Espressif SoCs. MSRV: **1.95.0** (source: `MSRV` env in `.github/workflows/ci.yml`). - -## Chip reference - -| Chip | Arch | Target | Toolchain flag | -|------|------|--------|----------------| -| esp32 | Xtensa | `xtensa-esp32-none-elf` | `--toolchain esp` | -| esp32s2 | Xtensa | `xtensa-esp32s2-none-elf` | `--toolchain esp` | -| esp32s3 | Xtensa | `xtensa-esp32s3-none-elf` | `--toolchain esp` | -| esp32c2 | RISC-V | `riscv32imc-unknown-none-elf` | `--toolchain stable` | -| esp32c3 | RISC-V | `riscv32imc-unknown-none-elf` | `--toolchain stable` | -| esp32c5 | RISC-V | `riscv32imac-unknown-none-elf` | `--toolchain stable` | -| esp32c6 | RISC-V | `riscv32imac-unknown-none-elf` | `--toolchain stable` | -| esp32c61 | RISC-V | `riscv32imac-unknown-none-elf` | `--toolchain stable` | -| esp32h2 | RISC-V | `riscv32imac-unknown-none-elf` | `--toolchain stable` | -| esp32p4 | RISC-V | `riscv32imafc-unknown-none-elf` | `--toolchain stable` | -| esp32s31 | RISC-V | `riscv32imafc-unknown-none-elf` | `--toolchain stable` | - -## Commands - -All automation goes through `cargo xtask`. Scope the work with `--chips` and with the package name, -which the `*-packages` commands take as a positional argument, not as `--packages`. - -| Task | Command | Notes | -|------|---------|-------| -| Format (required before PR) | `cargo xtask fmt-packages` | Fast | -| Lint | `cargo xtask lint-packages [...] [--chips X]` | Always scope: every chip and package takes minutes | -| Check | `cargo xtask check-packages [...] [--chips X]` | Compiles without linting | -| Host-side unit tests | `cargo xtask host-tests` | Fast, runs on host | -| Validate metadata | `cargo update-metadata --check` | Fast | -| Validate changelog | `cargo xtask check-changelog` | Fast | -| Build one example | `cargo xtask build examples --chip [--package ]` | Name is required — see below | -| Build every example | `cargo xtask build examples all --chip [--package ]` | `--package qa-test` for the `qa-test` binaries | -| Build and flash an example | `cargo xtask run example --chip ` | Requires a connected device | -| Build docs | `cargo xtask build documentation --chips ` | Slow — scope to affected chips | -| HIL tests (needs hardware) | `cargo xtask run tests [--test name]` | Requires connected device | -| Full CI check for one chip | `cargo xtask ci ` | **Very slow** — use only as final check before opening a PR | - -**Name the example, always.** `build examples` and `run example` take the example name as their first -argument, and `all` in that position means every example of the package. Leaving it out is not a -shortcut for `all`: the command asks which example to act on, and an agent or a script gets an error -instead of a build. The same holds for `--chip`. - -**Prefer targeted commands** (`lint-packages esp-hal --chips X`, `build examples --chip X`) during development. Only run `ci` as a final validation pass. - -## Test & example metadata - -Tests and examples use `//% KEY: value` comments to control xtask builds (full docs: `xtask/README.md`). - -| Annotation | Purpose | Example | -|------------|---------|---------| -| `//% CHIP_FILTER:` | Boolean expression selecting chips; prefer a capability cfg flag over a chip list; key-value cfg symbols support `==` / `!=` with quoted strings | `//% CHIP_FILTER: riscv && interrupt_controller != "clic"` | -| `//% FEATURES:` | Enable cargo features | `//% FEATURES: unstable embassy` | -| `//% ENV:` | Set environment variables | `//% ENV: ESP_HAL_CONFIG_STACK_GUARD_OFFSET=4` | -| `//% CARGO-CONFIG:` | Cargo `--config` passthrough | `//% CARGO-CONFIG: ...` | - -Named configs build the same file with different settings: -``` -//% CHIP_FILTER(wifi): esp32 || esp32c3 || esp32c6 || esp32s3 -//% CHIP_FILTER(ble_only): esp32h2 -//% FEATURES(wifi): esp-radio/wifi -//% FEATURES(ble_only): esp-radio/ble -``` - -## The `unstable` feature - -- **Libraries** must never enable `unstable`. Use `requires-unstable` instead. -- **Applications** (examples, tests) may enable `unstable` freely. -- Mark new unstable APIs with `#[instability::unstable]`. -- `unstable_module!` macro: makes a module `pub` when `unstable` is enabled, `pub(crate)` otherwise. -- Features prefixed with `__` (e.g. `__bluetooth`) are private — never enable directly. - -## esp-config - -Build-time configuration defined in `esp_config.yml` per crate. Override via environment variables. - -```rust -esp_config::esp_config_bool!("ESP_HAL_CONFIG_PLACE_SPI_MASTER_DRIVER_IN_RAM"); -esp_config::esp_config_int!(u32, "ESP_HAL_CONFIG_STACK_GUARD_OFFSET"); -esp_config::esp_config_str!("ESP_HAL_CONFIG_PSRAM_MODE"); -``` - -Config options must not alter the public API surface. - -## Driver conventions - -From `documentation/DEVELOPER-GUIDELINES.md` (read it for full details): - -- **Pins**: `fn with_signal_name(self, pin: impl PeripheralInput) -> Self` -- **Constructor**: takes `impl Instance + 'd`, returns `Result` -- **Config**: `Config` struct with `procmacros::BuilderLite` derive + separate `ConfigError` enum -- **Modes**: `DriverMode` type param; default `Blocking`; provide `into_async`/`into_blocking` -- **Drop**: must reset peripheral to idle state -- **Derives**: drivers: `Debug`; configs: `Default, Debug, PartialEq, Eq, Clone, Copy, Hash` -- **Doc examples**: use `#[doc = crate::before_snippet!()]`, `no_run`, `?` operator (not unwrap) - -## Conditional compilation - -Chip properties come from `esp-metadata/devices/*.toml`, generated into `esp-metadata-generated/`. - -Key symbols: `riscv` / `xtensa`, `single_core` / `multi_core`, `soc_has_`, `_driver_supported`. - -Prefer these over `#[cfg(feature = "esp32c3")]` where possible. - -## Changelog & migration - -- Changelog entries go in the **PR description**, not in `CHANGELOG.md` (those files are generated at release time — never edit them directly). -- Use a `# Changelog` section with H2 crate headings (e.g. `## esp-hal`). Each entry starts with a kind prefix: `Added`, `Changed`, `Fixed`, or `Removed` — e.g. `- Added: Support for the Foo peripheral.` Do not include a PR number. -- If a touched crate needs no user-visible entry, add `- No changelog necessary.` as the sole item in its section. -- Breaking changes: add a `# Migration guide` section with an H2 `## crate/area` heading (e.g. `## esp-hal/SPI driver`) and an H3 `### Title` per change, followed by migration steps. -- Breaking changes to stable API require a `breaking-change-` PR label. -- Validate with `cargo xtask check-pr-changelog` (pipe the body in, or pass `--pr `). - -## PR checklist - -1. `cargo xtask fmt-packages` -2. `cargo xtask lint-packages --chips ` — fix all warnings -3. `cargo update-metadata --check` — if metadata changed -4. `cargo xtask check-pr-changelog` — add changelog entries to the PR description if API changed -5. Build affected examples/tests for relevant chips -6. `cargo xtask host-tests` — if host-side code changed; when adding `#[test]` to a package for the first time, register it in `run_host_tests` (`xtask/src/lib.rs`) - -## Key references - -- `documentation/DEVELOPER-GUIDELINES.md` — full API design rules -- `documentation/API-DOC-RULES.md` — API / rustdoc writing rules (STE, EMoS, item docs) -- `documentation/CONTRIBUTING.md` — contribution workflow -- `xtask/README.md` — metadata annotations and xtask usage -- `.github/workflows/ci.yml` — CI steps and MSRV -- `esp-metadata/devices/*.toml` — per-chip peripheral definitions diff --git a/.github/scripts/binary-size.js b/.github/scripts/binary-size.js new file mode 100644 index 00000000000..bf0bff42e54 --- /dev/null +++ b/.github/scripts/binary-size.js @@ -0,0 +1,1029 @@ +// Binary size checks. `binary-size.yml` measures a pull request on demand +// (`/test-size`), `binary-size-nightly.yml` measures what `main` gained in a +// day or over a chosen date/tag range. Both pick the commits, `measure` +// (through `.github/actions/measure-binary-size`) and report with the +// functions here. + +const fs = require("fs"); +const path = require("path"); + +// All nightly reports go to the one open issue with this title. +const ISSUE_TITLE = "Nightly Workflow: Binary size regression on main"; +// Marks the pull request comment that holds the report. +const PR_REPORT_HEADING = "## Binary Size Report"; +// Sizes written by `measure` (and cached by `prepare`), one file per chip. +const SIZES_DIR = "sizes"; +const CACHED_FILE = path.join(SIZES_DIR, "cached.txt"); +// Metrics JSON file written by `reportNightly` for `esp-metrics-cli`. +const METRICS_FILE = "binary_size_metrics.json"; +const METRICS_NAMES = ["binary_size", "binary_size_sections"]; +const MAX_BETWEEN_COMMITS = 15; + +// Runs git and returns its trimmed output. +async function git(exec, args) { + const { stdout } = await exec.getExecOutput("git", args, { silent: true }); + return stdout.trim(); +} + +async function isAncestor(exec, ancestor, descendant) { + const { exitCode } = await exec.getExecOutput( + "git", + ["merge-base", "--is-ancestor", ancestor, descendant], + { ignoreReturnCode: true, silent: true }, + ); + return exitCode === 0; +} + +function runUrl(context) { + const { owner, repo } = context.repo; + return `${context.serverUrl}/${owner}/${repo}/actions/runs/${context.runId}`; +} + +function metricsApiConfig(context) { + const url = (process.env.ESP_METRICS_API_URL || "").trim().replace(/\/+$/, ""); + const token = (process.env.ESP_METRICS_API_TOKEN || "").trim(); + const projectId = Number( + process.env.GITHUB_REPOSITORY_ID || context.payload.repository?.id || 0, + ); + const { owner, repo } = context.repo; + const projectUrl = `${context.serverUrl}/${owner}/${repo}`; + return url && projectId ? { url, token, projectId, projectUrl } : null; +} + +async function postMetricsApi(config, endpoint, body) { + const headers = { "Content-Type": "application/json" }; + if (config.token) headers.Authorization = `Bearer ${config.token}`; + const response = await fetch(`${config.url}${endpoint}`, { + method: "POST", + headers, + body: JSON.stringify(body), + }); + if (response.status === 404) return null; + if (!response.ok) { + throw new Error(`${endpoint} returned HTTP ${response.status}`); + } + return await response.json(); +} + +// Queries `/api/v1/metrics/query` for `sha` and returns its stored metrics, or +// null when `sha` has not been uploaded to `app-metrics`. +async function fetchCommitMetrics({ context, core }, sha) { + const config = metricsApiConfig(context); + if (!config || !sha) return null; + try { + const data = await postMetricsApi(config, "/api/v1/metrics/query", { + project_id: config.projectId, + project_url: config.projectUrl, + commit_sha: sha, + metrics_names: METRICS_NAMES, + }); + return data?.success ? data.metrics : null; + } catch (error) { + core.warning(`Could not query metrics for ${sha.slice(0, 10)}: ${error.message}`); + return null; + } +} + +// Queries `/api/v1/metrics/latest_commit` for the latest commit on `main` +// stored in the `longterm` bucket. +async function fetchLatestCommitMetrics({ context, core }) { + const config = metricsApiConfig(context); + if (!config) return null; + try { + const data = await postMetricsApi(config, "/api/v1/metrics/latest_commit", { + project_id: config.projectId, + project_url: config.projectUrl, + branch_name: "main", + bucket_type: "longterm", + metrics_names: METRICS_NAMES, + }); + return data?.success && data.commit_sha ? data : null; + } catch (error) { + core.warning(`Could not query latest commit metrics: ${error.message}`); + return null; + } +} + +// Converts a `metrics` object from `/api/v1/metrics/query` into the +// `
` lines `groupSizes` +// reads. +function metricsToLines(metrics, role) { + const sections = metrics?.binary_size_sections?.data || []; + if (sections.length > 0) { + return sections.map( + (s) => `${s.chip} ${s.example} ${role} ${s.section} ${s.kind} ${s.bytes}`, + ); + } + const totals = metrics?.binary_size?.data || []; + return totals.flatMap((t) => [ + `${t.chip} ${t.example} ${role} .flash flash ${t.flash}`, + `${t.chip} ${t.example} ${role} .bss bss ${t.bss}`, + ]); +} + +// The head of the last successful scheduled run (or the latest commit on `main` +// in `app-metrics`), if `main` still contains it. +async function previousHead({ github, context, core, exec }) { + const { data } = await github.rest.actions.listWorkflowRuns({ + ...context.repo, + workflow_id: "binary-size-nightly.yml", + event: "schedule", + status: "success", + per_page: 1, + }); + const sha = data.workflow_runs[0]?.head_sha; + if (sha && (await isAncestor(exec, sha, "HEAD"))) return sha; + + const latest = await fetchLatestCommitMetrics({ context, core }); + if (latest?.commit_sha && (await isAncestor(exec, latest.commit_sha, "HEAD"))) { + return latest.commit_sha; + } + return ""; +} + +// Resolves a date/time window on `main`, preferring a commit near the boundary +// that already has stored metrics in `app-metrics`. +async function resolveBeforeWithCache(api, before, head = "HEAD") { + const { exec } = api; + const out = await git(exec, [ + "rev-list", + "--max-count=10", + "--first-parent", + `--before=${before}`, + head, + ]); + const candidates = out.split("\n").filter(Boolean); + if (candidates.length === 0) return ""; + if (metricsApiConfig(api.context)) { + for (const sha of candidates) { + const metrics = await fetchCommitMetrics(api, sha); + if (metrics && metricsToLines(metrics, "base").length > 0) return sha; + } + } + return candidates[0]; +} + +// Resolves a date (`YYYY-MM-DD`), release tag (`esp-hal-v1.2.0` / `v1.2.0`), +// or commit hash to a commit SHA. +async function resolveInput(api, input, isStart, head = "HEAD") { + const { exec } = api; + if (/^\d{4}-\d{2}-\d{2}$/.test(input)) { + const time = `${input}T${isStart ? "00:00:00" : "23:59:59"}Z`; + const sha = + (await resolveBeforeWithCache(api, time, head)) || + (await resolveBeforeWithCache(api, `${input}T23:59:59Z`, head)); + if (!sha) throw new Error(`No commit on main before ${input}.`); + return sha; + } + for (const ref of [input, `esp-hal-${input}`, `esp-hal-v${input}`]) { + const { exitCode, stdout } = await exec.getExecOutput( + "git", + ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], + { ignoreReturnCode: true, silent: true }, + ); + if (exitCode === 0) return stdout.trim(); + } + throw new Error(`Unknown commit, tag, or date: ${input}`); +} + +// Picks the `base` and `head` commits to compare, prefetches any sizes already +// stored in `app-metrics`, and outputs the chips that still need to be built. +// `--first-parent` keeps to `main` itself: one commit per merged pull request. +async function resolveNightlyRange({ github, context, core, exec }) { + const api = { github, context, core, exec }; + const range = process.env.INPUT_RANGE || "since-last-run"; + const baseInput = (process.env.INPUT_BASE || "").trim(); + const headInput = (process.env.INPUT_HEAD || "").trim(); + + fs.rmSync(SIZES_DIR, { recursive: true, force: true }); + + const head = headInput + ? await resolveInput(api, headInput, false) + : await git(exec, ["rev-parse", "HEAD"]); + + let base = ""; + if (baseInput) { + base = await resolveInput(api, baseInput, true, head); + } else if (range === "since-last-release") { + const tag = await git(exec, [ + "describe", + "--tags", + "--match", + "esp-hal-v*", + "--exclude", + "esp-hal-v*-*", + "--abbrev=0", + head, + ]); + base = await resolveInput(api, tag, true, head); + } else if (range === "last-7-days" || range === "last-30-days") { + const days = range === "last-7-days" ? 7 : 30; + base = await resolveBeforeWithCache(api, `${days} days ago`, head); + } else { + base = + (await previousHead(api)) || + (await resolveBeforeWithCache(api, "24 hours ago", head)); + } + core.info(`Comparing ${base} with ${head}`); + + // Empty outputs skip the other jobs. + if (base === head) { + core.info(`Nothing was merged since ${base}.`); + return; + } + + if (await isAncestor(exec, head, base)) { + throw new Error( + `Start commit ${base.slice(0, 10)} is newer than end commit ${head.slice(0, 10)}.`, + ); + } + + // The commits merged before `head`, oldest first. `measure` builds them only + // for examples that grew past the limits, to find the pull request behind it. + const between = (await isAncestor(exec, base, head)) + ? (await git(exec, ["rev-list", "--first-parent", "--reverse", `${base}..${head}`])) + .split("\n") + .slice(0, -1) + : []; + const shortBetween = between.length <= MAX_BETWEEN_COMMITS ? between : []; + + const cachedLines = []; + for (const [role, sha] of [ + ["base", base], + ["head", head], + ...shortBetween.map((sha) => [sha, sha]), + ]) { + const metrics = await fetchCommitMetrics(api, sha); + const lines = metricsToLines(metrics, role); + if (lines.length > 0) { + core.info(`Fetched stored metrics from app-metrics for ${role} (${sha.slice(0, 10)}).`); + cachedLines.push(...lines); + } + } + + if (cachedLines.length > 0) { + fs.mkdirSync(SIZES_DIR, { recursive: true }); + fs.writeFileSync(CACHED_FILE, `${cachedLines.join("\n")}\n`); + core.setOutput("has_cached", "true"); + } + + const allChips = JSON.parse(fs.readFileSync(".github/chips.json", "utf8")).map( + (chip) => chip.soc, + ); + core.setOutput("base", base); + core.setOutput("head", head); + core.setOutput("between", shortBetween.join(" ")); + core.setOutput("all_chips", JSON.stringify(allChips)); + + // Determine which chips still need a `measure` job: any chip missing `base` + // or `head` in `cachedLines`, or any chip that regressed between cached + // `base` and `head` and has uncached `between` commits to bisect. + const rolesByChip = new Map(allChips.map((soc) => [soc, new Set()])); + for (const line of cachedLines) { + const [chip, , role] = line.trim().split(/\s+/); + rolesByChip.get(chip)?.add(role); + } + const entries = groupSizes(cachedLines).filter((entry) => entry.head); + const regressedChips = new Set( + compareEntries(entries, limitsFromEnv()) + .filter((row) => row.regressed) + .map((row) => row.chip), + ); + const chipsToBuild = allChips.filter((soc) => { + const roles = rolesByChip.get(soc); + if (!roles.has("base") || !roles.has("head")) return true; + return regressedChips.has(soc) && shortBetween.some((sha) => !roles.has(sha)); + }); + + if (chipsToBuild.length === 0) { + core.info("All required measurements are already in app-metrics; skipping build."); + return; + } + core.setOutput("chips", JSON.stringify(chipsToBuild)); +} + +// Compares the pull request head with the commit it branched from, so changes +// merged into the base branch since then do not show up as its own. +async function resolvePullRequestRange({ github, context, core }) { + const { owner, repo } = context.repo; + const { data: pull } = await github.rest.pulls.get({ + owner, + repo, + pull_number: Number(process.env.PR_NUMBER), + }); + const { data: comparison } = await github.rest.repos.compareCommitsWithBasehead({ + owner, + repo, + basehead: `${pull.base.ref}...${pull.head.sha}`, + }); + const base = comparison.merge_base_commit.sha; + core.info(`Comparing ${base} with ${pull.head.sha}`); + core.setOutput("base", base); + core.setOutput("head", pull.head.sha); +} + +// Finds `/Cargo.toml` under `dir`, skipping build output. +function findManifest(dir, example) { + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (!entry.isDirectory() || entry.name === "target" || entry.name.startsWith(".")) { + continue; + } + const child = path.join(dir, entry.name); + const manifest = path.join(child, "Cargo.toml"); + if (entry.name === example && fs.existsSync(manifest)) return manifest; + const found = findManifest(child, example); + if (found) return found; + } + return null; +} + +// Returns the possible ELF names of an example, or null when it does not +// support the chip. A standalone example lists its chips as features and names +// its ELF in `[package]`. A binary of a package like `qa` is named after its +// source file, and the build itself rejects an unsupported chip. +function elfNames(example, soc, pkg) { + const guesses = [example, example.replaceAll("_", "-")]; + const manifest = pkg ? null : findManifest("examples", example); + if (!manifest) return guesses; + + const text = fs.readFileSync(manifest, "utf8"); + if (!new RegExp(`^${soc}\\s*=`, "m").test(text)) return null; + const packageSection = text.split(/^\[/m).find((part) => part.startsWith("package]")); + const name = packageSection?.match(/^name\s*=\s*"([^"]+)"/m)?.[1]; + return name ? [name] : guesses; +} + +// Indices of the sections that hold at least one variable or function. +async function sectionsWithSymbols(exec, elf) { + const { stdout } = await exec.getExecOutput("readelf", ["-s", "-W", elf], { + silent: true, + }); + const indices = new Set(); + for (const line of stdout.split("\n")) { + // "Num: Value Size Type Bind Vis Ndx Name" + const [num, , , type, , , ndx] = line.trim().split(/\s+/); + if (/^\d+:$/.test(num) && (type === "OBJECT" || type === "FUNC") && /^\d+$/.test(ndx)) { + indices.add(Number(ndx)); + } + } + if (indices.size === 0) throw new Error(`${elf} has no symbol table.`); + return indices; +} + +// Lists the sections of an ELF file that end up in the image (flag `A`): +// sections with contents count as flash, NOBITS ones as bss. A NOBITS section +// without a single variable in it, like `.stack` or `.text_gap`, only reserves +// address space for the memory layout and is skipped. +async function sectionsOf(exec, elf) { + const { stdout } = await exec.getExecOutput("readelf", ["-S", "-W", elf], { + silent: true, + }); + const withSymbols = await sectionsWithSymbols(exec, elf); + const sections = []; + for (const line of stdout.split("\n")) { + // "[Nr] Name Type Address Off Size ES Flg Lk Inf Al" + const row = line.match(/^\s*\[\s*(\d+)\]\s+(.*)$/); + if (!row) continue; + const [name, type, , , size, , flags] = row[2].trim().split(/\s+/); + const bytes = parseInt(size, 16); + if (!flags?.includes("A") || !bytes) continue; + if (type === "NOBITS" && !withSymbols.has(Number(row[1]))) continue; + sections.push({ name, kind: type === "NOBITS" ? "bss" : "flash", bytes }); + } + return sections; +} + +// Builds the examples for one chip at the base and at the head commit (skipping +// any commit already fetched from `app-metrics` in `sizes/cached.txt`) and +// writes their newly built sections to `sizes/.txt`. Node keeps this +// script in memory, so checking out other commits under it is fine. +async function measure({ core, exec }) { + const { SOC: soc, TARGET: target, BASE: base, HEAD: head } = process.env; + const pkg = process.env.PACKAGE || ""; + const examples = process.env.EXAMPLES.split(/\s+/).filter(Boolean); + const between = (process.env.BETWEEN || "").split(/\s+/).filter(Boolean); + + const cachedSoc = fs.existsSync(CACHED_FILE) + ? fs + .readFileSync(CACHED_FILE, "utf8") + .split("\n") + .filter((line) => line.startsWith(`${soc} `)) + : []; + const cachedRoles = new Set(cachedSoc.map((line) => line.trim().split(/\s+/)[2])); + + // A pull request head may only be reachable from `refs/pull/*`. + await exec.exec("git", ["fetch", "--quiet", "--no-tags", "origin", base, head]); + + // Older commits may lack this action, and its post steps need it on disk. + const original = await git(exec, ["rev-parse", "HEAD"]); + const built = []; + try { + for (const [role, commit] of [ + ["base", base], + ["head", head], + ]) { + if (cachedRoles.has(role)) { + core.info( + `Using stored metrics from app-metrics for ${soc} at ${role} (${commit.slice(0, 10)}).`, + ); + continue; + } + built.push( + ...(await measureCommit({ core, exec, soc, target, pkg, examples, role, commit })), + ); + } + const uncachedBetween = between.filter((sha) => !cachedRoles.has(sha)); + built.push( + ...(await measureBetween({ + core, + exec, + soc, + target, + pkg, + lines: [...cachedSoc, ...built], + between: uncachedBetween, + })), + ); + } finally { + await exec.exec("git", ["checkout", "--quiet", "--force", original]); + } + + if (built.length === 0) { + core.info(`Nothing new was built for ${soc}.`); + return; + } + fs.mkdirSync(SIZES_DIR, { recursive: true }); + fs.writeFileSync(path.join(SIZES_DIR, `${soc}.txt`), `${built.join("\n")}\n`); + core.info(built.join("\n")); +} + +// Checks out one commit and returns the section lines of its examples. +async function measureCommit({ core, exec, soc, target, pkg, examples, role, commit }) { + await exec.exec("git", ["checkout", "--quiet", "--force", commit]); + + const lines = []; + for (const example of examples) { + const names = elfNames(example, soc, pkg); + if (!names) { + core.info(`Skipping ${example}: it does not support ${soc}.`); + continue; + } + + const packageArgs = pkg ? ["--package", pkg] : []; + try { + await exec.exec("cargo", ["xtask", "build", example, ...packageArgs, soc]); + } catch (error) { + if (role === "head") throw error; + core.warning(`Skipping ${example} at ${commit} on ${soc}: ${error.message}`); + continue; + } + + const elf = names + .map((name) => path.join("target", target, "release", name)) + .find((file) => fs.existsSync(file)); + if (!elf) throw new Error(`No ELF found for ${example} on ${soc}.`); + + for (const section of await sectionsOf(exec, elf)) { + lines.push(`${soc} ${example} ${role} ${section.name} ${section.kind} ${section.bytes}`); + } + } + return lines; +} + +// Builds the examples that grew past the limits at every commit in between, +// so the report can name the pull request behind the growth. A commit that +// fails to build is skipped, its growth then shows up in the next one. +async function measureBetween({ core, exec, soc, target, pkg, lines, between }) { + if (between.length === 0) return []; + const entries = groupSizes(lines).filter((entry) => entry.head); + const examples = compareEntries(entries, limitsFromEnv()) + .filter((row) => row.regressed) + .map((row) => row.example); + if (examples.length === 0) return []; + + await exec.exec("git", ["fetch", "--quiet", "--no-tags", "origin", ...between]); + const found = []; + for (const commit of between) { + try { + found.push( + ...(await measureCommit({ core, exec, soc, target, pkg, examples, role: commit, commit })), + ); + } catch (error) { + core.warning(`Skipping ${commit} on ${soc}: ${error.message}`); + } + } + return found; +} + +// Reads the `MAX_*` limits from `env`. A typo fails the run instead of +// silently never reporting. +function limitsFromEnv() { + const limits = { + percent: Number(process.env.MAX_GROWTH_PERCENT), + flash: Number(process.env.MAX_FLASH_GROWTH_BYTES), + bss: Number(process.env.MAX_BSS_GROWTH_BYTES), + }; + for (const [name, value] of Object.entries(limits)) { + if (!Number.isFinite(value)) { + throw new Error(`The ${name} growth limit is not a number.`); + } + } + return limits; +} + +// Groups the "
" lines into +// one entry per chip and example, with the sections and totals of each commit. +// The role is `base`, `head`, or the hash of a commit in between. +function groupSizes(lines) { + const examples = new Map(); + for (const line of lines) { + if (!line.trim()) continue; + const [chip, example, role, section, kind, bytes] = line.trim().split(/\s+/); + const key = `${chip} ${example}`; + if (!examples.has(key)) { + examples.set(key, { chip, example, kinds: new Map(), between: {} }); + } + const entry = examples.get(key); + entry.kinds.set(section, kind); + const sizes = role === "base" || role === "head" ? entry : entry.between; + sizes[role] ??= { flash: 0, bss: 0, sections: new Map() }; + if (sizes[role].sections.has(section)) continue; + sizes[role][kind] += Number(bytes); + sizes[role].sections.set(section, Number(bytes)); + } + return [...examples.values()]; +} + +// Reads the sizes of all chips, sorted so tables keep the same order. +function readSizes() { + if (!fs.existsSync(SIZES_DIR)) return []; + + const lines = fs + .readdirSync(SIZES_DIR) + .flatMap((file) => fs.readFileSync(path.join(SIZES_DIR, file), "utf8").split("\n")); + + // An example that only exists at the base was removed, nothing to report. + return groupSizes(lines) + .filter((entry) => entry.head) + .sort( + (a, b) => + a.chip.localeCompare(b.chip) || a.example.localeCompare(b.example), + ); +} + +// Writes `binary_size_metrics.json` in the format `esp-metrics-cli` expects +// when `head` is the current `HEAD` commit and was freshly measured across all +// chips (because `esp-metrics-cli` stamps uploads with the current time). +async function writeMetrics(exec, entries, head, missing) { + if (entries.length === 0 || missing.length > 0) return false; + const currentHead = await git(exec, ["rev-parse", "HEAD"]); + if (head !== currentHead) return false; + + if (fs.existsSync(CACHED_FILE)) { + const cachedHead = fs + .readFileSync(CACHED_FILE, "utf8") + .split("\n") + .some((line) => line.trim().split(/\s+/)[2] === "head"); + if (cachedHead) return false; + } + + const totals = []; + const sections = []; + for (const entry of entries) { + totals.push({ + chip: entry.chip, + example: entry.example, + flash: entry.head.flash, + bss: entry.head.bss, + }); + for (const [section, bytes] of entry.head.sections) { + sections.push({ + chip: entry.chip, + example: entry.example, + section, + kind: entry.kinds.get(section), + bytes, + }); + } + } + if (totals.length === 0 || sections.length === 0) return false; + + fs.writeFileSync( + METRICS_FILE, + `${JSON.stringify({ binary_size: { data: totals }, binary_size_sections: { data: sections } }, null, 2)}\n`, + ); + return true; +} + +// Chips that were asked for but produced no sizes: their build failed, or +// none of the examples supports them. +function missingChips(entries) { + const measured = new Set(entries.map((entry) => entry.chip)); + return JSON.parse(process.env.CHIPS || "[]").filter((chip) => !measured.has(chip)); +} + +function signed(number) { + return number > 0 ? `+${number}` : `${number}`; +} + +// Formats a cell like `72734 (+4112, +5.99%)`. With limits, regressions and +// reductions that cross both thresholds are marked in bold. +function compare(was, now, maxBytes, maxPercent) { + if (was === undefined) { + return { text: `${now} (new)`, regressed: false, improved: false }; + } + + const delta = now - was; + if (delta === 0) { + return { text: `${now}`, regressed: false, improved: false }; + } + + const percent = was > 0 ? (100 * delta) / was : 0; + const sign = delta > 0 ? "+" : ""; + const text = `${now} (${sign}${delta}, ${sign}${percent.toFixed(2)}%)`; + const regressed = + maxBytes !== undefined && delta > maxBytes && percent > maxPercent; + const improved = + maxBytes !== undefined && -delta > maxBytes && -percent > maxPercent; + return { + text: regressed || improved ? `**${text}**` : text, + regressed, + improved, + }; +} + +// Compares the totals of every entry. Without limits nothing regresses. +function compareEntries(entries, limits) { + return entries.map((entry) => { + const flash = compare(entry.base?.flash, entry.head.flash, limits?.flash, limits?.percent); + const bss = compare(entry.base?.bss, entry.head.bss, limits?.bss, limits?.percent); + const regressed = flash.regressed || bss.regressed; + const improved = !regressed && (flash.improved || bss.improved); + return { ...entry, flash, bss, regressed, improved }; + }); +} + +// Renders compared entries as a Markdown table of their totals. +function totalsTable(rows) { + return [ + "| Chip | Example | Flash (bytes) | bss (bytes) |", + "|---|---|---|---|", + ...rows.map( + (row) => + `| \`${row.chip}\` | \`${row.example}\` | ${row.flash.text} | ${row.bss.text} |`, + ), + ].join("\n"); +} + +// Lists the sections that changed size, biggest change first, one collapsed +// table per example. Shows where the growth went, e.g. into `.trap`. +function sectionsDetails(rows) { + const blocks = []; + for (const row of rows) { + const before = row.base?.sections ?? new Map(); + const after = row.head.sections; + const names = new Set([...before.keys(), ...after.keys()]); + const changed = [...names] + .map((name) => ({ + name, + was: before.get(name) ?? 0, + now: after.get(name) ?? 0, + })) + .filter((section) => section.was !== section.now) + .sort((a, b) => Math.abs(b.now - b.was) - Math.abs(a.now - a.was)); + if (changed.length === 0) continue; + + blocks.push( + [ + `
${row.chip} ${row.example}: sections that changed`, + "", + "| Section | Before | After | Change |", + "|---|---|---|---|", + ...changed.map( + (section) => + `| \`${section.name}\` | ${section.was} | ${section.now} | ${signed(section.now - section.was)} |`, + ), + "", + "
", + ].join("\n"), + ); + } + return blocks.join("\n\n"); +} + +function missingNote(chips) { + if (chips.length === 0) return ""; + return `No sizes from ${chips.map((chip) => `\`${chip}\``).join(", ")}: the build failed or no example supports them, see the run.`; +} + +// Names a commit by its pull request, or by its hash and subject when it has +// none. Escaped for a table cell, with mentions kept from notifying anyone. +async function describeCommit({ github, context, exec }, sha) { + const { data: pulls } = await github.rest.repos.listPullRequestsAssociatedWithCommit({ + ...context.repo, + commit_sha: sha, + }); + const pull = pulls.find((pull) => pull.merged_at); + const text = pull + ? `#${pull.number} ${pull.title}` + : `${sha.slice(0, 10)} ${await git(exec, ["log", "-1", "--format=%s", sha])}`; + return text.replaceAll("@", "@\u200b").replaceAll("|", "\\|"); +} + +// Splits every regression into the growth of each merged pull request, from +// the sizes `measureBetween` recorded. Commits without sizes are counted +// together with the next one that has them. Returns the table, the examples +// each pull request alone grew past the limits, and the regressions that no +// single pull request explains. +async function growthByPullRequest(api, rows, chain, limits) { + const names = new Map(); + const lines = []; + const culprits = new Map(); + const unexplained = []; + for (const row of rows) { + if (!row.base) continue; + let previous = row.base; + let pending = []; + const explained = { flash: false, bss: false }; + for (const commit of chain.slice(1)) { + pending.push(commit); + const sizes = commit === chain.at(-1) ? row.head : row.between[commit]; + if (!sizes) continue; + + if (sizes.flash !== previous.flash || sizes.bss !== previous.bss) { + for (const sha of pending) { + if (!names.has(sha)) names.set(sha, await describeCommit(api, sha)); + } + const flash = compare(previous.flash, sizes.flash, limits.flash, limits.percent); + const bss = compare(previous.bss, sizes.bss, limits.bss, limits.percent); + const pulls = pending.map((sha) => names.get(sha)).join("
"); + lines.push( + `| \`${row.chip}\` | \`${row.example}\` | ${pulls} | ${flash.text} | ${bss.text} |`, + ); + + if (flash.regressed || bss.regressed) { + const culprit = pending.map((sha) => names.get(sha)).join(" or "); + if (!culprits.has(culprit)) culprits.set(culprit, []); + culprits.get(culprit).push(row); + } + explained.flash ||= flash.regressed; + explained.bss ||= bss.regressed; + } + previous = sizes; + pending = []; + } + if ((row.flash.regressed && !explained.flash) || (row.bss.regressed && !explained.bss)) { + unexplained.push(row); + } + } + const table = [ + "| Chip | Example | Pull request | Flash (bytes) | bss (bytes) |", + "|---|---|---|---|---|", + ...lines, + ].join("\n"); + return { table, hasRows: lines.length > 0, culprits, unexplained }; +} + +// Lists rows as "`example` on `chip`, `chip`; `example` on `chip`". +function whereText(rows) { + const chips = new Map(); + for (const row of rows) { + if (!chips.has(row.example)) chips.set(row.example, []); + chips.get(row.example).push(`\`${row.chip}\``); + } + return [...chips] + .map(([example, list]) => `\`${example}\` on ${list.join(", ")}`) + .join("; "); +} + +// Names the pull requests that alone grew past the limits, and where, and the +// regressions that only add up over several pull requests. +function causeText({ culprits, unexplained }) { + const lines = [...culprits].map( + ([culprit, rows]) => `**${culprit}** grew past the limits on its own: ${whereText(rows)}.`, + ); + if (unexplained.length > 0) { + lines.push( + `No single pull request grew past the limits on its own in ${whereText(unexplained)}, the growth adds up over several of them. See the growth by pull request below.`, + ); + } + return lines.length === 1 ? lines[0] : lines.map((line) => `- ${line}`).join("\n"); +} + +// Writes the nightly table to the run summary, exports `binary_size_metrics.json` +// for `esp-metrics-cli`, and on scheduled runs opens or updates the regression +// issue when an example grew past the limits. +async function reportNightly({ github, context, core, exec }) { + const base = process.env.BASE; + const head = process.env.HEAD; + const limits = limitsFromEnv(); + + const entries = readSizes(); + const missing = missingChips(entries); + const hasMetrics = await writeMetrics(exec, entries, head, missing); + core.setOutput("has_metrics", hasMetrics ? "true" : "false"); + + const rows = compareEntries(entries, limits); + const regressions = rows.filter((row) => row.regressed); + const improvements = rows.filter((row) => row.improved); + const missingText = missingNote(missing); + + const between = (process.env.BETWEEN || "").split(/\s+/).filter(Boolean); + const growth = + regressions.length > 0 + ? await growthByPullRequest( + { github, context, exec }, + regressions, + [base, ...between, head], + limits, + ) + : null; + + const summary = [ + "## Binary size report", + "", + `Base: \`${base.slice(0, 10)}\`, head: \`${head.slice(0, 10)}\`. Changes past the limits are marked in bold.`, + "", + ...(missingText ? [missingText, ""] : []), + ]; + + if (regressions.length > 0) { + summary.push("### Cause", "", causeText(growth), ""); + summary.push("### Regressions", "", totalsTable(regressions), "", sectionsDetails(regressions), ""); + if (growth.hasRows) { + summary.push( + "### Growth by pull request", + "", + "The size after each pull request that changed it. In bold where that pull request alone grew past the limits.", + "", + growth.table, + "", + ); + } + } + + if (improvements.length > 0) { + summary.push("### Improvements", "", totalsTable(improvements), "", sectionsDetails(improvements), ""); + } + + summary.push( + "
All examples", + "", + totalsTable(rows), + "", + sectionsDetails(rows), + "", + "
", + ); + + await core.summary.addRaw(summary.join("\n")).write(); + + if (regressions.length === 0) { + core.info("No example grew past the limits."); + return; + } + + if (context.eventName !== "schedule") { + core.info("Manual run: skipping issue creation."); + return; + } + + const { owner, repo } = context.repo; + // One line per merged pull request. A zero-width space after `@` keeps + // mentions in commit subjects from notifying anyone. + const merged = ( + await git(exec, ["log", "--first-parent", "--format=- %h %s", `${base}..${head}`]) + ).replaceAll("@", "@\u200b"); + + const body = [ + "The nightly binary size check found examples that grew past the limits.", + "", + `Workflow run: ${runUrl(context)}`, + "", + "### Cause", + "", + causeText(growth), + "", + "### Regressions", + "", + totalsTable(regressions), + "", + sectionsDetails(regressions), + "", + "### Growth by pull request", + "", + "The size after each pull request that changed it. In bold where that pull request alone grew past the limits.", + "", + growth.table, + "", + `### Merged between \`${base.slice(0, 10)}\` and \`${head.slice(0, 10)}\``, + "", + merged, + "", + ...(missingText ? [missingText, ""] : []), + "
All examples", + "", + totalsTable(rows), + "", + "
", + ].join("\n"); + + // Comment on the open issue, or open one. The API also lists pull requests. + const issues = await github.paginate(github.rest.issues.listForRepo, { + owner, + repo, + state: "open", + creator: "github-actions[bot]", + per_page: 100, + }); + const existing = issues.find( + (issue) => !issue.pull_request && issue.title === ISSUE_TITLE, + ); + + if (existing) { + await github.rest.issues.createComment({ + owner, + repo, + issue_number: existing.number, + body, + }); + core.info(`Commented on ${existing.html_url}`); + } else { + const { data: issue } = await github.rest.issues.create({ + owner, + repo, + title: ISSUE_TITLE, + body, + }); + core.info(`Opened ${issue.html_url}`); + } +} + +// Puts the `/test-size` report into the comment that triggered it, or into the +// earlier report comment, or a new one. +async function reportPullRequest({ github, context, core }) { + const { owner, repo } = context.repo; + const number = Number(process.env.PR_NUMBER); + const base = process.env.BASE; + const head = process.env.HEAD; + + const entries = readSizes(); + const rows = compareEntries(entries); + const missing = missingNote(missingChips(entries)); + + const body = [`Run: ${runUrl(context)}`, "", PR_REPORT_HEADING, ""]; + if (rows.length === 0) { + body.push("Binary size analysis **failed**, nothing was measured. See the run for details."); + } else { + body.push( + `Head \`${head.slice(0, 10)}\` against \`${base.slice(0, 10)}\`, the commit this pull request branched from.`, + "", + ...(missing ? [missing, ""] : []), + totalsTable(rows), + "", + sectionsDetails(rows), + ); + } + + let commentId = Number(process.env.COMMENT_ID) || 0; + if (!commentId) { + const comments = await github.paginate(github.rest.issues.listComments, { + owner, + repo, + issue_number: number, + per_page: 100, + }); + const earlier = comments.find( + (comment) => + comment.user?.login === "github-actions[bot]" && + String(comment.body || "").includes(PR_REPORT_HEADING), + ); + commentId = earlier?.id ?? 0; + } + + if (commentId) { + await github.rest.issues.updateComment({ + owner, + repo, + comment_id: commentId, + body: body.join("\n"), + }); + core.info(`Updated comment ${commentId} on #${number}`); + } else { + await github.rest.issues.createComment({ + owner, + repo, + issue_number: number, + body: body.join("\n"), + }); + core.info(`Commented on #${number}`); + } +} + +module.exports = { + resolveNightlyRange, + resolvePullRequestRange, + measure, + reportNightly, + reportPullRequest, +}; diff --git a/.github/scripts/hil-find-run.js b/.github/scripts/hil-find-run.js index a963fe67e8b..547d8398cc4 100644 --- a/.github/scripts/hil-find-run.js +++ b/.github/scripts/hil-find-run.js @@ -59,7 +59,7 @@ async function findDispatchedRun({ return null; } -async function findHilRun({ github, context, pr, selector, distinctId }) { +async function findHilRun({ github, context, pr, selector, tests = '', pkg = '', distinctId }) { const run = await findDispatchedRun({ github, context, @@ -69,9 +69,16 @@ async function findHilRun({ github, context, pr, selector, distinctId }) { const isMatrix = selector === 'quick' || selector === 'full'; + // Words of a command can go in any order + const details = [ + ...(isMatrix ? [] : [`chips: ${selector}`]), + ...(tests ? [`tests: ${tests.split(',').join(', ')}`] : []), + ...(pkg && pkg !== 'hil-test' ? [`package: ${pkg}`] : []), + ]; let body = isMatrix - ? `Triggered **${selector}** HIL run for #${pr}.` - : `Triggered **HIL** run for #${pr} (chips: ${selector}).`; + ? `Triggered **${selector}** HIL run for #${pr}` + : `Triggered **HIL** run for #${pr}`; + body += details.length ? ` (${details.join('; ')}).` : '.'; if (run?.html_url) { body += `\n\nRun: ${run.html_url}`; diff --git a/.github/scripts/hil-gate.js b/.github/scripts/hil-gate.js index c4f017cf76d..2f7576c5092 100644 --- a/.github/scripts/hil-gate.js +++ b/.github/scripts/hil-gate.js @@ -2,7 +2,7 @@ const RUN_TESTS_STEP = "Run Tests"; function isHilRunMatrixJob(name) { // Matches "hil-run (…)" but not "hil-run-radio (…)". - return /^hil-run \(/i.test(String(name || "")); + return /(?:^|\/\s*)hil-run \(/i.test(String(name || "")); } function classifyMatrixJob(job) { @@ -14,21 +14,13 @@ function classifyMatrixJob(job) { const conclusion = runTests.conclusion; if (conclusion === "skipped") { - // A successful job intentionally skipped this chip because it had no ELFs. - // An unsuccessful job skipped this step because an earlier step failed. + // The guard step skips a chip that produced no ELFs. A job that failed, was + // cancelled or timed out leaves the same skipped step behind, so only a + // successful job means "not tested". if (job.conclusion === "success") { return { kind: "skipped" }; } - if ( - job.conclusion === "failure" || - job.conclusion === "cancelled" || - job.conclusion === null - ) { - return { kind: "failed" }; - } - return { - error: `job "${job.name}" has skipped "${RUN_TESTS_STEP}" step and unexpected conclusion: ${job.conclusion}`, - }; + return { kind: "failed" }; } if (conclusion === "success") { return { kind: "passed" }; @@ -75,8 +67,12 @@ async function listWorkflowRunJobs(github, context) { page, }); - jobs.push(...(data.jobs || [])); - if (jobs.length >= data.total_count) { + const page_jobs = data.jobs || []; + jobs.push(...page_jobs); + // An empty page ends the walk even when total_count claims more: the count + // can drift while the run is still going, and trusting it alone spins here + // until the job times out. + if (page_jobs.length === 0 || jobs.length >= data.total_count) { break; } page += 1; diff --git a/.github/scripts/hil-parse.js b/.github/scripts/hil-parse.js index e25a2190c1c..0d2ec02a035 100644 --- a/.github/scripts/hil-parse.js +++ b/.github/scripts/hil-parse.js @@ -1,68 +1,155 @@ -const DEFAULT_ALLOWED = [ - "esp32c2", - "esp32c3", - "esp32c5", - "esp32c6", - "esp32c61", - "esp32h2", - "esp32p4", - "esp32s31", - "esp32", - "esp32s2", - "esp32s3", -]; - -function parsePackage(body) { - const text = String(body || "").trim().toLowerCase(); - if (text.includes("hil-test-radio")) { - return "hil-test-radio"; - } - if (text.includes("hil-test")) { - return "hil-test"; - } - return "hil-test"; +// Reads the `/hil` and `/test-size` commands. Like the tokens of `cargo xtask +// build` and `test`, their words go in any order: a chip, a package, a keyword, +// and everything else is a test or example name. + +const CHIPS = require("../chips.json"); +const SOCS = CHIPS.map((c) => c.soc); +const QUICK = CHIPS.filter((c) => c.quick).map((c) => c.soc); + +// What an ELF basename or example name can look like, plus `::` for the +// `test::filter` form xtask accepts. +const NAME = /^[A-Za-z0-9_:-]+$/; + +// xtask takes these as flags too, but here their values are words like any +// other, so the flags add nothing. +const FLAGS = ["--test", "--tests", "-t", "--package", "--packages"]; + +const HIL_PACKAGES = new Map([ + ["hil-test", "hil-test"], + ["test", "hil-test"], + ["tests", "hil-test"], + ["hil-test-radio", "hil-test-radio"], + ["radio", "hil-test-radio"], +]); + +// What `cargo xtask build --package` gets, empty for the default `examples`. +const SIZE_PACKAGES = new Map([ + ["examples", ""], + ["example", ""], + ["qa-test", "qa-test"], + ["qa", "qa-test"], +]); + +const USAGE = `Usage, with the words of a command in any order. \`/hil\` is the previous spelling and still works. +- \`/test quick\` — run a quick HIL matrix (only \`ESP32-S3\` (Xtensa) and \`ESP32-C6\` (RISC-V) tests) +- \`/test full\` — run the full HIL matrix for all supported chips, \`all\` works too +- \`/test [ ...]\` — run the HIL tests **only** for the listed chips. Example: \`/test c3 s3\` +- Add test names to run only those, in any position. Example: \`/test esp32 rmt c6 i2c\` or \`/test quick radio_basic::test_scan_doesnt_leak\` +- Add \`radio\` to run radio HIL instead of the default \`hil-test\` package, or both package names to run both. Example: \`/test c6 radio\` +- \`/test-size [ ...] [ ...]\` — run binary size analysis for the examples on the chips. Add \`qa\` for a binary of \`qa-test\`. Example: \`/test-size hello_world c3 c6\` or \`/test-size sleep_timer qa c3\` + +Chips can be shortened as in xtask: \`c6\`, \`esp32-c6\` and \`ESP32C6\` all mean \`esp32c6\`. Only the first line of the comment is read, the rest is free text. +If you aren't a repository **member/owner**, you must be **trusted for this PR**. +Maintainers can grant access with a \`trusted-author\` label or with: +\`\`\` +/trust @ +\`\`\` +and revoke with: +\`\`\` +/revoke @ +\`\`\``; + +// `esp32-c6`, `ESP32C6` and `c6` name the same chip as `esp32c6`, as in xtask. +function normalizeChip(word) { + const name = word.toLowerCase().replace(/[-_]/g, ""); + if (!name) return null; + const soc = name.startsWith("esp32") ? name : `esp32${name}`; + return SOCS.includes(soc) ? soc : null; +} + +// A misspelled chip would otherwise be taken for a test or example name. +function looksLikeChip(word) { + return /^esp32/i.test(word) || /^[a-z]\d+$/i.test(word); } -function parseTests(body) { - const text = String(body || "").trim(); - const m = text.match(/--tests?\s+(.+)$/i); - if (!m) return ""; - return m[1] - .trim() - .split(/[,\s]+/) - .map((s) => s.trim()) - .filter(Boolean) - .join(","); +// Backticks would end the code span the word is quoted in. +function quote(word) { + return `\`${word.replace(/`/g, "")}\``; } -function parseChips(body, allowed = DEFAULT_ALLOWED) { - const body_trimmed = String(body || "").trim(); +// The words after the command on the first line of the comment. Commas +// separate words like spaces do, and `--test=rmt` is `--test rmt`. +function commandWords(body, command) { + const line = String(body || "").split(/\r?\n/, 1)[0].trim(); + const match = line.match(new RegExp(`^${command}(?:\\s+(.*))?$`, "i")); + if (!match) return null; + return (match[1] || "").split(/[\s,=]+/).filter(Boolean); +} - // Remove the leading "/hil" - const withoutCmd = body_trimmed.replace(/^\/hil\s+/i, ""); +function sortWords(words, { keywords, packages }) { + const sorted = { chips: [], keywords: [], packages: [], names: [], errors: [] }; + const add = (list, value) => list.includes(value) || list.push(value); + for (const word of words) { + const lower = word.toLowerCase(); + const chip = normalizeChip(word); + if (FLAGS.includes(lower)) continue; + if (chip) add(sorted.chips, chip); + else if (keywords.includes(lower)) add(sorted.keywords, lower); + else if (packages.has(lower)) add(sorted.packages, packages.get(lower)); + else if (word.startsWith("-")) sorted.errors.push(`Unknown option ${quote(word)}.`); + else if (looksLikeChip(word)) + sorted.errors.push(`Unknown chip ${quote(word)}. Known chips are: ${SOCS.join(", ")}.`); + else if (!NAME.test(word)) sorted.errors.push(`${quote(word)} is not a test or example name.`); + else add(sorted.names, word); + } + return sorted; +} - // Split on commas and/or whitespace, normalize and dedupe - const parts = withoutCmd - .split(/[,\s]+/) - .map((s) => s.toLowerCase().replace(/[,]+$/, "")) - .filter(Boolean); +// `null` for a comment that is not a `/hil` or `/test` command. `help` when it asks +// for the usage, `error` when it can't be run. `/test` stops at a word boundary, so +// `/test-size` is not one of these. +function parseHilCommand(body) { + const words = ["/hil", "/test"].map((command) => commandWords(body, command)).find(Boolean); + if (!words) return null; - const chips = Array.from(new Set(parts.filter((s) => allowed.includes(s)))); + const result = { help: false, error: "", chips: "", selector: "", tests: "", package: "" }; + const sorted = sortWords(words, { + keywords: ["quick", "full", "all", "help"], + packages: HIL_PACKAGES, + }); + if (words.length === 0 || sorted.keywords.includes("help")) return { ...result, help: true }; + if (sorted.errors.length) return { ...result, error: sorted.errors.join("\n") }; - if (!chips.length) { - return { - chips: "", - chipsLabel: "", - error: - "No valid chips specified.\n\nAllowed chips are: " + allowed.join(", "), - }; + const full = sorted.keywords.includes("full") || sorted.keywords.includes("all"); + const quick = sorted.keywords.includes("quick"); + const chips = SOCS.filter( + (soc) => full || (quick && QUICK.includes(soc)) || sorted.chips.includes(soc), + ); + if (chips.length === 0) { + return { ...result, error: "Name the chips to test, like `c6` or `esp32s3`, or `quick` or `full`." }; } + let selector = chips.join(" "); + if (full) selector = "full"; + else if (quick && sorted.chips.every((soc) => QUICK.includes(soc))) selector = "quick"; + return { + ...result, chips: chips.join(" "), - chipsLabel: chips.join(", "), - error: "", + selector, + tests: sorted.names.join(","), + package: sorted.packages.length > 1 ? "all" : sorted.packages[0] || "hil-test", + }; +} + +// `null` for a comment that is not a `/test-size` command, `error` when it +// can't be run. +function parseTestSizeCommand(body) { + const words = commandWords(body, "/test-size"); + if (!words) return null; + + const sorted = sortWords(words, { keywords: [], packages: SIZE_PACKAGES }); + const errors = [...sorted.errors]; + if (sorted.names.length === 0) errors.push("Name the example to measure, like `hello_world`."); + if (sorted.chips.length === 0) errors.push("Name at least one chip, like `c6` or `esp32s3`."); + if (sorted.packages.length > 1) errors.push("Examples and `qa-test` binaries are measured one package at a time."); + + return { + error: errors.join("\n"), + examples: sorted.names.join(" "), + package: sorted.packages[0] || "", + chips: SOCS.filter((soc) => sorted.chips.includes(soc)), }; } -module.exports = { parseTests, parseChips, parsePackage }; \ No newline at end of file +module.exports = { parseHilCommand, parseTestSizeCommand, USAGE }; diff --git a/.github/scripts/hil-status.js b/.github/scripts/hil-status.js index 40df5f3e7ff..5ae8442add2 100644 --- a/.github/scripts/hil-status.js +++ b/.github/scripts/hil-status.js @@ -1,62 +1,58 @@ -function statusSuffix(kind, conclusion) { - if (!conclusion) { - return `\n\n**Status update:** ${kind} run is still in progress or status unknown.`; - } +// Verdict reporting for dispatched HIL runs. +// +// hil.yml's report job calls this when a dispatched run finishes. +const STATUS_MARKER = ""; + +function statusText(conclusion, attempt) { + const rerun = attempt > 1 ? ` on re-run (attempt ${attempt})` : ""; if (conclusion === "success") { - return `\n\n**Status update:** ✅ ${kind} run **succeeded**.`; + return `**Status update:** ✅ HIL run **succeeded**${rerun}.`; } if (conclusion === "cancelled") { - return `\n\n**Status update:** ⚠️ ${kind} run was **cancelled**.`; + return `**Status update:** ⚠️ HIL run was **cancelled**${rerun}.`; } - return `\n\n**Status update:** ❌ ${kind} run **failed** (conclusion: ${conclusion}).`; + return `**Status update:** ❌ HIL run **failed**${rerun} (conclusion: ${conclusion}).`; } -async function pollRun({ - github, - context, - runId, - commentId, - kind, - maxPolls = 60, - pollIntervalMs = 15000, -}) { - const { owner, repo } = context.repo; - const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); - - let conclusion = null; - - // Poll up to ~15 minutes by default (60 * 15s) - for (let i = 0; i < maxPolls; i++) { - await delay(pollIntervalMs); - - const { data } = await github.rest.actions.getWorkflowRun({ - owner, - repo, - run_id: runId, - }); +function applyStatus(body, text) { + const [head] = body.split(STATUS_MARKER); + return `${head.trimEnd()}\n\n${STATUS_MARKER}\n${text}`; +} - if (data.status === "completed") { - conclusion = data.conclusion; - break; - } - } +function runConclusion(results) { + if (results.includes("cancelled")) return "cancelled"; + if (results.includes("failure")) return "failure"; + return "success"; +} - const suffix = statusSuffix(kind, conclusion); +async function updateRunStatus({ github, context, core, pr, conclusion }) { + const { owner, repo } = context.repo; + const runId = context.runId; + const attempt = Number(process.env.GITHUB_RUN_ATTEMPT); - const comment = await github.rest.issues.getComment({ + // The dispatcher's confirmation comment is the one carrying this run's URL. + const comments = await github.paginate(github.rest.issues.listComments, { owner, repo, - comment_id: commentId, + issue_number: pr, + per_page: 100, }); - - const body = `${comment.data.body}\n${suffix}`; + const comment = comments.findLast( + (c) => + c.user?.login === "github-actions[bot]" && + c.body?.includes(`/actions/runs/${runId}`), + ); + if (!comment) { + core.info(`No bot comment on #${pr} references run ${runId}.`); + return; + } await github.rest.issues.updateComment({ owner, repo, - comment_id: commentId, - body, + comment_id: comment.id, + body: applyStatus(comment.body, statusText(conclusion, attempt)), }); } -module.exports = { pollRun }; +module.exports = { updateRunStatus, runConclusion }; diff --git a/.github/scripts/hil-trust.js b/.github/scripts/hil-trust.js index a114bf9ae79..ee1e0c6d97d 100644 --- a/.github/scripts/hil-trust.js +++ b/.github/scripts/hil-trust.js @@ -4,11 +4,14 @@ const TRUST_HEADER = "### [HIL trust list]"; const JSON_BEGIN = ""; +// The command is the first line, the rest of the comment is free text. function parseTrustCommand(body, cmd) { - const text = String(body || "").trim(); + const line = String(body || "").trim().split(/\r?\n/)[0].trim(); const re = new RegExp(`^\\/${cmd}\\s+@([A-Za-z0-9-]+)\\b$`, "i"); - const m = text.match(re); - if (!m) return { login: "", error: `Usage: /${cmd} @` }; + const m = line.match(re); + if (!m) { + return { login: "", error: `Usage: \`/${cmd} @\` on the first line of the comment.` }; + } return { login: m[1].toLowerCase(), error: "" }; } diff --git a/.github/scripts/merge-freeze.js b/.github/scripts/merge-freeze.js new file mode 100644 index 00000000000..61d69ba623b --- /dev/null +++ b/.github/scripts/merge-freeze.js @@ -0,0 +1,287 @@ +// Merge freeze: `gate` enforces it, `recordExemptMerge` notes what slipped +// through. +// +// The state is an open issue labelled `merge-freeze`, opened and closed by +// hand. While it is open, merges into `main` are rejected unless the pull +// request carries `merge-freeze-exempt`. + +// We only ever hold merging into `main`, so the freeze is not configurable. +// This can be customized in future if we want to freeze other branches. +const FROZEN_BRANCH = "main"; + +const FREEZE_LABEL = "merge-freeze"; +const EXEMPT_LABEL = "merge-freeze-exempt"; +const NOTICE_MARKER = ""; +const auditMarker = (prNumber) => ``; + +// The gate is required for every merge, so a transient API error would block all +// merging. Retry before giving up. A failure still fails closed. +async function withRetries({ core, attempts = 3, delayMs = 2000 }, action) { + for (let attempt = 1; ; attempt += 1) { + try { + return await action(); + } catch (error) { + // A 404 or a 422 will not become a different answer on the second ask. + const permanent = + error.status >= 400 && error.status < 500 && error.status !== 429; + if (permanent || attempt >= attempts) throw error; + + core.warning( + `${error.message} - retrying (attempt ${attempt} of ${attempts}).`, + ); + await new Promise((resolve) => setTimeout(resolve, delayMs * attempt)); + } + } +} + +// More than one issue may end up claiming to hold the freeze, so the oldest +// wins and a stray duplicate cannot take over. Pull requests are dropped +// because the API lists them alongside issues, and one carrying the label must +// not freeze anything. +async function findFreezeIssue({ github, context }) { + const { owner, repo } = context.repo; + const issues = await github.paginate(github.rest.issues.listForRepo, { + owner, + repo, + state: "open", + labels: FREEZE_LABEL, + sort: "created", + direction: "asc", + per_page: 100, + }); + + return issues.find((issue) => !issue.pull_request) || null; +} + +async function upsertComment({ + github, + context, + core, + issueNumber, + marker, + body, + updateOnly = false, +}) { + const { owner, repo } = context.repo; + + try { + const comments = await github.paginate(github.rest.issues.listComments, { + owner, + repo, + issue_number: issueNumber, + per_page: 100, + }); + const existing = comments.find((comment) => + String(comment.body || "").includes(marker), + ); + + if (existing) { + await github.rest.issues.updateComment({ + owner, + repo, + comment_id: existing.id, + body: `${marker}\n${body}`, + }); + } else if (!updateOnly) { + await github.rest.issues.createComment({ + owner, + repo, + issue_number: issueNumber, + body: `${marker}\n${body}`, + }); + } + } catch (error) { + core.warning(`Could not comment on #${issueNumber}: ${error.message}`); + } +} + +// A merge group can batch several pull requests, and its ref names only one of +// them, so walk the commits the group adds on top of the base as well. +async function pullRequestNumbersFromMergeGroup({ github, context, core }) { + const { owner, repo } = context.repo; + const mergeGroup = (context.payload || {}).merge_group; + if (!mergeGroup) return []; + + const numbers = new Set(); + + // `gh-readonly-queue/main/pr-1234-`. + const fromRef = String(mergeGroup.head_ref || "").match(/\/pr-(\d+)-/); + if (fromRef) numbers.add(Number(fromRef[1])); + + if (mergeGroup.base_sha && mergeGroup.head_sha) { + try { + const { data } = await withRetries({ core }, () => + github.rest.repos.compareCommitsWithBasehead({ + owner, + repo, + basehead: `${mergeGroup.base_sha}...${mergeGroup.head_sha}`, + }), + ); + + for (const commit of data.commits || []) { + // Only the `(#1234)` suffix of a merge or squash subject: a bare + // `#1234` anywhere else is as likely to be an issue reference. + const subject = String(commit.commit.message || "").split("\n")[0]; + const suffix = subject.match(/\(#(\d+)\)\s*$/); + if (suffix) numbers.add(Number(suffix[1])); + } + } catch (error) { + core.warning( + `Could not list the commits of this merge queue entry: ${error.message}`, + ); + } + } + + return [...numbers].sort((a, b) => a - b); +} + +async function gate({ github, context, core }) { + const { owner, repo } = context.repo; + let issue; + + try { + issue = await withRetries({ core }, () => + findFreezeIssue({ github, context }), + ); + } catch (error) { + core.setFailed( + `Could not determine whether a merge freeze is active: ${error.message}`, + ); + return; + } + + if (!issue) { + core.info("No merge freeze active."); + return; + } + + const mergeGroup = (context.payload || {}).merge_group; + if (!mergeGroup) { + core.info( + `Merge freeze (#${issue.number}) is active, and it is enforced when a pull request enters the merge queue.`, + ); + return; + } + + const baseRef = String(mergeGroup.base_ref || "").replace(/^refs\/heads\//, ""); + if (baseRef !== FROZEN_BRANCH) { + core.info( + `Merge freeze (#${issue.number}) only covers \`${FROZEN_BRANCH}\`, not \`${baseRef}\`.`, + ); + return; + } + + const numbers = await pullRequestNumbersFromMergeGroup({ + github, + context, + core, + }); + + const pulls = []; + for (const number of numbers) { + try { + const response = await withRetries({ core }, () => + github.rest.pulls.get({ owner, repo, pull_number: number }), + ); + pulls.push(response.data); + } catch (error) { + // A number scraped from a commit subject need not be a pull request at + // all. As long as the entry yields one, the freeze can still be judged. + core.warning(`Could not read #${number}: ${error.message}`); + } + } + + if (pulls.length === 0) { + core.setFailed( + `Merge freeze (#${issue.number}) is active and the pull requests behind this merge queue entry could not be identified.`, + ); + return; + } + + const exempt = (pull) => + (pull.labels || []).some((label) => label.name === EXEMPT_LABEL); + const blocked = pulls.filter((pull) => !exempt(pull)); + const list = (items) => items.map((pull) => `#${pull.number}`).join(", "); + + await core.summary + .addHeading("Merge freeze", 3) + .addRaw( + blocked.length === 0 + ? `${list(pulls)} carries \`${EXEMPT_LABEL}\` and may merge during the freeze.` + : `${list(blocked)} is blocked by the merge freeze.`, + ) + .addBreak() + .addLink(`Freeze issue #${issue.number}`, issue.html_url) + .write(); + + // Clear earlier "blocked" notices so an exempted pull request does not keep + // claiming it cannot be merged. + for (const pull of pulls.filter(exempt)) { + await upsertComment({ + github, + context, + core, + issueNumber: pull.number, + marker: NOTICE_MARKER, + body: `\`${EXEMPT_LABEL}\` is set, so merge freeze (#${issue.number}) no longer blocks this pull request.`, + updateOnly: true, + }); + } + + if (blocked.length === 0) { + core.info(`${list(pulls)} is exempt from merge freeze (#${issue.number}).`); + return; + } + + const message = `Blocked by merge freeze (#${issue.number}). If this change is urgent enough to land during the freeze, add the \`${EXEMPT_LABEL}\` label.`; + + // The merge attempt is the first time the author hears about the freeze, so + // spell out the way forward on the pull request itself. + for (const pull of blocked) { + await upsertComment({ + github, + context, + core, + issueNumber: pull.number, + marker: NOTICE_MARKER, + body: `${message}\n\nSee ${issue.html_url} for the details of this freeze.`, + }); + } + + // A batched entry is only as mergeable as its least mergeable member. + core.setFailed( + pulls.length === 1 + ? message + : `${list(blocked)} of this merge group is blocked by merge freeze (#${issue.number}).`, + ); +} + +// The gate runs before the rest of CI, so it cannot claim anything was merged. +// This runs once the merge has actually happened. +async function recordExemptMerge({ github, context, core }) { + const pull = (context.payload || {}).pull_request; + if (!pull || !pull.merged) return; + + if (String((pull.base || {}).ref || "") !== FROZEN_BRANCH) return; + if (!(pull.labels || []).some((label) => label.name === EXEMPT_LABEL)) return; + + const issue = await findFreezeIssue({ github, context }); + if (!issue) { + core.info( + `#${pull.number} was merged with \`${EXEMPT_LABEL}\`, but no freeze is active - nothing to record.`, + ); + return; + } + + await upsertComment({ + github, + context, + core, + issueNumber: issue.number, + marker: auditMarker(pull.number), + body: `#${pull.number} (${pull.title}) was merged during the freeze, exempted by \`${EXEMPT_LABEL}\`.`, + }); + core.info(`Recorded #${pull.number} on freeze issue #${issue.number}.`); +} + +module.exports = { gate, recordExemptMerge }; diff --git a/.github/workflows/api-baseline-check.yml b/.github/workflows/api-baseline-check.yml index b0ce4d95e54..76ed3c89369 100644 --- a/.github/workflows/api-baseline-check.yml +++ b/.github/workflows/api-baseline-check.yml @@ -22,17 +22,10 @@ jobs: steps: - uses: actions/checkout@v6 - # Install the Rust toolchain for Xtensa devices: - - uses: esp-rs/xtensa-toolchain@v1.6 + - uses: ./.github/actions/setup-toolchains with: - version: 1.97.0.0 - - # Install the Rust stable toolchain for RISC-V devices: - - uses: dtolnay/rust-toolchain@v1 - with: - target: riscv32imc-unknown-none-elf,riscv32imac-unknown-none-elf,riscv32imafc-unknown-none-elf - toolchain: stable - components: rust-src + xtensa: "true" + riscv: "true" - name: Semver-Check run: | diff --git a/.github/workflows/api-baseline-generation.yml b/.github/workflows/api-baseline-generation.yml index f37affe013f..5b631c36b6c 100644 --- a/.github/workflows/api-baseline-generation.yml +++ b/.github/workflows/api-baseline-generation.yml @@ -12,9 +12,9 @@ on: default: "main" type: string package_name: - description: "The package name" + description: "The package name(s), comma-separated" required: true - default: "esp-hal" + default: "esp-hal,esp-rom-sys,esp-radio" force_regeneration: description: "Force baseline regeneration even without breaking change" required: false @@ -35,6 +35,10 @@ env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_REPOSITORY: ${{ github.repository }} +permissions: + contents: write + pull-requests: read + jobs: manage-baselines: runs-on: ubuntu-latest @@ -71,7 +75,7 @@ jobs: - name: Install xtensa toolchain uses: esp-rs/xtensa-toolchain@v1.6 with: - version: 1.97.0.0 + version: 1.99.0.0 - name: Check if baseline generation is needed id: check-generation @@ -119,7 +123,7 @@ jobs: # -P: Perl-compatible regular expressions # `(?<=)`: look-behind: match only if this is present, but do not make this part of the match PACKAGES=$(echo "$LABELS" \ - | grep -oP '(?<=^breaking-change-)[a-z0-9-]+$' || true \ + | { grep -oP '(?<=^breaking-change-)[a-z0-9-]+$' || true; } \ | tr '\n' ',' \ | sed 's/,$//') fi @@ -159,24 +163,44 @@ jobs: echo "API baseline generation completed" - - name: Upload API baselines as artifact + - name: Upload API baselines to release if: steps.check-generation.outputs.should_generate == 'true' - uses: actions/upload-artifact@v6 - with: - name: api-baselines-${{ steps.check-generation.outputs.packages }} - path: ${{ steps.check-generation.outputs.packages }}/api-baseline/ - retention-days: 90 # Maximum for public repos + shell: bash + run: | + if ! gh release view api-baselines -R "$GITHUB_REPOSITORY" > /dev/null 2>&1; then + if ! gh api "repos/$GITHUB_REPOSITORY/git/ref/tags/api-baselines" > /dev/null 2>&1; then + SHA=$(gh api "repos/$GITHUB_REPOSITORY/git/commits" -f message="Storage for the API baselines release, not part of any branch" -f tree=4b825dc642cb6eb9a060e54bf8d69288fbee4904 --jq .sha) + gh api "repos/$GITHUB_REPOSITORY/git/refs" -f ref=refs/tags/api-baselines -f sha="$SHA" + fi + gh release create api-baselines -R "$GITHUB_REPOSITORY" --verify-tag --prerelease --latest=false --title "API baselines" --notes "Latest API baselines for semver checks. Not a release." + fi + COMMIT=$(git rev-parse HEAD) + PACKAGES="${{ steps.check-generation.outputs.packages }}" + for PACKAGE_NAME in ${PACKAGES//,/ }; do + ASSET_NAME="api-baselines-$PACKAGE_NAME.zip" + TEMP_ASSET="api-baselines-$PACKAGE_NAME-$GITHUB_RUN_ID.tmp.zip" + ASSET_LABEL="$ASSET_NAME ($COMMIT)" + (cd "$PACKAGE_NAME/api-baseline" && zip -q "$GITHUB_WORKSPACE/$TEMP_ASSET" ./*.json.gz) + gh release upload api-baselines "$GITHUB_WORKSPACE/$TEMP_ASSET#$ASSET_LABEL" -R "$GITHUB_REPOSITORY" --clobber + ASSET_ID=$(gh api "repos/$GITHUB_REPOSITORY/releases/tags/api-baselines" --jq ".assets[] | select(.name == \"$TEMP_ASSET\") | .id") + if [ -z "$ASSET_ID" ]; then + echo "Uploaded asset $TEMP_ASSET not found in the api-baselines release" + exit 1 + fi + gh release delete-asset api-baselines "$ASSET_NAME" -R "$GITHUB_REPOSITORY" -y || true + gh api -X PATCH "repos/$GITHUB_REPOSITORY/releases/assets/$ASSET_ID" -f name="$ASSET_NAME" -f label="$ASSET_LABEL" > /dev/null + done - name: Create baseline summary if: steps.check-generation.outputs.should_generate == 'true' shell: bash run: | PACKAGE_NAME="${{ steps.check-generation.outputs.packages }}" + COMMIT=$(git rev-parse HEAD) echo "Successfully generated and uploaded API baselines" - echo "Artifact name: api-baselines-$PACKAGE_NAME" - echo "Retention: 90 days (expires on $(date -d '+90 days' '+%Y-%m-%d'))" - echo "Source branch: ${{ github.event.inputs.source_branch || 'main' }}" - echo "Commit: ${{ github.sha }}" + echo "Packages: $PACKAGE_NAME" + echo "Source ref: ${{ github.event.inputs.tag_name || github.event.inputs.source_branch || 'main' }}" + echo "Commit: $COMMIT" echo "Target repository: $GITHUB_REPOSITORY" # Create appropriate summary based on trigger reason @@ -201,21 +225,22 @@ jobs: fi echo "- **Target Repository**: \`$GITHUB_REPOSITORY\`" >> $GITHUB_STEP_SUMMARY - echo "- **Source Branch**: \`${{ github.event.inputs.source_branch || 'main' }}\`" >> $GITHUB_STEP_SUMMARY - echo "- **Artifact Name**: \`api-baselines-$PACKAGE_NAME\`" >> $GITHUB_STEP_SUMMARY - echo "- **Retention**: 90 days (expires $(date -d '+90 days' '+%Y-%m-%d'))" >> $GITHUB_STEP_SUMMARY + echo "- **Source Ref**: \`${{ github.event.inputs.tag_name || github.event.inputs.source_branch || 'main' }}\`" >> $GITHUB_STEP_SUMMARY + echo "- **Commit**: \`$COMMIT\`" >> $GITHUB_STEP_SUMMARY + echo "- **Packages**: \`$PACKAGE_NAME\`" >> $GITHUB_STEP_SUMMARY echo "" >> $GITHUB_STEP_SUMMARY echo "### Baseline Files Generated" >> $GITHUB_STEP_SUMMARY echo "| Chip | File Size |" >> $GITHUB_STEP_SUMMARY echo "|------|-----------|" >> $GITHUB_STEP_SUMMARY - cd "$PACKAGE_NAME/api-baseline" - for file in *.json.gz; do + for pkg in ${PACKAGE_NAME//,/ }; do + for file in "$pkg"/api-baseline/*.json.gz; do if [ -f "$file" ]; then chip=$(basename "$file" .json.gz) size=$(du -h "$file" | cut -f1) - echo "| $chip | $size |" >> $GITHUB_STEP_SUMMARY + echo "| $pkg ($chip) | $size |" >> $GITHUB_STEP_SUMMARY fi + done done - name: Create no-action summary diff --git a/.github/workflows/binary-size-nightly.yml b/.github/workflows/binary-size-nightly.yml new file mode 100644 index 00000000000..20b919554e9 --- /dev/null +++ b/.github/workflows/binary-size-nightly.yml @@ -0,0 +1,182 @@ +# Builds a few examples on every chip, once at the current `main` (or a chosen +# end commit) and once at the `main` the last successful run measured (or a +# chosen start commit, date, or release tag), and compares their sizes. Commits +# whose sizes are already stored in the Espressif App Metrics service are +# fetched via its API instead of being rebuilt. Reports to the job summary, +# uploads newly measured `HEAD` metrics to S3 from a Brno self-hosted runner, +# and on scheduled runs opens or comments on the regression issue. +# +# `binary-size.yml` measures a single pull request the same way (`/test-size`). + +name: Binary Size Nightly + +on: + schedule: + - cron: "0 2 * * *" + workflow_dispatch: + inputs: + range: + description: "Range to compare (overridden by base/head below)" + required: false + default: "since-last-run" + type: choice + options: + - since-last-run + - since-last-release + - last-7-days + - last-30-days + base: + description: "Start date (YYYY-MM-DD), tag (esp-hal-v1.2.0), or commit" + required: false + default: "" + type: string + head: + description: "End date (YYYY-MM-DD), tag, or commit. Empty: HEAD" + required: false + default: "" + type: string + +permissions: + contents: read + +# Two runs at once would report the same regression twice. +concurrency: + group: binary-size-nightly + +env: + CARGO_TERM_COLOR: always + EXAMPLES: hello_world embassy_hello_world embassy_dhcp bas_peripheral + # An example regresses when it grows by more than this many percent and by + # more than this many bytes. + MAX_GROWTH_PERCENT: 1 + MAX_FLASH_GROWTH_BYTES: 2048 + MAX_BSS_GROWTH_BYTES: 512 + # Read at compile time by the Wi-Fi examples. + SSID: SSID + PASSWORD: PASSWORD + STATIC_IP: 1.1.1.1 + GATEWAY_IP: 1.1.1.1 + HOST_IP: 1.1.1.1 + +jobs: + prepare: + # Forks can still dispatch the workflow by hand. + if: github.event_name != 'schedule' || github.repository_owner == 'esp-rs' + runs-on: ${{ github.repository_owner == 'esp-rs' && 'macos-m1-self-hosted' || 'ubuntu-latest' }} + permissions: + contents: read + # Finds the last successful run. + actions: read + outputs: + base: ${{ steps.range.outputs.base }} + head: ${{ steps.range.outputs.head }} + between: ${{ steps.range.outputs.between }} + chips: ${{ steps.range.outputs.chips }} + all_chips: ${{ steps.range.outputs.all_chips }} + has_cached: ${{ steps.range.outputs.has_cached }} + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + + - name: Resolve the commits to compare + id: range + uses: actions/github-script@v8 + env: + INPUT_RANGE: ${{ inputs.range }} + INPUT_BASE: ${{ inputs.base }} + INPUT_HEAD: ${{ inputs.head }} + ESP_METRICS_API_URL: ${{ secrets.ESP_METRICS_API_URL }} + ESP_METRICS_API_TOKEN: ${{ secrets.ESP_METRICS_API_TOKEN }} + with: + script: | + const { resolveNightlyRange } = require('./.github/scripts/binary-size.js'); + await resolveNightlyRange({ github, context, core, exec }); + + - uses: actions/upload-artifact@v6 + if: steps.range.outputs.has_cached == 'true' + with: + name: sizes-cached + path: sizes/cached.txt + if-no-files-found: ignore + + measure: + needs: prepare + if: needs.prepare.outputs.chips != '' + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + soc: ${{ fromJSON(needs.prepare.outputs.chips) }} + steps: + - uses: actions/checkout@v6 + with: + persist-credentials: false + + - uses: ./.github/actions/measure-binary-size + with: + soc: ${{ matrix.soc }} + examples: ${{ env.EXAMPLES }} + base: ${{ needs.prepare.outputs.base }} + head: ${{ needs.prepare.outputs.head }} + between: ${{ needs.prepare.outputs.between }} + has-cached: ${{ needs.prepare.outputs.has_cached }} + + report: + needs: [prepare, measure] + # Report what was measured, also when some chips failed or all sizes were cached. + if: always() && needs.prepare.outputs.base != '' + runs-on: ubuntu-latest + permissions: + contents: read + issues: write + outputs: + has_metrics: ${{ steps.report.outputs.has_metrics }} + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + + # Nothing to download when every build failed. + - uses: actions/download-artifact@v4 + continue-on-error: true + with: + pattern: sizes-* + path: sizes + merge-multiple: true + + - name: Compare and report + id: report + uses: actions/github-script@v8 + env: + BASE: ${{ needs.prepare.outputs.base }} + HEAD: ${{ needs.prepare.outputs.head }} + BETWEEN: ${{ needs.prepare.outputs.between }} + CHIPS: ${{ needs.prepare.outputs.all_chips }} + with: + script: | + const { reportNightly } = require('./.github/scripts/binary-size.js'); + await reportNightly({ github, context, core, exec }); + + - uses: actions/upload-artifact@v6 + if: steps.report.outputs.has_metrics == 'true' + with: + name: binary-size-metrics + path: binary_size_metrics.json + if-no-files-found: ignore + + upload-metrics: + needs: [prepare, report] + if: github.repository_owner == 'esp-rs' && needs.report.outputs.has_metrics == 'true' + runs-on: macos-m1-self-hosted + steps: + - uses: actions/checkout@v6 + with: + sparse-checkout: .github + + - uses: ./.github/actions/upload-metrics + with: + commit-sha: ${{ needs.prepare.outputs.head }} + s3-server: ${{ secrets.ESP_METRICS_S3_SERVER }} + s3-access-key: ${{ secrets.ESP_METRICS_S3_ACCESS_KEY }} + s3-secret-key: ${{ secrets.ESP_METRICS_S3_SECRET_KEY }} diff --git a/.github/workflows/binary-size.yml b/.github/workflows/binary-size.yml index 7644c743572..df80176afcf 100644 --- a/.github/workflows/binary-size.yml +++ b/.github/workflows/binary-size.yml @@ -1,3 +1,10 @@ +# Measures how much a pull request changes the size of an example, on request +# (`/test-size`, see `dispatch.yml`). Builds the example at the pull request +# head and at the commit it branched from, and reports every section that +# changed in a comment on the pull request. +# +# `binary-size-nightly.yml` measures what `main` gained in a day the same way. + name: Binary Size Analysis run-name: >- @@ -18,7 +25,7 @@ on: required: true type: string package: - description: "Optional --package argument (e.g., qa-test)" + description: "Optional --package argument (e.g., qa)" required: false default: "" type: string @@ -37,263 +44,90 @@ on: default: "" type: string -jobs: - binary-size: - runs-on: ubuntu-latest - permissions: - actions: read - pull-requests: write - contents: read +permissions: + contents: read - strategy: - fail-fast: false - matrix: - soc: ${{ fromJSON(inputs.chips) }} +env: + CARGO_TERM_COLOR: always + # Read at compile time by the Wi-Fi examples. + SSID: SSID + PASSWORD: PASSWORD + STATIC_IP: 1.1.1.1 + GATEWAY_IP: 1.1.1.1 + HOST_IP: 1.1.1.1 +jobs: + prepare: + runs-on: ubuntu-latest + outputs: + base: ${{ steps.range.outputs.base }} + head: ${{ steps.range.outputs.head }} steps: - # Install the Rust toolchain for RISC-V devices: - - name: Resolve Rust target - id: target - run: | - case "${{ matrix.soc }}" in - esp32|esp32s2|esp32s3) - echo "rust-target=xtensa-${{ matrix.soc }}-none-elf" >> $GITHUB_OUTPUT - ;; - esp32c2|esp32c3) - echo "rust-target=riscv32imc-unknown-none-elf" >> $GITHUB_OUTPUT - ;; - esp32c5|esp32c6|esp32c61|esp32h2) - echo "rust-target=riscv32imac-unknown-none-elf" >> $GITHUB_OUTPUT - ;; - esp32p4|esp32s31) - echo "rust-target=riscv32imafc-unknown-none-elf" >> $GITHUB_OUTPUT - ;; - *) - echo "Error: Unknown SoC: ${{ matrix.soc }}" - exit 1 - ;; - esac - - - name: Setup Rust (RISC-V) - if: ${{ !contains(fromJson('["esp32", "esp32s2", "esp32s3"]'), matrix.soc) }} - uses: dtolnay/rust-toolchain@v1 - with: - target: ${{ steps.target.outputs.rust-target }} - toolchain: stable - components: rust-src, llvm-tools - - # Install the Rust toolchain for Xtensa devices: - - name: Setup Rust (Xtensa) - if: contains(fromJson('["esp32", "esp32s2", "esp32s3"]'), matrix.soc) - uses: esp-rs/xtensa-toolchain@v1.6 + - uses: actions/checkout@v6 with: - buildtargets: ${{ matrix.soc }} - default: true - version: 1.97.0.0 + sparse-checkout: .github/scripts - - name: Install Binutils and Hub - run: | - cargo install cargo-binutils - sudo apt-get update - sudo apt-get install -y hub - - # Checkout repo & PR - - name: Checkout Repo (Initial) - uses: actions/checkout@v6 - - # context https://github.com/actions/checkout/issues/331 - - name: Checkout Pull Request (PR Code at Root) - run: hub pr checkout ${{ github.event.inputs.pr_number }} + - name: Resolve the commits to compare + id: range + uses: actions/github-script@v8 env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - - - name: Cache Cargo Dependencies - uses: actions/cache@v6 - with: - path: | - ~/.cargo/bin/ - ~/.cargo/registry/ - ~/.cargo/git/ - ./target/ - key: ${{ runner.os }}-${{ matrix.soc }}-cargo-${{ hashFiles('**/Cargo.lock') }} - - - name: Dir for result files - run: mkdir -p $HOME/results - - - name: Build PR example - run: | - set -euo pipefail - - RAW_INPUT="${{ github.event.inputs.example_name }}" - PACKAGE="${{ github.event.inputs.package }}" - PKG_ARGS="" - if [ -n "$PACKAGE" ]; then - PKG_ARGS="--package $PACKAGE" - fi - - cargo xtask build examples $RAW_INPUT $PKG_ARGS --chip "${{ matrix.soc }}" - - EXAMPLE_NAME=$(echo "$RAW_INPUT" | awk '{print $1}') - MANIFEST=$(find examples -path "*/${EXAMPLE_NAME}/Cargo.toml" -print -quit 2>/dev/null || true) - if [ -n "$MANIFEST" ]; then - EXAMPLE_NAME=$(sed -n '/^\[package\]$/,/^\[/{s/^[[:space:]]*name[[:space:]]*=[[:space:]]*"\([^"]*\)".*/\1/p}' "$MANIFEST" | head -n 1) - fi - BIN_NAME=$(echo "$EXAMPLE_NAME" | tr '_' '-') - - BIN=$(find target qa-test/target examples -type f \ - -path "*/release/${BIN_NAME}" -executable 2>/dev/null | head -n 1 || true) - - # Fallback to `_` instead of `-` - if [ -z "$BIN" ]; then - BIN=$(find target qa-test/target examples -type f \ - -path "*/release/${EXAMPLE_NAME}" -executable 2>/dev/null | head -n 1 || true) - fi - - if [ -z "$BIN" ]; then - echo "Error: Built PR binary not found" - exit 1 - fi - - cp "$BIN" $HOME/results/pr_qa_build_${{ matrix.soc }}.elf - - # Checkout base - - name: Checkout Base Commit - uses: actions/checkout@v6 + PR_NUMBER: ${{ inputs.pr_number }} with: - fetch-depth: 0 + script: | + const { resolvePullRequestRange } = require('./.github/scripts/binary-size.js'); + await resolvePullRequestRange({ github, context, core }); - - name: Build Base example - run: | - set -euo pipefail - cargo clean - - RAW_INPUT="${{ github.event.inputs.example_name }}" - PACKAGE="${{ github.event.inputs.package }}" - PKG_ARGS="" - if [ -n "$PACKAGE" ]; then - PKG_ARGS="--package $PACKAGE" - fi - - cargo xtask build examples $RAW_INPUT $PKG_ARGS --chip "${{ matrix.soc }}" - - EXAMPLE_NAME=$(echo "$RAW_INPUT" | awk '{print $1}') - MANIFEST=$(find examples -path "*/${EXAMPLE_NAME}/Cargo.toml" -print -quit 2>/dev/null || true) - if [ -n "$MANIFEST" ]; then - EXAMPLE_NAME=$(sed -n '/^\[package\]$/,/^\[/{s/^[[:space:]]*name[[:space:]]*=[[:space:]]*"\([^"]*\)".*/\1/p}' "$MANIFEST" | head -n 1) - fi - BIN_NAME=$(echo "$EXAMPLE_NAME" | tr '_' '-') - - BIN=$(find target qa-test/target examples -type f \ - -path "*/release/${BIN_NAME}" -executable 2>/dev/null | head -n 1 || true) - - # Fallback to `_` instead of `-` - if [ -z "$BIN" ]; then - BIN=$(find target qa-test/target examples -type f \ - -path "*/release/${EXAMPLE_NAME}" -executable 2>/dev/null | head -n 1 || true) - fi - - if [ -z "$BIN" ]; then - echo "Error: Built BASE binary not found" - exit 1 - fi - - cp "$BIN" $HOME/results/base_qa_build_${{ matrix.soc }}.elf - - - name: Copy binaries to workspace for Bloaty - run: | - # Copy files from $HOME/results to current workspace - cp $HOME/results/base_qa_build_${{ matrix.soc }}.elf ./ - cp $HOME/results/pr_qa_build_${{ matrix.soc }}.elf ./ - ls -la *.elf - - # Diffs and Artifacts - - name: Run Bloaty Diff - id: bloaty-qa - uses: carlosperate/bloaty-action@v1 + # Builds the pull request's code, so it gets no write access. + measure: + needs: prepare + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + soc: ${{ fromJSON(inputs.chips) }} + steps: + - uses: actions/checkout@v6 with: - bloaty-args: -d sections --domain vm --source-filter "^.text$|^.data|^.bss|^.rwdata|^.rwtext" pr_qa_build_${{ matrix.soc }}.elf -- base_qa_build_${{ matrix.soc }}.elf - output-to-summary: false - continue-on-error: true - - - name: Save Bloaty output - run: | - echo "EXAMPLE_DIFF< result-pr-${{ matrix.soc }}.txt - echo "\`\`\`" >> result-pr-${{ matrix.soc }}.txt - echo "${{ steps.bloaty-qa.outputs.bloaty-output || 'N/A' }}" >> result-pr-${{ matrix.soc }}.txt - echo "\`\`\`" >> result-pr-${{ matrix.soc }}.txt - echo "EOF" >> result-pr-${{ matrix.soc }}.txt + persist-credentials: false - - name: Upload Result Artifact - uses: actions/upload-artifact@v6 + - uses: ./.github/actions/measure-binary-size with: - name: result-${{ matrix.soc }} - path: result-pr-${{ matrix.soc }}.txt - - report-results: - needs: binary-size + soc: ${{ matrix.soc }} + examples: ${{ inputs.example_name }} + package: ${{ inputs.package }} + base: ${{ needs.prepare.outputs.base }} + head: ${{ needs.prepare.outputs.head }} + + report: + needs: [prepare, measure] + # Report what was measured, also when some chips failed. if: always() runs-on: ubuntu-latest permissions: - pull-requests: write contents: read + pull-requests: write steps: - - name: Checkout repository - uses: actions/checkout@v6 + - uses: actions/checkout@v6 + with: + sparse-checkout: .github/scripts + # Nothing to download when every build failed. - uses: actions/download-artifact@v4 + continue-on-error: true with: - pattern: result-* - path: ./results + pattern: sizes-* + path: sizes merge-multiple: true - - name: Generate Combined Report - if: needs.binary-size.result == 'success' - id: combine - working-directory: ${{ github.workspace }} - run: cargo run -p esp-devtool --features report -- generate-report --input results - - - name: Find and Update Comment with GH CLI + - name: Report on the pull request + uses: actions/github-script@v8 env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - ISSUE_NUMBER=${{ github.event.inputs.pr_number }} - echo "Processing PR Number: $ISSUE_NUMBER" - - COMMENTS=$(gh api repos/${{ github.repository }}/issues/$ISSUE_NUMBER/comments) - RUN_URL="${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}" - RESULT="${{ needs.binary-size.result }}" - - COMMENT_ID="${{ github.event.inputs.comment_id }}" - - { - echo "Run: $RUN_URL" - echo - if [ "$RESULT" = "success" ]; then - cat report.txt - else - echo "Binary size analysis **failed** (conclusion: $RESULT)." - echo - echo "Please inspect the workflow run for details." - fi - } > comment-body.md - - # Fallback to an existing Binary Size Report comment (for older runs) - if [ -z "$COMMENT_ID" ] || [ "$COMMENT_ID" = "null" ]; then - COMMENT_ID=$(echo "$COMMENTS" | jq -r ' - .[] - | select(.user.login == "github-actions[bot]") - | select(.body | test("^## Binary Size Report")) - | .id' | head -n1) - fi - - if [ -n "$COMMENT_ID" ] && [ "$COMMENT_ID" != "null" ]; then - echo "Updating existing comment: $COMMENT_ID" - gh api -X PATCH \ - repos/${{ github.repository }}/issues/comments/$COMMENT_ID \ - -f "body=$(cat comment-body.md)" - else - echo "Creating new comment" - gh api -X POST \ - repos/${{ github.repository }}/issues/$ISSUE_NUMBER/comments \ - -f "body=$(cat comment-body.md)" - fi + PR_NUMBER: ${{ inputs.pr_number }} + COMMENT_ID: ${{ inputs.comment_id }} + CHIPS: ${{ inputs.chips }} + BASE: ${{ needs.prepare.outputs.base }} + HEAD: ${{ needs.prepare.outputs.head }} + with: + script: | + const { reportPullRequest } = require('./.github/scripts/binary-size.js'); + await reportPullRequest({ github, context, core }); diff --git a/.github/workflows/changelog.yml b/.github/workflows/changelog.yml index 17b7297a311..3b938a2c3b6 100644 --- a/.github/workflows/changelog.yml +++ b/.github/workflows/changelog.yml @@ -1,19 +1,39 @@ name: Changelog check +# Separate from CI because this check depends on the PR body and labels, so it +# has to re-run when either changes, and it is cheap enough to do so on every +# such event. Branch protection requires the `changelog` job next to `ci-result`. on: - workflow_call: - inputs: - pr-number: - description: "Pull request number to check" - required: true - type: number + pull_request: + types: [ + opened, + edited, + synchronize, + reopened, + labeled, + unlabeled, + ready_for_review, + ] + # A required check must report in the merge queue too, where `changelog` is + # skipped, which counts as success. + merge_group: permissions: contents: read - pull-requests: write + pull-requests: read + +concurrency: + cancel-in-progress: true + group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} jobs: changelog: + # Do not skip based on which label changed or what an edit touched: a + # skipped required check counts as success and would replace a failure. + if: > + github.event_name == 'pull_request' && + !github.event.pull_request.draft && + github.event.pull_request.state != 'closed' runs-on: ubuntu-latest steps: - name: Checkout sources @@ -23,6 +43,6 @@ jobs: uses: dtolnay/rust-toolchain@stable - name: Check PR changelog - run: cargo xtask check-pr-changelog --pr ${{ inputs.pr-number }} + run: cargo xtask check-pr-changelog --pr ${{ github.event.pull_request.number }} env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/ci-nightly.yml b/.github/workflows/ci-nightly.yml index 8873a860a50..0dc9e30e375 100644 --- a/.github/workflows/ci-nightly.yml +++ b/.github/workflows/ci-nightly.yml @@ -12,8 +12,26 @@ env: DEFMT_LOG: trace jobs: + chips: + runs-on: ubuntu-latest + outputs: + riscv: ${{ steps.resolve.outputs.riscv }} + xtensa: ${{ steps.resolve.outputs.xtensa }} + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 1 + + - id: resolve + run: | + for arch in riscv xtensa; do + echo "$arch=$(jq -c --arg a "$arch" \ + '[.[] | select(.arch == $a) | .soc]' .github/chips.json)" >> "$GITHUB_OUTPUT" + done + esp-hal-riscv-nightly: name: esp-hal | nightly (${{ matrix.device }}) + needs: chips runs-on: ubuntu-latest env: CI: 1 @@ -26,24 +44,14 @@ jobs: strategy: fail-fast: false matrix: - device: - [ - "esp32c2", - "esp32c3", - "esp32c5", - "esp32c6", - "esp32c61", - "esp32h2", - "esp32p4", - "esp32s31", - ] + device: ${{ fromJSON(needs.chips.outputs.riscv) }} steps: - uses: actions/checkout@v6 # Install the Rust nightly toolchain for RISC-V devices: - uses: ./.github/actions/setup-nightly with: - targets: riscv32imc-unknown-none-elf,riscv32imac-unknown-none-elf,riscv32imafc-unknown-none-elf + targets: all components: rust-src, clippy, rustfmt alias: "true" @@ -53,6 +61,7 @@ jobs: esp-hal-xtensa-clippy: name: esp-hal | xtensa clippy (${{ matrix.device }}) + needs: chips runs-on: ubuntu-latest env: CI: 1 @@ -64,17 +73,16 @@ jobs: strategy: fail-fast: false matrix: - device: ["esp32", "esp32s2", "esp32s3"] + device: ${{ fromJSON(needs.chips.outputs.xtensa) }} steps: - uses: actions/checkout@v6 - # Install the Rust toolchain for Xtensa devices: - - uses: esp-rs/xtensa-toolchain@v1.6 + - uses: ./.github/actions/setup-toolchains with: - version: 1.97.0.0 + xtensa: "true" - name: Lint esp-hal on Xtensa chip - run: cargo xtask lint-packages --chips ${{ matrix.device }} --toolchain esp + run: cargo xtask lint ${{ matrix.device }} --toolchain esp check-global-symbols: name: Check Global Symbols in esp-hal @@ -82,10 +90,9 @@ jobs: steps: - uses: actions/checkout@v6 - # Install the Rust toolchain for Xtensa devices: - - uses: esp-rs/xtensa-toolchain@v1.6 + - uses: ./.github/actions/setup-toolchains with: - version: 1.97.0.0 + xtensa: "true" # Check all chips at once only for esp-hal - name: Run check-global-symbols @@ -94,7 +101,13 @@ jobs: create-issue: name: Create GitHub Issue if any job failed runs-on: ubuntu-latest - needs: [esp-hal-riscv-nightly, esp-hal-xtensa-clippy, check-global-symbols] + needs: + [ + chips, + esp-hal-riscv-nightly, + esp-hal-xtensa-clippy, + check-global-symbols, + ] if: ${{ failure() }} steps: - uses: actions/checkout@v6 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 501d492f6c4..933dd83f5e4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,26 +1,30 @@ # NOTE: # -# When adding support for a new chip to `esp-hal`, there are a number of -# updates which must be made to the CI workflow in order to reflect this; the -# changes are: +# Adding support for a new chip to `esp-hal` only needs `.github/chips.json`, +# which feeds the 'esp-hal', 'docs' and 'msrv' jobs, the toolchain setup +# actions, ci-nightly, binary-size and the HIL matrix. # -# 1.) In the 'esp-hal' job, add the appropriate build command. -# 1a.) If the device has a low-power core (which is supported in -# `esp-lp-hal`), then update the `if` condition to build prerequisites. -# 2.) In the 'msrv' job, add checks as needed for the new chip. +# `ci-toolchain` picks the 'esp-hal' build group the chip lands in, which is +# also how the load is balanced across the runners. Give the chip a +# `hil-runner` (and `hil-radio-runner`) once it has a board on the rack; +# without one it is built but not HIL tested. name: CI on: pull_request: - types: [opened, synchronize, reopened, labeled, unlabeled, ready_for_review] + # No `labeled`/`unlabeled`: a label change would rebuild everything and + # cancel the run in progress. `calculate` reads labels live instead, so + # "Re-run all jobs" picks up labels added after the run started. + # Re-run after removing `skip-ci-non-code-change`: the merge queue does not + # run `esp-hal` or `xtensa-lld`, so a stale green run would skip them. + types: [opened, synchronize, reopened, ready_for_review] merge_group: workflow_dispatch: env: CARGO_TERM_COLOR: always GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - MSRV: "1.95.0" DEFMT_LOG: trace PROBE_RS_CONFIG_PRESET: local-hil @@ -37,9 +41,12 @@ jobs: # jobs and reusable workflows run. Every other job/workflow in this file # gates on `calculate` outputs. # Draft PRs run no CI at all: every other job needs `calculate`, so skipping - # it skips them too. + # it skips them too. Closed and merged PRs are skipped the same way. calculate: - if: ${{ !github.event.pull_request.draft }} + if: > + !github.event.pull_request.draft && + (github.event_name != 'pull_request' || + github.event.pull_request.state != 'closed') runs-on: ubuntu-latest outputs: labels: ${{ steps.labels.outputs.labels }} @@ -49,7 +56,6 @@ jobs: run-msrv: ${{ steps.decide.outputs.run-msrv }} run-host-tests: ${{ steps.decide.outputs.run-host-tests }} run-hil: ${{ steps.decide.outputs.run-hil }} - run-changelog: ${{ steps.decide.outputs.run-changelog }} run-semver-check: ${{ steps.decide.outputs.run-semver-check }} steps: - uses: actions/checkout@v6 @@ -59,8 +65,9 @@ jobs: env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | - if [[ "${{ github.event_name }}" == "pull_request" || "${{ github.event_name }}" == "pull_request_target" ]]; then - LABELS=$(printf "%b" "${{ join(github.event.pull_request.labels.*.name, '\n') }}") + if [[ "${{ github.event_name }}" == "pull_request" ]]; then + # Not the event payload: a re-run reuses it, labels and all. + LABELS=$(gh pr view "${{ github.event.pull_request.number }}" --json labels --jq '.labels[].name') elif [[ "${{ github.event_name }}" == "merge_group" ]]; then COMMIT_MSG=$(git log -1 --pretty=%B) PR_NUMBER=$(echo "$COMMIT_MSG" | grep -o "#[0-9]*" | grep -o "[0-9]*" || true) @@ -71,20 +78,18 @@ jobs: PACKAGES="" if [ -n "$LABELS" ]; then - PACKAGES=$(echo "$LABELS" \ - | grep -oP '(?<=^breaking-change-)[a-z0-9-]+$' || true \ - | tr '\n' ',' \ - | sed 's/,$//') + PACKAGES=$(printf '%s\n' "$LABELS" \ + | { grep -oP '(?<=^breaking-change-)[a-z0-9-]+$' || true; } \ + | tr '\n' ' ' | xargs) fi LABELS_SPACE=$(echo "$LABELS" | tr '\n' ' ' | xargs) - PACKAGES_SPACE=$(echo "$PACKAGES" | tr ',' ' ') echo "labels=$LABELS_SPACE" >> "$GITHUB_OUTPUT" - echo "packages=$PACKAGES_SPACE" >> "$GITHUB_OUTPUT" + echo "packages=$PACKAGES" >> "$GITHUB_OUTPUT" echo "Detected labels: $LABELS_SPACE" - echo "Detected packages: $PACKAGES_SPACE" + echo "Detected packages: $PACKAGES" - name: Decide what to run id: decide @@ -92,7 +97,7 @@ jobs: LABELS: ${{ steps.labels.outputs.labels }} run: | BUILD=true; DOCS=true; MSRV=true; HOST=true - CHANGELOG=true; SEMVER=true + SEMVER=true HIL=false if [[ "${{ github.event_name }}" == "merge_group" ]]; then @@ -107,7 +112,6 @@ jobs: HIL=false fi if echo "$LABELS" | grep -qw 'skip-semver-checks'; then SEMVER=false; fi - if echo "$LABELS" | grep -qw 'skip-changelog'; then CHANGELOG=false; fi for pair in \ "run-build=$BUILD" \ @@ -115,12 +119,55 @@ jobs: "run-msrv=$MSRV" \ "run-host-tests=$HOST" \ "run-hil=$HIL" \ - "run-changelog=$CHANGELOG" \ "run-semver-check=$SEMVER"; do echo "$pair" >> "$GITHUB_OUTPUT" done - echo "Decision: build=$BUILD docs=$DOCS msrv=$MSRV host=$HOST hil=$HIL changelog=$CHANGELOG semver=$SEMVER" + echo "Decision: build=$BUILD docs=$DOCS msrv=$MSRV host=$HOST hil=$HIL semver=$SEMVER" + + # Merge freeze — see documentation/CONTRIBUTING.md. + # + # Lives here so that `ci-result` carries it: a check that never reports on + # `pull_request` cannot be a required check on its own, GitHub would wait for + # it forever. Outside the merge queue this only asks whether a freeze issue is + # open and exits, so it runs on every event to keep `hil` reachable. + merge-freeze-gate: + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + contents: read + issues: read + pull-requests: write + steps: + # Base branch, never the queue branch: a queued pull request must not be + # able to rewrite the gate that judges it. + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.merge_group.base_ref || github.base_ref }} + sparse-checkout: .github/scripts + persist-credentials: false + + # A base branch without the script is a base branch without merge + # freezes, so there is nothing to enforce. This is not only for + # bootstrapping, backport pull requests target `esp-hal-x.y.x` branches + # that were cut before the gate existed, and CI runs on those too. + - name: Look for the gate + id: gate + env: + BASE_REF: ${{ github.event.merge_group.base_ref || github.base_ref }} + run: | + if [ -f .github/scripts/merge-freeze.js ]; then + echo "present=true" >> "$GITHUB_OUTPUT" + else + echo "No merge freeze gate on $BASE_REF, nothing to enforce." + fi + + - uses: actions/github-script@v8 + if: steps.gate.outputs.present == 'true' + with: + script: | + const { gate } = require('./.github/scripts/merge-freeze.js'); + await gate({ github, context, core }); # -------------------------------------------------------------------------- # Build Packages @@ -139,28 +186,17 @@ jobs: strategy: matrix: - # load-blance runners a bit - group: - - chips: [esp32, esp32s2, esp32s3, esp32c2, esp32c3] - toolchain: esp - - chips: [esp32c5, esp32c6, esp32c61, esp32h2, esp32p4, esp32s31] - toolchain: stable + # Which chips each toolchain builds comes from `ci-toolchain` in + # .github/chips.json, which is also how the runner load is balanced. + toolchain: [esp, stable] steps: - uses: actions/checkout@v6 - # Install the Rust toolchain for Xtensa devices: - - uses: esp-rs/xtensa-toolchain@v1.6 - if: matrix.group.toolchain == 'esp' - with: - version: 1.97.0.0 - - # Install the Rust stable toolchain for RISC-V devices: - - uses: dtolnay/rust-toolchain@v1 + - uses: ./.github/actions/setup-toolchains with: - target: riscv32imc-unknown-none-elf,riscv32imac-unknown-none-elf,riscv32imafc-unknown-none-elf - toolchain: stable - components: rust-src + xtensa: ${{ matrix.toolchain == 'esp' }} + riscv: "true" - name: Setup cargo-batch run: | @@ -168,11 +204,18 @@ jobs: cargo install --git https://github.com/embassy-rs/cargo-batch cargo --bin cargo-batch --locked --force fi + - name: Resolve chips for this toolchain + id: chips + shell: bash + run: | + echo "chips=$(jq -r --arg t '${{ matrix.toolchain }}' \ + '[.[] | select(."ci-toolchain" == $t) | .soc] | join(" ")' .github/chips.json)" >> "$GITHUB_OUTPUT" + - name: Build and Check shell: bash env: - CHIPS: ${{ join(matrix.group.chips, ' ') }} - TOOLCHAIN: ${{ matrix.group.toolchain }} + CHIPS: ${{ steps.chips.outputs.chips }} + TOOLCHAIN: ${{ matrix.toolchain }} run: | # lints and docs are checked separately for chip in $CHIPS; do @@ -194,54 +237,54 @@ jobs: steps: - uses: actions/checkout@v6 - # Install the Rust toolchain for Xtensa devices: - - uses: esp-rs/xtensa-toolchain@v1.6 + # Docs mix toolchains: Xtensa builds on the MSRV pin while + # RISC-V builds on stable. + - uses: ./.github/actions/setup-toolchains with: - version: 1.95.0.0 + channel: msrv + xtensa: "true" - # Install the Rust stable toolchain for RISC-V devices: - - uses: dtolnay/rust-toolchain@v1 + - uses: ./.github/actions/setup-toolchains with: - target: riscv32imc-unknown-none-elf,riscv32imac-unknown-none-elf,riscv32imafc-unknown-none-elf - toolchain: stable - components: rust-src + riscv: "true" + # Install the Rust nightly toolchain for RISC-V devices: - uses: ./.github/actions/setup-nightly with: - targets: riscv32imc-unknown-none-elf,riscv32imac-unknown-none-elf,riscv32imafc-unknown-none-elf + targets: all components: rust-src alias: "true" - - name: Build Xtensa docs - if: matrix.group == 'xtensa' - shell: bash - run: cargo xtask build documentation --chips esp32,esp32s2,esp32s3 + # The xtensa and riscv build disjoint chip sets, so give them + # separate cache entries + - uses: Swatinem/rust-cache@v2 + with: + shared-key: docs-${{ matrix.group }} + # Every merge_group run gets a unique ephemeral ref, so a cache saved + # there can never be restored. Restore everywhere, save elsewhere. + save-if: ${{ github.event_name != 'merge_group' }} - - name: Build RISC-V docs - if: matrix.group == 'riscv' + - name: Resolve chips for this group + id: chips shell: bash - run: cargo xtask build documentation --chips esp32c2,esp32c3,esp32c5,esp32c6,esp32c61,esp32h2,esp32p4,esp32s31 + run: | + echo "chips=$(jq -r --arg a '${{ matrix.group }}' \ + '[.[] | select(.arch == $a) | .soc] | join(",")' .github/chips.json)" >> "$GITHUB_OUTPUT" - - name: Run Xtensa doc tests - if: matrix.group == 'xtensa' + - name: Build docs shell: bash - run: | - cargo xtask run doc-tests esp32 - cargo xtask run doc-tests esp32s2 - cargo xtask run doc-tests esp32s3 + env: + CHIPS: ${{ steps.chips.outputs.chips }} + run: cargo xtask docs ${CHIPS//,/ } - - name: Run RISC-V doc tests - if: matrix.group == 'riscv' + - name: Run doc tests shell: bash + env: + CHIPS: ${{ steps.chips.outputs.chips }} run: | - cargo xtask run doc-tests esp32c2 - cargo xtask run doc-tests esp32c3 - cargo xtask run doc-tests esp32c5 - cargo xtask run doc-tests esp32c6 - cargo xtask run doc-tests esp32c61 - cargo xtask run doc-tests esp32h2 - cargo xtask run doc-tests esp32p4 - cargo xtask run doc-tests esp32s31 + for chip in ${CHIPS//,/ }; do + cargo xtask doc-tests "$chip" + done # -------------------------------------------------------------------------- # MSRV @@ -261,36 +304,42 @@ jobs: steps: - uses: actions/checkout@v6 - - uses: esp-rs/xtensa-toolchain@v1.6 - if: matrix.group == 'xtensa' + - id: toolchains + uses: ./.github/actions/setup-toolchains with: - version: ${{ env.MSRV }} + channel: msrv + xtensa: ${{ matrix.group == 'xtensa' }} + riscv: ${{ matrix.group == 'riscv' }} + riscv-extra-targets: x86_64-unknown-linux-gnu + riscv-components: rust-src,clippy - name: esp toolchain checks if: matrix.group == 'xtensa' run: rustc +esp --version --verbose - - uses: dtolnay/rust-toolchain@v1 - if: matrix.group == 'riscv' - with: - target: riscv32imc-unknown-none-elf,riscv32imac-unknown-none-elf,riscv32imafc-unknown-none-elf,x86_64-unknown-linux-gnu - toolchain: ${{ env.MSRV }} - components: rust-src,clippy - - name: Stable toolchain checks if: matrix.group == 'riscv' - run: rustc +${{ env.MSRV }} --version --verbose + run: rustc +${{ steps.toolchains.outputs.riscv-toolchain }} --version --verbose - # Verify the MSRV for all chips by running a lint session - - name: msrv RISC-V (esp-hal) - if: matrix.group == 'riscv' + # The xtensa and riscv lint disjoint chip sets under different + # toolchains, so keep their caches separate. + - uses: Swatinem/rust-cache@v2 + with: + shared-key: msrv-${{ matrix.group }} + save-if: ${{ github.event_name != 'merge_group' }} + + - name: Resolve chips for this group + id: chips run: | - cargo xtask lint-packages --chips esp32c2,esp32c3,esp32c5,esp32c6,esp32c61,esp32h2,esp32p4,esp32s31 --toolchain ${{ env.MSRV }} + echo "chips=$(jq -r --arg a '${{ matrix.group }}' \ + '[.[] | select(.arch == $a) | .soc] | join(",")' .github/chips.json)" >> "$GITHUB_OUTPUT" - - name: msrv Xtensa (esp-hal) - if: matrix.group == 'xtensa' + - name: msrv lint (esp-hal) + env: + CHIPS: ${{ steps.chips.outputs.chips }} run: | - cargo xtask lint-packages --chips esp32,esp32s2,esp32s3 --toolchain esp + cargo xtask lint ${CHIPS//,/ } \ + --toolchain ${{ matrix.group == 'xtensa' && 'esp' || steps.toolchains.outputs.riscv-toolchain }} # -------------------------------------------------------------------------- # Xtensa LLD linking @@ -316,12 +365,11 @@ jobs: steps: - uses: actions/checkout@v6 - # Install the Rust toolchain for Xtensa devices. Keep this in sync with - # the `esp-hal` build job above so the LLD linking test exercises the - # same compiler as the rest of CI. - - uses: esp-rs/xtensa-toolchain@v1.6 + # Uses the same pin as the `esp-hal` build job above, so the LLD linking + # test exercises the same compiler as the rest of CI. + - uses: ./.github/actions/setup-toolchains with: - version: 1.97.0.0 + xtensa: "true" - name: Build hello_world with LLD working-directory: examples/hello_world @@ -359,12 +407,24 @@ jobs: components: rustfmt,miri alias: "true" + # xtask funnels every package it drives into the root `target`, but the + # `extras` crates are built directly and keep their own target dirs. + - uses: Swatinem/rust-cache@v2 + with: + shared-key: host-tests + save-if: ${{ github.event_name != 'merge_group' }} + workspaces: | + . -> target + extras/bench-server -> target + extras/esp-wifishark -> target + extras/ieee802154-sniffer -> target + # Run xtask tests - name: Run xtask tests run: cd xtask && cargo test --features release # Check the formatting of all packages: - - run: cargo xtask fmt-packages --check + - run: cargo xtask fmt --check # Check metadata generation for all packages: - run: cargo update-metadata --check @@ -415,6 +475,8 @@ jobs: # -------------------------------------------------------------------------- # Check links in .rs, .md, and .toml files + # + # Deliberately absent from `ci-result` below. link-check: needs: calculate @@ -430,7 +492,7 @@ jobs: --max-concurrency 4 --retry-wait-time 5 --max-retries 10 - --accept "200,301,302" + --accept "200,301,302,503" --exclude-path ".*/target/.*|.*/static\.files/.*|.*/docs/.*" --remap "https://github.com/${{ github.repository }}/(?:blob|tree)/[^/]+/(.+) file://$GITHUB_WORKSPACE/\$1" './**/*.rs' @@ -440,17 +502,6 @@ jobs: # -------------------------------------------------------------------------- # Reusable workflow calls — gated by calculate outputs - changelog: - needs: calculate - if: > - github.event_name == 'pull_request' && - !github.event.pull_request.draft && - needs.calculate.outputs.run-changelog == 'true' - uses: ./.github/workflows/changelog.yml - with: - pr-number: ${{ github.event.pull_request.number }} - secrets: inherit - semver-check: needs: calculate if: needs.calculate.outputs.run-semver-check == 'true' @@ -462,296 +513,44 @@ jobs: # -------------------------------------------------------------------------- # HIL — build jobs gate artifacts; hil-gate gates device runs (≥50% rule). - hil-build: - needs: calculate - if: needs.calculate.outputs.run-hil == 'true' - runs-on: macos-m1-self-hosted - outputs: - matrix: ${{ steps.chips.outputs.matrix }} - steps: - - name: Resolve chip matrix - id: chips - run: | - ALL_CHIPS='[ - {"soc":"esp32", "rust-target":"xtensa-esp32-none-elf", "runner":"esp32-jtag", "host":"aarch64"}, - {"soc":"esp32s2", "rust-target":"xtensa-esp32s2-none-elf", "runner":"esp32s2-jtag", "host":"aarch64"}, - {"soc":"esp32s3", "rust-target":"xtensa-esp32s3-none-elf", "runner":"esp32s3-usb", "host":"aarch64"}, - {"soc":"esp32c2", "rust-target":"riscv32imc-unknown-none-elf", "runner":"esp32c2-jtag", "host":"aarch64"}, - {"soc":"esp32c3", "rust-target":"riscv32imc-unknown-none-elf", "runner":"esp32c3-usb", "host":"aarch64"}, - {"soc":"esp32c5", "rust-target":"riscv32imac-unknown-none-elf", "runner":"esp32c5-usb", "host":"aarch64"}, - {"soc":"esp32c6", "rust-target":"riscv32imac-unknown-none-elf", "runner":"esp32c6-usb", "host":"aarch64"}, - {"soc":"esp32c61","rust-target":"riscv32imac-unknown-none-elf", "runner":"esp32c61-usb", "host":"aarch64"}, - {"soc":"esp32h2", "rust-target":"riscv32imac-unknown-none-elf", "runner":"esp32h2-usb", "host":"aarch64"}, - {"soc":"esp32p4", "rust-target":"riscv32imafc-unknown-none-elf","runner":"esp32p4", "host":"aarch64"}, - {"soc":"esp32s31","rust-target":"riscv32imafc-unknown-none-elf","runner":"esp32s31-jtag", "host":"aarch64"} - ]' - echo "matrix={\"target\":$(echo "$ALL_CHIPS" | jq -c .)}" >> "$GITHUB_OUTPUT" - - - uses: actions/checkout@v6 - - - uses: esp-rs/xtensa-toolchain@v1.6 - with: - buildtargets: esp32,esp32s2,esp32s3 - default: true - version: 1.97.0.0 - - - uses: ./.github/actions/setup-nightly - with: - targets: riscv32imc-unknown-none-elf,riscv32imac-unknown-none-elf,riscv32imafc-unknown-none-elf - components: rust-src - alias: "true" - - - name: Build hil-test tests - run: | - for chip in esp32 esp32s2 esp32s3 esp32s31 esp32c2 esp32c3 esp32c5 esp32c6 esp32c61 esp32h2 esp32p4; do - if cargo xtask build tests "$chip" --help >/dev/null 2>&1; then - echo "Building ALL hil-test tests for $chip" - cargo xtask build tests "$chip" - else - echo "Skipping $chip: not supported by this ref's xtask" - fi - done - - - uses: actions/upload-artifact@v6 - with: - name: hil-tests - path: target/tests/ - if-no-files-found: error - - # Build radio HIL tests (hil-test-radio). Chips for which the radio - # package has no applicable binaries produce no output and are silently - # skipped via `if-no-files-found: ignore`. - - name: Reset tests output directory for radio build - run: rm -rf target/tests - - - name: Build hil-test-radio tests - run: | - for chip in esp32 esp32s2 esp32s3 esp32c2 esp32c3 esp32c5 esp32c6 esp32c61 esp32h2; do - if cargo xtask build tests "$chip" hil-test-radio --help >/dev/null 2>&1; then - echo "Building ALL hil-test-radio tests for $chip" - cargo xtask build tests "$chip" hil-test-radio - else - echo "Skipping $chip: not supported by this ref's xtask" - fi - done - - - uses: actions/upload-artifact@v6 - with: - name: hil-tests-radio - path: target/tests/ - if-no-files-found: ignore - - hil-devtool: - needs: calculate + # `merge-freeze-gate` is a dependency so that a frozen-out queue entry never + # occupies the device runners. + hil: + needs: [calculate, merge-freeze-gate] if: needs.calculate.outputs.run-hil == 'true' - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v6 - - - name: Cache Dependencies - uses: Swatinem/rust-cache@v2 - - # xtask runs on the AArch64 HIL runners as a host tool. - # Restore the binary after the dependency cache, which may replace the - # target directory while restoring its own cache. - - name: Cache xtask binary - id: xtask-cache - uses: actions/cache@v6 - with: - path: target/aarch64-unknown-linux-gnu/release/esp-devtool - key: xtask-hil-aarch64-${{ runner.os }}-${{ hashFiles('Cargo.lock', 'xtask/**', 'xtask-mcp-macros/**') }} - - - name: Install cross-compilation target - if: steps.xtask-cache.outputs.cache-hit != 'true' - run: rustup target add aarch64-unknown-linux-gnu - - - uses: taiki-e/install-action@v2 - if: steps.xtask-cache.outputs.cache-hit != 'true' - with: - tool: cross - - - name: Build xtask for HIL runners - if: steps.xtask-cache.outputs.cache-hit != 'true' - run: cross build --release --target aarch64-unknown-linux-gnu -p esp-devtool - - - uses: actions/upload-artifact@v6 - with: - name: xtask-aarch64 - path: target/aarch64-unknown-linux-gnu/release/esp-devtool - if-no-files-found: error - - # Device runs — aggregated by hil-gate (see below). - hil-run: - needs: [hil-build, hil-devtool] - runs-on: - labels: [self-hosted, "${{ matrix.target.runner }}"] - strategy: - fail-fast: false - matrix: ${{ fromJSON(needs.hil-build.outputs.matrix) }} - steps: - - uses: actions/download-artifact@v4 - with: - name: hil-tests - path: tests/ - continue-on-error: true - - - uses: actions/download-artifact@v4 - with: - name: xtask-${{ matrix.target.host }} - - - name: Skip if this target wasn't built - id: guard - run: | - if [ ! -d "tests/${{ matrix.target.soc }}" ]; then - echo "skip=true" >> $GITHUB_OUTPUT - echo "No tests for ${{ matrix.target.soc }} in this run; skipping." - fi - - - name: Run Tests - if: steps.guard.outputs.skip != 'true' - run: | - [ -f ~/setup.sh ] && source ~/setup.sh - - export PATH=$PATH:/home/espressif/.cargo/bin - chmod +x esp-devtool - ./esp-devtool run elfs ${{ matrix.target.soc }} tests/${{ matrix.target.soc }} - - - name: Clean up - if: always() - run: | - rm -rf tests/ || true - rm -f esp-devtool || true - - # Radio HIL device runs — wifi/BT capable chips on dedicated radio runners. - # Not gated by hil-gate or ci-result. - hil-run-radio: - needs: [hil-build, hil-devtool] - runs-on: - labels: [self-hosted, "${{ matrix.target.runner }}"] - strategy: - fail-fast: false - matrix: - target: - - soc: esp32c6 - runner: esp32c6-radio - host: aarch64 - - soc: esp32s3 - runner: esp32s3-radio - host: aarch64 - steps: - - uses: actions/download-artifact@v4 - with: - name: hil-tests-radio - path: tests/ - continue-on-error: true - - - uses: actions/download-artifact@v4 - with: - name: xtask-${{ matrix.target.host }} - - - name: Skip if this target wasn't built - id: guard - run: | - if [ ! -d "tests/${{ matrix.target.soc }}" ]; then - echo "skip=true" >> $GITHUB_OUTPUT - echo "No radio tests for ${{ matrix.target.soc }} in this run; skipping." - fi - - - name: Reset ESP USB-JTAG devices - if: steps.guard.outputs.skip != 'true' - timeout-minutes: 1 - shell: bash - run: | - # The support firmware runs forever on the harness probe; a previous - # run can leave the in-chip USB-Serial-JTAG bridge wedged so the next - # flash hangs. Issue USBDEVFS_RESET to force a clean re-enumeration. - python3 - <<'PY' - import fcntl, glob, os, time - USBDEVFS_RESET = (ord('U') << 8) | 20 # _IO('U', 20) - reset_any = False - for dev in glob.glob('/sys/bus/usb/devices/*'): - try: - vid = open(os.path.join(dev, 'idVendor')).read().strip().lower() - pid = open(os.path.join(dev, 'idProduct')).read().strip().lower() - except OSError: - continue - if (vid, pid) != ('303a', '1001'): - continue - busnum = int(open(os.path.join(dev, 'busnum')).read()) - devnum = int(open(os.path.join(dev, 'devnum')).read()) - node = f'/dev/bus/usb/{busnum:03d}/{devnum:03d}' - try: - with open(node, 'wb') as f: - fcntl.ioctl(f, USBDEVFS_RESET, 0) - print(f'reset {node} ({vid}:{pid})') - reset_any = True - except OSError as e: - print(f'failed to reset {node}: {e}') - if reset_any: - time.sleep(2) # allow udev to re-enumerate before probe-rs runs - PY - - - name: Run Radio Tests - if: steps.guard.outputs.skip != 'true' - timeout-minutes: 3 - run: | - [ -f ~/setup.sh ] && source ~/setup.sh - - export PATH=$PATH:/home/espressif/.cargo/bin - chmod +x esp-devtool - - ./esp-devtool run elfs ${{ matrix.target.soc }} tests/${{ matrix.target.soc }} - - - name: Clean up - if: always() - run: | - rm -rf tests/ || true - rm -f esp-devtool || true - - # Merge gate for hil-run matrix legs. Blocks when ≥50% of legs that actually - # ran tests failed or were cancelled. Skipped legs (no ELFs for that chip) - # are excluded. hil-run-radio is not part of this gate. - hil-gate: - needs: [hil-build, hil-run] - if: > - always() && - needs.hil-build.result == 'success' && - needs.hil-run.result != 'skipped' - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v6 - with: - fetch-depth: 1 - - - name: Evaluate hil-run results - uses: actions/github-script@v7 - with: - script: | - const { evaluateHilGate } = require('./.github/scripts/hil-gate.js'); - await evaluateHilGate({ github, context, core }); + uses: ./.github/workflows/hil.yml + with: + chips: all + package: all + secrets: inherit # -------------------------------------------------------------------------- # Gate job for branch protection # - # Branch protection should require this single job instead of individual jobs. + # Branch protection should require this job instead of individual jobs, plus + # `changelog` from changelog.yml. # Skipped jobs (due to calculate outputs) are treated as success. # Failed or cancelled jobs cause this gate to fail. # - # hil-build gates test compilation, and hil-devtool gates the runner tool. - # hil-gate gates device runs when ≥50% of executed hil-run matrix legs fail. - # hil-run-radio is informational only. + # The `hil` job is the reusable hil.yml workflow, so it covers test + # compilation and the runner tool as well; its hil-gate job blocks when ≥50% + # of executed hil-run matrix legs fail. hil-run-radio is informational only. + # merge-freeze-gate rejects queue entries while a merge freeze is in effect. ci-result: if: ${{ always() }} needs: + # `calculate` gates everything below it, so a failure there leaves every + # other job `skipped` — which this gate treats as success. Depend on it + # directly, or a broken decision step passes CI without running any. + - calculate - esp-hal - docs - msrv + - xtensa-lld - host-tests - - changelog - semver-check - - hil-build - - hil-devtool - - hil-gate + - hil + - merge-freeze-gate runs-on: ubuntu-latest steps: - name: Check CI results diff --git a/.github/workflows/dispatch.yml b/.github/workflows/dispatch.yml index 69af7814729..0631e959235 100644 --- a/.github/workflows/dispatch.yml +++ b/.github/workflows/dispatch.yml @@ -75,7 +75,7 @@ jobs: issue-number: ${{ github.event.pull_request.number }} body: | Author **@${{ steps.pr.outputs.login }}** was trusted for this PR via the `trusted-author` label. - They can now use `/hil quick`, `/hil full` and `/hil ` and their features. + They can now use `/test` (`quick`, `full`, or chips and test names). `/hil` still works too. # --------------------------------------------------------------------------- # TRUST MANAGEMENT (/trust, /revoke) @@ -101,7 +101,14 @@ jobs: script: | const { parseTrustCommand } = require('./.github/scripts/hil-trust.js'); const res = parseTrustCommand(context.payload.comment.body, 'trust'); - if (res.error) core.setFailed(res.error); + if (res.error) { + await github.rest.issues.createComment({ + ...context.repo, + issue_number: context.issue.number, + body: res.error, + }); + core.setFailed(res.error); + } core.setOutput('login', res.login); - id: find @@ -134,7 +141,7 @@ jobs: with: issue-number: ${{ github.event.issue.number }} # separate short confirmation comment - body: "Trusted **@${{ steps.parse.outputs.login }}** for this PR. They can now use `/hil quick`, `/hil full` and `/hil ` and their features." + body: "Trusted **@${{ steps.parse.outputs.login }}** for this PR. They can now use `/test` (`quick`, `full`, or chips and test names). `/hil` still works too." revoke: if: > @@ -156,7 +163,14 @@ jobs: script: | const { parseTrustCommand } = require('./.github/scripts/hil-trust.js'); const res = parseTrustCommand(context.payload.comment.body, 'revoke'); - if (res.error) core.setFailed(res.error); + if (res.error) { + await github.rest.issues.createComment({ + ...context.repo, + issue_number: context.issue.number, + body: res.error, + }); + core.setFailed(res.error); + } core.setOutput('login', res.login); - id: find @@ -191,7 +205,7 @@ jobs: body: "Revoked **@${{ steps.parse.outputs.login }}** for this PR." # --------------------------------------------------------------------------- - # SLASH-BASED DISPATCHES (/hil quick, /hil full, /hil ) + # SLASH-BASED DISPATCHES (/test quick, /test full, /test , and the previous /hil spelling) # --------------------------------------------------------------------------- auth: @@ -238,32 +252,34 @@ jobs: } core.setOutput('allowed', allowed ? 'true' : 'false'); - hil-quick: + hil: needs: auth if: github.event_name == 'issue_comment' && needs.auth.outputs.allowed == 'true' && - startsWith(github.event.comment.body, '/hil quick') + (startsWith(github.event.comment.body, '/hil ') || + startsWith(github.event.comment.body, '/test ')) runs-on: ubuntu-latest - outputs: - run_id: ${{ steps.find-run.outputs.run_id }} - comment_id: ${{ steps.comment.outputs.comment-id }} steps: - uses: actions/checkout@v6 # for `require` with: fetch-depth: 1 - - name: Parse tests - id: parse-tests + - name: Resolve dispatch parameters + id: mode uses: actions/github-script@v7 with: + # A command that can't be run is answered by `hil-help`. script: | - const { parseTests, parsePackage } = require('./.github/scripts/hil-parse.js'); - const body = context.payload.comment.body; + const { parseHilCommand } = require('./.github/scripts/hil-parse.js'); + const res = parseHilCommand(context.payload.comment.body) || {}; - core.setOutput('tests', parseTests(body)); - core.setOutput('package', parsePackage(body)); + core.setOutput('selector', res.selector || ''); + core.setOutput('chips', res.chips || ''); + core.setOutput('tests', res.tests || ''); + core.setOutput('package', res.package || ''); - - name: Dispatch HIL (quick) + - name: Dispatch HIL + if: steps.mode.outputs.chips != '' uses: benc-uk/workflow-dispatch@v1 with: workflow: hil.yml @@ -273,277 +289,45 @@ jobs: "repository": "${{ github.repository }}", "branch": "refs/pull/${{ github.event.issue.number }}/head", "pr_number": "${{ github.event.issue.number }}", - "chips": "esp32c6 esp32s3", - "tests": "${{ steps.parse-tests.outputs.tests }}", - "package": "${{ steps.parse-tests.outputs.package }}", + "chips": "${{ steps.mode.outputs.chips }}", + "tests": "${{ steps.mode.outputs.tests }}", + "package": "${{ steps.mode.outputs.package }}", "distinct_id": "${{ env.DISTINCT_ID }}" } - - name: Find HIL run URL (quick) + - name: Find HIL run URL + if: steps.mode.outputs.chips != '' id: find-run uses: actions/github-script@v7 with: script: | const { findHilRun } = require('./.github/scripts/hil-find-run.js'); - const { runId, body } = await findHilRun({ + const { body } = await findHilRun({ github, context, pr: context.payload.issue.number, - selector: 'quick', + selector: '${{ steps.mode.outputs.selector }}', + tests: '${{ steps.mode.outputs.tests }}', + pkg: '${{ steps.mode.outputs.package }}', distinctId: '${{ env.DISTINCT_ID }}', }); - core.setOutput('run_id', runId); core.setOutput('body', body); - name: Confirm in PR - id: comment + if: steps.mode.outputs.chips != '' uses: peter-evans/create-or-update-comment@v4 with: issue-number: ${{ github.event.issue.number }} body: ${{ steps.find-run.outputs.body }} - hil-quick-status: - needs: hil-quick - if: needs.hil-quick.outputs.run_id != '' && needs.hil-quick.outputs.comment_id != '' - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v6 # for `require` - with: - fetch-depth: 1 - - - name: Wait for quick HIL run and update comment - uses: actions/github-script@v7 - with: - script: | - const { pollRun } = require('./.github/scripts/hil-status.js'); - - await pollRun({ - github, - context, - runId: Number('${{ needs.hil-quick.outputs.run_id }}'), - commentId: Number('${{ needs.hil-quick.outputs.comment_id }}'), - kind: 'HIL (quick)', - // Quick runs can legitimately take >15min, especially with queueing. - maxPolls: 180, - }); - - hil-full: - needs: auth - if: github.event_name == 'issue_comment' && - needs.auth.outputs.allowed == 'true' && - startsWith(github.event.comment.body, '/hil full') - runs-on: ubuntu-latest - outputs: - run_id: ${{ steps.find-run.outputs.run_id }} - comment_id: ${{ steps.comment.outputs.comment-id }} - steps: - - uses: actions/checkout@v6 # for `require` - with: - fetch-depth: 1 - - - name: Parse tests - id: parse-tests - uses: actions/github-script@v7 - with: - script: | - const { parseTests, parsePackage } = require('./.github/scripts/hil-parse.js'); - const body = context.payload.comment.body; - - core.setOutput('tests', parseTests(body)); - core.setOutput('package', parsePackage(body)); - - - name: Dispatch HIL (full) - uses: benc-uk/workflow-dispatch@v1 - with: - workflow: hil.yml - ref: ${{ github.event.repository.default_branch }} - inputs: | - { - "repository": "${{ github.repository }}", - "branch": "refs/pull/${{ github.event.issue.number }}/head", - "pr_number": "${{ github.event.issue.number }}", - "chips": "esp32 esp32s2 esp32s3 esp32s31 esp32c2 esp32c3 esp32c5 esp32c6 esp32c61 esp32h2 esp32p4", - "tests": "${{ steps.parse-tests.outputs.tests }}", - "package": "${{ steps.parse-tests.outputs.package }}", - "distinct_id": "${{ env.DISTINCT_ID }}" - } - - - name: Find HIL run URL (full) - id: find-run - uses: actions/github-script@v7 - with: - script: | - const { findHilRun } = require('./.github/scripts/hil-find-run.js'); - - const { runId, body } = await findHilRun({ - github, - context, - pr: context.payload.issue.number, - selector: 'full', - distinctId: '${{ env.DISTINCT_ID }}', - }); - - core.setOutput('run_id', runId); - core.setOutput('body', body); - - - name: Confirm in PR - id: comment - uses: peter-evans/create-or-update-comment@v4 - with: - issue-number: ${{ github.event.issue.number }} - body: ${{ steps.find-run.outputs.body }} - - hil-full-status: - needs: hil-full - if: needs.hil-full.outputs.run_id != '' && needs.hil-full.outputs.comment_id != '' - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v6 # for `require` - with: - fetch-depth: 1 - - - name: Wait for full HIL run and update comment - uses: actions/github-script@v7 - with: - script: | - const { pollRun } = require('./.github/scripts/hil-status.js'); - - await pollRun({ - github, - context, - runId: Number('${{ needs.hil-full.outputs.run_id }}'), - commentId: Number('${{ needs.hil-full.outputs.comment_id }}'), - kind: 'HIL (full)', - }); - - # --------------------------------------------------------------------------- - # PER-CHIP HIL: /hil esp32c3 [esp32s3 ...] [--tests ...] - # --------------------------------------------------------------------------- - - hil-chips: - needs: auth - if: github.event_name == 'issue_comment' && - needs.auth.outputs.allowed == 'true' && - startsWith(github.event.comment.body, '/hil ') && - !startsWith(github.event.comment.body, '/hil quick') && - !startsWith(github.event.comment.body, '/hil full') - runs-on: ubuntu-latest - outputs: - run_id: ${{ steps.find-run.outputs.run_id }} - comment_id: ${{ steps.comment.outputs.comment-id }} - steps: - - uses: actions/checkout@v6 # for `require` - with: - fetch-depth: 1 - - - name: Parse chips - id: parse - uses: actions/github-script@v7 - with: - script: | - const { parseChips } = require('./.github/scripts/hil-parse.js'); - - const res = parseChips(context.payload.comment.body); - - core.setOutput('chips', res.chips); - core.setOutput('chips_label', res.chipsLabel); - core.setOutput('error', res.error); - - - name: Parse tests - id: parse-tests - uses: actions/github-script@v7 - with: - script: | - const { parseTests, parsePackage } = require('./.github/scripts/hil-parse.js'); - const body = context.payload.comment.body; - - core.setOutput('tests', parseTests(body)); - core.setOutput('package', parsePackage(body)); - - - name: Report invalid chips - if: steps.parse.outputs.chips == '' && steps.parse.outputs.error != '' - uses: peter-evans/create-or-update-comment@v4 - with: - issue-number: ${{ github.event.issue.number }} - body: | - @${{ github.event.comment.user.login }}, HIL **per-chip** request failed: ${{ steps.parse.outputs.error }} - - - name: Dispatch HIL (per-chip) - if: steps.parse.outputs.chips != '' - uses: benc-uk/workflow-dispatch@v1 - with: - workflow: hil.yml - ref: ${{ github.event.repository.default_branch }} - inputs: | - { - "repository": "${{ github.repository }}", - "branch": "refs/pull/${{ github.event.issue.number }}/head", - "pr_number": "${{ github.event.issue.number }}", - "chips": "${{ steps.parse.outputs.chips }}", - "tests": "${{ steps.parse-tests.outputs.tests }}", - "package": "${{ steps.parse-tests.outputs.package }}", - "distinct_id": "${{ env.DISTINCT_ID }}" - } - - - name: Find HIL run URL (per-chip) - if: steps.parse.outputs.chips != '' - id: find-run - uses: actions/github-script@v7 - with: - script: | - const { findHilRun } = require('./.github/scripts/hil-find-run.js'); - - const { runId, body } = await findHilRun({ - github, - context, - pr: context.payload.issue.number, - selector: '${{ steps.parse.outputs.chips }}', - distinctId: '${{ env.DISTINCT_ID }}', - }); - - core.setOutput('run_id', runId); - core.setOutput('body', body); - - - name: Confirm in PR - if: steps.parse.outputs.chips != '' - id: comment - uses: peter-evans/create-or-update-comment@v4 - with: - issue-number: ${{ github.event.issue.number }} - body: ${{ steps.find-run.outputs.body }} - - hil-chips-status: - needs: hil-chips - if: needs.hil-chips.outputs.run_id != '' && needs.hil-chips.outputs.comment_id != '' - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v6 # for `require` - with: - fetch-depth: 1 - - - name: Wait for per-chip HIL run and update comment - uses: actions/github-script@v7 - with: - script: | - const { pollRun } = require('./.github/scripts/hil-status.js'); - - await pollRun({ - github, - context, - runId: Number('${{ needs.hil-chips.outputs.run_id }}'), - commentId: Number('${{ needs.hil-chips.outputs.comment_id }}'), - kind: 'HIL (per-chip)', - }); - hil-deny: needs: auth if: github.event_name == 'issue_comment' && needs.auth.outputs.allowed != 'true' && - (startsWith(github.event.comment.body, '/hil quick') || - startsWith(github.event.comment.body, '/hil full') || - startsWith(github.event.comment.body, '/hil ') || + (startsWith(github.event.comment.body, '/hil ') || + startsWith(github.event.comment.body, '/test ') || startsWith(github.event.comment.body, '/test-size')) runs-on: ubuntu-latest steps: @@ -557,38 +341,35 @@ jobs: ``` /trust @${{ github.event.comment.user.login }} ``` - After that, you can use `/hil quick`, `/hil full`, `/hil ` or `/test-size`. + After that, you can use `/test` (`quick`, `full`, or chips and test names; `/hil` still works) or `/test-size`. hil-help: if: github.event_name == 'issue_comment' && github.event.issue.pull_request && - startsWith(github.event.comment.body, '/hil') && - !startsWith(github.event.comment.body, '/hil quick') && - !startsWith(github.event.comment.body, '/hil full') && - !contains(github.event.comment.body, 'esp32') + (startsWith(github.event.comment.body, '/hil') || + startsWith(github.event.comment.body, '/test')) && + !startsWith(github.event.comment.body, '/test-') runs-on: ubuntu-latest steps: + - uses: actions/checkout@v6 # for `require` + with: + fetch-depth: 1 + - name: Explain usage - uses: peter-evans/create-or-update-comment@v4 + uses: actions/github-script@v7 with: - issue-number: ${{ github.event.issue.number }} - body: | - Usage: - - `/hil quick` — run a quick HIL matrix (only `ESP32-S3` (Xtensa) and `ESP32-C6` (RISC-V) tests) - - `/hil full` — run the full HIL matrix for all supported chips - - `/hil [ ...]` — run the full HIL tests **only** for the listed chips - - `/test-size [--package ] [chip2 ...]` — run binary size analysis for the specified example on one or more chips. Example: `/test-size embassy_hello_world esp32c3 esp32c6` or `/test-size sleep_timer --package qa-test esp32c3` - - You can optionally append `--test [,...]` to any `/hil` command to only run selected tests. - - You can optionally include `hil-test-radio` in the comment body of any `/hil` command to run radio HIL instead of the default `hil-test` package. - If you aren't a repository **member/owner**, you must be **trusted for this PR**. - Maintainers can grant access with a `trusted-author` label or with: - ``` - /trust @ - ``` - and revoke with: - ``` - /revoke @ - ``` + script: | + const { parseHilCommand, USAGE } = require('./.github/scripts/hil-parse.js'); + const res = parseHilCommand(context.payload.comment.body); + if (!res || (!res.help && !res.error)) return; + + const login = context.payload.comment.user.login; + const problem = res.error ? `@${login}, this command can't be run:\n${res.error}\n\n` : ''; + await github.rest.issues.createComment({ + ...context.repo, + issue_number: context.issue.number, + body: problem + USAGE, + }); binary-size: needs: auth @@ -603,67 +384,30 @@ jobs: - name: Extract parameters from comment id: extract - run: | - # Expected format: /test-size example_name chip(s) - COMMENT="${{ github.event.comment.body }}" - # Use only the line that holds the command (let users add free-form - # text in the rest of the comment) and strip any CR characters that - # GitHub may include on CRLF line endings. - COMMAND_LINE=$(printf '%s' "$COMMENT" | tr -d '\r' | grep -m1 -E '^/test-size' || true) - if [ -z "$COMMAND_LINE" ]; then - echo "Error: Could not find /test-size command line in comment." - exit 1 - fi - # Strip the /test-size prefix - ARGS=$(printf '%s' "$COMMAND_LINE" | sed 's|/test-size[[:space:]]*||') - - # Extract --package value if present - PACKAGE="" - if echo "$ARGS" | grep -q '\-\-package'; then - PACKAGE=$(echo "$ARGS" | sed 's/.*--package[[:space:]]\+\([^[:space:]]\+\).*/\1/') - # Remove --package from ARGS for further parsing - ARGS=$(echo "$ARGS" | sed 's/--package[[:space:]]\+[^[:space:]]\+//') - fi - - # Known chips — everything matching these is a chip, first token is the example - KNOWN_CHIPS="esp32 esp32c2 esp32c3 esp32c5 esp32c6 esp32c61 esp32h2 esp32s2 esp32s3 esp32s31 esp32p4" - - EXAMPLE_NAME="" - CHIPS_JSON="[" - FIRST=true - - for token in $ARGS; do - if echo "$KNOWN_CHIPS" | grep -qw "$token"; then - if [ "$FIRST" = "true" ]; then - CHIPS_JSON="${CHIPS_JSON}\"${token}\"" - FIRST=false - else - CHIPS_JSON="${CHIPS_JSON},\"${token}\"" - fi - elif [ -z "$EXAMPLE_NAME" ]; then - EXAMPLE_NAME="$token" - fi - done - CHIPS_JSON="${CHIPS_JSON}]" - - if [ -z "$EXAMPLE_NAME" ]; then - echo "Error: No example name provided." - echo "Expected: /test-size example_name [--package pkg] chip1 [chip2 ...]" - exit 1 - fi - - if [ "$CHIPS_JSON" = "[]" ]; then - echo "Error: No valid chip names provided." - echo "Valid chips: $KNOWN_CHIPS" - exit 1 - fi - - echo "example_name=$EXAMPLE_NAME" >> $GITHUB_OUTPUT - echo "package=$PACKAGE" >> $GITHUB_OUTPUT - echo "chips=$CHIPS_JSON" >> $GITHUB_OUTPUT - CHIPS_ESCAPED=$(echo "$CHIPS_JSON" | sed 's/"/\\"/g') - echo "chips_escaped=$CHIPS_ESCAPED" >> $GITHUB_OUTPUT - echo "Parsed — example: $EXAMPLE_NAME | package: $PACKAGE | chips: $CHIPS_JSON" + uses: actions/github-script@v7 + with: + script: | + const { parseTestSizeCommand, USAGE } = require('./.github/scripts/hil-parse.js'); + const res = parseTestSizeCommand(context.payload.comment.body); + if (!res || res.error) { + const login = context.payload.comment.user.login; + const error = res?.error || 'Write the command as `/test-size` followed by its words.'; + await github.rest.issues.createComment({ + ...context.repo, + issue_number: context.issue.number, + body: `@${login}, this \`/test-size\` command can't be run:\n${error}\n\n${USAGE}`, + }); + core.setFailed(error); + return; + } + + // `example_name` takes several examples, separated by spaces. + const chips = JSON.stringify(res.chips); + core.setOutput('example_name', res.examples); + core.setOutput('package', res.package); + core.setOutput('chips', chips); + core.setOutput('chips_escaped', JSON.stringify(chips).slice(1, -1)); + core.info(`Parsed — examples: ${res.examples} | package: ${res.package} | chips: ${chips}`); - name: Confirm in PR id: comment diff --git a/.github/workflows/documentation.yml b/.github/workflows/documentation.yml index 01a015879e1..6a659180433 100644 --- a/.github/workflows/documentation.yml +++ b/.github/workflows/documentation.yml @@ -109,10 +109,10 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v6 - - uses: esp-rs/xtensa-toolchain@v1.6 + - uses: ./.github/actions/setup-toolchains with: - default: true - version: 1.97.0.0 + xtensa: "true" + xtensa-default: "true" # xtensa-toolchain installs rustup and a basic toolchain, but doesn't install rust-src - name: rust-src @@ -146,7 +146,7 @@ jobs: if [ -n "${{ needs.setup.outputs.channel }}" ]; then CHANNEL_ARGS="--channel ${{ needs.setup.outputs.channel }}" fi - ~/.cargo/bin/esp-devtool build documentation --packages=${{ matrix.packages.name }} --base-url ${{ needs.setup.outputs.base_url }} $CHANNEL_ARGS + ~/.cargo/bin/esp-devtool documentation --packages=${{ matrix.packages.name }} --base-url ${{ needs.setup.outputs.base_url }} $CHANNEL_ARGS # https://github.com/actions/deploy-pages/issues/303#issuecomment-1951207879 - name: Remove problematic '.lock' files @@ -176,7 +176,7 @@ jobs: - name: Create index.html run: | chmod +x docs/xtask/esp-devtool - docs/xtask/esp-devtool build documentation-index --base-url ${{ needs.setup.outputs.base_url }} + docs/xtask/esp-devtool documentation-index --base-url ${{ needs.setup.outputs.base_url }} rm -rf docs/xtask - if: ${{ github.event.inputs.server == 'preview' || github.event_name == 'pull_request' }} diff --git a/.github/workflows/hil.yml b/.github/workflows/hil.yml index 99b94b9fed8..193be29862a 100644 --- a/.github/workflows/hil.yml +++ b/.github/workflows/hil.yml @@ -12,7 +12,7 @@ on: workflow_call: inputs: chips: - description: "Space-separated list of SoCs to build and test" + description: 'Space-separated list of SoCs to build and test, or "all"' required: true type: string tests: @@ -25,6 +25,18 @@ on: required: false type: string default: "hil-test" + # Set only by the workflow_dispatch path. Declared here with empty + # defaults so the `inputs.branch == ''` tests that select the plain + # checkout, enable continue-on-error and enable hil-gate are + # well-defined on the workflow_call path too. + repository: + required: false + type: string + default: "" + branch: + required: false + type: string + default: "" # Not used by the workflow_call path, but referenced in run-name; declared # here (with empty defaults) so that expression is well-defined for both # triggers. @@ -51,9 +63,9 @@ on: required: false default: "" chips: - description: "Space-separated list of SoCs to build and test" + description: 'Space-separated list of SoCs to build and test, or "all"' required: true - default: "esp32 esp32s2 esp32s3 esp32s31 esp32c2 esp32c3 esp32c5 esp32c6 esp32c61 esp32h2 esp32p4" + default: "all" tests: description: "Optional list of test names to run (ELF basenames)" required: false @@ -77,104 +89,110 @@ jobs: outputs: matrix: ${{ steps.chips.outputs.matrix }} radio_matrix: ${{ steps.chips.outputs.radio_matrix }} + has_radio: ${{ steps.chips.outputs.has_radio }} steps: + # Unconditional and first, because the chip table below has to come from + # the tree this workflow file came from. + - uses: actions/checkout@v6 + - name: Resolve chip matrix id: chips + env: + REQUESTED_CHIPS: ${{ inputs.chips }} + PKG: ${{ inputs.package }} run: | - ALL_CHIPS='[ - {"soc":"esp32", "rust-target":"xtensa-esp32-none-elf", "runner":"esp32-jtag", "host":"aarch64"}, - {"soc":"esp32s2", "rust-target":"xtensa-esp32s2-none-elf", "runner":"esp32s2-jtag", "host":"aarch64"}, - {"soc":"esp32s3", "rust-target":"xtensa-esp32s3-none-elf", "runner":"esp32s3-usb", "host":"aarch64"}, - {"soc":"esp32c2", "rust-target":"riscv32imc-unknown-none-elf", "runner":"esp32c2-jtag", "host":"aarch64"}, - {"soc":"esp32c3", "rust-target":"riscv32imc-unknown-none-elf", "runner":"esp32c3-usb", "host":"aarch64"}, - {"soc":"esp32c5", "rust-target":"riscv32imac-unknown-none-elf", "runner":"esp32c5-usb", "host":"aarch64"}, - {"soc":"esp32c6", "rust-target":"riscv32imac-unknown-none-elf", "runner":"esp32c6-usb", "host":"aarch64"}, - {"soc":"esp32c61","rust-target":"riscv32imac-unknown-none-elf", "runner":"esp32c61-usb", "host":"aarch64"}, - {"soc":"esp32h2", "rust-target":"riscv32imac-unknown-none-elf", "runner":"esp32h2-usb", "host":"aarch64"}, - {"soc":"esp32p4", "rust-target":"riscv32imafc-unknown-none-elf","runner":"esp32p4", "host":"aarch64"}, - {"soc":"esp32s31","rust-target":"riscv32imafc-unknown-none-elf","runner":"esp32s31-jtag", "host":"aarch64"} - ]' - - # Chips that have a dedicated radio HIL runner. - RADIO_CHIPS='[ - {"soc":"esp32c6", "rust-target":"riscv32imac-unknown-none-elf", "runner":"esp32c6-radio", "host":"aarch64"}, - {"soc":"esp32s3", "rust-target":"xtensa-esp32s3-none-elf", "runner":"esp32s3-radio", "host":"aarch64"} - ]' - - REQUESTED="${{ inputs.chips }}" - MATRIX=$(echo "$ALL_CHIPS" | jq -c --arg chips "$REQUESTED" \ - '[.[] | select(.soc as $s | $chips | split(" ") | index($s))]') + REQUESTED="$REQUESTED_CHIPS" + # `all` saves callers from restating the chip list. Chips without a + # `hil-runner` have no board on the rack, so they stay out of the + # matrix: a null runner label would queue forever. + if [ "$REQUESTED" = "all" ]; then + REQUESTED=$(jq -r '[.[] | select(has("hil-runner")) | .soc] | join(" ")' \ + .github/chips.json) + echo "Expanded 'all' to: $REQUESTED" + fi + + MATRIX=$(jq -c --arg chips "$REQUESTED" ' + [ .[] + | select(has("hil-runner")) + | select(.soc as $s | $chips | split(" ") | index($s)) + | { soc, arch, runner: ."hil-runner" } ]' .github/chips.json) if [ "$(echo "$MATRIX" | jq 'length')" -eq 0 ]; then echo "::error::No valid chips selected from input: '$REQUESTED'" exit 1 fi - RADIO_MATRIX=$(echo "$RADIO_CHIPS" | jq -c --arg chips "$REQUESTED" \ - '[.[] | select(.soc as $s | $chips | split(" ") | index($s))]') + RADIO_MATRIX=$(jq -c --arg chips "$REQUESTED" ' + [ .[] + | select(has("hil-radio-runner")) + | select(.soc as $s | $chips | split(" ") | index($s)) + | { soc, runner: ."hil-radio-runner" } ]' .github/chips.json) - PKG="${{ inputs.package }}" # `package: hil-test` disables the radio HIL run entirely. if [ "$PKG" = "hil-test" ]; then RADIO_MATRIX='[]' fi - echo "matrix={\"target\":$(echo "$MATRIX" | jq -c .)}" >> "$GITHUB_OUTPUT" - echo "radio_matrix={\"target\":$(echo "$RADIO_MATRIX" | jq -c .)}" >> "$GITHUB_OUTPUT" - echo "Selected chips: $(echo "$MATRIX" | jq -r '.[].soc' | tr '\n' ' ')" - echo "Selected radio chips: $(echo "$RADIO_MATRIX" | jq -r '.[].soc' | tr '\n' ' ')" + echo "matrix={\"target\":$MATRIX}" >> "$GITHUB_OUTPUT" + echo "radio_matrix={\"target\":$RADIO_MATRIX}" >> "$GITHUB_OUTPUT" + # A plain flag for the hil-run-radio `if`, so that job condition does + # not have to string-match the serialized matrix. + echo "has_radio=$(echo "$RADIO_MATRIX" | jq -r 'length > 0')" >> "$GITHUB_OUTPUT" - - name: Determine required architectures - id: arch - run: | - NEED_XTENSA=false - NEED_RISCV=false - for chip in ${{ inputs.chips }}; do - case $chip in - esp32|esp32s2|esp32s3) NEED_XTENSA=true ;; - *) NEED_RISCV=true ;; - esac - done - echo "xtensa=$NEED_XTENSA" >> "$GITHUB_OUTPUT" - echo "riscv=$NEED_RISCV" >> "$GITHUB_OUTPUT" + # Which toolchains the build below needs. + echo "xtensa=$(echo "$MATRIX" | jq 'any(.[]; .arch == "xtensa")')" >> "$GITHUB_OUTPUT" + echo "riscv=$(echo "$MATRIX" | jq 'any(.[]; .arch == "riscv")')" >> "$GITHUB_OUTPUT" - - uses: actions/checkout@v6 - if: github.event_name != 'workflow_dispatch' - - uses: actions/checkout@v6 - if: github.event_name == 'workflow_dispatch' - with: - repository: ${{ github.event.inputs.repository }} - ref: ${{ github.event.inputs.branch }} + echo "Selected chips: $(echo "$MATRIX" | jq -r '.[].soc' | tr '\n' ' ')" + echo "Selected radio chips: $(echo "$RADIO_MATRIX" | jq -r '.[].soc' | tr '\n' ' ')" - - uses: esp-rs/xtensa-toolchain@v1.6 - if: steps.arch.outputs.xtensa == 'true' + # Xtensa before RISC-V, because dtolnay/rust-toolchain makes the toolchain + # it installs the rustup default. + - uses: ./.github/actions/setup-toolchains + if: steps.chips.outputs.xtensa == 'true' with: - buildtargets: esp32,esp32s2,esp32s3 - default: true - version: 1.97.0.0 + xtensa: "true" + xtensa-default: "true" - uses: ./.github/actions/setup-nightly - if: steps.arch.outputs.riscv == 'true' + if: steps.chips.outputs.riscv == 'true' with: - targets: riscv32imc-unknown-none-elf,riscv32imac-unknown-none-elf,riscv32imafc-unknown-none-elf + targets: all components: rust-src alias: "true" + # Only the code under test comes from the dispatched ref. The chip table + # and the toolchains above come from the tree this workflow came from. + - uses: actions/checkout@v6 + if: inputs.branch != '' + with: + repository: ${{ inputs.repository }} + ref: ${{ inputs.branch }} + # Build hil-test ELFs for each requested chip (unless the dispatch # asked for radio-only via package=hil-test-radio). - name: Build hil-test tests if: ${{ inputs.package != 'hil-test-radio' }} + env: + # The probe below only earns its keep on a dispatch, where the ref that + # got checked out may predate a chip its xtask never learned about. On + # the workflow_call path the tree and the chip list ship together, so + # every chip is by definition supported and probing is pure overhead. + PROBE_XTASK: ${{ inputs.branch != '' }} + MATRIX: ${{ steps.chips.outputs.matrix }} + TESTS: ${{ inputs.tests }} run: | - CHIPS=$(echo '${{ steps.chips.outputs.matrix }}' | jq -r '.target[].soc') - TESTS="${{ inputs.tests }}" + CHIPS=$(echo "$MATRIX" | jq -r '.target[].soc') for chip in $CHIPS; do - if ! cargo xtask build tests "$chip" --help >/dev/null 2>&1; then + # `build` accepts any chip token, `ci` rejects a chip this ref never learned. + if [ "$PROBE_XTASK" = "true" ] && \ + ! cargo xtask ci "$chip" --help >/dev/null 2>&1; then echo "Skipping $chip: not supported by this ref's xtask" continue fi if [ -n "$TESTS" ]; then echo "Building selected hil-test tests for $chip: $TESTS" - cargo xtask build tests "$chip" --tests "$TESTS" + cargo xtask build tests "$chip" --test "$TESTS" else echo "Building ALL hil-test tests for $chip" cargo xtask build tests "$chip" @@ -187,7 +205,9 @@ jobs: with: name: hil-tests path: target/tests/ - if-no-files-found: warn + # An unfiltered build must produce ELFs, so silence there is a real + # failure. A --tests filter legitimately matches nothing for a chip. + if-no-files-found: ${{ inputs.tests == '' && 'error' || 'warn' }} # Build hil-test-radio ELFs (unless the dispatch asked for hil-test # only). Chips for which the radio package has no applicable binaries @@ -198,16 +218,27 @@ jobs: - name: Build hil-test-radio tests if: ${{ inputs.package != 'hil-test' }} + env: + # Same reasoning as the hil-test build above: only a dispatch can + # land on a ref whose xtask predates a chip in the list. + PROBE_XTASK: ${{ inputs.branch != '' }} + MATRIX: ${{ steps.chips.outputs.matrix }} + TESTS: ${{ inputs.tests }} run: | - CHIPS=$(echo '${{ steps.chips.outputs.matrix }}' | jq -r '.target[].soc') - TESTS="${{ inputs.tests }}" + CHIPS=$(echo "$MATRIX" | jq -r '.target[].soc') for chip in $CHIPS; do + # See the hil-test build above for why the probe uses `ci`. + if [ "$PROBE_XTASK" = "true" ] && \ + ! cargo xtask ci "$chip" --help >/dev/null 2>&1; then + echo "Skipping $chip: not supported by this ref's xtask" + continue + fi if [ -n "$TESTS" ]; then echo "Building selected hil-test-radio tests for $chip: $TESTS" - cargo xtask build tests "$chip" hil-test-radio --tests "$TESTS" + cargo xtask build hil-test-radio "$chip" --test "$TESTS" else echo "Building ALL hil-test-radio tests for $chip" - cargo xtask build tests "$chip" hil-test-radio + cargo xtask build hil-test-radio "$chip" fi done @@ -223,12 +254,23 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v6 - if: github.event_name != 'workflow_dispatch' + if: inputs.branch == '' - uses: actions/checkout@v6 - if: github.event_name == 'workflow_dispatch' + if: inputs.branch != '' + with: + repository: ${{ inputs.repository }} + ref: ${{ inputs.branch }} + + - name: Cache Dependencies + uses: Swatinem/rust-cache@v2 with: - repository: ${{ github.event.inputs.repository }} - ref: ${{ github.event.inputs.branch }} + # Restore everywhere, but only the dispatch path is worth saving + # from: it runs on the default branch ref, so the entry lands in the + # base-branch scope every later run can read. The workflow_call path + # runs under merge_group, whose ephemeral ref nothing can restore + # from. `cross` mounts $CARGO_HOME, so a warm registry does speed up + # the cross build whenever the esp-devtool binary cache misses. + save-if: ${{ inputs.branch != '' }} # xtask runs on the AArch64 HIL runners as a host tool. # We build the actual tests separately using the correct toolchain. @@ -264,9 +306,13 @@ jobs: path: target/aarch64-unknown-linux-gnu/release/esp-devtool if-no-files-found: error - hil: + hil-run: needs: [build, devtool] if: ${{ inputs.package != 'hil-test-radio' }} + # When called from ci.yml, hil-gate below decides the verdict from the ≥50% + # rule, so a single flaky runner must not fail the run and with it the + # caller's job. + continue-on-error: ${{ inputs.branch == '' }} runs-on: labels: [self-hosted, "${{ matrix.target.runner }}"] strategy: @@ -281,7 +327,7 @@ jobs: - uses: actions/download-artifact@v4 with: - name: xtask-${{ matrix.target.host }} + name: xtask-aarch64 - name: Skip if this target wasn't built id: guard @@ -291,26 +337,26 @@ jobs: echo "No tests for ${{ matrix.target.soc }} in this run; skipping." fi - - name: Compute tests arg - if: steps.guard.outputs.skip != 'true' - id: tests - run: | - if [ -n "${{ inputs.tests }}" ]; then - echo "value=--filter ${{ inputs.tests }}" >> $GITHUB_OUTPUT - else - echo "value=" >> $GITHUB_OUTPUT - fi - - name: Run Tests if: steps.guard.outputs.skip != 'true' id: run-tests + env: + SOC: ${{ matrix.target.soc }} + TESTS: ${{ inputs.tests }} run: | [ -f ~/setup.sh ] && source ~/setup.sh export PATH=$PATH:/home/espressif/.cargo/bin chmod +x esp-devtool - ./esp-devtool run elfs ${{ matrix.target.soc }} tests/${{ matrix.target.soc }} ${{ steps.tests.outputs.value }} + # An array keeps the flag off the command line entirely when no + # filter was asked for, without word-splitting the value itself. + FILTER=() + if [ -n "$TESTS" ]; then + FILTER=(--filter "$TESTS") + fi + + ./esp-devtool elfs "$SOC" "tests/$SOC" "${FILTER[@]}" - name: Clean up if: always() @@ -321,11 +367,12 @@ jobs: # Radio HIL device runs (hil-test-radio) — wifi/BT capable chips on dedicated # radio runners. The matrix is empty when no requested chip has a radio # runner, which causes this job to be skipped entirely. - hil-radio: + hil-run-radio: needs: [build, devtool] if: > inputs.package != 'hil-test' && - needs.build.outputs.radio_matrix != '{"target":[]}' + needs.build.outputs.has_radio == 'true' + continue-on-error: ${{ inputs.branch == '' }} runs-on: labels: [self-hosted, "${{ matrix.target.runner }}"] strategy: @@ -340,7 +387,7 @@ jobs: - uses: actions/download-artifact@v4 with: - name: xtask-${{ matrix.target.host }} + name: xtask-aarch64 - name: Skip if this target wasn't built id: guard @@ -350,16 +397,6 @@ jobs: echo "No radio tests for ${{ matrix.target.soc }} in this run; skipping." fi - - name: Compute tests arg - if: steps.guard.outputs.skip != 'true' - id: tests - run: | - if [ -n "${{ inputs.tests }}" ]; then - echo "value=--filter ${{ inputs.tests }}" >> $GITHUB_OUTPUT - else - echo "value=" >> $GITHUB_OUTPUT - fi - - name: Reset ESP USB-JTAG devices if: steps.guard.outputs.skip != 'true' timeout-minutes: 1 @@ -398,15 +435,79 @@ jobs: if: steps.guard.outputs.skip != 'true' id: run-tests timeout-minutes: 3 + env: + SOC: ${{ matrix.target.soc }} + TESTS: ${{ inputs.tests }} run: | [ -f ~/setup.sh ] && source ~/setup.sh export PATH=$PATH:/home/espressif/.cargo/bin chmod +x esp-devtool - ./esp-devtool run elfs ${{ matrix.target.soc }} tests/${{ matrix.target.soc }} ${{ steps.tests.outputs.value }} + + FILTER=() + if [ -n "$TESTS" ]; then + FILTER=(--filter "$TESTS") + fi + + ./esp-devtool elfs "$SOC" "tests/$SOC" "${FILTER[@]}" - name: Clean up if: always() run: | rm -rf tests/ || true rm -f esp-devtool || true + + # Merge gate for hil-run matrix legs. Blocks when ≥50% of legs that actually + # ran tests failed or were cancelled. Skipped legs (no ELFs for that chip) + # are excluded. hil-run-radio is not part of this gate. + hil-gate: + needs: [build, hil-run] + if: > + always() && + inputs.branch == '' && + needs.build.result == 'success' && + needs.hil-run.result != 'skipped' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 1 + + - name: Evaluate hil-run results + uses: actions/github-script@v7 + with: + script: | + const { evaluateHilGate } = require('./.github/scripts/hil-gate.js'); + await evaluateHilGate({ github, context, core }); + + # The dispatcher cannot report the verdict: a run it starts with GITHUB_TOKEN + # raises no workflow_run event. Reporting from inside the run also covers + # re-runs, which re-run this job along with the legs it depends on. + report: + needs: [build, devtool, hil-run, hil-run-radio] + # `always()` rather than `!cancelled()`: a cancelled run must still report + # its verdict. + if: always() && inputs.pr_number != '' + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + contents: read + pull-requests: write + steps: + - uses: actions/checkout@v6 # for `require` + with: + fetch-depth: 1 + + - name: Update HIL status comment + uses: actions/github-script@v7 + with: + script: | + const { updateRunStatus, runConclusion } = require('./.github/scripts/hil-status.js'); + + await updateRunStatus({ + github, + context, + core, + pr: Number('${{ inputs.pr_number }}'), + conclusion: runConclusion(${{ toJSON(needs.*.result) }}), + }); diff --git a/.github/workflows/issue-handler.yml b/.github/workflows/issue-handler.yml index b846239435a..e55160ac48c 100644 --- a/.github/workflows/issue-handler.yml +++ b/.github/workflows/issue-handler.yml @@ -21,13 +21,14 @@ jobs: [/low power/i, "Area: low power"], [/\bbug\b/i, "bug"], - [/\besp32(?![-_ ]?(?:c2|c3|c5|c6|c61|h2|p4|s2|s3|s31)\b)\b/i, "chip:esp32"], + [/\besp32(?![-_ ]?(?:c2|c3|c5|c6|c61|h2|h4|p4|s2|s3|s31)\b)\b/i, "chip:esp32"], [/\besp32[-_ ]?c2\b/i, "chip:esp32c2"], [/\besp32[-_ ]?c3\b/i, "chip:esp32c3"], [/\besp32[-_ ]?c5\b/i, "chip:esp32c5"], [/\besp32[-_ ]?c6\b/i, "chip:esp32c6"], [/\besp32[-_ ]?c61\b/i, "chip:esp32c61"], [/\besp32[-_ ]?h2\b/i, "chip:esp32h2"], + [/\besp32[-_ ]?h4\b/i, "chip:esp32h4"], [/\besp32[-_ ]?p4\b/i, "chip:esp32p4"], [/\besp32[-_ ]?s2\b/i, "chip:esp32s2"], [/\besp32[-_ ]?s3\b/i, "chip:esp32s3"], diff --git a/.github/workflows/merge-freeze-audit.yml b/.github/workflows/merge-freeze-audit.yml new file mode 100644 index 00000000000..a669c607994 --- /dev/null +++ b/.github/workflows/merge-freeze-audit.yml @@ -0,0 +1,34 @@ +# Records on the freeze issue what was merged during a freeze. +# +# The gate itself cannot do this, it runs before the rest of CI, so a later +# failure would leave "merged" on the freeze issue for something that never was. + +name: Merge freeze audit + +on: + pull_request_target: + types: [closed] + +permissions: + contents: read + issues: write + +jobs: + record: + if: >- + github.event.pull_request.merged == true && + contains(github.event.pull_request.labels.*.name, 'merge-freeze-exempt') + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@v6 + with: + ref: ${{ github.event.pull_request.base.ref }} + sparse-checkout: .github/scripts + persist-credentials: false + + - uses: actions/github-script@v8 + with: + script: | + const { recordExemptMerge } = require('./.github/scripts/merge-freeze.js'); + await recordExemptMerge({ github, context, core }); diff --git a/.github/workflows/pre-rel-check.yml b/.github/workflows/pre-rel-check.yml index 01227bbfb7e..e3708f5f3f7 100644 --- a/.github/workflows/pre-rel-check.yml +++ b/.github/workflows/pre-rel-check.yml @@ -2,6 +2,11 @@ # # We want to check if we can compile examples/tests after bumping the deps by using a local registry. # (i.e. if we will publish the right set of crates) +# +# The compile-test build runs on every release PR; xtask derives its project-by-chip matrix from +# each project's metadata. The heavier examples/qa/tests build runs by default (skipped by the +# `release:registry:skip-ci` label) and loops the chips in `.github/chips.json`, the same source +# the main CI uses. name: pre-release-checks @@ -17,27 +22,23 @@ env: jobs: check: runs-on: macos-m1-self-hosted - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && (contains(github.event.pull_request.labels.*.name, 'release:registry:compile-test') || contains(github.event.pull_request.labels.*.name, 'release:registry:ci'))) }} + # Only release PRs (branched as `release-branch-*` by `execute-plan`) carry a + # plan, so ordinary PRs never run this. `xrel-check` bails if the plan is + # missing. + if: ${{ github.event_name == 'workflow_dispatch' || startsWith(github.head_ref, 'release-branch-') }} steps: - uses: actions/checkout@v6 - # Install the Rust toolchain for Xtensa devices: - - uses: esp-rs/xtensa-toolchain@v1.6 - with: - version: 1.97.0.0 - - # Install the Rust stable toolchain for RISC-V devices: - - uses: dtolnay/rust-toolchain@v1 + - uses: ./.github/actions/setup-toolchains with: - target: riscv32imc-unknown-none-elf,riscv32imac-unknown-none-elf,riscv32imafc-unknown-none-elf - toolchain: stable - components: rust-src + xtensa: "true" + riscv: "true" # Install the Rust nightly toolchain for RISC-V devices: - uses: ./.github/actions/setup-nightly with: - targets: riscv32imc-unknown-none-elf,riscv32imac-unknown-none-elf,riscv32imafc-unknown-none-elf + targets: all components: rust-src alias: "true" @@ -60,40 +61,23 @@ jobs: cargo xrel-check update cargo xrel-check replace-path-deps - # Build the compile-tests against the local registry. This is the cheap smoke - # test, so it runs first. Gated on `release:registry:compile-test` so it can be - # run independently of the heavier CI build. + # Build the compile-tests against the local registry. xtask derives the + # project-by-chip matrix from each project's metadata (and the toolchain + # per chip), so there is no fixed chip set to keep in sync here. - name: try-build [compile-tests] - if: ${{ github.event_name == 'workflow_dispatch' || contains(github.event.pull_request.labels.*.name, 'release:registry:compile-test') }} - shell: bash - run: | - cargo xtask build examples --toolchain esp --package=compile-tests all --chip=esp32 - cargo xtask build examples --toolchain esp --package=compile-tests all --chip=esp32s2 - cargo xtask build examples --toolchain esp --package=compile-tests all --chip=esp32s3 - cargo xtask build examples --toolchain stable --package=compile-tests all --chip=esp32s31 - cargo xtask build examples --toolchain stable --package=compile-tests all --chip=esp32c2 - cargo xtask build examples --toolchain stable --package=compile-tests all --chip=esp32c3 - cargo xtask build examples --toolchain stable --package=compile-tests all --chip=esp32c5 - cargo xtask build examples --toolchain stable --package=compile-tests all --chip=esp32c6 - cargo xtask build examples --toolchain stable --package=compile-tests all --chip=esp32c61 - cargo xtask build examples --toolchain stable --package=compile-tests all --chip=esp32p4 - cargo xtask build examples --toolchain stable --package=compile-tests all --chip=esp32h2 + run: cargo xtask build compile-tests - # Build the examples/qa-test/tests against the local registry. Gated on - # `release:registry:ci` so a release can opt out of this heavy check. - - name: try-build [examples/qa-test/tests] - if: ${{ github.event_name == 'workflow_dispatch' || contains(github.event.pull_request.labels.*.name, 'release:registry:ci') }} + # Build the examples/qa/tests against the local registry. Runs by default; + # add `release:registry:skip-ci` to the PR to opt out of this heavy check. + - name: try-build [examples/qa/tests] + if: ${{ !contains(github.event.pull_request.labels.*.name, 'release:registry:skip-ci') }} shell: bash run: | # lints and docs are checked a couple of times already by other workflows - cargo xcheck ci esp32 --toolchain esp --steps=lp-examples,examples,qa-test,tests - cargo xcheck ci esp32s2 --toolchain esp --steps=lp-examples,examples,qa-test,tests - cargo xcheck ci esp32s3 --toolchain esp --steps=lp-examples,examples,qa-test,tests - cargo xcheck ci esp32s31 --toolchain stable --steps=lp-examples,examples,qa-test,tests - cargo xcheck ci esp32c2 --toolchain stable --steps=lp-examples,examples,qa-test,tests - cargo xcheck ci esp32c3 --toolchain stable --steps=lp-examples,examples,qa-test,tests - cargo xcheck ci esp32c5 --toolchain stable --steps=lp-examples,examples,qa-test,tests - cargo xcheck ci esp32c6 --toolchain stable --steps=lp-examples,examples,qa-test,tests - cargo xcheck ci esp32c61 --toolchain stable --steps=lp-examples,examples,qa-test,tests - cargo xcheck ci esp32p4 --toolchain stable --steps=lp-examples,examples,qa-test,tests - cargo xcheck ci esp32h2 --toolchain stable --steps=lp-examples,examples,qa-test,tests + for soc in $(jq -r '.[].soc' .github/chips.json); do + toolchain=$(jq -r --arg s "$soc" \ + '.[] | select(.soc == $s) | ."ci-toolchain"' .github/chips.json) + echo "::group::examples/qa/tests $soc ($toolchain)" + cargo xcheck ci "$soc" --toolchain "$toolchain" --steps=lp-examples,examples,qa-test,tests + echo "::endgroup::" + done diff --git a/.lycheeignore b/.lycheeignore index 769a2c8212d..a0ecc12c087 100644 --- a/.lycheeignore +++ b/.lycheeignore @@ -21,3 +21,6 @@ img\.shields\.io/badge/MSRV- # Ignore sites that may not tolerate us spamming them http://httpbin\.org/ https://stackoverflow\.com/ + +# Unreleased documentation +^https://www\.espressif\.com/sites/default/files/documentation/esp32-h4_(datasheet|technical_reference_manual)_en\.pdf$ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000000..2afaf87b579 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,50 @@ +# AGENTS.md + +esp-hal is a monorepo of bare-metal `no_std` Rust crates for Espressif chips. Each top-level crate +directory is its own Cargo project, and most have a README. The root workspace only holds the +`xtask` tooling, and all building, linting and testing goes through `cargo xtask`. + +This file is an index. Read a linked document when your current step needs it, not at the start of a +task. + +## Where to look + +| Task | Read | +| --- | --- | +| Any code change: API design, drivers, cfg symbols, metadata | `documentation/DEVELOPER-GUIDELINES.md` | +| Rustdoc | `documentation/API-DOC-RULES.md` | +| xtask commands, `//%` annotations in examples and tests, host tests | `xtask/README.md` | +| Opening a PR or asking for review: expectations, description, changelog | `documentation/PULL-REQUESTS.md` | +| Writing an issue | `documentation/CONTRIBUTING.md`, `documentation/REPRODUCERS.md` | +| Examples | `examples/README.md` | +| HIL tests | `hil-test/README.md`, `documentation/HIL-GUIDE.md` | +| Log output from HIL tests (off by default) | `hil-test/README.md`, "Logging in tests" | +| Build-time configuration (`esp_config.yml`) | `esp-config/README.md` | +| New chip bring-up | `documentation/CHIP_BRING_UP.md` | +| Releases | `documentation/RELEASING.md` | +| Chip list and Rust targets | `.github/chips.json` | +| Per-chip hardware description | `esp-metadata/devices/` | + +## Rules + +- When the change works, and before you open a PR or ask for review, read + `documentation/PULL-REQUESTS.md` and apply it. +- Never edit a `CHANGELOG.md` file, even though crates ship one. They are updated from PR + descriptions at the end of the release cycle. Put changelog and migration entries in the PR body. +- Never edit `esp-metadata-generated/`. Make metadata changes in `esp-metadata/`, run + `cargo update-metadata`, and commit both. +- Library crates never enable `unstable`, they use `requires-unstable`. Features starting with `__` + are for this repo's crates only, never for examples, tests or users. +- Xtensa chips (`esp32`, `esp32s2`, `esp32s3`) need the `esp` toolchain. xtask picks it + automatically, plain `cargo` needs `+esp`. +- Do not open GitHub issues on your own. + +## Editing this file + +Every agent loads this file on every task, so each line costs every run. + +- Add a line only if agents get something wrong without it and the index cannot lead them to the + answer. One-off lessons from a single task do not qualify. +- Put detail in the linked document, never here. If no document fits, point a new row at a new one. +- Keep this file under 80 lines. To add something, first remove or shorten something else. +- Delete lines that go stale instead of rewording them. diff --git a/Cargo.toml b/Cargo.toml index 278692b44f1..80101437f11 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,7 +26,6 @@ exclude = [ "extras/ieee802154-sniffer", "hil-test", "hil-test-radio", - "qa-test", "xtensa-lx", "xtensa-lx-rt", "xtensa-lx-rt-proc-macros", diff --git a/README.md b/README.md index 29dbf8e2f70..236f0bb82bd 100644 --- a/README.md +++ b/README.md @@ -72,18 +72,7 @@ Using the [`~` operator](https://doc.rust-lang.org/cargo/reference/specifying-de ## Release policy -We follow a few general guidelines regarding releases: - -- Releases happen organically alongside development rather than on a fixed schedule. The table below outlines our general approach to each release type and when one might be cut. -- During the `rc` phase of a release: - - We aim to leave them in the wild for testing for at least one week per release. - - If a considerable change (like a new addition) is added, we must extend the `rc` by at least another release. - -| Release Type | Cadence | Pre-release Requirement | -| ------------ | ---------- | ----------------------------------------------- | -| Patch | Frequent | None | -| Minor | Periodic | `rc` release required | -| Major | Infrequent | Full pre-release cycle (`alpha` may be skipped) | +For how releases are prepared, staged as release candidates, and published, see [RELEASING.md](https://github.com/esp-rs/esp-hal/blob/main/documentation/RELEASING.md). ## AI Contribution Policy diff --git a/compile-tests/README.md b/compile-tests/README.md index 0ff11a87ea0..b253649f9cf 100644 --- a/compile-tests/README.md +++ b/compile-tests/README.md @@ -2,7 +2,8 @@ The projects here are using fixed versions and are meant to make sure that an upcoming release won't break existing code. -The dependencies' version numbers are bumped manually when needed / wanted. -(e.g. only stable releases - no release-candidates etc.) +The `hal` project's pins track the current lines and are rewritten when those +crates are released. Frozen `ble_*` / `wifi_*` projects stay on the minor they +were snapshotted at; bump those by hand when you want a new frozen line. Make sure to never check-in `Cargo.lock` files here. diff --git a/compile-tests/ble_1-0/Cargo.toml b/compile-tests/ble_1-0/Cargo.toml index ff6b004810b..c584bc8f78e 100644 --- a/compile-tests/ble_1-0/Cargo.toml +++ b/compile-tests/ble_1-0/Cargo.toml @@ -15,7 +15,8 @@ esp-backtrace = { version = "0.18.0", features = [ "println", ] } esp-bootloader-esp-idf = { version = "0.4.0" } -esp-hal = { version = "1.0.0", features = ["log-04", "unstable"] } +# esp-radio 0.17 accepts any esp-hal 1.x; without `~` cargo resolves the newest and this line goes untested. +esp-hal = { version = "~1.0.0", features = ["log-04", "unstable"] } esp-println = { version = "0.16.0", features = ["log-04"] } esp-rtos = { version = "0.2.0", features = ["esp-radio", "embassy", "log-04"] } esp-radio = { version = "0.17.0", features = [ @@ -31,50 +32,6 @@ trouble-host = { version = "0.5.0", features = [ ] } static_cell = "2.1.1" -[features] -esp32 = [ - "esp-backtrace/esp32", - "esp-bootloader-esp-idf/esp32", - "esp-hal/esp32", - "esp-rtos/esp32", - "esp-radio/esp32", -] -esp32c2 = [ - "esp-backtrace/esp32c2", - "esp-bootloader-esp-idf/esp32c2", - "esp-hal/esp32c2", - "esp-rtos/esp32c2", - "esp-radio/esp32c2", -] -esp32c3 = [ - "esp-backtrace/esp32c3", - "esp-bootloader-esp-idf/esp32c3", - "esp-hal/esp32c3", - "esp-rtos/esp32c3", - "esp-radio/esp32c3", -] -esp32c6 = [ - "esp-backtrace/esp32c6", - "esp-bootloader-esp-idf/esp32c6", - "esp-hal/esp32c6", - "esp-rtos/esp32c6", - "esp-radio/esp32c6", -] -esp32h2 = [ - "esp-backtrace/esp32h2", - "esp-bootloader-esp-idf/esp32h2", - "esp-hal/esp32h2", - "esp-rtos/esp32h2", - "esp-radio/esp32h2", -] -esp32s3 = [ - "esp-backtrace/esp32s3", - "esp-bootloader-esp-idf/esp32s3", - "esp-hal/esp32s3", - "esp-rtos/esp32s3", - "esp-radio/esp32s3", -] - [profile.release] debug = true debug-assertions = true diff --git a/compile-tests/ble_1-0/src/main.rs b/compile-tests/ble_1-0/src/main.rs index 60d4fc6f380..5f3bbfcaf3b 100644 --- a/compile-tests/ble_1-0/src/main.rs +++ b/compile-tests/ble_1-0/src/main.rs @@ -3,6 +3,8 @@ #![no_std] #![no_main] +//% CHIP_FILTER: bt_driver_supported + use embassy_executor::Spawner; use embassy_futures::{join::join, select::select}; use embassy_time::Timer; diff --git a/compile-tests/ble_1-1/Cargo.toml b/compile-tests/ble_1-1/Cargo.toml index 7c575755343..ed45632cc89 100644 --- a/compile-tests/ble_1-1/Cargo.toml +++ b/compile-tests/ble_1-1/Cargo.toml @@ -15,7 +15,8 @@ esp-backtrace = { version = "0.19.0", features = [ "println", ] } esp-bootloader-esp-idf = { version = "0.5.0" } -esp-hal = { version = "1.1.0", features = ["log-04", "unstable"] } +# `~` keeps this project on the 1.1 line it was frozen at, whatever esp-radio accepts. +esp-hal = { version = "~1.1.0", features = ["log-04", "unstable"] } esp-println = { version = "0.17.0", features = ["log-04"] } esp-rtos = { version = "0.3.0", features = ["esp-radio", "embassy", "log-04"] } esp-radio = { version = "0.18.0", features = [ @@ -31,64 +32,6 @@ trouble-host = { version = "0.6.0", features = [ ] } static_cell = "2.1.1" -[features] -esp32 = [ - "esp-backtrace/esp32", - "esp-bootloader-esp-idf/esp32", - "esp-hal/esp32", - "esp-rtos/esp32", - "esp-radio/esp32", -] -esp32c2 = [ - "esp-backtrace/esp32c2", - "esp-bootloader-esp-idf/esp32c2", - "esp-hal/esp32c2", - "esp-rtos/esp32c2", - "esp-radio/esp32c2", -] -esp32c3 = [ - "esp-backtrace/esp32c3", - "esp-bootloader-esp-idf/esp32c3", - "esp-hal/esp32c3", - "esp-rtos/esp32c3", - "esp-radio/esp32c3", -] -esp32c5 = [ - "esp-backtrace/esp32c5", - "esp-bootloader-esp-idf/esp32c5", - "esp-hal/esp32c5", - "esp-rtos/esp32c5", - "esp-radio/esp32c5", -] -esp32c6 = [ - "esp-backtrace/esp32c6", - "esp-bootloader-esp-idf/esp32c6", - "esp-hal/esp32c6", - "esp-rtos/esp32c6", - "esp-radio/esp32c6", -] -esp32c61 = [ - "esp-backtrace/esp32c61", - "esp-bootloader-esp-idf/esp32c61", - "esp-hal/esp32c61", - "esp-rtos/esp32c61", - "esp-radio/esp32c61", -] -esp32h2 = [ - "esp-backtrace/esp32h2", - "esp-bootloader-esp-idf/esp32h2", - "esp-hal/esp32h2", - "esp-rtos/esp32h2", - "esp-radio/esp32h2", -] -esp32s3 = [ - "esp-backtrace/esp32s3", - "esp-bootloader-esp-idf/esp32s3", - "esp-hal/esp32s3", - "esp-rtos/esp32s3", - "esp-radio/esp32s3", -] - [profile.release] debug = true debug-assertions = true diff --git a/compile-tests/ble_1-1/src/main.rs b/compile-tests/ble_1-1/src/main.rs index f41d4f852f0..d0e711ede21 100644 --- a/compile-tests/ble_1-1/src/main.rs +++ b/compile-tests/ble_1-1/src/main.rs @@ -3,6 +3,8 @@ #![no_std] #![no_main] +//% CHIP_FILTER: bt_driver_supported + use embassy_executor::Spawner; use embassy_futures::{join::join, select::select}; use embassy_time::Timer; diff --git a/compile-tests/hal/.cargo/config.toml b/compile-tests/hal/.cargo/config.toml new file mode 100644 index 00000000000..44dacc4278b --- /dev/null +++ b/compile-tests/hal/.cargo/config.toml @@ -0,0 +1,24 @@ +[target.'cfg(target_arch = "riscv32")'] +runner = "espflash flash --monitor" +rustflags = [ + "-C", "link-arg=-Tlinkall.x", + "-C", "force-frame-pointers", +] + +[target.'cfg(target_arch = "xtensa")'] +runner = "espflash flash --monitor" +rustflags = [ + # GNU LD + "-C", "link-arg=-Wl,-Tlinkall.x", + "-C", "link-arg=-nostartfiles", + + # LLD + # "-C", "link-arg=-Tlinkall.x", + # "-C", "linker=rust-lld", +] + +[env] +ESP_LOG = "info" + +[unstable] +build-std = ["core", "alloc"] diff --git a/compile-tests/hal/Cargo.toml b/compile-tests/hal/Cargo.toml new file mode 100644 index 00000000000..44c95fc55a1 --- /dev/null +++ b/compile-tests/hal/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "hal" +version = "0.0.0" +edition = "2024" +publish = false + +# Pins track the current lines. bump_crate_version rewrites this file only; +# ble_*/wifi_* stay on the minor they were frozen at. +[dependencies] +esp-hal = { version = "1.2" } +esp-backtrace = { version = "0.20", features = [ + "panic-handler", + "println", +] } +esp-bootloader-esp-idf = { version = "0.6" } +esp-println = { version = "0.18" } + +[profile.release] +debug = true +debug-assertions = true +lto = "fat" +codegen-units = 1 + +[package.metadata.cargo-machete] +# esp-println is pulled in only as esp-backtrace's print backend. +ignored = ["esp-println"] diff --git a/compile-tests/hal/src/main.rs b/compile-tests/hal/src/main.rs new file mode 100644 index 00000000000..10505945df9 --- /dev/null +++ b/compile-tests/hal/src/main.rs @@ -0,0 +1,20 @@ +//! Minimal esp-hal program. Exists so that every chip is covered by at least one +//! compile-test project, including chips no radio project selects. + +#![no_std] +#![no_main] + +//% CHIP_FILTER: true + +use esp_backtrace as _; +use esp_hal::main; +use esp_println as _; + +esp_bootloader_esp_idf::esp_app_desc!(); + +#[main] +fn main() -> ! { + let _peripherals = esp_hal::init(esp_hal::Config::default()); + + loop {} +} diff --git a/compile-tests/wifi_1-0/Cargo.toml b/compile-tests/wifi_1-0/Cargo.toml index 21eca6420b3..d6316c4c773 100644 --- a/compile-tests/wifi_1-0/Cargo.toml +++ b/compile-tests/wifi_1-0/Cargo.toml @@ -21,7 +21,8 @@ esp-backtrace = { version = "0.18.0", features = [ "println", ] } esp-bootloader-esp-idf = { version = "0.4.0" } -esp-hal = { version = "1.0.0" , features = ["log-04", "unstable"] } +# esp-radio 0.17 accepts any esp-hal 1.x; without `~` cargo resolves the newest and this line goes untested. +esp-hal = { version = "~1.0.0" , features = ["log-04", "unstable"] } esp-println = { version = "0.16.0", features = ["log-04"] } esp-rtos = { version = "0.2.0", features = ["esp-radio", "embassy", "log-04"] } esp-radio = { version = "0.17.0", features = [ @@ -31,50 +32,6 @@ esp-radio = { version = "0.17.0", features = [ reqwless = { version = "0.14.0", default-features = false } static_cell = "2.1.0" -[features] -esp32 = [ - "esp-backtrace/esp32", - "esp-bootloader-esp-idf/esp32", - "esp-hal/esp32", - "esp-rtos/esp32", - "esp-radio/esp32", -] -esp32c2 = [ - "esp-backtrace/esp32c2", - "esp-bootloader-esp-idf/esp32c2", - "esp-hal/esp32c2", - "esp-rtos/esp32c2", - "esp-radio/esp32c2", -] -esp32c3 = [ - "esp-backtrace/esp32c3", - "esp-bootloader-esp-idf/esp32c3", - "esp-hal/esp32c3", - "esp-rtos/esp32c3", - "esp-radio/esp32c3", -] -esp32c6 = [ - "esp-backtrace/esp32c6", - "esp-bootloader-esp-idf/esp32c6", - "esp-hal/esp32c6", - "esp-rtos/esp32c6", - "esp-radio/esp32c6", -] -esp32s2 = [ - "esp-backtrace/esp32s2", - "esp-bootloader-esp-idf/esp32s2", - "esp-hal/esp32s2", - "esp-rtos/esp32s2", - "esp-radio/esp32s2", -] -esp32s3 = [ - "esp-backtrace/esp32s3", - "esp-bootloader-esp-idf/esp32s3", - "esp-hal/esp32s3", - "esp-rtos/esp32s3", - "esp-radio/esp32s3", -] - [profile.release] debug = true debug-assertions = true diff --git a/compile-tests/wifi_1-0/src/main.rs b/compile-tests/wifi_1-0/src/main.rs index 701a45a84ec..3de04dd812f 100644 --- a/compile-tests/wifi_1-0/src/main.rs +++ b/compile-tests/wifi_1-0/src/main.rs @@ -1,6 +1,8 @@ #![no_std] #![no_main] +//% CHIP_FILTER: wifi_driver_supported + use core::net::Ipv4Addr; use embassy_executor::Spawner; diff --git a/compile-tests/wifi_1-1/Cargo.toml b/compile-tests/wifi_1-1/Cargo.toml index 9c0f5feb62a..fbdaa5fc0db 100644 --- a/compile-tests/wifi_1-1/Cargo.toml +++ b/compile-tests/wifi_1-1/Cargo.toml @@ -21,7 +21,8 @@ esp-backtrace = { version = "0.19.0", features = [ "println", ] } esp-bootloader-esp-idf = { version = "0.5.0" } -esp-hal = { version = "1.1.0" , features = ["log-04", "unstable"] } +# `~` keeps this project on the 1.1 line it was frozen at, whatever esp-radio accepts. +esp-hal = { version = "~1.1.0" , features = ["log-04", "unstable"] } esp-println = { version = "0.17.0", features = ["log-04"] } esp-rtos = { version = "0.3.0", features = ["esp-radio", "embassy", "log-04"] } esp-radio = { version = "0.18.0", features = [ @@ -31,64 +32,6 @@ esp-radio = { version = "0.18.0", features = [ reqwless = { version = "0.14.0", default-features = false } static_cell = "2.1.0" -[features] -esp32 = [ - "esp-backtrace/esp32", - "esp-bootloader-esp-idf/esp32", - "esp-hal/esp32", - "esp-rtos/esp32", - "esp-radio/esp32", -] -esp32c2 = [ - "esp-backtrace/esp32c2", - "esp-bootloader-esp-idf/esp32c2", - "esp-hal/esp32c2", - "esp-rtos/esp32c2", - "esp-radio/esp32c2", -] -esp32c3 = [ - "esp-backtrace/esp32c3", - "esp-bootloader-esp-idf/esp32c3", - "esp-hal/esp32c3", - "esp-rtos/esp32c3", - "esp-radio/esp32c3", -] -esp32c5 = [ - "esp-backtrace/esp32c5", - "esp-bootloader-esp-idf/esp32c5", - "esp-hal/esp32c5", - "esp-rtos/esp32c5", - "esp-radio/esp32c5", -] -esp32c6 = [ - "esp-backtrace/esp32c6", - "esp-bootloader-esp-idf/esp32c6", - "esp-hal/esp32c6", - "esp-rtos/esp32c6", - "esp-radio/esp32c6", -] -esp32c61 = [ - "esp-backtrace/esp32c61", - "esp-bootloader-esp-idf/esp32c61", - "esp-hal/esp32c61", - "esp-rtos/esp32c61", - "esp-radio/esp32c61", -] -esp32s2 = [ - "esp-backtrace/esp32s2", - "esp-bootloader-esp-idf/esp32s2", - "esp-hal/esp32s2", - "esp-rtos/esp32s2", - "esp-radio/esp32s2", -] -esp32s3 = [ - "esp-backtrace/esp32s3", - "esp-bootloader-esp-idf/esp32s3", - "esp-hal/esp32s3", - "esp-rtos/esp32s3", - "esp-radio/esp32s3", -] - [profile.release] debug = true debug-assertions = true diff --git a/compile-tests/wifi_1-1/src/main.rs b/compile-tests/wifi_1-1/src/main.rs index 0f0b13d7a90..8110819994b 100644 --- a/compile-tests/wifi_1-1/src/main.rs +++ b/compile-tests/wifi_1-1/src/main.rs @@ -1,6 +1,8 @@ #![no_std] #![no_main] +//% CHIP_FILTER: wifi_driver_supported + use embassy_executor::Spawner; use embassy_net::{ Runner, diff --git a/documentation/API-DOC-RULES.md b/documentation/API-DOC-RULES.md index 14d2cd62c2e..d9ca5dc8ff7 100644 --- a/documentation/API-DOC-RULES.md +++ b/documentation/API-DOC-RULES.md @@ -49,7 +49,7 @@ After any bulk doc pass: - typos: `Fow `, `Finishes of`, British spellings (`behaviour`, `whilst`, `initialised`) - empty sections: `# Examples` / `# Errors` / `# Panics` / `# Safety` / `# Cancellation Safety` immediately followed by the next item or another `#` heading with no body - stray characters: unexpected non-ASCII in `///` / `//!` lines (e.g. `ç`, `Ã`, mojibake), or a letter immediately after a sentence-ending `.` (`level.ç`, `pin.x`) -3. Run `cargo xtask build documentation --packages=esp-hal --chips=` (esp-hal denies `rustdoc::all` warnings). +3. Run `cargo xtask documentation --packages=esp-hal ` (esp-hal denies `rustdoc::all` warnings). ## Simplified Technical English (ASD-STE100) diff --git a/documentation/CONTRIBUTING.md b/documentation/CONTRIBUTING.md index 8aa6a4d0cd9..6310051d9fc 100644 --- a/documentation/CONTRIBUTING.md +++ b/documentation/CONTRIBUTING.md @@ -13,6 +13,7 @@ This guide outlines the contribution workflow, from reporting issues and submitt * [Testing Your Contributions] * [Commit Your Updates] * [Pull Request: From Submission to Merge] +* [Merge Freezes] * [Your PR is merged!] [New Contributor Guide]: #new-contributor-guide @@ -22,6 +23,7 @@ This guide outlines the contribution workflow, from reporting issues and submitt [Testing Your Contributions]: #testing-your-contributions [Commit your updates]: #commit-your-updates [Pull Request: From Submission to Merge]: #pull-request-from-submission-to-merge +[Merge Freezes]: #merge-freezes [Your PR is merged!]: #your-pr-is-merged ## New Contributor Guide @@ -50,11 +52,15 @@ Before adding or changing code, review the [esp-rs developer guidelines]. Encountered a problem or have an idea? First, [check existing issues] to avoid duplicates. If your concern is new, use our [issue form] to submit it. -An AI agent must not open issues automatically. We will close those issues without looking at them. Take the time to verify that the issue is real, and -make sure you use the correct issue form to open it. +Include only the information someone needs to reproduce the problem, or at least to explore it, and +leave out everything else. [REPRODUCERS.md] describes a good minimal reproducer. + +If an AI tool helps you write the issue, also follow [AI-Assisted Contributions]. [check existing issues]: https://github.com/esp-rs/esp-hal/issues [issue form]: https://github.com/esp-rs/esp-hal/issues/new/ +[REPRODUCERS.md]: ./REPRODUCERS.md +[AI-Assisted Contributions]: ./PULL-REQUESTS.md#ai-assisted-contributions #### Working on an Issue @@ -88,8 +94,8 @@ Ensuring the quality and reliability of `esp-hal` is a shared responsibility, an Further steps that can (or should) be taken in testing: -* Using [xtask], build examples for the specified chip. -* When documentation or doctests change, run `cargo xtask build documentation` and `cargo xtask run doc-tests ` to build the documentation and run the doctests. To reduce build/test time, use `--packages` to specify the package(s) and `--chips` (for documentation builds) to specify the target chip(s). +* Using [xtask], build examples for the specified chip (`cargo xtask build `, or `cargo xtask build examples all `). +* When documentation or doctests change, run `cargo xtask documentation` and `cargo xtask doc-tests ` to build the documentation and run the doctests. To reduce build/test time, use `--packages` to specify the package(s) and pass chip names to `documentation`. * Run the [HIL] tests locally if changes have been made to them. * Run host-side unit tests with `cargo xtask host-tests` (or `cargo xtask host-tests `). When adding `#[test]` functions to a package for the first time, also add a match arm for that package in `run_host_tests` in `xtask/src/lib.rs` — see [xtask/README.md#host-tests]. @@ -110,24 +116,23 @@ We _strongly_ recommend that you format your code before committing to ensure co To format all packages in the workspace, run the following command in a terminal from the root of the repository: ```shell -cargo xtask fmt-packages +cargo xtask fmt ``` -We also recommend using the `lint-packages` subcommand, which uses `cargo clippy` and will lint the entire driver in order to catch common mistakes in the code. +We also recommend using the `lint` subcommand, which uses `cargo clippy` and will lint the entire driver in order to catch common mistakes in the code. ```shell -cargo xtask lint-packages +cargo xtask lint ``` This will use `rustfmt` to ensure that all source code is formatted correctly prior to committing. ## Pull Request: From Submission to Merge +* Before you open the PR, read [PULL-REQUESTS.md]. It lists what reviewers expect, how to write the description, the changelog and migration guide format, and the rules for AI-assisted contributions. * Fill the pull request template so that we can review your PR. This template helps reviewers understand your changes as well as the purpose of your pull request. * [Link your PR] to any relevant issues it addresses. * [Allow edits from maintainers] so the branch can be updated for a merge. Once you submit your PR, a Docs team member will review your proposal. We may ask questions or request additional information. -* If your change is user-visible, consider adding a brief changelog entry and/or migration guide note in the PR description using the structured sections provided by the template (see below). This is optional — if you skip it, a maintainer will either add the entries or apply the `skip-changelog` label on your behalf. Do **not** edit `CHANGELOG.md` files directly — those are updated automatically at release time. -* If your change requires user code to be updated, add a `# Migration guide` section. Each breaking change needs a `## crate/area` heading and a `### Title` for the specific change, followed by the migration steps. * We may ask for changes to be made before a PR can be merged, either using [suggested changes] or pull request comments. You can apply suggested changes directly through the UI. You can make any other changes in your fork, then commit them to your branch. * As you update your PR and apply changes, mark each conversation as [resolved]. * Resolve merge conflicts if they arise, using resources like [this git tutorial] for help. @@ -137,109 +142,20 @@ This will use `rustfmt` to ensure that all source code is formatted correctly pr [suggested changes]: https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/reviewing-changes-in-pull-requests/incorporating-feedback-in-your-pull-request [resolved]: https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/reviewing-changes-in-pull-requests/commenting-on-a-pull-request#resolving-conversations [this git tutorial]: https://github.com/skills/resolve-merge-conflicts +[PULL-REQUESTS.md]: ./PULL-REQUESTS.md +## Merge Freezes -## Changelog and Migration Guide Entries - -Changelog entries are **optional for contributors**. If you don't add them a -maintainer will either write them or apply the `skip-changelog` label before the -PR is merged. - -If you do want to document your change, add entries directly in the PR description -using the structured sections in the template. Do **not** edit `CHANGELOG.md` — -those files are updated automatically at release time from the PR descriptions. - -### Format - -Use `# Changelog` and `# Migration guide` as top-level headings (H1). Under each -heading, group entries using H2 headings. Changelog H2 headings may use just the -crate name (e.g. `## esp-hal`), while migration guide H2 headings _must_ include -an area (e.g. `## esp-hal/SPI driver`). - -```markdown -# Changelog - -## esp-hal - -- Added: Support for the Foo peripheral. -- Fixed: A bug in the Bar driver that caused incorrect output. - -## esp-hal/SPI driver - -- Changed: `SpiDevice::transfer` now accepts a mutable slice. - -# Migration guide - -## esp-hal/SPI driver - -### `SpiDevice::transfer` signature changed - -`SpiDevice::transfer` now takes `&mut [u8]` instead of `(&[u8], &mut [u8])`. -Update your call sites accordingly. -``` - -### Entry kinds - -Each item in the `# Changelog` section must begin with one of: - -| Kind | When to use | -| --------- | -------------------------------------------------- | -| `Added` | New public API, feature, or peripheral support | -| `Changed` | Behaviour or API change (non-breaking preferred) | -| `Fixed` | Bug fixes | -| `Removed` | Removed API or feature | +Around a release we stop merging into `main`, so that what gets published is +tested in isolation from new changes. -### Skipping the changelog for a specific crate - -If your PR touches a published crate but the change genuinely needs no -user-visible entry (e.g. a documentation fix, an internal refactor, or a -build-system tweak), you can exempt that crate by writing the special marker -as the **sole** item in its `# Changelog` section: - -```markdown -# Changelog - -## esp-metadata - -- No changelog necessary. -``` - -This tells CI that the omission is intentional. The marker must be the only -item in the section — combining it with real entries is an error. - -When the whole PR needs no changelog at all, a maintainer can apply the -`skip-changelog` label instead. - -### Manually editing `CHANGELOG.md` - -In rare cases — such as backports, hotfixes, or curated release notes that -cannot be expressed through the structured PR description format — a maintainer -can apply the `manual-changelog` label to a PR. This label: - -- Allows direct edits to `CHANGELOG.md` files (the automated "no direct - CHANGELOG.md edits" check is skipped). -- Skips the per-package coverage check (the PR is not required to have - structured entries in the description). -- Still validates any PR description entries that *are* present, as a - safety net against formatting accidents. - -Do **not** use `manual-changelog` for routine changes — the structured PR -description format exists precisely to keep changelog maintenance consistent -and automatable. - -### Validation - -You can validate your PR description locally before pushing: - -```shell -# Pipe the body directly: -echo "# Changelog\n\n## esp-hal\n\n- Added: Something." | cargo xtask check-pr-changelog - -# Or validate an open PR by number (requires the `gh` CLI): -cargo xtask check-pr-changelog --pr 1234 -``` +A "freeze" is an open issue labelled `merge-freeze`, pinned so that everyone can +see it. Anyone with write access starts a freeze by opening or reopening that +issue and lifts it by closing it. Review and CI carry on as usual, only the +merge queue rejects pull requests targeting `main` while it is open. -CI will also validate the format automatically on every PR. +To land a release blocker anyway, label the pull request with +`merge-freeze-exempt`. Such merge gets recorded on the freeze issue. ## Your PR is Merged! diff --git a/documentation/HIL-GUIDE.md b/documentation/HIL-GUIDE.md index 4996888bddb..339453f20a9 100644 --- a/documentation/HIL-GUIDE.md +++ b/documentation/HIL-GUIDE.md @@ -11,7 +11,11 @@ By default, only `esp-rs` organization **members** and **owners** can trigger HI Behind the scenes, all comment-commands are first handled by `dispatch.yml`. This workflow parses the comment, checks trust/permissions, and then triggers the appropriate workflow (such as `hil.yml` or `binary_size.yml`) via `workflow_dispatch`. -### `/hil quick` +The words of a command go in any order, like the arguments of `cargo xtask test`: each is a chip, a package, a keyword such as `quick`, or else a test name. Separate them with spaces or commas, so `/test esp32 rmt c6 i2c` runs `rmt` and `i2c` on ESP32 and ESP32-C6. Chips can be shortened as in xtask, so `c6`, `esp32-c6` and `ESP32C6` all mean `esp32c6`. Only the first line of the comment is read, the rest is free text. + +`/hil` is the previous spelling of `/test` and still works, with the same words. + +### `/test quick` Runs a **minimal** HIL matrix on a limited set of chips: @@ -21,51 +25,70 @@ The CI will: 1. Trigger appropriate workflow. 2. Post a comment with a link to the triggered HIL run. -3. Edit that comment later with a status update (succeeded / failed / cancelled / still running). +3. Edit that comment when the run finishes with a status update (succeeded / failed / cancelled), and re-edit that same update whenever the run is re-run. In further commands, the feedback from the bot will be identical. -### `/hil full` +### `/test full` -Runs the **full** HIL matrix on **all supported chips**. +Runs the **full** HIL matrix on **all supported chips**. `/test all` does the same. The full matrix run will also be executed in the merge queue and is a prerequisite for a successful merge. -### `/hil [ ...]` +### `/test [ ...]` Runs HIL tests **only for the listed chips**. Examples: -- `/hil esp32c3` -- `/hil esp32c3 esp32s3` -- `/hil esp32c3,esp32c6, esp32s3` +- `/test c3` +- `/test esp32c3 s3` +- `/test c3, c6, ESP32-S3` + +Chips can be added to the quick matrix too: `/test quick c3` runs on ESP32-S3, ESP32-C6 and ESP32-C3. -### `/hil --test [, ...]` +### `/test [ ...]` -Runs **only chosen** HIL tests for selected chip(-s) or matrix. +Runs **only chosen** HIL tests for selected chip(-s) or matrix. Every word that is not a chip, a package or a keyword is a test name, wherever it stands. Examples: -- `/hil quick --test rmt` -- `/hil esp32 esp32c6 --tests rmt, i2c` -- `/hil esp32c6 hil-test-radio` -- `/hil esp32c6 hil-test-radio --tests wifi` -- `/hil esp32c6 --test radio_basic::test_scan_doesnt_leak` +- `/test quick rmt` +- `/test esp32 rmt c6 i2c` +- `/test c6 radio_basic::test_scan_doesnt_leak` + +Use `binary::test_name` to run a single embedded-test case inside a matching HIL test binary. For example, `/test c6 radio_basic::test_scan_doesnt_leak` builds the `radio_basic` ELF and forwards `test_scan_doesnt_leak` as the embedded-test filter when CI runs the prebuilt ELF. + +The `--test` and `--tests` flags of xtask are accepted as well, `/test c6 --tests rmt, i2c` is the same as `/test c6 rmt i2c`. + +### Radio HIL -Both `--test` and `--tests` will work. +By default, `/test` runs the `hil-test` package. Add `radio` (or `hil-test-radio`) to run the radio HIL package instead, or both `radio` and `hil-test` to run both. -Use `binary::test_name` to run a single embedded-test case inside a matching HIL test binary. For example, `/hil esp32c6 --test radio_basic::test_scan_doesnt_leak` builds the `radio_basic` ELF and forwards `test_scan_doesnt_leak` as the embedded-test filter when CI runs the prebuilt ELF. +Examples: -By default, `/hil` commands run the `hil-test` package. Include `hil-test-radio` in the comment body to run the radio HIL package instead. +- `/test c6 radio` +- `/test c6 radio wifi` +- `/test quick radio hil-test` -### `/test-size` +### `/test-size [ ...] [ ...]` Triggers the binary size analysis workflow, which: -- Builds selected binaries for the PR and for the base branch. -- Runs `bloaty` to compare section sizes. -- Generates a report. +- Builds the selected example for the PR head and for the commit the PR branched from. +- Compares the size of every section that ends up in the image. +- Reports the flash and bss totals and the sections that changed in a comment on the PR. + +Examples: + +- `/test-size hello_world c6` +- `/test-size embassy_hello_world esp32 c3 s3` +- `/test-size hello_world embassy_hello_world c6` +- `/test-size embassy-adc qa c6` + +Every word that is not a chip or a package is an example. At least one example and one chip are required. + +By default, the examples come from the `examples` package, the projects under `examples/`. Add `qa` (or `qa-test`) for binaries from `examples/qa/src/bin`, named after their files. `--package qa` from before still works. ## Trust Management Commands @@ -92,4 +115,4 @@ After revocation, the user loses access to the commands above for that PR. ## Help / Usage Hints -If you request `/hil help` or `/hil` without a valid variant or chips, the bot will respond with a short usage explanation, and a reminder that the requester must be a maintainer or trusted author. +If you request `/test help` or `/test` alone, the bot will respond with a short usage explanation, and a reminder that the requester must be a maintainer or trusted author. A `/test` or `/test-size` command that can't be run, for example one without a chip or with an unknown chip like `c66`, gets the same explanation with what went wrong. `/hil` is answered the same way. diff --git a/documentation/PULL-REQUESTS.md b/documentation/PULL-REQUESTS.md new file mode 100644 index 00000000000..6e6c0241a4c --- /dev/null +++ b/documentation/PULL-REQUESTS.md @@ -0,0 +1,208 @@ +# Pull Requests + +Read this when your change works and you are about to open a pull request or ask for a review. For +the rest of the contribution workflow, see [CONTRIBUTING.md](./CONTRIBUTING.md). + +## Before you ask for review + +Reviewers ask for the same changes again and again. Check your PR against this list before you ask +for a review. + +- **Comments**: Keep only comments that tell the reader something the code cannot, such as a + hardware quirk or an order that must hold. Do not write comments for the reviewer into the code. + Remove comments that narrate the code, explain how you found the bug, or describe how the code + worked before. Do not add section separators. Do not add a `TODO` for a known limitation: fix it + in the PR, or open an issue. +- **Approach**: Fix the cause, not the symptom. Make the smallest change that solves the problem. + Before you add new code, a dependency or an abstraction, look for one that the codebase already + has. +- **Scope**: Keep the PR to one change. Send unrelated fixes, refactors and formatting changes as + separate PRs. +- **Tests**: Add a test that fails without your change and passes with it. Put it in an existing + test suite where one fits. Use host tests for logic that does not need hardware, and HIL or QA + tests for hardware behavior. +- **Chip differences**: Use metadata and cfg symbols (`soc_has_`, + `_driver_supported`, or a new metadata flag) instead of lists of chips. Gate + chip-specific documentation with `cfg_attr`, so it only appears for the chips it applies to. Do + not hard-code values that the PAC or the metadata already provide. +- **API**: Follow the [esp-rs developer guidelines]. Mark new public API as unstable. Use the names + and patterns of the existing drivers. Do not break stable API. +- **Evidence**: Back performance, memory and code size claims with numbers from before and after + the change. If the change can affect existing behavior, run the affected examples or QA tests on + hardware. +- **Changelog**: Add an entry for each user-visible change, including changed defaults and + behavior. If you change a crate but the change is not user-visible, such as a test or an internal + refactor, write `- No changelog necessary.` as the only item under that crate. Do not add + sections for crates that you did not change. See [Changelog and Migration Guide Entries]. +- **Clean up**: Remove leftover code, unused items and accidental changes. Make CI pass, including + `cargo xtask fmt`. +- **Updates**: When the change moves during review, update the PR title and description to match. + Do not merge or rebase on `main` unless there is a conflict, because each push runs CI again. + +[esp-rs developer guidelines]: ./DEVELOPER-GUIDELINES.md +[Changelog and Migration Guide Entries]: #changelog-and-migration-guide-entries + +## Writing the description + +Reviewers read the diff. The description tells them what the diff cannot: why the change is needed +and how you know it works. Include only the information a reviewer needs to review the change, and +leave out everything else. Two sentences are enough for a small fix. A timing bug needs its +measurements. + +- Open with the problem and the fix. If an issue exists, link it (`Closes #1234`). Do not open an + issue only to link it from your PR. +- Under **Testing**, name the chip, the board, and the example or HIL test you ran, and the affected + chips you could not test. Leave out `fmt`, `lint`, and other checks CI runs. +- Write each changelog entry as one line describing the user-visible effect. The explanation belongs + in the description. + +The part of the template you write should look like this: + +```markdown +#### Description + +What was wrong or missing, and what this changes. + +Closes #1234 + +#### Testing + +Ran `` on (). Not tested on . +``` + +If an AI tool wrote a significant part of your contribution, also follow [AI-Assisted Contributions]. + +[AI-Assisted Contributions]: #ai-assisted-contributions + +## AI-Assisted Contributions + +> [!NOTE] +> This section applies only when an AI tool writes a significant part of your contribution: the +> code, the pull request description, or an issue. Its requirements add to the general rules in +> [Reporting a New Issue] and [Writing the description]. If you write your contribution yourself, +> skip this section. + +We follow the Rust Embedded working group's [AI tool use policy]. You are responsible for everything +you submit, so review and test it before you ask for a review. + +- An AI agent must not open issues automatically. We close those issues without looking at them. + Verify that the issue is real, and use the correct issue form. +- Say in one line of the pull request description that an AI tool generated a significant part of + the change. This applies even where your own agent instructions forbid AI attribution. +- Write pull request descriptions in Simplified Technical English (ASD-STE100), as the API + documentation does. Follow its [Style](./API-DOC-RULES.md#style) and + [Wording](./API-DOC-RULES.md#wording) rules: short sentences with one idea each, active voice, + and the present tense. +- Leave out the template's greeting and submission checklist, and start the body at + `#### Description`. +- Do not walk through the diff, restate the issue, or describe how you found the bug. +- Raise trade-offs, open questions, or follow-ups only when you need a reviewer's decision. +- Add no headings beyond the template's, no emoji, and no sign-offs. + +[Reporting a New Issue]: ./CONTRIBUTING.md#reporting-a-new-issue +[Writing the description]: #writing-the-description +[AI tool use policy]: https://github.com/rust-embedded/wg/blob/HEAD/CODE_OF_CONDUCT.md#ai-tool-use-policy + +## Changelog and Migration Guide Entries + +Changelog entries are **optional for contributors**. If you don't add them a +maintainer will either write them or apply the `skip-changelog` label before the +PR is merged. + +If you do want to document your change, add entries directly in the PR description +using the structured sections in the template. Do **not** edit `CHANGELOG.md`. +Those files are updated automatically at release time from the PR descriptions. + +### Format + +Use `# Changelog` and `# Migration guide` as top-level headings (H1). Under each +heading, group entries using H2 headings. Changelog H2 headings may use just the +crate name (e.g. `## esp-hal`), while migration guide H2 headings _must_ include +an area (e.g. `## esp-hal/SPI driver`). + +Only published crates can have changelog entries. CI rejects sections for crates +with `publish = false` in their `Cargo.toml` (e.g. `esp-metadata`, `xtask`, +`hil-test`). Published crates with `changelog-exempt = true` under +`[package.metadata.espressif]` (e.g. `esp-metadata-generated`) do not need a +section. + +```markdown +# Changelog + +## esp-hal + +- Added: Support for the Foo peripheral. +- Fixed: A bug in the Bar driver that caused incorrect output. + +## esp-hal/SPI driver + +- Changed: `SpiDevice::transfer` now accepts a mutable slice. + +# Migration guide + +## esp-hal/SPI driver + +### `SpiDevice::transfer` signature changed + +`SpiDevice::transfer` now takes `&mut [u8]` instead of `(&[u8], &mut [u8])`. +Update your call sites accordingly. +``` + +### Entry kinds + +Each item in the `# Changelog` section must begin with one of: + +| Kind | When to use | +| --------- | -------------------------------------------------- | +| `Added` | New public API, feature, or peripheral support | +| `Changed` | Behaviour or API change (non-breaking preferred) | +| `Fixed` | Bug fixes | +| `Removed` | Removed API or feature | + +### Breaking changes + +If your change requires user code to be updated, add a `# Migration guide` section. Each breaking +change needs a `## crate/area` heading and a `### Title` for the specific change, followed by the +migration steps. + +If your change breaks the stable API of a crate, the PR needs the `breaking-change-` +label (e.g. `breaking-change-esp-hal`). Without it, the semver check in CI fails. Ask a maintainer +to add the label. See [Breaking changes](./DEVELOPER-GUIDELINES.md#breaking-changes) in the +developer guidelines. + +### Skipping the changelog for a specific crate + +If your PR touches a published crate but the change genuinely needs no +user-visible entry (e.g. a documentation fix, an internal refactor, or a +build-system tweak), you can exempt that crate by writing the special marker +as the **sole** item in its `# Changelog` section: + +```markdown +# Changelog + +## esp-hal + +- No changelog necessary. +``` + +This tells CI that the omission is intentional. The marker must be the only +item in the section. Combining it with real entries is an error. + +When the whole PR needs no changelog at all, a maintainer can apply the +`skip-changelog` label instead. For the rare changes that this format cannot +express, maintainers use the `manual-changelog` label, see +[Manual changelog edits](./RELEASING.md#manual-changelog-edits). + +### Validation + +You can validate your PR description locally before pushing: + +```shell +# Pipe the body directly: +echo "# Changelog\n\n## esp-hal\n\n- Added: Something." | cargo xtask check-pr-changelog + +# Or validate an open PR by number (requires the `gh` CLI): +cargo xtask check-pr-changelog --pr 1234 +``` + +CI will also validate the format automatically on every PR. diff --git a/documentation/RELEASING.md b/documentation/RELEASING.md new file mode 100644 index 00000000000..1a102d261fb --- /dev/null +++ b/documentation/RELEASING.md @@ -0,0 +1,157 @@ +# Releasing `esp-hal` + +Reference for preparing, staging, and publishing a release. + +A release starts about two weeks before the intended publish date, to leave time +for testing. The date is a target, not a deadline: a release ships when it is +ready. The work runs in five phases: + +| Phase | Goal | +| -------------- | ------------------------------------------------- | +| Kickoff | Freeze `main` and publish the first pre-release | +| Stabilization | Soak pre-releases and fix bugs while `dev` moves | +| Shipping | Promote to stable, publish, and roll over | +| Reconciliation | Merge `dev` back into `main` and unfreeze | +| Post-mortem | Record what to improve next time | + +## Freeze and `dev` + +During a release, `main` is frozen and development moves to a temporary `dev` +branch. + +- Freeze `main` by opening and pinning an issue from the `Merge freeze` template. + The merge queue then rejects pull requests that target `main`. See + [Merge Freezes](./CONTRIBUTING.md#merge-freezes) for the mechanics. +- The freeze covers `main` only. Retarget open, non-blocking pull requests to + `dev`, and keep reviewing and merging there. +- Only release pull requests and urgent fixes reach the release. Everything else + waits on `dev`. + +## Soak testing + +Soak testing decides when a pre-release can be promoted, so run it for every +pre-release during the freeze. + +- Update projects to the published pre-release to test against real code. +- Run QA tests that CI does not run routinely. + +## Publishing + +Each pre-release and the final stable release publish the same way, on `main`: + +``` +cargo xrelease plan [more packages...] # writes release_plan.jsonc +# edit release_plan.jsonc to set the bump, then remove the comment header +cargo xrelease execute-plan --no-dry-run # bumps versions, opens the release PR +# review and merge the release PR into main, then: +cargo xrelease publish-plan --no-dry-run # publishes to crates.io, tags, pushes +``` + +The bump in `release_plan.jsonc` has two fields: `base` (how much to raise +`major.minor.patch`) and `pre` (the pre-release identifier, such as `alpha`, +`beta`, or `rc`). + +- Start a pre-release cycle by setting both: `"bump": { "base": "Minor", "pre": "beta" }`. +- Continue the cycle by leaving `base` null and keeping `pre`: `"bump": { "base": null, "pre": "beta" }`. +- Promote to stable by setting `base` and leaving `pre` null: `"bump": { "base": "Minor", "pre": null }`. + +Notes: + +- `execute-plan` also merges changelog and migration-guide entries from merged + pull request descriptions, and labels the release PR with `manual-changelog`, + `release:docs`, and `merge-freeze-exempt`. The `pre-release-checks` workflow + then builds the compile-tests and the examples/qa/tests against a local + registry on every release PR. Add `release:registry:skip-ci` to the PR to skip + the heavier examples/qa/tests build. +- Run `post-release` only for the final stable release. +- `plan` fills in `new_stable_api` for semver-checked packages, diffing the + package's API baselines against the working tree. Both sides use the features + in the package's `semver-config`. Each entry is an object with `item` and + `chips`; paths in `item` are `public-api` Display output, not rustdoc + definition sites. Chips without a baseline are skipped and listed in +`new_stable_api_unchecked_chips`. If the comparison fails for a chip that +does have a baseline, `plan` exits with an error. Baselines are regenerated +after a breaking change, so items stabilized before the last regeneration +are not listed. + +## Manual changelog edits + +In rare cases, such as backports, hotfixes, or curated release notes that cannot +be expressed through the structured PR description format, a maintainer can +apply the `manual-changelog` label to a PR. This label: + +- Allows direct edits to `CHANGELOG.md` files (the automated "no direct + CHANGELOG.md edits" check is skipped). +- Skips the per-package coverage check (the PR is not required to have + structured entries in the description). +- Still validates any PR description entries that *are* present, as a + safety net against formatting accidents. + +Do **not** use `manual-changelog` for routine changes. The structured PR +description format exists to keep changelog maintenance consistent and +automatable. + +## Kickoff + +- Land toolchain changes first. If the MSRV or CI toolchain must move, run + `cargo xrelease bump-msrv` before the freeze. +- Freeze `main` and branch `dev` off it (see [Freeze and `dev`](#freeze-and-dev)). +- Publish the first pre-release (see [Publishing](#publishing)). +- Track the release on the freeze issue. It also records exempt merges. + +## Stabilization + +Soak test each published pre-release (see [Soak testing](#soak-testing)). +Publish another pre-release whenever stabilization fixes accumulate on `main`. + +Pre-release requirements: + +- Patch: none +- Minor: at least one pre-release +- Major: a full pre-release cycle (an alpha can be skipped) + +Soak rules: + +- Each pre-release stays out for at least a week before promotion. +- A change larger than a small bug fix resets the clock and needs a further + pre-release. + +To land an urgent fix on frozen `main`, add the `merge-freeze-exempt` label. +Reserve it for regressions and release blockers, and remove it after merging. +Anything that is not a blocker goes to `dev`. + +## Shipping + +- Promote the soaked pre-release to the stable version (see [Publishing](#publishing)). +- After it is published and tagged, roll over: + +``` +cargo xrelease post-release --no-dry-run +``` + +For a stable minor or major release (major version 1 or higher), `post-release`: + +- creates the next migration guide +- cuts the backport branch `-..x` from the release tag and + deletes the previous minor's branch +- triggers the API baseline generation workflow for semver-checked packages +- opens the rollover pull request + +## Reconciliation + +- Merge `dev` into `main` in a single merge. Resolve `Cargo.toml` and + `CHANGELOG.md` conflicts in favor of the released versions. +- Close the freeze issue to lift the freeze, and delete `dev`. +- Backport later fixes by landing them on `main` with the `-backport` label. + The `Backport merged PR` workflow opens the cherry-pick against + `-..x`. + +## Post-mortem + +Record on the tracking issue before closing it: + +- whether the release started two weeks out, and where the schedule slipped +- what broke during testing, and how many pre-releases it took +- what landed through `merge-freeze-exempt`, and whether it was worth it +- which manual step was error-prone, and whether it can be automated +- action items, each with an owner diff --git a/esp-alloc/CHANGELOG.md b/esp-alloc/CHANGELOG.md index f29894ea265..8b24da34eba 100644 --- a/esp-alloc/CHANGELOG.md +++ b/esp-alloc/CHANGELOG.md @@ -9,18 +9,35 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- Support for ESP32-P4 (#5523) ### Changed ### Fixed -- Fixed `realloc_with_caps` over-reading issue (#5502) ### Removed +## [v0.11.0] - 2026-08-25 + +### Added + +- Support for ESP32-P4 (#5523) +- `DmaCompatibleInternalMemory` and `DmaCompatibleExternalMemory` allocators that ensure the returned variable is properly aligned as a DMA buffer. (#6068) +- ESP32-S31 support (#5959) + +### Changed + +- The chip selector feature(s) are now mandatory. (#6068) +- updated defmt to 1.1 (#5752) + +### Fixed + +- Fixed `realloc_with_caps` over-reading issue (#5502) +- Memory allocated from a secondary heap region could not always be freed, causing a silent leak. (#6018) +- Freeing memory could affect the wrong heap when using multiple adjacent memory regions (#6018) + ## [v0.10.0] - 2026-04-16 ### Added @@ -110,4 +127,5 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 [v0.8.0]: https://github.com/esp-rs/esp-hal/compare/esp-alloc-v0.7.0...esp-alloc-v0.8.0 [v0.9.0]: https://github.com/esp-rs/esp-hal/compare/esp-alloc-v0.8.0...esp-alloc-v0.9.0 [v0.10.0]: https://github.com/esp-rs/esp-hal/compare/esp-alloc-v0.9.0...esp-alloc-v0.10.0 -[Unreleased]: https://github.com/esp-rs/esp-hal/compare/esp-alloc-v0.10.0...HEAD +[v0.11.0]: https://github.com/esp-rs/esp-hal/compare/esp-alloc-v0.10.0...esp-alloc-v0.11.0 +[Unreleased]: https://github.com/esp-rs/esp-hal/compare/esp-alloc-v0.11.0...HEAD diff --git a/esp-alloc/Cargo.toml b/esp-alloc/Cargo.toml index 84076a534fd..349cc326618 100644 --- a/esp-alloc/Cargo.toml +++ b/esp-alloc/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "esp-alloc" -version = "0.10.0" +version = "0.11.0" edition = "2024" rust-version = "1.95.0" description = "A heap allocator for Espressif devices" @@ -37,6 +37,7 @@ test = false allocator-api2 = { version = "0.3.0", default-features = false } defmt = { version = "1.1", optional = true } enumset = "1" +esp-config = { version = "0.8.0", path = "../esp-config" } esp-sync = { version = "0.3.0", path = "../esp-sync" } document-features = "0.2" @@ -45,7 +46,7 @@ rlsf = { version = "0.2", features = ["unstable"] } [build-dependencies] esp-config = { version = "0.8.0", path = "../esp-config", features = ["build"] } -esp-metadata-generated = { version = "0.5.0", path = "../esp-metadata-generated", features = ["build-script"] } +esp-metadata-generated = { version = "0.6.0", path = "../esp-metadata-generated", features = ["build-script"] } [features] default = ["compat", "global-allocator"] @@ -122,6 +123,8 @@ esp32c61 = ["esp-sync/esp32c61", "esp-metadata-generated/esp32c61"] ## esp32h2 = ["esp-sync/esp32h2", "esp-metadata-generated/esp32h2"] ## +esp32h4 = ["esp-sync/esp32h4", "esp-metadata-generated/esp32h4"] +## esp32p4 = ["esp-sync/esp32p4", "esp-metadata-generated/esp32p4"] ## esp32s31 = ["esp-sync/esp32s31", "esp-metadata-generated/esp32s31"] diff --git a/esp-alloc/esp_config.yml b/esp-alloc/esp_config.yml index ce2d608e8db..d2fcc639657 100644 --- a/esp-alloc/esp_config.yml +++ b/esp-alloc/esp_config.yml @@ -1,6 +1,17 @@ crate: esp-alloc options: + - name: max_regions + description: "Maximum number of memory regions that can be added to a + heap allocator. Each region slot is a small constant cost in the + allocator itself; only increase this if you need to register more + regions than the default allows." + default: + - value: 3 + constraints: + - type: + validator: positive_integer + - name: heap_algorithm description: "The heap algorithm to use. TLSF offers higher performance and bounded allocation time, but uses more memory." diff --git a/esp-alloc/src/lib.rs b/esp-alloc/src/lib.rs index 24c56625b93..ca5f0fb2f10 100644 --- a/esp-alloc/src/lib.rs +++ b/esp-alloc/src/lib.rs @@ -161,10 +161,15 @@ pub mod export { pub use allocators::*; use enumset::{EnumSet, EnumSetType}; +use esp_config::esp_config_int; use esp_sync::NonReentrantMutex; use crate::heap::Heap; +/// Maximum number of memory regions that can be added to a heap allocator, +/// configurable via `ESP_ALLOC_CONFIG_MAX_REGIONS`. +const MAX_REGIONS: usize = esp_config_int!(usize, "ESP_ALLOC_CONFIG_MAX_REGIONS"); + /// The global allocator instance #[cfg_attr(feature = "global-allocator", global_allocator)] pub static HEAP: EspHeap = EspHeap::empty(); @@ -329,11 +334,11 @@ impl HeapRegion { /// Stats for a heap allocator /// /// Enable the "internal-heap-stats" feature if you want collect additional heap -/// informations at the cost of extra cpu time during every alloc/dealloc. +/// information at the cost of extra cpu time during every alloc/dealloc. #[derive(Debug)] pub struct HeapStats { /// Granular stats for all the configured memory regions. - pub region_stats: [Option; 3], + pub region_stats: [Option; MAX_REGIONS], /// Total size of all combined heap regions in bytes. pub size: usize, @@ -406,7 +411,7 @@ struct InternalHeapStats { } struct EspHeapInner { - heap: [Option; 3], + heap: [Option; MAX_REGIONS], #[cfg(feature = "internal-heap-stats")] internal_heap_stats: InternalHeapStats, } @@ -415,7 +420,7 @@ impl EspHeapInner { /// Crate a new UNINITIALIZED heap allocator pub const fn empty() -> Self { EspHeapInner { - heap: [const { None }; 3], + heap: [const { None }; MAX_REGIONS], #[cfg(feature = "internal-heap-stats")] internal_heap_stats: InternalHeapStats { max_usage: 0, @@ -461,7 +466,7 @@ impl EspHeapInner { /// called from within `println!()` to pretty-print the usage of the /// heap. pub fn stats(&self) -> HeapStats { - let mut region_stats: [Option; 3] = [const { None }; 3]; + let mut region_stats: [Option; MAX_REGIONS] = [const { None }; MAX_REGIONS]; let mut used = 0; let mut free = 0; @@ -588,7 +593,8 @@ impl EspHeap { /// /// `size` is the size of the heap in bytes. /// - /// You can add up to three regions per allocator. + /// You can add up to three regions per allocator by default. The limit is + /// configurable via `ESP_ALLOC_CONFIG_MAX_REGIONS`. /// /// Note that: /// diff --git a/esp-backtrace/CHANGELOG.md b/esp-backtrace/CHANGELOG.md index 911eb808fd7..5b04ef00a59 100644 --- a/esp-backtrace/CHANGELOG.md +++ b/esp-backtrace/CHANGELOG.md @@ -9,8 +9,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- Initial ESP32-P4 (chip revision v3.0+) support (#5400) -- Add ESP32-S31 support (#5922) ### Changed @@ -21,6 +19,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Removed +## [v0.20.0] - 2026-08-25 + +### Added + +- Initial ESP32-P4 (chip revision v3.0+) support (#5400) +- Add ESP32-S31 support (#5922) + +### Changed + +- updated defmt to 1.1 (#5752) + +### Fixed + +- Xtensa: Fixed an issue that could corrupt a register value (#6027) + ## [v0.19.0] - 2026-04-16 ### Added @@ -123,4 +136,5 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 [v0.18.0]: https://github.com/esp-rs/esp-hal/compare/esp-backtrace-v0.17.0...esp-backtrace-v0.18.0 [v0.18.1]: https://github.com/esp-rs/esp-hal/compare/esp-backtrace-v0.18.0...esp-backtrace-v0.18.1 [v0.19.0]: https://github.com/esp-rs/esp-hal/compare/esp-backtrace-v0.18.1...esp-backtrace-v0.19.0 -[Unreleased]: https://github.com/esp-rs/esp-hal/compare/esp-backtrace-v0.19.0...HEAD +[v0.20.0]: https://github.com/esp-rs/esp-hal/compare/esp-backtrace-v0.19.0...esp-backtrace-v0.20.0 +[Unreleased]: https://github.com/esp-rs/esp-hal/compare/esp-backtrace-v0.20.0...HEAD diff --git a/esp-backtrace/Cargo.toml b/esp-backtrace/Cargo.toml index 288b87da2e7..2778b2efa50 100644 --- a/esp-backtrace/Cargo.toml +++ b/esp-backtrace/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "esp-backtrace" -version = "0.19.0" +version = "0.20.0" edition = "2024" rust-version = "1.95.0" description = "Bare-metal backtrace support for Espressif devices" @@ -36,8 +36,8 @@ test = false [dependencies] defmt = { version = "1.1", optional = true } esp-config = { version = "0.8.0", path = "../esp-config" } -esp-metadata-generated = { version = "0.5.0", path = "../esp-metadata-generated" } -esp-println = { version = "0.17.0", optional = true, default-features = false, path = "../esp-println" } +esp-metadata-generated = { version = "0.6.0", path = "../esp-metadata-generated" } +esp-println = { version = "0.18.0", optional = true, default-features = false, path = "../esp-println" } heapless = "0.9" semihosting = { version = "0.1.20", optional = true } document-features = "0.2" @@ -50,7 +50,7 @@ xtensa-lx = { version = "0.13.0", path = "../xtensa-lx" } [build-dependencies] esp-config = { version = "0.8.0", path = "../esp-config", features = ["build"] } -esp-metadata-generated = { version = "0.5.0", path = "../esp-metadata-generated", features = ["build-script"] } +esp-metadata-generated = { version = "0.6.0", path = "../esp-metadata-generated", features = ["build-script"] } [features] default = ["colors"] @@ -62,6 +62,7 @@ esp32c5 = ["esp-println?/esp32c5", "esp-metadata-generated/esp32c5"] esp32c6 = ["esp-println?/esp32c6", "esp-metadata-generated/esp32c6"] esp32c61 = ["esp-println?/esp32c61", "esp-metadata-generated/esp32c61"] esp32h2 = ["esp-println?/esp32h2", "esp-metadata-generated/esp32h2"] +esp32h4 = ["esp-println?/esp32h4", "esp-metadata-generated/esp32h4"] esp32p4 = ["esp-println?/esp32p4", "esp-metadata-generated/esp32p4"] esp32s2 = ["esp-println?/esp32s2", "esp-metadata-generated/esp32s2", "semihosting?/openocd-semihosting"] esp32s3 = ["esp-println?/esp32s3", "esp-metadata-generated/esp32s3", "semihosting?/openocd-semihosting", "print-float-registers"] diff --git a/esp-bootloader-esp-idf/CHANGELOG.md b/esp-bootloader-esp-idf/CHANGELOG.md index abfd0b7afa2..78ccc1190f5 100644 --- a/esp-bootloader-esp-idf/CHANGELOG.md +++ b/esp-bootloader-esp-idf/CHANGELOG.md @@ -9,17 +9,49 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added + +### Changed + + +### Fixed + + +### Removed + + +## [v0.6.0] - 2026-08-25 + +### Added + - Add ESP32-S31 support (#5922) +- `PartitionEntry::sha256()` for partition integrity checks (#6061) +- FlashRegion::as_nor_flash() and FlashRegion::as_nor_flash_encrypted() for NOR flash access with correct encryption semantics. (#5857) +- FlashRegionPlainNorFlash and FlashRegionEncryptedNorFlash wrapper types. (#5857) +- Error::NotSupported for incompatible partition/accessor combinations. (#5857) +- `OtaUpdater::reset_data()` to erase the OTA data partition and select the factory app (#5767) +- OTA / partition table support for ESP32-P4 (#5751) +- Inherent `read`, `write`, and `capacity` methods on [`FlashRegion`](crate::partitions::FlashRegion) (#5739) ### Changed - ESP32-P4: Use ROM CRC32 / MD5 functions instead of the software fallback (#5400) +- `PartitionEntry` is now no longer lifetime-tied to `PartitionTable`. (#6056) +- `FlashRegion` supports transparent encryption support (#5810) +- updated defmt to 1.1 (#5752) +- `esp-bootloader-esp-idf` now directly depends on `esp-storage` (#5739) +- `embedded-storage` trait implementations are now an opt-in feature (non-default) (#5739) +- `PartitionEntry::as_embedded_storage` is deprecated in favor of [`PartitionEntry::as_flash_region`](crate::partitions::PartitionEntry::as_flash_region) (#5739) ### Fixed +- `FlashRegion::erase` no longer fails when erasing up to the end of the partition (e.g. the last sector or the whole partition) (#6045) +- `SOURCE_DATE_EPOCH` is now interpreted as seconds since the Unix epoch, as the reproducible-builds specification requires, and changing it re-runs the build script. (#6017) +- OTA select entries are now validated (CRC and state) before being read into Rust types, avoiding UB on corrupted flash (#5767) ### Removed +- Direct ReadNorFlash, NorFlash, and MultiwriteNorFlash impls on FlashRegion. (#5857) +- `as_embedded_storage` - use `as_flash_region` instead (#5739) ## [v0.5.0] - 2026-04-16 @@ -100,4 +132,5 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 [v0.3.0]: https://github.com/esp-rs/esp-hal/compare/esp-bootloader-esp-idf-v0.2.0...esp-bootloader-esp-idf-v0.3.0 [v0.4.0]: https://github.com/esp-rs/esp-hal/compare/esp-bootloader-esp-idf-v0.3.0...esp-bootloader-esp-idf-v0.4.0 [v0.5.0]: https://github.com/esp-rs/esp-hal/compare/esp-bootloader-esp-idf-v0.4.0...esp-bootloader-esp-idf-v0.5.0 -[Unreleased]: https://github.com/esp-rs/esp-hal/compare/esp-bootloader-esp-idf-v0.5.0...HEAD +[v0.6.0]: https://github.com/esp-rs/esp-hal/compare/esp-bootloader-esp-idf-v0.5.0...esp-bootloader-esp-idf-v0.6.0 +[Unreleased]: https://github.com/esp-rs/esp-hal/compare/esp-bootloader-esp-idf-v0.6.0...HEAD diff --git a/esp-bootloader-esp-idf/Cargo.toml b/esp-bootloader-esp-idf/Cargo.toml index 821383114ab..a72f25afb3a 100644 --- a/esp-bootloader-esp-idf/Cargo.toml +++ b/esp-bootloader-esp-idf/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "esp-bootloader-esp-idf" -version = "0.5.0" +version = "0.6.0" edition = "2024" rust-version = "1.95.0" description = "Functionality related to the esp-idf bootloader" @@ -21,6 +21,9 @@ check-configs = [ clippy-configs = [ { features = ["defmt", "validation"] }, ] +host-test-configs = [ + { features = ["std", "embedded-storage"], cargo-args = ["--lib", "--tests"], test-args = ["--test-threads=1"] }, +] [package.metadata.docs.rs] default-target = "riscv32imac-unknown-none-elf" @@ -34,10 +37,9 @@ defmt = { version = "1.1", optional = true } document-features = "0.2" esp-config = { version = "0.8.0", path = "../esp-config" } esp-hal-procmacros = { version = "0.23.0", path = "../esp-hal-procmacros", features = ["__esp_idf_bootloader"] } -esp-metadata-generated = { version = "0.5.0", path = "../esp-metadata-generated" } +esp-metadata-generated = { version = "0.6.0", path = "../esp-metadata-generated" } esp-rom-sys = { version = "~0.1", path = "../esp-rom-sys", optional = true } embedded-storage = { version = "0.3.1", optional = true } -esp-storage = { path = "../esp-storage", default-features = false, optional = true } log-04 = { package = "log", version = "0.4", optional = true } strum = { version = "0.27", default-features = false, features = ["derive"] } @@ -48,11 +50,14 @@ sha2 = { version = "0.11", default-features = false } [build-dependencies] jiff = { version = "0.2.13", default-features = false, features = ["std"] } esp-config = { version = "0.8.0", path = "../esp-config", features = ["build"] } -esp-metadata-generated = { version = "0.5.0", path = "../esp-metadata-generated", features = ["build-script"] } +esp-metadata-generated = { version = "0.6.0", path = "../esp-metadata-generated", features = ["build-script"] } + +[target.'cfg(any(target_arch = "riscv32", target_arch = "xtensa"))'.dependencies] +esp-hal = { version = "~1.2.0", path = "../esp-hal", default-features = false, features = ["unstable"] } # Make doctests & host-tests work together: [target.'cfg(any(target_arch = "riscv32", target_arch = "xtensa"))'.dev-dependencies] -esp-hal = { version = "~1.2.0-rc.0", path = "../esp-hal" } +esp-hal = { version = "~1.2.0", path = "../esp-hal" } [features] default = ["validation"] @@ -76,27 +81,29 @@ embedded-storage = ["dep:embedded-storage"] #! One of the following features must be enabled to select the target chip: ## -esp32c2 = ["esp-rom-sys/esp32c2", "esp-metadata-generated/esp32c2", "esp-hal/esp32c2", "esp-storage/esp32c2"] +esp32c2 = ["esp-rom-sys/esp32c2", "esp-metadata-generated/esp32c2", "esp-hal/esp32c2"] +## +esp32c3 = ["esp-rom-sys/esp32c3", "esp-metadata-generated/esp32c3", "esp-hal/esp32c3"] ## -esp32c3 = ["esp-rom-sys/esp32c3", "esp-metadata-generated/esp32c3", "esp-hal/esp32c3", "esp-storage/esp32c3"] +esp32c5 = ["esp-rom-sys/esp32c5", "esp-metadata-generated/esp32c5", "esp-hal/esp32c5"] ## -esp32c5 = ["esp-rom-sys/esp32c5", "esp-metadata-generated/esp32c5", "esp-hal/esp32c5", "esp-storage/esp32c5"] +esp32c6 = ["esp-rom-sys/esp32c6", "esp-metadata-generated/esp32c6", "esp-hal/esp32c6"] ## -esp32c6 = ["esp-rom-sys/esp32c6", "esp-metadata-generated/esp32c6", "esp-hal/esp32c6", "esp-storage/esp32c6"] +esp32c61 = ["esp-rom-sys/esp32c61", "esp-metadata-generated/esp32c61", "esp-hal/esp32c61"] ## -esp32c61 = ["esp-rom-sys/esp32c61", "esp-metadata-generated/esp32c61", "esp-hal/esp32c61", "esp-storage/esp32c61"] +esp32h2 = ["esp-rom-sys/esp32h2", "esp-metadata-generated/esp32h2", "esp-hal/esp32h2"] ## -esp32h2 = ["esp-rom-sys/esp32h2", "esp-metadata-generated/esp32h2", "esp-hal/esp32h2", "esp-storage/esp32h2"] +esp32h4 = ["esp-rom-sys/esp32h4", "esp-metadata-generated/esp32h4", "esp-hal/esp32h4"] ## -esp32p4 = ["esp-rom-sys/esp32p4", "esp-metadata-generated/esp32p4", "esp-hal/esp32p4", "esp-storage/esp32p4"] +esp32p4 = ["esp-rom-sys/esp32p4", "esp-metadata-generated/esp32p4", "esp-hal/esp32p4"] ## -esp32 = ["esp-rom-sys/esp32", "esp-metadata-generated/esp32", "esp-hal/esp32", "esp-storage/esp32"] +esp32 = ["esp-rom-sys/esp32", "esp-metadata-generated/esp32", "esp-hal/esp32"] ## -esp32s2 = ["esp-rom-sys/esp32s2", "esp-metadata-generated/esp32s2", "esp-hal/esp32s2", "esp-storage/esp32s2"] +esp32s2 = ["esp-rom-sys/esp32s2", "esp-metadata-generated/esp32s2", "esp-hal/esp32s2"] ## -esp32s3 = ["esp-rom-sys/esp32s3", "esp-metadata-generated/esp32s3", "esp-hal/esp32s3", "esp-storage/esp32s3"] +esp32s3 = ["esp-rom-sys/esp32s3", "esp-metadata-generated/esp32s3", "esp-hal/esp32s3"] ## -esp32s31 = ["esp-rom-sys/esp32s31", "esp-metadata-generated/esp32s31", "esp-hal/esp32s31", "esp-storage/esp32s31"] +esp32s31 = ["esp-rom-sys/esp32s31", "esp-metadata-generated/esp32s31", "esp-hal/esp32s31"] # "md-5" is hidden behind `std` feature and `cargo machete` incorrectly marks it as unused. [package.metadata.cargo-machete] diff --git a/esp-bootloader-esp-idf/build.rs b/esp-bootloader-esp-idf/build.rs index b27d4dc857c..640c8396b28 100644 --- a/esp-bootloader-esp-idf/build.rs +++ b/esp-bootloader-esp-idf/build.rs @@ -33,6 +33,12 @@ fn main() -> Result<(), Box> { None }; + // Partition and OTA access is built on `esp_hal::flash`. Host tests replace it with a mock. + println!("cargo::rustc-check-cfg=cfg(flash_driver_supported)"); + if chip.is_none_or(|chip| chip.contains("flash_driver_supported")) { + println!("cargo::rustc-cfg=flash_driver_supported"); + } + // emit config println!("cargo:rerun-if-changed=./esp_config.yml"); let cfg_yaml = std::fs::read_to_string("./esp_config.yml") diff --git a/esp-bootloader-esp-idf/src/flash/flash_access.rs b/esp-bootloader-esp-idf/src/flash/flash_access.rs index a2abd544cbb..b496fbfd6d0 100644 --- a/esp-bootloader-esp-idf/src/flash/flash_access.rs +++ b/esp-bootloader-esp-idf/src/flash/flash_access.rs @@ -8,62 +8,125 @@ pub trait FlashAccess { fn flash_erase(&mut self, from: u32, to: u32) -> Result<(), Error>; fn flash_read_encrypted(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Error>; fn flash_write_encrypted(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Error>; - - #[cfg(feature = "embedded-storage")] - const READ_SIZE: usize; - #[cfg(feature = "embedded-storage")] - const WRITE_SIZE: usize; - #[cfg(feature = "embedded-storage")] - const ERASE_SIZE: usize; - #[cfg(feature = "embedded-storage")] - const SECTOR_SIZE: u32; - - #[cfg(feature = "embedded-storage")] - fn flash_read_nor(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Error>; - #[cfg(feature = "embedded-storage")] - fn flash_write_nor(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Error>; } #[cfg(not(feature = "std"))] -impl FlashAccess for super::FlashStorage<'_> { - #[cfg(feature = "embedded-storage")] - const READ_SIZE: usize = esp_storage::FlashStorage::READ_SIZE; - #[cfg(feature = "embedded-storage")] - const WRITE_SIZE: usize = esp_storage::FlashStorage::WRITE_SIZE; - #[cfg(feature = "embedded-storage")] - const ERASE_SIZE: usize = esp_storage::FlashStorage::ERASE_SIZE; - #[cfg(feature = "embedded-storage")] - const SECTOR_SIZE: u32 = esp_storage::FlashStorage::SECTOR_SIZE; - - fn flash_read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Error> { - esp_storage::FlashStorage::read(self, offset, bytes).map_err(|_| Error::StorageError) - } +mod esp_hal_flash { + use super::*; + use crate::flash::{FlashStorage, WORD_SIZE}; - fn flash_write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Error> { - esp_storage::FlashStorage::write(self, offset, bytes).map_err(|_| Error::StorageError) - } + /// Size of the stack buffer that stages data between byte slices and the + /// word-based flash driver, which needs word-aligned buffers in DRAM. + const BOUNCE_BUFFER_WORDS: usize = 64; + const BOUNCE_BUFFER_BYTES: usize = BOUNCE_BUFFER_WORDS * WORD_SIZE as usize; - fn flash_erase(&mut self, from: u32, to: u32) -> Result<(), Error> { - esp_storage::FlashStorage::erase(self, from, to).map_err(|_| Error::StorageError) + fn words_as_bytes(words: &[u32]) -> &[u8] { + // SAFETY: every bit pattern is a valid `u8`, and `u8` has no alignment requirement. + unsafe { core::slice::from_raw_parts(words.as_ptr().cast(), size_of_val(words)) } } - fn flash_read_encrypted(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Error> { - esp_storage::FlashStorage::read_encrypted(self, offset, bytes) - .map_err(|_| Error::StorageError) + fn words_as_bytes_mut(words: &mut [u32]) -> &mut [u8] { + // SAFETY: every bit pattern is a valid `u8` and `u32`, and `u8` has no alignment + // requirement. + unsafe { core::slice::from_raw_parts_mut(words.as_mut_ptr().cast(), size_of_val(words)) } } - fn flash_write_encrypted(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Error> { - esp_storage::FlashStorage::write_encrypted(self, offset, bytes) - .map_err(|_| Error::StorageError) + /// Reads `bytes.len()` bytes at any `offset`, one bounce buffer at a time. + fn read_bytes( + flash: &mut FlashStorage<'_>, + offset: u32, + mut bytes: &mut [u8], + encrypted: bool, + ) -> Result<(), Error> { + let mut buffer = [0u32; BOUNCE_BUFFER_WORDS]; + let mut address = offset; + + while !bytes.is_empty() { + let lead = (address % WORD_SIZE) as usize; + let len = bytes.len().min(BOUNCE_BUFFER_BYTES - lead); + let words = &mut buffer[..(lead + len).div_ceil(WORD_SIZE as usize)]; + let aligned_address = address - lead as u32; + + if encrypted { + flash.read_encrypted(aligned_address, words) + } else { + flash.read(aligned_address, words) + } + .map_err(|_| Error::StorageError)?; + + let (head, tail) = bytes.split_at_mut(len); + head.copy_from_slice(&words_as_bytes(words)[lead..][..len]); + bytes = tail; + address += len as u32; + } + + Ok(()) } - #[cfg(feature = "embedded-storage")] - fn flash_read_nor(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Error> { - esp_storage::FlashStorage::read_nor(self, offset, bytes).map_err(|_| Error::StorageError) + /// Writes `bytes` at a word-aligned `offset`, one bounce buffer at a time. + /// + /// The target range must be erased: the driver does not erase before + /// programming. + fn write_bytes( + flash: &mut FlashStorage<'_>, + offset: u32, + mut bytes: &[u8], + encrypted: bool, + ) -> Result<(), Error> { + if !offset.is_multiple_of(WORD_SIZE) || !bytes.len().is_multiple_of(WORD_SIZE as usize) { + return Err(Error::NotAligned); + } + + let mut buffer = [0u32; BOUNCE_BUFFER_WORDS]; + let mut address = offset; + + while !bytes.is_empty() { + let len = bytes.len().min(BOUNCE_BUFFER_BYTES); + let words = &mut buffer[..len / WORD_SIZE as usize]; + let (head, tail) = bytes.split_at(len); + words_as_bytes_mut(words).copy_from_slice(head); + + // SAFETY: all writes and erases go through `Region`, which refuses to + // modify the partition of the running application, the only flash that + // is mapped for instruction fetch or as immutable data after boot. + unsafe { + if encrypted { + flash.write_encrypted(address, words) + } else { + flash.write(address, words) + } + } + .map_err(|_| Error::StorageError)?; + + bytes = tail; + address += len as u32; + } + + Ok(()) } - #[cfg(feature = "embedded-storage")] - fn flash_write_nor(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Error> { - esp_storage::FlashStorage::write_nor(self, offset, bytes).map_err(|_| Error::StorageError) + impl FlashAccess for FlashStorage<'_> { + fn flash_read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Error> { + read_bytes(self, offset, bytes, false) + } + + fn flash_write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Error> { + write_bytes(self, offset, bytes, false) + } + + fn flash_erase(&mut self, from: u32, to: u32) -> Result<(), Error> { + // SAFETY: all writes and erases go through `Region`, which refuses to + // modify the partition of the running application, the only flash that + // is mapped for instruction fetch or as immutable data after boot. + unsafe { self.erase(from, to) }.map_err(|_| Error::StorageError) + } + + fn flash_read_encrypted(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Error> { + read_bytes(self, offset, bytes, true) + } + + fn flash_write_encrypted(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Error> { + write_bytes(self, offset, bytes, true) + } } } diff --git a/esp-bootloader-esp-idf/src/flash/mock_flash.rs b/esp-bootloader-esp-idf/src/flash/mock_flash.rs index e60720aa9f4..4361dfc79ef 100644 --- a/esp-bootloader-esp-idf/src/flash/mock_flash.rs +++ b/esp-bootloader-esp-idf/src/flash/mock_flash.rs @@ -1,10 +1,8 @@ use core::marker::PhantomData; -use super::flash_access::FlashAccess; +use super::{SECTOR_SIZE, flash_access::FlashAccess}; use crate::partitions::Error; -const WORD_SIZE: u32 = 4; -const SECTOR_SIZE: u32 = 4096; const BLOCK_SIZE: u32 = 65536; const FLASH_SIZE: usize = (BLOCK_SIZE * 4) as usize; const ERASE_BYTE: u8 = 0xff; @@ -43,8 +41,12 @@ impl MockFlash<'_> { self.flash_read(offset, bytes) } + /// Overwrites flash contents with `bytes`, without NOR semantics. pub fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Error> { - self.flash_write(offset, bytes) + Self::check_bounds(offset, bytes.len())?; + let offset = offset as usize; + Self::with_flash(|flash| flash[offset..][..bytes.len()].copy_from_slice(bytes)); + Ok(()) } pub fn erase(&mut self, from: u32, to: u32) -> Result<(), Error> { @@ -53,23 +55,14 @@ impl MockFlash<'_> { } impl FlashAccess for MockFlash<'_> { - #[cfg(feature = "embedded-storage")] - const READ_SIZE: usize = WORD_SIZE as usize; - #[cfg(feature = "embedded-storage")] - const WRITE_SIZE: usize = WORD_SIZE as usize; - #[cfg(feature = "embedded-storage")] - const ERASE_SIZE: usize = SECTOR_SIZE as usize; - #[cfg(feature = "embedded-storage")] - const SECTOR_SIZE: u32 = SECTOR_SIZE; - fn flash_read(&mut self, offset: u32, mut bytes: &mut [u8]) -> Result<(), Error> { Self::check_bounds(offset, bytes.len())?; - let mut data_offset = offset % Self::SECTOR_SIZE; + let mut data_offset = offset % SECTOR_SIZE; let mut aligned_offset = offset - data_offset; while !bytes.is_empty() { - let len = bytes.len().min((Self::SECTOR_SIZE - data_offset) as usize); + let len = bytes.len().min((SECTOR_SIZE - data_offset) as usize); Self::with_flash(|flash| { bytes[..len].copy_from_slice( @@ -77,7 +70,7 @@ impl FlashAccess for MockFlash<'_> { ); }); - aligned_offset += Self::SECTOR_SIZE; + aligned_offset += SECTOR_SIZE; data_offset = 0; bytes = &mut bytes[len..]; } @@ -88,18 +81,21 @@ impl FlashAccess for MockFlash<'_> { fn flash_write(&mut self, offset: u32, mut bytes: &[u8]) -> Result<(), Error> { Self::check_bounds(offset, bytes.len())?; - let mut data_offset = offset % Self::SECTOR_SIZE; + let mut data_offset = offset % SECTOR_SIZE; let mut aligned_offset = offset - data_offset; while !bytes.is_empty() { - let len = bytes.len().min((Self::SECTOR_SIZE - data_offset) as usize); + let len = bytes.len().min((SECTOR_SIZE - data_offset) as usize); + // NOR flash programming can only clear bits, setting them needs an erase. Self::with_flash(|flash| { flash[aligned_offset as usize + data_offset as usize..][..len] - .copy_from_slice(&bytes[..len]); + .iter_mut() + .zip(&bytes[..len]) + .for_each(|(cell, byte)| *cell &= byte); }); - aligned_offset += Self::SECTOR_SIZE; + aligned_offset += SECTOR_SIZE; data_offset = 0; bytes = &bytes[len..]; } @@ -115,9 +111,9 @@ impl FlashAccess for MockFlash<'_> { while address < to && !address.is_multiple_of(BLOCK_SIZE) { let sector = address as usize; Self::with_flash(|flash| { - flash[sector..sector + Self::SECTOR_SIZE as usize].fill(ERASE_BYTE); + flash[sector..sector + SECTOR_SIZE as usize].fill(ERASE_BYTE); }); - address += Self::SECTOR_SIZE; + address += SECTOR_SIZE; } while (to - address) >= BLOCK_SIZE { @@ -131,9 +127,9 @@ impl FlashAccess for MockFlash<'_> { while address < to { let sector = address as usize; Self::with_flash(|flash| { - flash[sector..sector + Self::SECTOR_SIZE as usize].fill(ERASE_BYTE); + flash[sector..sector + SECTOR_SIZE as usize].fill(ERASE_BYTE); }); - address += Self::SECTOR_SIZE; + address += SECTOR_SIZE; } Ok(()) @@ -146,14 +142,38 @@ impl FlashAccess for MockFlash<'_> { fn flash_write_encrypted(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Error> { self.flash_write(offset, bytes) } +} - #[cfg(feature = "embedded-storage")] - fn flash_read_nor(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Error> { - self.flash_read(offset, bytes) +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn write_cannot_set_bits() { + let mut flash = MockFlash::new(); + flash.flash_erase(0, SECTOR_SIZE).unwrap(); + + flash.flash_write(0, &[0x0f; 4]).unwrap(); + flash.flash_write(0, &[0xf0; 4]).unwrap(); + + let mut bytes = [0u8; 4]; + flash.flash_read(0, &mut bytes).unwrap(); + assert_eq!(bytes, [0x00; 4]); } - #[cfg(feature = "embedded-storage")] - fn flash_write_nor(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Error> { - self.flash_write(offset, bytes) + #[test] + fn erase_restores_erased_state() { + let mut flash = MockFlash::new(); + flash.flash_erase(0, SECTOR_SIZE).unwrap(); + flash.flash_write(0, &[0x00; 4]).unwrap(); + + flash.flash_write(0, &[ERASE_BYTE; 4]).unwrap(); + let mut bytes = [0u8; 4]; + flash.flash_read(0, &mut bytes).unwrap(); + assert_eq!(bytes, [0x00; 4]); + + flash.flash_erase(0, SECTOR_SIZE).unwrap(); + flash.flash_read(0, &mut bytes).unwrap(); + assert_eq!(bytes, [ERASE_BYTE; 4]); } } diff --git a/esp-bootloader-esp-idf/src/flash/mod.rs b/esp-bootloader-esp-idf/src/flash/mod.rs index 4ed2678171b..b7f4f89e4d1 100644 --- a/esp-bootloader-esp-idf/src/flash/mod.rs +++ b/esp-bootloader-esp-idf/src/flash/mod.rs @@ -4,13 +4,20 @@ mod mock_flash; pub use flash_access::FlashAccess; -/// Alias for [`esp_storage::FlashStorage`]. +/// Alignment of plaintext writes, the flash driver programs whole words. +pub(crate) const WORD_SIZE: u32 = 4; +/// Alignment of encrypted writes, one flash encryption block. +pub(crate) const ENCRYPTED_WRITE_SIZE: u32 = 16; +/// Alignment of erases. +pub(crate) const SECTOR_SIZE: u32 = 4096; + +/// Alias for [`esp_hal::flash::Flash`]. /// /// Pass this to [`crate::partitions::read_partition_table`], /// [`crate::partitions::PartitionEntry::as_flash_region`], [`crate::ota_updater::OtaUpdater`], and /// related partition/OTA APIs. #[cfg(not(feature = "std"))] -pub type FlashStorage<'d> = esp_storage::FlashStorage<'d>; +pub type FlashStorage<'d> = esp_hal::flash::Flash<'d, esp_hal::Blocking>; #[cfg(feature = "std")] pub type FlashStorage<'d> = mock_flash::MockFlash<'d>; diff --git a/esp-bootloader-esp-idf/src/fmt.rs b/esp-bootloader-esp-idf/src/fmt.rs index 14722707e80..a8d40c7f4a6 100644 --- a/esp-bootloader-esp-idf/src/fmt.rs +++ b/esp-bootloader-esp-idf/src/fmt.rs @@ -321,7 +321,7 @@ impl Try for Result { } } -/// A way to `{:x?}` format a byte slice which is compatible with `defmt` +/// A way to `{:x?}` format a byte slice which is compatible with `defmt`. #[allow(unused)] pub(crate) struct Bytes<'a>(pub &'a [u8]); diff --git a/esp-bootloader-esp-idf/src/lib.rs b/esp-bootloader-esp-idf/src/lib.rs index ed5fcd2c53a..188c631b874 100644 --- a/esp-bootloader-esp-idf/src/lib.rs +++ b/esp-bootloader-esp-idf/src/lib.rs @@ -78,9 +78,9 @@ //! //! After the bootloader has started the application, the `.dram2_uninit` region becomes available //! for use. This region can be used for dynamic memory allocation or other purposes, but the data -//! placed there cannot be initialized (i.e. it must be `MaybeUninit`). For convenience, you can -//! use the `#[esp_hal::ram(reclaimed)]` attribute, which will also check that the variable can be -//! placed in the reclaimed memory. +//! placed there cannot be initialized (i.e. it must be `MaybeUninit`). The +//! `#[esp_hal::ram(reclaimed)]` attribute places a variable there and checks that the variable can +//! be placed in the reclaimed memory. #![doc = ""] #![cfg_attr(not(feature = "std"), doc = concat!("For ", esp_metadata_generated::chip!(), " the size of the reclaimed memory is ", esp_metadata_generated::memory_range!(size as str, "DRAM2_UNINIT")," bytes."))] #![doc = ""] @@ -98,12 +98,17 @@ #![doc(html_logo_url = "https://docs.espressif.com/projects/rust/esp-rs-grey-bg.svg")] #![no_std] +// Assumptions about the bootloader which needs to get double checked for other supported +// bootloaders +// +// - The bootloader unlocked the flash chip - see https://github.com/espressif/esp-idf/blob/383dda6c182e3dabf6355160166fe007df775629/components/bootloader_support/bootloader_flash/src/bootloader_flash.c#L734 + // MUST be the first module mod fmt; -#[cfg(not(feature = "std"))] +#[cfg(all(not(feature = "std"), flash_driver_supported))] mod rom; -#[cfg(not(feature = "std"))] +#[cfg(all(not(feature = "std"), flash_driver_supported))] pub(crate) use rom as crypto; #[cfg(feature = "std")] @@ -113,12 +118,16 @@ pub use crypto::Crc32 as Crc32ForTesting; #[cfg(feature = "std")] pub(crate) use non_rom as crypto; +#[cfg(flash_driver_supported)] mod flash; +#[cfg(flash_driver_supported)] pub mod partitions; +#[cfg(flash_driver_supported)] pub mod ota; +#[cfg(flash_driver_supported)] pub mod ota_updater; // We run tests on the host which happens to be MacOS machines and mach-o @@ -129,45 +138,43 @@ pub mod ota_updater; #[unsafe(export_name = "bootloader.NAME")] static OTA_FEATURE: [u8; 7] = *b"ESP-IDF"; -/// ESP-IDF compatible application descriptor +/// ESP-IDF compatible application descriptor. /// /// This gets populated by the [esp_app_desc] macro. #[repr(C)] pub struct EspAppDesc { - /// Magic word ESP_APP_DESC_MAGIC_WORD + /// Magic word ESP_APP_DESC_MAGIC_WORD. magic_word: u32, - /// Secure version + /// Secure version. secure_version: u32, - /// Reserved + /// Reserved. reserv1: [u32; 2], - /// Application version + /// Application version. version: [core::ffi::c_char; 32], - /// Project name + /// Project name. project_name: [core::ffi::c_char; 32], - /// Compile time + /// Compile time. time: [core::ffi::c_char; 16], - /// Compile date + /// Compile date. date: [core::ffi::c_char; 16], - /// Version IDF + /// Version IDF. idf_ver: [core::ffi::c_char; 32], - /// sha256 of elf file + /// sha256 of elf file. app_elf_sha256: [u8; 32], - /// Minimal eFuse block revision supported by image, in format: major * 100 - /// + minor + /// Minimal eFuse block revision supported by image, in format `major * 100 + minor`. min_efuse_blk_rev_full: u16, - /// Maximal eFuse block revision supported by image, in format: major * 100 - /// + minor + /// Maximal eFuse block revision supported by image, in format `major * 100 + minor`. max_efuse_blk_rev_full: u16, - /// MMU page size in log base 2 format + /// MMU page size in log base 2 format. mmu_page_size: u8, - /// Reserved + /// Reserved. reserv3: [u8; 3], - /// Reserved + /// Reserved. reserv2: [u32; 18], } impl EspAppDesc { - /// Needs to be public since it's used by the macro + /// Needs to be public since it's used by the macro. #[doc(hidden)] #[expect(clippy::too_many_arguments, reason = "For internal use only")] pub const fn new_internal( @@ -199,63 +206,63 @@ impl EspAppDesc { } } - /// The magic word - should be `0xABCD5432` + /// The magic word - should be `0xABCD5432`. pub fn magic_word(&self) -> u32 { self.magic_word } - /// Secure version + /// Secure version. pub fn secure_version(&self) -> u32 { self.secure_version } - /// Application version + /// Application version. pub fn version(&self) -> &str { array_to_str(&self.version) } - /// Application name + /// Application name. pub fn project_name(&self) -> &str { array_to_str(&self.project_name) } - /// Compile time + /// Compile time. pub fn time(&self) -> &str { array_to_str(&self.time) } - /// Compile data + /// Compile date. pub fn date(&self) -> &str { array_to_str(&self.date) } - /// IDF version + /// IDF version. pub fn idf_ver(&self) -> &str { array_to_str(&self.idf_ver) } - /// SHA256 + /// SHA256. /// - /// The default tooling won't populate this + /// The default tooling won't populate this. pub fn app_elf_sha256(&self) -> &[u8; 32] { &self.app_elf_sha256 } - /// Minimal eFuse block revision supported by image + /// Minimal eFuse block revision supported by image. /// - /// Format `major * 100 + minor` + /// Format `major * 100 + minor`. pub fn min_efuse_blk_rev_full(&self) -> u16 { self.min_efuse_blk_rev_full } - /// Maximal eFuse block revision supported by image + /// Maximal eFuse block revision supported by image. /// - /// Format `major * 100 + minor` + /// Format `major * 100 + minor`. pub fn max_efuse_blk_rev_full(&self) -> u16 { self.max_efuse_blk_rev_full } - /// MMU page size in bytes + /// MMU page size in bytes. pub fn mmu_page_size(&self) -> u32 { 2_u32.pow(self.mmu_page_size as u32) } @@ -335,13 +342,13 @@ const fn str_to_cstr_array(s: &str) -> [::core::ffi::c_char; C] ret } -/// Build time +/// Build time. pub const BUILD_TIME: &str = env!("ESP_BOOTLOADER_BUILD_TIME"); -/// Build date +/// Build date. pub const BUILD_DATE: &str = env!("ESP_BOOTLOADER_BUILD_DATE"); -/// MMU page size in bytes +/// MMU page size in bytes. pub const MMU_PAGE_SIZE: u32 = { let mmu_page_size = esp_config::esp_config_str!("ESP_BOOTLOADER_ESP_IDF_CONFIG_MMU_PAGE_SIZE").as_bytes(); @@ -358,14 +365,14 @@ pub const MMU_PAGE_SIZE: u32 = { pub const SECURE_VERSION: u32 = esp_config::esp_config_int!(u32, "ESP_BOOTLOADER_ESP_IDF_CONFIG_SECURE_VERSION"); -/// The (pretended) ESP-IDF version +/// The (pretended) ESP-IDF version. pub const ESP_IDF_COMPATIBLE_VERSION: &str = esp_config::esp_config_str!("ESP_BOOTLOADER_ESP_IDF_CONFIG_ESP_IDF_VERSION"); -/// This macro populates the application descriptor (see [EspAppDesc]) which is -/// available as a static named `ESP_APP_DESC` +/// Populates the application descriptor (see [EspAppDesc]) which is +/// available as a static named `ESP_APP_DESC`. /// -/// In most cases you can just use the no-arguments version of this macro. +/// In most cases, the no-arguments version of this macro is enough. #[macro_export] macro_rules! esp_app_desc { () => { diff --git a/esp-bootloader-esp-idf/src/ota.rs b/esp-bootloader-esp-idf/src/ota.rs index 71d17cd6865..ad452782550 100644 --- a/esp-bootloader-esp-idf/src/ota.rs +++ b/esp-bootloader-esp-idf/src/ota.rs @@ -15,7 +15,7 @@ //! should be used for the next boot. //! //! Note: The prebuilt bootloaders provided by `espflash` _might not_ include -//! OTA support. In that case you need to build the bootloader yourself. +//! OTA support. In that case, the bootloader must be built from source. //! //! The general procedure to change the active slot //! - read the partition table [crate::partitions::read_partition_table] @@ -26,14 +26,15 @@ //! For more details see use crate::partitions::{ AppPartitionSubType, + AutoFlashRegion, DataPartitionSubType, Error, - FlashRegion, PartitionType, }; const SLOT0_DATA_OFFSET: u32 = 0x0000; const SLOT1_DATA_OFFSET: u32 = 0x1000; +const SLOT_SIZE: u32 = 0x1000; const UNINITIALIZED_SEQUENCE: u32 = 0xffffffff; @@ -41,16 +42,16 @@ const UNINITIALIZED_SEQUENCE: u32 = 0xffffffff; #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, strum::FromRepr)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] enum OtaDataSlot { - /// If there is a `firmware` app-partition it's used. Otherwise OTA-0 + /// If there is a `firmware` app-partition it's used. Otherwise OTA-0. None, - /// OTA-0 + /// OTA-0. Slot0, - /// OTA-1 + /// OTA-1. Slot1, } impl OtaDataSlot { - /// The next logical OTA-data slot + /// The next logical OTA-data slot. fn next(&self) -> OtaDataSlot { match self { OtaDataSlot::None => OtaDataSlot::Slot0, @@ -76,7 +77,7 @@ pub enum OtaImageState { /// Monitor the first boot. The bootloader will change this to /// `PendingVerify` if auto-rollback is enabled. /// - /// You want to set this state after activating a newly installed update. + /// Applications set this state after activating a newly installed update. New = 0x0, /// Bootloader changes [OtaImageState::New] to @@ -130,7 +131,7 @@ struct OtaSelectEntry { } impl OtaSelectEntry { - fn read<'a, 'd>(region: &mut FlashRegion<'a, 'd>, offset: u32) -> Result { + fn read<'a, 'd>(region: &mut AutoFlashRegion<'a, 'd>, offset: u32) -> Result { fn is_valid(buffer: &[u8]) -> bool { let ota_seq = u32::from_le_bytes(unwrap!(buffer[0..4].try_into())); let ota_state = u32::from_le_bytes(unwrap!(buffer[24..28].try_into())); @@ -145,11 +146,8 @@ impl OtaSelectEntry { } let calculated_crc = crate::crypto::Crc32::new().crc(&ota_seq.to_le_bytes()); - if crc != calculated_crc { - return false; - } - true + crc == calculated_crc } let mut buffer = [0u8; 32]; @@ -166,31 +164,42 @@ impl OtaSelectEntry { fn write<'a, 'd>( &mut self, - region: &mut FlashRegion<'a, 'd>, + region: &mut AutoFlashRegion<'a, 'd>, offset: u32, ) -> Result<(), Error> { let bytes: &mut [u8; 32] = unwrap!( unsafe { core::slice::from_raw_parts_mut(self as *mut _ as *mut u8, 0x20) }.try_into() ); - region.write(offset, bytes)?; - - Ok(()) + write_slot(region, offset, bytes) } } -/// This is used to manipulate the OTA-data partition. +/// Erases the OTA-data slot at `offset` and programs `bytes` into it. +/// +/// Programming can only clear bits, so the slot has to be erased explicitly +/// before it is rewritten. +fn write_slot( + region: &mut AutoFlashRegion<'_, '_>, + offset: u32, + bytes: &[u8; 32], +) -> Result<(), Error> { + region.erase(offset, offset + SLOT_SIZE)?; + region.write(offset, bytes) +} + +/// Reads and updates the OTA-data partition. /// -/// If you are looking for a more high-level way to do this, see [crate::ota_updater::OtaUpdater] +/// For a higher-level API, see [crate::ota_updater::OtaUpdater]. #[derive(Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub struct Ota<'a, 'd> { - flash: FlashRegion<'a, 'd>, + flash: AutoFlashRegion<'a, 'd>, ota_partition_count: usize, } impl<'a, 'd> Ota<'a, 'd> { - /// Create a [Ota] instance from the given [FlashRegion] and the count of OTA app partitions - /// (not including "firmware" and "test" partitions) + /// Creates a new [Ota] instance from the given [AutoFlashRegion] and the count of OTA app + /// partitions (not including "firmware" and "test" partitions). /// /// # Errors /// A [Error::InvalidPartition] if the given flash region @@ -198,7 +207,7 @@ impl<'a, 'd> Ota<'a, 'd> { /// /// [Error::InvalidArgument] if the `ota_partition_count` exceeds the maximum or if it's 0. pub fn new( - flash: FlashRegion<'a, 'd>, + flash: AutoFlashRegion<'a, 'd>, ota_partition_count: usize, ) -> Result, Error> { if ota_partition_count == 0 || ota_partition_count > 16 { @@ -206,7 +215,7 @@ impl<'a, 'd> Ota<'a, 'd> { } if flash.capacity() != 0x2000 - || flash.partition_type != PartitionType::Data(DataPartitionSubType::Ota) + || flash.partition_type() != PartitionType::Data(DataPartitionSubType::Ota) { return Err(Error::InvalidPartition { expected_size: 0x2000, @@ -268,8 +277,8 @@ impl<'a, 'd> Ota<'a, 'd> { /// number exceeds the value given to the constructor. pub fn set_current_app_partition(&mut self, app: AppPartitionSubType) -> Result<(), Error> { if app == AppPartitionSubType::Factory { - self.flash.write(SLOT0_DATA_OFFSET, &[0xffu8; 0x20])?; - self.flash.write(SLOT1_DATA_OFFSET, &[0xffu8; 0x20])?; + write_slot(&mut self.flash, SLOT0_DATA_OFFSET, &[0xffu8; 0x20])?; + write_slot(&mut self.flash, SLOT1_DATA_OFFSET, &[0xffu8; 0x20])?; return Ok(()); } @@ -352,7 +361,7 @@ impl<'a, 'd> Ota<'a, 'd> { Ok(slot) } - /// Set the [OtaImageState] of the currently selected slot. + /// Sets the [OtaImageState] of the currently selected slot. /// /// # Errors /// A [Error::InvalidState] if no partition is currently selected. @@ -368,7 +377,7 @@ impl<'a, 'd> Ota<'a, 'd> { } } - /// Get the [OtaImageState] of the currently selected slot. + /// Returns the [OtaImageState] of the currently selected slot. /// /// # Errors /// A [Error::InvalidState] if no partition is currently selected. @@ -426,8 +435,8 @@ mod tests { fn ota_region<'a>( flash: &'a mut FlashStorage<'static>, binary: [u8; 32], - ) -> FlashRegion<'a, 'static> { - PartitionEntry { binary }.as_flash_region(flash) + ) -> AutoFlashRegion<'a, 'static> { + PartitionEntry { binary }.as_auto_flash_region(flash) } fn init_ota_flash(flash: &mut FlashStorage<'static>) { diff --git a/esp-bootloader-esp-idf/src/ota_updater.rs b/esp-bootloader-esp-idf/src/ota_updater.rs index 62903ac4ce3..546526a1de8 100644 --- a/esp-bootloader-esp-idf/src/ota_updater.rs +++ b/esp-bootloader-esp-idf/src/ota_updater.rs @@ -2,12 +2,12 @@ use crate::{ ota::OtaImageState, - partitions::{AppPartitionSubType, Error, FlashRegion, FlashStorage, PartitionTable}, + partitions::{AppPartitionSubType, AutoFlashRegion, Error, FlashStorage, PartitionTable}, }; -/// This can be used as more convenient - yet less flexible, way to do OTA updates. +/// Provides a more convenient, but less flexible, way to do OTA updates. /// -/// If you need lower level access see [crate::ota::Ota] +/// For lower-level access, see [crate::ota::Ota]. #[derive(Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub struct OtaUpdater<'a, 'd> { @@ -17,7 +17,7 @@ pub struct OtaUpdater<'a, 'd> { } impl<'a, 'd> OtaUpdater<'a, 'd> { - /// Create a new instance of [OtaUpdater]. + /// Creates a new instance of [OtaUpdater]. /// /// # Errors /// [Error::Invalid] if no OTA data partition or less than two OTA app partition were found. @@ -72,7 +72,7 @@ impl<'a, 'd> OtaUpdater<'a, 'd> { crate::partitions::DataPartitionSubType::Ota, ))?; if let Some(ota_part) = ota_part { - let ota_part = ota_part.as_flash_region(self.flash); + let ota_part = ota_part.as_auto_flash_region(self.flash); let ota = crate::ota::Ota::new(ota_part, self.ota_count)?; Ok(ota) } else { @@ -94,7 +94,7 @@ impl<'a, 'd> OtaUpdater<'a, 'd> { let next = if let Some(booted) = booted { if booted.partition_type() == crate::partitions::PartitionType::App(next) { AppPartitionSubType::from_ota_app_number( - (current.ota_app_number() + 2) % self.ota_count as u8, + (next.ota_app_number() + 1) % self.ota_count as u8, )? } else { next @@ -111,7 +111,7 @@ impl<'a, 'd> OtaUpdater<'a, 'd> { self.ota_data()?.current_app_partition() } - /// Get the [OtaImageState] of the currently selected partition. + /// Returns the [OtaImageState] of the currently selected partition. /// /// # Errors /// A [Error::InvalidState] if no partition is currently selected. @@ -119,7 +119,7 @@ impl<'a, 'd> OtaUpdater<'a, 'd> { self.ota_data()?.current_ota_state() } - /// Set the [OtaImageState] of the currently selected slot. + /// Sets the [OtaImageState] of the currently selected slot. /// /// # Errors /// A [Error::InvalidState] if no partition is currently selected. @@ -136,21 +136,26 @@ impl<'a, 'd> OtaUpdater<'a, 'd> { self.ota_data()?.set_current_app_partition(next_slot) } - /// Returns a [FlashRegion] along with the [AppPartitionSubType] for the + /// Returns an [AutoFlashRegion] along with the [AppPartitionSubType] for the /// partition which would be selected by [Self::activate_next_partition]. - pub fn next_partition(&mut self) -> Result<(FlashRegion<'_, 'd>, AppPartitionSubType), Error> { + /// + /// The region is encrypted when flash encryption is enabled. Erase it before + /// writing the new image. + pub fn next_partition( + &mut self, + ) -> Result<(AutoFlashRegion<'_, 'd>, AppPartitionSubType), Error> { let next_slot = self.next_ota_part()?; let flash_region = self .pt .find_partition(crate::partitions::PartitionType::App(next_slot))? .ok_or(Error::Invalid)? - .as_flash_region(self.flash); + .as_auto_flash_region(self.flash); Ok((flash_region, next_slot)) } - /// Reset the OTA-data. + /// Resets the OTA-data. /// /// If present this will activate the FACTORY image, OTA0 otherwise. pub fn reset_data(&mut self) -> Result<(), Error> { diff --git a/esp-bootloader-esp-idf/src/partitions.rs b/esp-bootloader-esp-idf/src/partitions.rs deleted file mode 100644 index 36717c80e55..00000000000 --- a/esp-bootloader-esp-idf/src/partitions.rs +++ /dev/null @@ -1,1549 +0,0 @@ -//! # Partition Table Support -//! -//! ## Overview -//! -//! This module allows reading the partition table and conveniently -//! writing/reading partition contents. -//! -//! For more information see - -/// Maximum length of a partition table. -pub const PARTITION_TABLE_MAX_LEN: usize = 0xC00; - -const PARTITION_TABLE_OFFSET: u32 = - esp_config::esp_config_int!(u32, "ESP_BOOTLOADER_ESP_IDF_CONFIG_PARTITION_TABLE_OFFSET"); - -const RAW_ENTRY_LEN: usize = 32; -const ENTRY_MAGIC: u16 = 0x50aa; -#[cfg(feature = "validation")] -const MD5_MAGIC: u16 = 0xebeb; - -const OTA_SUBTYPE_OFFSET: u8 = 0x10; - -use crate::flash::FlashAccess; -pub use crate::flash::FlashStorage; - -/// Represents a single partition entry. -#[derive(Clone, Copy)] -pub struct PartitionEntry { - pub(crate) binary: [u8; RAW_ENTRY_LEN], -} - -impl PartitionEntry { - fn new(binary: &[u8; RAW_ENTRY_LEN]) -> Self { - Self { binary: *binary } - } - - /// The magic value of the entry. - pub fn magic(&self) -> u16 { - u16::from_le_bytes(unwrap!(self.binary[..2].try_into())) - } - - /// The partition type in raw representation. - pub fn raw_type(&self) -> u8 { - self.binary[2] - } - - /// The partition sub-type in raw representation. - pub fn raw_subtype(&self) -> u8 { - self.binary[3] - } - - /// Offset of the partition on flash. - pub fn offset(&self) -> u32 { - u32::from_le_bytes(unwrap!(self.binary[4..][..4].try_into())) - } - - /// Length of the partition in bytes. - pub fn len(&self) -> u32 { - u32::from_le_bytes(unwrap!(self.binary[8..][..4].try_into())) - } - - /// Checks for a zero-length partition. - pub fn is_empty(&self) -> bool { - self.len() == 0 - } - - /// The label of the partition. - pub fn label(&self) -> &[u8] { - &self.binary[12..][..16] - } - - /// The label of the partition as `&str`. - pub fn label_as_str(&self) -> &str { - let array = self.label(); - let len = array - .iter() - .position(|b| *b == 0 || *b == 0xff) - .unwrap_or(array.len()); - unsafe { - core::str::from_utf8_unchecked(core::slice::from_raw_parts(array.as_ptr().cast(), len)) - } - } - - /// Raw flags of this partition. You probably want to use - /// [Self::is_read_only] and [Self::is_encrypted] instead. - pub fn flags(&self) -> u32 { - u32::from_le_bytes(unwrap!(self.binary[28..][..4].try_into())) - } - - /// If the partition is read only. - pub fn is_read_only(&self) -> bool { - self.flags() & 0b01 != 0 - } - - /// If the partition is encrypted. - /// - /// This is the flag from the partition table. - /// If flash encryption is enabled certain partition types are encrypted - /// regardless of this. - pub fn is_encrypted(&self) -> bool { - self.flags() & 0b10 != 0 - } - - /// Like [PartitionEntry::is_encrypted] but also takes into account: - /// - is flash encryption enabled, otherwise this will always return false - /// - certain partition types are always encrypted, no matter what the partition table says - pub(crate) fn is_effectively_encrypted(&self) -> bool { - #[cfg(feature = "std")] - let enabled = false; - - #[cfg(not(feature = "std"))] - let enabled = esp_storage::flash_encryption(); - - enabled - && (self.is_encrypted() - || matches!(self.partition_type(), PartitionType::App(_)) - || matches!(self.partition_type(), PartitionType::PartitionTable(_)) - || matches!( - self.partition_type(), - PartitionType::Data(DataPartitionSubType::NvsKeys) - ) - || matches!( - self.partition_type(), - PartitionType::Data(DataPartitionSubType::Ota) - )) - } - - /// The partition type (type and sub-type). - pub fn partition_type(&self) -> PartitionType { - match self.raw_type() { - 0 => PartitionType::App(unwrap!(self.raw_subtype().try_into())), - 1 => PartitionType::Data(unwrap!(self.raw_subtype().try_into())), - 2 => PartitionType::Bootloader(unwrap!(self.raw_subtype().try_into())), - 3 => PartitionType::PartitionTable(unwrap!(self.raw_subtype().try_into())), - _ => unreachable!(), - } - } - - /// Provides a "view" into the partition allowing to read/write the - /// partition contents using the given [`FlashStorage`]. - pub fn as_flash_region<'a, 'd>(self, flash: &'a mut FlashStorage<'d>) -> FlashRegion<'a, 'd> { - FlashRegion { - offset: self.offset(), - len: self.len(), - partition_type: self.partition_type(), - read_only: self.is_read_only(), - encrypted: self.is_effectively_encrypted(), - flash, - } - } - - /// Calculate the SHA-256 digest of this partition. - /// - /// - App / bootloader with appended hash: return that digest after verifying it - /// - App / bootloader without appended hash: hash the image (not the whole partition) - /// - Other types: hash the entire partition - /// - /// For app images this is the **validation hash** (shown by - /// `esptool.py image-info`), not the ELF file SHA-256 stored in - /// [`crate::EspAppDesc`]. - pub fn sha256(&self, flash: &mut FlashStorage<'_>) -> Result<[u8; 32], Error> { - if self.is_empty() { - return Err(Error::InvalidArgument); - } - - let address = self.offset(); - let encrypted = self.is_effectively_encrypted(); - let mut size = self.len(); - - if matches!( - self.partition_type(), - PartitionType::App(_) | PartitionType::Bootloader(_) - ) { - let data = get_image_metadata(flash, address, size, encrypted)?; - if data.hash_appended { - let calc = sha256_flash_contents( - flash, - address, - data.image_len - PARTITION_HASH_LEN as u32, - encrypted, - )?; - if calc != data.image_digest { - return Err(Error::InvalidImage); - } - return Ok(data.image_digest); - } - size = data.image_len; - } - - sha256_flash_contents(flash, address, size, encrypted) - } -} - -impl core::fmt::Debug for PartitionEntry { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - f.debug_struct("PartitionEntry") - .field("magic", &self.magic()) - .field("raw_type", &self.raw_type()) - .field("raw_subtype", &self.raw_subtype()) - .field("offset", &self.offset()) - .field("len", &self.len()) - .field("label", &self.label_as_str()) - .field("flags", &self.flags()) - .field("is_read_only", &self.is_read_only()) - .field("is_encrypted", &self.is_encrypted()) - .finish() - } -} - -#[cfg(feature = "defmt")] -impl defmt::Format for PartitionEntry { - fn format(&self, fmt: defmt::Formatter) { - defmt::write!( - fmt, - "PartitionEntry (\ - magic = {}, \ - raw_type = {}, \ - raw_subtype = {}, \ - offset = {}, \ - len = {}, \ - label = {}, \ - flags = {}, \ - is_read_only = {}, \ - is_encrypted = {}\ - )", - self.magic(), - self.raw_type(), - self.raw_subtype(), - self.offset(), - self.len(), - self.label_as_str(), - self.flags(), - self.is_read_only(), - self.is_encrypted() - ) - } -} - -/// Errors which can be returned. -#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, strum::Display)] -#[cfg_attr(feature = "defmt", derive(defmt::Format))] -#[non_exhaustive] -pub enum Error { - /// The partition table is invalid or doesn't contain a needed partition. - Invalid, - /// An operation tries to access data that is out of bounds. - OutOfBounds, - /// An error which originates from the embedded-storage implementation. - StorageError, - /// The partition is write protected. - WriteProtected, - /// The partition is invalid. - InvalidPartition { - expected_size: usize, - expected_type: PartitionType, - }, - /// Invalid state - InvalidState, - /// The given argument is invalid. - InvalidArgument, - /// The operation is not supported for this partition (e.g. `as_nor_flash` on an encrypted - /// partition). - NotSupported, - /// The partition does not contain a valid application or bootloader image. - InvalidImage, -} - -impl core::error::Error for Error {} - -/// A partition table. -#[derive(Debug)] -#[cfg_attr(feature = "defmt", derive(defmt::Format))] -pub struct PartitionTable<'a> { - binary: &'a [[u8; RAW_ENTRY_LEN]], - entries: usize, -} - -impl<'a> PartitionTable<'a> { - fn new(binary: &'a [u8]) -> Result { - if binary.len() > PARTITION_TABLE_MAX_LEN { - return Err(Error::Invalid); - } - - let (binary, rem) = binary.as_chunks::(); - if !rem.is_empty() { - return Err(Error::Invalid); - } - - if binary.is_empty() { - return Ok(Self { - binary: &[], - entries: 0, - }); - } - - let mut raw_table = Self { - binary, - entries: binary.len(), - }; - - #[cfg(feature = "validation")] - { - let index = raw_table - .binary - .iter() - .position(|entry| u16::from_le_bytes([entry[0], entry[1]]) == MD5_MAGIC) - .ok_or(Error::Invalid)?; - let hash = &raw_table.binary[index][16..][..16]; - - let mut hasher = crate::crypto::Md5::new(); - - for entry in &raw_table.binary[..index] { - hasher.update(entry); - } - let calculated_hash = hasher.finalize(); - - if calculated_hash != hash { - return Err(Error::Invalid); - } - } - - let entries = { - let mut i = 0; - loop { - if let Ok(entry) = raw_table.get_partition(i) { - if entry.magic() != ENTRY_MAGIC { - break; - } - - i += 1; - - if i == raw_table.entries { - break; - } - } else { - return Err(Error::Invalid); - } - } - i - }; - - raw_table.entries = entries; - - Ok(raw_table) - } - - /// Number of partitions contained in the partition table. - pub fn len(&self) -> usize { - self.entries - } - - /// Checks if there are no recognized partitions. - pub fn is_empty(&self) -> bool { - self.entries == 0 - } - - /// Get a partition entry. - pub fn get_partition(&self, index: usize) -> Result { - if index >= self.entries { - return Err(Error::OutOfBounds); - } - Ok(PartitionEntry::new(&self.binary[index])) - } - - /// Get the first partition matching the given partition type. - pub fn find_partition(&self, pt: PartitionType) -> Result, Error> { - for i in 0..self.entries { - let entry = self.get_partition(i)?; - if entry.partition_type() == pt { - return Ok(Some(entry)); - } - } - Ok(None) - } - - /// Returns an iterator over the partitions. - pub fn iter(&self) -> impl Iterator { - (0..self.entries).filter_map(|i| self.get_partition(i).ok()) - } - - #[cfg(feature = "std")] - /// Get the currently booted partition. - pub fn booted_partition(&self) -> Result, Error> { - Err(Error::Invalid) - } - - #[cfg(not(feature = "std"))] - /// Get the currently booted partition. - pub fn booted_partition(&self) -> Result, Error> { - // Read entry 0 from MMU to know which partition is mapped - // - // See - cfg_select! { - feature = "esp32" => { - let paddr = unsafe { ((0x3FF10000 as *const u32).read_volatile() & 0xff) << 16 }; - } - feature = "esp32s2" => { - let paddr = unsafe { - (((0x61801000 + 128 * 4) as *const u32).read_volatile() & 0xff) << 16 - }; - } - feature = "esp32s3" => { - // Revisit this once we support XiP from PSRAM for ESP32-S3 - let paddr = unsafe { ((0x600C5000 as *const u32).read_volatile() & 0xff) << 16 }; - } - any(feature = "esp32c2", feature = "esp32c3") => { - let paddr = unsafe { ((0x600c5000 as *const u32).read_volatile() & 0xff) << 16 }; - } - feature = "esp32p4" => { - // DR_REG_FLASH_SPI0_BASE : 0x5008C000 = DR_REG_HPPERIPH0_BASE + 0x8C000 - // TODO: verify MSPI register for partition physical address read - let paddr = unsafe { - ((0x5008C000 + 0x380) as *mut u32).write_volatile(0); // SPI_MEM_C_MMU_ITEM_INDEX_REG - (((0x5008C000 + 0x37c) as *const u32).read_volatile() & 0xff) << 16 // SPI_MEM_C_MMU_ITEM_CONTENT_REG - }; - } - feature = "esp32s31" => { - // Read MMU entry 0, which maps the beginning of the flash - // virtual-address range. - let paddr = unsafe { - ((0x20500000 + 0x380) as *mut u32).write_volatile(0); // SPI_MEM_C_MMU_ITEM_INDEX_REG - (((0x20500000 + 0x37c) as *const u32).read_volatile() & 0x7ff) << 16 // SPI_MEM_C_MMU_ITEM_CONTENT_REG - }; - } - any( - feature = "esp32c5", - feature = "esp32c6", - feature = "esp32c61", - feature = "esp32h2" - ) => { - let paddr = unsafe { - ((0x60002000 + 0x380) as *mut u32).write_volatile(0); - (((0x60002000 + 0x37c) as *const u32).read_volatile() & 0xff) << 16 - }; - } - _ => {} - } - - for id in 0..self.len() { - let entry = self.get_partition(id)?; - if entry.offset() == paddr { - return Ok(Some(entry)); - } - } - - Ok(None) - } -} - -/// A partition type including the sub-type. -#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)] -#[cfg_attr(feature = "defmt", derive(defmt::Format))] -pub enum PartitionType { - /// Application. - App(AppPartitionSubType), - /// Data. - Data(DataPartitionSubType), - /// Bootloader. - Bootloader(BootloaderPartitionSubType), - /// Partition table. - PartitionTable(PartitionTablePartitionSubType), -} - -/// A partition type -#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)] -#[cfg_attr(feature = "defmt", derive(defmt::Format))] -#[repr(u8)] -pub enum RawPartitionType { - /// Application. - App = 0, - /// Data. - Data, - /// Bootloader. - Bootloader, - /// Partition table. - PartitionTable, -} - -/// Sub-types of an application partition. -#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, strum::FromRepr)] -#[cfg_attr(feature = "defmt", derive(defmt::Format))] -#[repr(u8)] -pub enum AppPartitionSubType { - /// Factory image - Factory = 0, - /// OTA slot 0 - Ota0 = OTA_SUBTYPE_OFFSET, - /// OTA slot 1 - Ota1, - /// OTA slot 2 - Ota2, - /// OTA slot 3 - Ota3, - /// OTA slot 4 - Ota4, - /// OTA slot 5 - Ota5, - /// OTA slot 6 - Ota6, - /// OTA slot 7 - Ota7, - /// OTA slot 8 - Ota8, - /// OTA slot 9 - Ota9, - /// OTA slot 10 - Ota10, - /// OTA slot 11 - Ota11, - /// OTA slot 12 - Ota12, - /// OTA slot 13 - Ota13, - /// OTA slot 14 - Ota14, - /// OTA slot 15 - Ota15, - /// Test image - Test, -} - -impl AppPartitionSubType { - pub(crate) fn ota_app_number(&self) -> u8 { - *self as u8 - OTA_SUBTYPE_OFFSET - } - - pub(crate) fn from_ota_app_number(number: u8) -> Result { - if number > 16 { - return Err(Error::InvalidArgument); - } - Self::try_from(number + OTA_SUBTYPE_OFFSET) - } -} - -impl TryFrom for AppPartitionSubType { - type Error = Error; - - fn try_from(value: u8) -> Result { - AppPartitionSubType::from_repr(value).ok_or(Error::Invalid) - } -} - -/// Sub-types of the data partition type. -#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, strum::FromRepr)] -#[cfg_attr(feature = "defmt", derive(defmt::Format))] -#[repr(u8)] -pub enum DataPartitionSubType { - /// Data partition which stores information about the currently selected OTA - /// app slot. This partition should be 0x2000 bytes in size. Refer to - /// the OTA documentation for more details. - Ota = 0, - /// Phy is for storing PHY initialization data. This allows PHY to be - /// configured per-device, instead of in firmware. - Phy, - /// Used for Non-Volatile Storage (NVS). - Nvs, - /// Used for storing core dumps while using a custom partition table - Coredump, - /// NvsKeys is used for the NVS key partition. (NVS). - NvsKeys, - /// Used for emulating eFuse bits using Virtual eFuses. - EfuseEm, - /// Implicitly used for data partitions with unspecified (empty) subtype, - /// but it is possible to explicitly mark them as undefined as well. - Undefined, - /// FAT Filesystem Support. - Fat = 0x81, - /// SPIFFS Filesystem. - Spiffs = 0x82, - /// LittleFS filesystem. - LittleFs = 0x83, -} - -impl TryFrom for DataPartitionSubType { - type Error = Error; - - fn try_from(value: u8) -> Result { - DataPartitionSubType::from_repr(value).ok_or(Error::Invalid) - } -} - -/// Sub-type of the bootloader partition type. -#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, strum::FromRepr)] -#[cfg_attr(feature = "defmt", derive(defmt::Format))] -#[repr(u8)] -pub enum BootloaderPartitionSubType { - /// It is the so-called 2nd stage bootloader. - Primary = 0, - /// It is a temporary bootloader partition used by the bootloader OTA update - /// functionality for downloading a new image. - Ota = 1, -} - -impl TryFrom for BootloaderPartitionSubType { - type Error = Error; - - fn try_from(value: u8) -> Result { - BootloaderPartitionSubType::from_repr(value).ok_or(Error::Invalid) - } -} - -/// Sub-type of the partition table type. -#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, strum::FromRepr)] -#[cfg_attr(feature = "defmt", derive(defmt::Format))] -#[repr(u8)] -pub enum PartitionTablePartitionSubType { - /// It is the primary partition table. - Primary = 0, - /// It is a temporary partition table partition used by the partition table - /// OTA update functionality for downloading a new image. - Ota = 1, -} - -impl TryFrom for PartitionTablePartitionSubType { - type Error = Error; - - fn try_from(value: u8) -> Result { - PartitionTablePartitionSubType::from_repr(value).ok_or(Error::Invalid) - } -} - -/// Read the partition table. -/// -/// Pass [`FlashStorage`] and a buffer to read the partition table into. -pub fn read_partition_table<'a, 'd>( - flash: &mut FlashStorage<'d>, - storage: &'a mut [u8], -) -> Result, Error> { - read_partition_table_impl(flash, storage) -} - -fn read_partition_table_impl<'a, F: FlashAccess>( - flash: &mut F, - storage: &'a mut [u8], -) -> Result, Error> { - #[cfg(feature = "std")] - let enabled = false; - - #[cfg(not(feature = "std"))] - let enabled = esp_storage::flash_encryption(); - - if enabled { - flash.flash_read_encrypted(PARTITION_TABLE_OFFSET, storage)?; - } else { - flash.flash_read(PARTITION_TABLE_OFFSET, storage)?; - } - - PartitionTable::new(storage) -} - -const PARTITION_HASH_LEN: usize = 32; -const IMAGE_HEADER_MAGIC: u8 = 0xE9; -const IMAGE_HEADER_LEN: u32 = 24; -const IMAGE_MAX_SEGMENTS: u8 = 16; -const IMAGE_MAX_FLASH_ADDR_SIZE: u32 = 16 * 1024 * 1024; - -/// Subset of ESP-IDF `esp_image_metadata_t` for partition SHA-256 convenience. -struct ImageMetadata { - image_len: u32, - image_digest: [u8; PARTITION_HASH_LEN], - hash_appended: bool, -} - -/// Parse an app/bootloader image on flash and return its length and optional -/// appended SHA-256 digest. -/// -/// Walks the image header and segment table, accounts for the checksum -/// padding, and — if the image has a simple hash appended — reads that digest. -/// Does not verify the checksum or load any segments. -fn get_image_metadata( - flash: &mut F, - address: u32, - part_size: u32, - encrypted: bool, -) -> Result { - if part_size == 0 || part_size > IMAGE_MAX_FLASH_ADDR_SIZE { - return Err(Error::InvalidArgument); - } - - // process_image_header() - let mut hdr = [0u8; IMAGE_HEADER_LEN as usize]; - flash_read(flash, address, &mut hdr, encrypted)?; - // `esp_image_get_metadata` skips header verify, but refuse obvious garbage. - if hdr[0] != IMAGE_HEADER_MAGIC || hdr[1] > IMAGE_MAX_SEGMENTS { - return Err(Error::InvalidImage); - } - - let mut image_len = IMAGE_HEADER_LEN; - - // process_segments() - for _ in 0..hdr[1] { - let mut seg = [0u8; 8]; - flash_read(flash, address + image_len, &mut seg, encrypted)?; - // seg[0..4] - load address - let data_len = u32::from_le_bytes(unwrap!(seg[4..8].try_into())); - if data_len % 4 != 0 || data_len >= IMAGE_MAX_FLASH_ADDR_SIZE { - return Err(Error::InvalidImage); - } - image_len = image_len - .checked_add(8 + data_len) - .ok_or(Error::InvalidImage)?; - } - - // process_checksum() - // add a byte for the checksum, pad to next full 16 byte block - image_len = (image_len + 1 + 15) & !15; - - // process_appended_hash_and_sig() - let hash_appended = hdr[23] != 0; - let mut image_digest = [0u8; PARTITION_HASH_LEN]; - if hash_appended { - flash_read(flash, address + image_len, &mut image_digest, encrypted)?; - image_len += PARTITION_HASH_LEN as u32; - } - - if image_len > part_size { - return Err(Error::InvalidImage); - } - - Ok(ImageMetadata { - image_len, - image_digest, - hash_appended, - }) -} - -fn flash_read( - flash: &mut F, - address: u32, - bytes: &mut [u8], - encrypted: bool, -) -> Result<(), Error> { - if encrypted { - flash.flash_read_encrypted(address, bytes) - } else { - flash.flash_read(address, bytes) - } -} - -/// Hash `len` bytes of flash starting at `flash_offset`. -/// -/// Reads the region in fixed-size chunks so large partitions do not need to be -/// loaded into memory at once. -fn sha256_flash_contents( - flash: &mut F, - mut flash_offset: u32, - mut len: u32, - encrypted: bool, -) -> Result<[u8; PARTITION_HASH_LEN], Error> { - use sha2::{Digest, Sha256}; - - let mut hasher = Sha256::new(); - let mut chunk = [0u8; 4096]; - - while len > 0 { - let n = len.min(chunk.len() as u32) as usize; - flash_read(flash, flash_offset, &mut chunk[..n], encrypted)?; - hasher.update(&chunk[..n]); - flash_offset += n as u32; - len -= n as u32; - } - - Ok(hasher.finalize().into()) -} - -/// A flash region is a "view" into the partition. -/// -/// It allows to read and write to the partition without the need to account for -/// the partition offset. -#[derive(Debug)] -#[cfg_attr(feature = "defmt", derive(defmt::Format))] -pub struct FlashRegion<'a, 'd> { - pub(crate) offset: u32, - pub(crate) len: u32, - pub(crate) partition_type: PartitionType, - pub(crate) read_only: bool, - /// Whether the partition is effectively encrypted (see - /// `PartitionEntry::is_effectively_encrypted`). - pub(crate) encrypted: bool, - pub(crate) flash: &'a mut FlashStorage<'d>, -} - -impl<'a, 'd> FlashRegion<'a, 'd> { - /// Returns the size of the partition in bytes. - pub fn partition_size(&self) -> usize { - self.len as _ - } - - fn range(&self) -> core::ops::Range { - self.offset..self.offset + self.len - } - - fn in_range(&self, start: u32, len: usize) -> bool { - self.range().contains(&start) && (start + len as u32 <= self.range().end) - } - - /// Read bytes from the partition. - pub fn read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Error> { - let address = offset + self.offset; - - if !self.in_range(address, bytes.len()) { - return Err(Error::OutOfBounds); - } - - if self.encrypted { - self.flash.flash_read_encrypted(address, bytes) - } else { - self.flash.flash_read(address, bytes) - } - } - - /// Write bytes to the partition. - pub fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Error> { - let address = offset + self.offset; - - if self.read_only { - return Err(Error::WriteProtected); - } - - if !self.in_range(address, bytes.len()) { - return Err(Error::OutOfBounds); - } - - if self.encrypted { - self.flash.flash_write_encrypted(address, bytes) - } else { - self.flash.flash_write(address, bytes) - } - } - - /// Returns the size of the partition in bytes. - pub fn capacity(&self) -> usize { - self.partition_size() - } - - /// Erase flash in the partition from `from` up to but not including `to`. - /// - /// Addresses are relative to the partition start. - pub fn erase(&mut self, from: u32, to: u32) -> Result<(), Error> { - let address_from = from + self.offset; - let address_to = to + self.offset; - - if self.read_only { - return Err(Error::WriteProtected); - } - - if from > to { - return Err(Error::OutOfBounds); - } - - if !self.in_range(address_from, (address_to - address_from) as usize) { - return Err(Error::OutOfBounds); - } - - self.flash.flash_erase(address_from, address_to) - } -} - -#[cfg(feature = "embedded-storage")] -/// [`NorFlash`] and [`MultiwriteNorFlash`] view of a non-encrypted [`FlashRegion`]. -pub struct NorFlashRegion<'r, 'a, 'd> { - region: &'r mut FlashRegion<'a, 'd>, -} - -#[cfg(feature = "embedded-storage")] -/// [`NorFlash`] view of an encrypted [`FlashRegion`]. -/// -/// Write size is one flash sector ([`esp_storage::FlashStorage::SECTOR_SIZE`]): the ROM encrypts -/// whole sectors. -pub struct EncryptedNorFlashRegion<'r, 'a, 'd> { - region: &'r mut FlashRegion<'a, 'd>, -} - -#[cfg(feature = "embedded-storage")] -mod embedded_storage_traits { - use ::embedded_storage::{ - ReadStorage, - Region, - Storage, - nor_flash::{ - ErrorType, - MultiwriteNorFlash, - NorFlash, - NorFlashError, - NorFlashErrorKind, - ReadNorFlash, - }, - }; - - use super::*; - - const NOR_READ_SIZE: usize = as FlashAccess>::READ_SIZE; - const NOR_WRITE_SIZE: usize = as FlashAccess>::WRITE_SIZE; - const NOR_ERASE_SIZE: usize = as FlashAccess>::ERASE_SIZE; - const ENCRYPTED_WRITE_SIZE: usize = - as FlashAccess>::SECTOR_SIZE as usize; - - impl<'a, 'd> FlashRegion<'a, 'd> { - /// Returns a [`NorFlashRegion`] for [`NorFlash`] access. - /// - /// # Errors - /// - /// Returns [`Error::NotSupported`] if this partition is treated as encrypted (e.g. app - /// partitions when flash encryption is enabled). - pub fn as_nor_flash<'r>(&'r mut self) -> Result, Error> { - if self.encrypted { - return Err(Error::NotSupported); - } - - Ok(NorFlashRegion { region: self }) - } - - /// Returns a [`EncryptedNorFlashRegion`] for [`NorFlash`] access. - /// - /// # Errors - /// - /// Returns [`Error::NotSupported`] if this partition is not treated as encrypted. - pub fn as_nor_flash_encrypted<'r>( - &'r mut self, - ) -> Result, Error> { - if !self.encrypted { - return Err(Error::NotSupported); - } - - Ok(EncryptedNorFlashRegion { region: self }) - } - } - - impl Region for FlashRegion<'_, '_> { - fn contains(&self, address: u32) -> bool { - self.range().contains(&address) - } - } - - impl ReadStorage for FlashRegion<'_, '_> { - type Error = Error; - - fn read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Self::Error> { - FlashRegion::read(self, offset, bytes) - } - - fn capacity(&self) -> usize { - FlashRegion::capacity(self) - } - } - - impl Storage for FlashRegion<'_, '_> { - fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> { - FlashRegion::write(self, offset, bytes) - } - } - - impl NorFlashError for Error { - fn kind(&self) -> NorFlashErrorKind { - match self { - Error::OutOfBounds => NorFlashErrorKind::OutOfBounds, - _ => NorFlashErrorKind::Other, - } - } - } - - impl ErrorType for NorFlashRegion<'_, '_, '_> { - type Error = Error; - } - - impl ReadNorFlash for NorFlashRegion<'_, '_, '_> { - const READ_SIZE: usize = NOR_READ_SIZE; - - fn read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Self::Error> { - let address = offset + self.region.offset; - - if !self.region.in_range(address, bytes.len()) { - return Err(Error::OutOfBounds); - } - - self.region.flash.flash_read_nor(address, bytes) - } - - fn capacity(&self) -> usize { - self.region.capacity() - } - } - - impl NorFlash for NorFlashRegion<'_, '_, '_> { - const WRITE_SIZE: usize = NOR_WRITE_SIZE; - const ERASE_SIZE: usize = NOR_ERASE_SIZE; - - fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> { - self.region.erase(from, to) - } - - fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> { - let address = offset + self.region.offset; - - if self.region.read_only { - return Err(Error::WriteProtected); - } - - if !self.region.in_range(address, bytes.len()) { - return Err(Error::OutOfBounds); - } - - self.region.flash.flash_write_nor(address, bytes) - } - } - - impl MultiwriteNorFlash for NorFlashRegion<'_, '_, '_> {} - - impl ErrorType for EncryptedNorFlashRegion<'_, '_, '_> { - type Error = Error; - } - - impl ReadNorFlash for EncryptedNorFlashRegion<'_, '_, '_> { - const READ_SIZE: usize = NOR_READ_SIZE; - - fn read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Self::Error> { - let address = offset + self.region.offset; - - if !self.region.in_range(address, bytes.len()) { - return Err(Error::OutOfBounds); - } - - self.region.flash.flash_read_encrypted(address, bytes) - } - - fn capacity(&self) -> usize { - self.region.capacity() - } - } - - impl NorFlash for EncryptedNorFlashRegion<'_, '_, '_> { - const WRITE_SIZE: usize = ENCRYPTED_WRITE_SIZE; - const ERASE_SIZE: usize = NOR_ERASE_SIZE; - - fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> { - self.region.erase(from, to) - } - - fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> { - let address = offset + self.region.offset; - - if self.region.read_only { - return Err(Error::WriteProtected); - } - - if !self.region.in_range(address, bytes.len()) { - return Err(Error::OutOfBounds); - } - - self.region.flash.flash_write_encrypted(address, bytes) - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - static SIMPLE: &[u8] = include_bytes!("../testdata/single_factory_no_ota.bin"); - static OTA: &[u8] = include_bytes!("../testdata/factory_app_two_ota.bin"); - - #[test] - fn read_simple() { - let pt = PartitionTable::new(SIMPLE).unwrap(); - - assert_eq!(3, pt.len()); - - assert_eq!(1, pt.get_partition(0).unwrap().raw_type()); - assert_eq!(1, pt.get_partition(1).unwrap().raw_type()); - assert_eq!(0, pt.get_partition(2).unwrap().raw_type()); - - assert_eq!(2, pt.get_partition(0).unwrap().raw_subtype()); - assert_eq!(1, pt.get_partition(1).unwrap().raw_subtype()); - assert_eq!(0, pt.get_partition(2).unwrap().raw_subtype()); - - assert_eq!( - PartitionType::Data(DataPartitionSubType::Nvs), - pt.get_partition(0).unwrap().partition_type() - ); - assert_eq!( - PartitionType::Data(DataPartitionSubType::Phy), - pt.get_partition(1).unwrap().partition_type() - ); - assert_eq!( - PartitionType::App(AppPartitionSubType::Factory), - pt.get_partition(2).unwrap().partition_type() - ); - - assert_eq!(0x9000, pt.get_partition(0).unwrap().offset()); - assert_eq!(0xf000, pt.get_partition(1).unwrap().offset()); - assert_eq!(0x10000, pt.get_partition(2).unwrap().offset()); - - assert_eq!(0x6000, pt.get_partition(0).unwrap().len()); - assert_eq!(0x1000, pt.get_partition(1).unwrap().len()); - assert_eq!(0x100000, pt.get_partition(2).unwrap().len()); - - assert_eq!("nvs", pt.get_partition(0).unwrap().label_as_str()); - assert_eq!("phy_init", pt.get_partition(1).unwrap().label_as_str()); - assert_eq!("factory", pt.get_partition(2).unwrap().label_as_str()); - - assert_eq!(false, pt.get_partition(0).unwrap().is_read_only()); - assert_eq!(false, pt.get_partition(1).unwrap().is_read_only()); - assert_eq!(false, pt.get_partition(2).unwrap().is_read_only()); - - assert_eq!(false, pt.get_partition(0).unwrap().is_encrypted()); - assert_eq!(false, pt.get_partition(1).unwrap().is_encrypted()); - assert_eq!(false, pt.get_partition(2).unwrap().is_encrypted()); - } - - #[test] - fn read_ota() { - let pt = PartitionTable::new(OTA).unwrap(); - - assert_eq!(6, pt.len()); - - assert_eq!(1, pt.get_partition(0).unwrap().raw_type()); - assert_eq!(1, pt.get_partition(1).unwrap().raw_type()); - assert_eq!(1, pt.get_partition(2).unwrap().raw_type()); - assert_eq!(0, pt.get_partition(3).unwrap().raw_type()); - assert_eq!(0, pt.get_partition(4).unwrap().raw_type()); - assert_eq!(0, pt.get_partition(5).unwrap().raw_type()); - - assert_eq!(2, pt.get_partition(0).unwrap().raw_subtype()); - assert_eq!(0, pt.get_partition(1).unwrap().raw_subtype()); - assert_eq!(1, pt.get_partition(2).unwrap().raw_subtype()); - assert_eq!(0, pt.get_partition(3).unwrap().raw_subtype()); - assert_eq!(0x10, pt.get_partition(4).unwrap().raw_subtype()); - assert_eq!(0x11, pt.get_partition(5).unwrap().raw_subtype()); - - assert_eq!( - PartitionType::Data(DataPartitionSubType::Nvs), - pt.get_partition(0).unwrap().partition_type() - ); - assert_eq!( - PartitionType::Data(DataPartitionSubType::Ota), - pt.get_partition(1).unwrap().partition_type() - ); - assert_eq!( - PartitionType::Data(DataPartitionSubType::Phy), - pt.get_partition(2).unwrap().partition_type() - ); - assert_eq!( - PartitionType::App(AppPartitionSubType::Factory), - pt.get_partition(3).unwrap().partition_type() - ); - assert_eq!( - PartitionType::App(AppPartitionSubType::Ota0), - pt.get_partition(4).unwrap().partition_type() - ); - assert_eq!( - PartitionType::App(AppPartitionSubType::Ota1), - pt.get_partition(5).unwrap().partition_type() - ); - - assert_eq!(0x9000, pt.get_partition(0).unwrap().offset()); - assert_eq!(0xd000, pt.get_partition(1).unwrap().offset()); - assert_eq!(0xf000, pt.get_partition(2).unwrap().offset()); - assert_eq!(0x10000, pt.get_partition(3).unwrap().offset()); - assert_eq!(0x110000, pt.get_partition(4).unwrap().offset()); - assert_eq!(0x210000, pt.get_partition(5).unwrap().offset()); - - assert_eq!(0x4000, pt.get_partition(0).unwrap().len()); - assert_eq!(0x2000, pt.get_partition(1).unwrap().len()); - assert_eq!(0x1000, pt.get_partition(2).unwrap().len()); - assert_eq!(0x100000, pt.get_partition(3).unwrap().len()); - assert_eq!(0x100000, pt.get_partition(4).unwrap().len()); - assert_eq!(0x100000, pt.get_partition(5).unwrap().len()); - - assert_eq!("nvs", pt.get_partition(0).unwrap().label_as_str()); - assert_eq!("otadata", pt.get_partition(1).unwrap().label_as_str()); - assert_eq!("phy_init", pt.get_partition(2).unwrap().label_as_str()); - assert_eq!("factory", pt.get_partition(3).unwrap().label_as_str()); - assert_eq!("ota_0", pt.get_partition(4).unwrap().label_as_str()); - assert_eq!("ota_1", pt.get_partition(5).unwrap().label_as_str()); - - assert_eq!(false, pt.get_partition(0).unwrap().is_read_only()); - assert_eq!(false, pt.get_partition(1).unwrap().is_read_only()); - assert_eq!(false, pt.get_partition(2).unwrap().is_read_only()); - assert_eq!(false, pt.get_partition(3).unwrap().is_read_only()); - assert_eq!(false, pt.get_partition(4).unwrap().is_read_only()); - assert_eq!(false, pt.get_partition(5).unwrap().is_read_only()); - - assert_eq!(false, pt.get_partition(0).unwrap().is_encrypted()); - assert_eq!(false, pt.get_partition(1).unwrap().is_encrypted()); - assert_eq!(false, pt.get_partition(2).unwrap().is_encrypted()); - assert_eq!(false, pt.get_partition(3).unwrap().is_encrypted()); - assert_eq!(false, pt.get_partition(4).unwrap().is_encrypted()); - assert_eq!(false, pt.get_partition(5).unwrap().is_encrypted()); - } - - #[test] - fn empty_byte_array() { - let pt = PartitionTable::new(&[]).unwrap(); - - assert_eq!(0, pt.len()); - assert!(matches!(pt.get_partition(0), Err(Error::OutOfBounds))); - } - - #[test] - fn validation_fails_wo_hash() { - assert!(matches!( - PartitionTable::new(&SIMPLE[..RAW_ENTRY_LEN * 3]), - Err(Error::Invalid) - )); - } - - #[test] - fn validation_fails_wo_hash_max_entries() { - let mut data = [0u8; PARTITION_TABLE_MAX_LEN]; - for i in 0..96 { - data[(i * RAW_ENTRY_LEN)..][..RAW_ENTRY_LEN].copy_from_slice(&SIMPLE[..32]); - } - - assert!(matches!(PartitionTable::new(&data), Err(Error::Invalid))); - } - - #[test] - fn validation_succeeds_with_enough_entries() { - assert_eq!( - 3, - PartitionTable::new(&SIMPLE[..RAW_ENTRY_LEN * 4]) - .unwrap() - .len() - ); - } -} - -#[cfg(test)] -mod storage_tests { - use super::*; - - fn test_flash() -> FlashStorage<'static> { - let mut flash = FlashStorage::new(); - let mut data = [23u8; 0x10000]; - data[PARTITION_TABLE_OFFSET as usize..][..PARTITION_TABLE_MAX_LEN] - .copy_from_slice(include_bytes!("../testdata/single_factory_no_ota.bin")); - flash.write(0, &data).unwrap(); - flash - } - - #[test] - fn can_read_write_all_of_nvs() { - let mut storage = test_flash(); - - let mut buffer = [0u8; PARTITION_TABLE_MAX_LEN]; - let pt = read_partition_table(&mut storage, &mut buffer).unwrap(); - - let nvs = pt - .find_partition(PartitionType::Data(DataPartitionSubType::Nvs)) - .unwrap() - .unwrap(); - let mut nvs_partition = nvs.as_flash_region(&mut storage); - assert_eq!(nvs_partition.offset, 36864); - - assert_eq!(nvs_partition.capacity(), 24576); - - let mut buffer = [0u8; 24576]; - nvs_partition.read(0, &mut buffer).unwrap(); - assert!(buffer.iter().all(|v| *v == 23)); - buffer.fill(42); - nvs_partition.write(0, &buffer).unwrap(); - let mut buffer = [0u8; 24576]; - nvs_partition.read(0, &mut buffer).unwrap(); - assert!(buffer.iter().all(|v| *v == 42)); - } - - #[test] - fn cannot_read_write_more_than_partition_size() { - let mut storage = test_flash(); - - let mut buffer = [0u8; PARTITION_TABLE_MAX_LEN]; - let pt = read_partition_table(&mut storage, &mut buffer).unwrap(); - - let nvs = pt - .find_partition(PartitionType::Data(DataPartitionSubType::Nvs)) - .unwrap() - .unwrap(); - let mut nvs_partition = nvs.as_flash_region(&mut storage); - assert_eq!(nvs_partition.offset, 36864); - - assert_eq!(nvs_partition.capacity(), 24576); - - let mut buffer = [0u8; 24577]; - assert!(nvs_partition.read(0, &mut buffer) == Err(Error::OutOfBounds)); - } - - #[test] - fn can_erase_up_to_partition_end() { - let mut storage = test_flash(); - - let mut buffer = [0u8; PARTITION_TABLE_MAX_LEN]; - let pt = read_partition_table(&mut storage, &mut buffer).unwrap(); - - let nvs = pt - .find_partition(PartitionType::Data(DataPartitionSubType::Nvs)) - .unwrap() - .unwrap(); - let mut nvs_partition = nvs.as_flash_region(&mut storage); - - let capacity = nvs_partition.capacity() as u32; - assert_eq!(capacity, 24576); - - nvs_partition.write(0, &[42u8; 24576]).unwrap(); - - nvs_partition.erase(capacity - 4096, capacity).unwrap(); - let mut buffer = [0u8; 4096]; - nvs_partition.read(capacity - 4096, &mut buffer).unwrap(); - assert!(buffer.iter().all(|v| *v == 0xff)); - - nvs_partition.erase(0, capacity).unwrap(); - let mut buffer = [0u8; 24576]; - nvs_partition.read(0, &mut buffer).unwrap(); - assert!(buffer.iter().all(|v| *v == 0xff)); - } - - #[test] - fn cannot_erase_out_of_bounds() { - let mut storage = test_flash(); - - let mut buffer = [0u8; PARTITION_TABLE_MAX_LEN]; - let pt = read_partition_table(&mut storage, &mut buffer).unwrap(); - - let nvs = pt - .find_partition(PartitionType::Data(DataPartitionSubType::Nvs)) - .unwrap() - .unwrap(); - let mut nvs_partition = nvs.as_flash_region(&mut storage); - - let capacity = nvs_partition.capacity() as u32; - - assert!(nvs_partition.erase(0, capacity + 4096) == Err(Error::OutOfBounds)); - assert!(nvs_partition.erase(capacity, capacity + 4096) == Err(Error::OutOfBounds)); - assert!(nvs_partition.erase(4096, 0) == Err(Error::OutOfBounds)); - } -} - -#[cfg(test)] -mod sha256_tests { - use super::*; - - /// SHA-256 of `0x6000` bytes filled with `0xA5`. - const NVS_DIGEST: [u8; 32] = [ - 0xb0, 0x5b, 0x4f, 0x2c, 0xc2, 0xa7, 0x54, 0x25, 0x54, 0xfa, 0x32, 0x8b, 0xd0, 0x5d, 0x86, - 0x7f, 0x0c, 0x1d, 0xae, 0xed, 0x46, 0x48, 0x8e, 0x31, 0xb0, 0x0c, 0xb0, 0xaa, 0xe5, 0xb5, - 0x49, 0x81, - ]; - - /// SHA-256 of the minimal test image body (32 bytes) with `hash_appended = 1`. - const IMAGE_DIGEST_WITH_HASH_FLAG: [u8; 32] = [ - 0xb2, 0xb7, 0x64, 0x4a, 0x57, 0x62, 0x46, 0x05, 0xf7, 0xe4, 0xb1, 0xc3, 0xbf, 0x96, 0x5a, - 0x20, 0x87, 0x37, 0x3d, 0x7a, 0xc6, 0x2d, 0xf8, 0x6a, 0xcf, 0x2b, 0x1a, 0xcf, 0xe4, 0x8e, - 0xe8, 0xa0, - ]; - - /// SHA-256 of the same minimal image body with `hash_appended = 0`. - const IMAGE_DIGEST_WITHOUT_HASH_FLAG: [u8; 32] = [ - 0x02, 0x50, 0xbb, 0x56, 0xe1, 0x91, 0xf6, 0x6d, 0xde, 0xf1, 0x5e, 0x2d, 0x7c, 0xb4, 0x48, - 0x23, 0x75, 0x36, 0x52, 0x54, 0x7f, 0xc3, 0xd9, 0xd5, 0x83, 0xaa, 0xca, 0x2e, 0xec, 0xfe, - 0x99, 0x00, - ]; - - fn test_flash() -> FlashStorage<'static> { - let mut flash = FlashStorage::new(); - let mut data = [0xffu8; 0x10000]; - data[PARTITION_TABLE_OFFSET as usize..][..PARTITION_TABLE_MAX_LEN] - .copy_from_slice(include_bytes!("../testdata/single_factory_no_ota.bin")); - flash.write(0, &data).unwrap(); - flash - } - - /// Header-only ESP image (0 segments); body pads to 32 bytes for the checksum. - fn write_minimal_app_image( - flash: &mut FlashStorage<'static>, - offset: u32, - hash_appended: bool, - ) { - let mut image = [0u8; 64]; - image[0] = IMAGE_HEADER_MAGIC; - image[23] = u8::from(hash_appended); - // image[1] = 0 segments; bytes 24..32 are checksum padding - if hash_appended { - image[32..64].copy_from_slice(&IMAGE_DIGEST_WITH_HASH_FLAG); - flash.write(offset, &image).unwrap(); - } else { - flash.write(offset, &image[..32]).unwrap(); - } - } - - #[test] - fn sha256_of_data_partition_matches_known_digest() { - let mut flash = test_flash(); - - let mut buffer = [0u8; PARTITION_TABLE_MAX_LEN]; - let pt = read_partition_table(&mut flash, &mut buffer).unwrap(); - let nvs = pt - .find_partition(PartitionType::Data(DataPartitionSubType::Nvs)) - .unwrap() - .unwrap(); - - nvs.as_flash_region(&mut flash) - .write(0, &[0xa5u8; 0x6000]) - .unwrap(); - - assert_eq!(nvs.sha256(&mut flash).unwrap(), NVS_DIGEST); - } - - #[test] - fn sha256_of_app_with_appended_hash_returns_validation_digest() { - let mut flash = test_flash(); - - let mut buffer = [0u8; PARTITION_TABLE_MAX_LEN]; - let pt = read_partition_table(&mut flash, &mut buffer).unwrap(); - let factory = pt - .find_partition(PartitionType::App(AppPartitionSubType::Factory)) - .unwrap() - .unwrap(); - - write_minimal_app_image(&mut flash, factory.offset(), true); - - assert_eq!( - factory.sha256(&mut flash).unwrap(), - IMAGE_DIGEST_WITH_HASH_FLAG - ); - } - - #[test] - fn sha256_of_app_without_appended_hash_hashes_image() { - let mut flash = test_flash(); - - let mut buffer = [0u8; PARTITION_TABLE_MAX_LEN]; - let pt = read_partition_table(&mut flash, &mut buffer).unwrap(); - let factory = pt - .find_partition(PartitionType::App(AppPartitionSubType::Factory)) - .unwrap() - .unwrap(); - - write_minimal_app_image(&mut flash, factory.offset(), false); - - assert_eq!( - factory.sha256(&mut flash).unwrap(), - IMAGE_DIGEST_WITHOUT_HASH_FLAG - ); - } - - #[test] - fn sha256_rejects_corrupt_appended_hash() { - let mut flash = test_flash(); - - let mut buffer = [0u8; PARTITION_TABLE_MAX_LEN]; - let pt = read_partition_table(&mut flash, &mut buffer).unwrap(); - let factory = pt - .find_partition(PartitionType::App(AppPartitionSubType::Factory)) - .unwrap() - .unwrap(); - - write_minimal_app_image(&mut flash, factory.offset(), true); - - // Corrupt the appended digest - flash.write(factory.offset() + 32, &[0u8; 32]).unwrap(); - - assert_eq!(factory.sha256(&mut flash), Err(Error::InvalidImage)); - } -} - -#[cfg(all(test, feature = "embedded-storage"))] -mod nor_flash_tests { - use embedded_storage::nor_flash::{MultiwriteNorFlash, NorFlash, ReadNorFlash}; - - use super::*; - - fn test_flash() -> FlashStorage<'static> { - let mut flash = FlashStorage::new(); - let mut data = [23u8; 0x10000]; - data[PARTITION_TABLE_OFFSET as usize..][..PARTITION_TABLE_MAX_LEN] - .copy_from_slice(include_bytes!("../testdata/single_factory_no_ota.bin")); - flash.write(0, &data).unwrap(); - flash - } - - #[test] - fn plain_nor_flash_implements_multi_write() { - fn assert_multi_write() {} - assert_multi_write::>(); - } - - #[test] - fn as_nor_flash_succeeds_on_plain_partition() { - let mut storage = test_flash(); - - let mut buffer = [0u8; PARTITION_TABLE_MAX_LEN]; - let pt = read_partition_table(&mut storage, &mut buffer).unwrap(); - - let nvs = pt - .find_partition(PartitionType::Data(DataPartitionSubType::Nvs)) - .unwrap() - .unwrap(); - let mut nvs_partition = nvs.as_flash_region(&mut storage); - - assert!(nvs_partition.as_nor_flash().is_ok()); - assert!(matches!( - nvs_partition.as_nor_flash_encrypted(), - Err(Error::NotSupported) - )); - } - - #[test] - fn nor_flash_write_sizes() { - assert_eq!( - as NorFlash>::WRITE_SIZE, - as FlashAccess>::WRITE_SIZE - ); - assert_eq!( - as NorFlash>::WRITE_SIZE, - as FlashAccess>::SECTOR_SIZE as usize - ); - assert_eq!( - as ReadNorFlash>::READ_SIZE, - as FlashAccess>::READ_SIZE - ); - assert_eq!( - as ReadNorFlash>::READ_SIZE, - as FlashAccess>::READ_SIZE - ); - } - - #[test] - fn nor_flash_erase_bounds() { - let mut storage = test_flash(); - - let mut buffer = [0u8; PARTITION_TABLE_MAX_LEN]; - let pt = read_partition_table(&mut storage, &mut buffer).unwrap(); - - let nvs = pt - .find_partition(PartitionType::Data(DataPartitionSubType::Nvs)) - .unwrap() - .unwrap(); - let mut nvs_partition = nvs.as_flash_region(&mut storage); - let capacity = nvs_partition.capacity() as u32; - let mut nor_flash = nvs_partition.as_nor_flash().unwrap(); - - nor_flash.erase(0, capacity).unwrap(); - let mut buffer = [0u8; 4096]; - nor_flash.read(capacity - 4096, &mut buffer).unwrap(); - assert!(buffer.iter().all(|v| *v == 0xff)); - - assert!(nor_flash.erase(0, capacity + 4096) == Err(Error::OutOfBounds)); - assert!(nor_flash.erase(4096, 0) == Err(Error::OutOfBounds)); - } -} diff --git a/esp-bootloader-esp-idf/src/partitions/entry.rs b/esp-bootloader-esp-idf/src/partitions/entry.rs new file mode 100644 index 00000000000..e048765bfa8 --- /dev/null +++ b/esp-bootloader-esp-idf/src/partitions/entry.rs @@ -0,0 +1,165 @@ +use super::{DataPartitionSubType, PartitionType, RAW_ENTRY_LEN}; + +/// Represents a single partition entry. +#[derive(Clone, Copy)] +pub struct PartitionEntry { + pub(crate) binary: [u8; RAW_ENTRY_LEN], +} + +impl PartitionEntry { + pub(super) fn new(binary: &[u8; RAW_ENTRY_LEN]) -> Self { + Self { binary: *binary } + } + + /// Returns the magic value of the entry. + pub fn magic(&self) -> u16 { + u16::from_le_bytes(unwrap!(self.binary[..2].try_into())) + } + + /// Returns the partition type in raw representation. + pub fn raw_type(&self) -> u8 { + self.binary[2] + } + + /// Returns the partition sub-type in raw representation. + pub fn raw_subtype(&self) -> u8 { + self.binary[3] + } + + /// Returns the offset of the partition on flash. + pub fn offset(&self) -> u32 { + u32::from_le_bytes(unwrap!(self.binary[4..][..4].try_into())) + } + + /// Returns the length of the partition in bytes. + pub fn len(&self) -> u32 { + u32::from_le_bytes(unwrap!(self.binary[8..][..4].try_into())) + } + + /// Returns whether the partition has zero length. + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + /// Returns the label of the partition. + pub fn label(&self) -> &[u8] { + &self.binary[12..][..16] + } + + /// Returns the label of the partition as `&str`. + pub fn label_as_str(&self) -> &str { + let array = self.label(); + let len = array + .iter() + .position(|b| *b == 0 || *b == 0xff) + .unwrap_or(array.len()); + unsafe { + core::str::from_utf8_unchecked(core::slice::from_raw_parts(array.as_ptr().cast(), len)) + } + } + + /// Returns the raw flags of this partition. + /// + /// [Self::is_read_only] and [Self::is_encrypted] decode the individual flags. + pub fn flags(&self) -> u32 { + u32::from_le_bytes(unwrap!(self.binary[28..][..4].try_into())) + } + + /// Returns whether the partition is read-only. + pub fn is_read_only(&self) -> bool { + // Bit 1, see `PART_FLAG_READONLY` in . + self.flags() & 0b10 != 0 + } + + /// Returns whether the partition is encrypted. + /// + /// This is the flag from the partition table. + /// If flash encryption is enabled certain partition types are encrypted + /// regardless of this. + pub fn is_encrypted(&self) -> bool { + // Bit 0, see `PART_FLAG_ENCRYPTED` in . + self.flags() & 0b01 != 0 + } + + /// Returns whether the partition is effectively encrypted. + /// + /// Unlike [PartitionEntry::is_encrypted], this also takes into account: + /// - is flash encryption enabled, otherwise this will always return false + /// - certain partition types are always encrypted, no matter what the partition table says + pub(crate) fn is_effectively_encrypted(&self) -> bool { + #[cfg(feature = "std")] + let enabled = false; + + #[cfg(not(feature = "std"))] + let enabled = esp_hal::efuse::flash_encryption(); + + // Same types as `is_partition_encrypted` in ESP-IDF, minus TEE OTA, which this crate + // does not know: + enabled + && (self.is_encrypted() + || matches!( + self.partition_type(), + PartitionType::App(_) + | PartitionType::Bootloader(_) + | PartitionType::PartitionTable(_) + | PartitionType::Data(DataPartitionSubType::NvsKeys) + | PartitionType::Data(DataPartitionSubType::Ota) + )) + } + + /// Returns the partition type (type and sub-type). + pub fn partition_type(&self) -> PartitionType { + match self.raw_type() { + 0 => PartitionType::App(unwrap!(self.raw_subtype().try_into())), + 1 => PartitionType::Data(unwrap!(self.raw_subtype().try_into())), + 2 => PartitionType::Bootloader(unwrap!(self.raw_subtype().try_into())), + 3 => PartitionType::PartitionTable(unwrap!(self.raw_subtype().try_into())), + _ => unreachable!(), + } + } +} + +impl core::fmt::Debug for PartitionEntry { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("PartitionEntry") + .field("magic", &self.magic()) + .field("raw_type", &self.raw_type()) + .field("raw_subtype", &self.raw_subtype()) + .field("offset", &self.offset()) + .field("len", &self.len()) + .field("label", &self.label_as_str()) + .field("flags", &self.flags()) + .field("is_read_only", &self.is_read_only()) + .field("is_encrypted", &self.is_encrypted()) + .finish() + } +} + +#[cfg(feature = "defmt")] +impl defmt::Format for PartitionEntry { + fn format(&self, fmt: defmt::Formatter) { + defmt::write!( + fmt, + "PartitionEntry (\ + magic = {}, \ + raw_type = {}, \ + raw_subtype = {}, \ + offset = {}, \ + len = {}, \ + label = {}, \ + flags = {}, \ + is_read_only = {}, \ + is_encrypted = {}\ + )", + self.magic(), + self.raw_type(), + self.raw_subtype(), + self.offset(), + self.len(), + self.label_as_str(), + self.flags(), + self.is_read_only(), + self.is_encrypted() + ) + } +} diff --git a/esp-bootloader-esp-idf/src/partitions/image.rs b/esp-bootloader-esp-idf/src/partitions/image.rs new file mode 100644 index 00000000000..6ee039b7a3c --- /dev/null +++ b/esp-bootloader-esp-idf/src/partitions/image.rs @@ -0,0 +1,296 @@ +use super::{Error, FlashStorage, PartitionEntry, PartitionType}; +use crate::flash::FlashAccess; + +impl PartitionEntry { + /// Calculates the SHA-256 digest of this partition. + /// + /// - App / bootloader with appended hash: return that digest after verifying it + /// - App / bootloader without appended hash: hash the image (not the whole partition) + /// - Other types: hash the entire partition + /// + /// For app images this is the **validation hash** (shown by + /// `esptool.py image-info`), not the ELF file SHA-256 stored in + /// [`crate::EspAppDesc`]. + pub fn sha256(&self, flash: &mut FlashStorage<'_>) -> Result<[u8; 32], Error> { + if self.is_empty() { + return Err(Error::InvalidArgument); + } + + let address = self.offset(); + let encrypted = self.is_effectively_encrypted(); + let mut size = self.len(); + + if matches!( + self.partition_type(), + PartitionType::App(_) | PartitionType::Bootloader(_) + ) { + let data = get_image_metadata(flash, address, size, encrypted)?; + if data.hash_appended { + let calc = sha256_flash_contents( + flash, + address, + data.image_len - PARTITION_HASH_LEN as u32, + encrypted, + )?; + if calc != data.image_digest { + return Err(Error::InvalidImage); + } + return Ok(data.image_digest); + } + size = data.image_len; + } + + sha256_flash_contents(flash, address, size, encrypted) + } +} + +const PARTITION_HASH_LEN: usize = 32; +const IMAGE_HEADER_MAGIC: u8 = 0xE9; +const IMAGE_HEADER_LEN: u32 = 24; +const IMAGE_MAX_SEGMENTS: u8 = 16; +const IMAGE_MAX_FLASH_ADDR_SIZE: u32 = 16 * 1024 * 1024; + +/// Subset of ESP-IDF `esp_image_metadata_t` for partition SHA-256 convenience. +struct ImageMetadata { + image_len: u32, + image_digest: [u8; PARTITION_HASH_LEN], + hash_appended: bool, +} + +/// Parses an app/bootloader image on flash and returns its length and optional +/// appended SHA-256 digest. +/// +/// Walks the image header and segment table, accounts for the checksum +/// padding, and — if the image has a simple hash appended — reads that digest. +/// Does not verify the checksum or load any segments. +fn get_image_metadata( + flash: &mut F, + address: u32, + part_size: u32, + encrypted: bool, +) -> Result { + if part_size == 0 || part_size > IMAGE_MAX_FLASH_ADDR_SIZE { + return Err(Error::InvalidArgument); + } + + // process_image_header() + let mut hdr = [0u8; IMAGE_HEADER_LEN as usize]; + flash_read(flash, address, &mut hdr, encrypted)?; + // `esp_image_get_metadata` skips header verify, but refuse obvious garbage. + if hdr[0] != IMAGE_HEADER_MAGIC || hdr[1] > IMAGE_MAX_SEGMENTS { + return Err(Error::InvalidImage); + } + + let mut image_len = IMAGE_HEADER_LEN; + + // process_segments() + for _ in 0..hdr[1] { + let mut seg = [0u8; 8]; + flash_read(flash, address + image_len, &mut seg, encrypted)?; + // seg[0..4] - load address + let data_len = u32::from_le_bytes(unwrap!(seg[4..8].try_into())); + if data_len % 4 != 0 || data_len >= IMAGE_MAX_FLASH_ADDR_SIZE { + return Err(Error::InvalidImage); + } + image_len = image_len + .checked_add(8 + data_len) + .ok_or(Error::InvalidImage)?; + } + + // process_checksum() + // add a byte for the checksum, pad to next full 16 byte block + image_len = (image_len + 1 + 15) & !15; + + // process_appended_hash_and_sig() + let hash_appended = hdr[23] != 0; + let mut image_digest = [0u8; PARTITION_HASH_LEN]; + if hash_appended { + flash_read(flash, address + image_len, &mut image_digest, encrypted)?; + image_len += PARTITION_HASH_LEN as u32; + } + + if image_len > part_size { + return Err(Error::InvalidImage); + } + + Ok(ImageMetadata { + image_len, + image_digest, + hash_appended, + }) +} + +fn flash_read( + flash: &mut F, + address: u32, + bytes: &mut [u8], + encrypted: bool, +) -> Result<(), Error> { + if encrypted { + flash.flash_read_encrypted(address, bytes) + } else { + flash.flash_read(address, bytes) + } +} + +/// Hashes `len` bytes of flash starting at `flash_offset`. +/// +/// Reads the region in fixed-size chunks so large partitions do not need to be +/// loaded into memory at once. +fn sha256_flash_contents( + flash: &mut F, + mut flash_offset: u32, + mut len: u32, + encrypted: bool, +) -> Result<[u8; PARTITION_HASH_LEN], Error> { + use sha2::{Digest, Sha256}; + + let mut hasher = Sha256::new(); + let mut chunk = [0u8; 4096]; + + while len > 0 { + let n = len.min(chunk.len() as u32) as usize; + flash_read(flash, flash_offset, &mut chunk[..n], encrypted)?; + hasher.update(&chunk[..n]); + flash_offset += n as u32; + len -= n as u32; + } + + Ok(hasher.finalize().into()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::partitions::{ + AppPartitionSubType, + DataPartitionSubType, + PARTITION_TABLE_MAX_LEN, + PARTITION_TABLE_OFFSET, + read_partition_table, + }; + + /// SHA-256 of `0x6000` bytes filled with `0xA5`. + const NVS_DIGEST: [u8; 32] = [ + 0xb0, 0x5b, 0x4f, 0x2c, 0xc2, 0xa7, 0x54, 0x25, 0x54, 0xfa, 0x32, 0x8b, 0xd0, 0x5d, 0x86, + 0x7f, 0x0c, 0x1d, 0xae, 0xed, 0x46, 0x48, 0x8e, 0x31, 0xb0, 0x0c, 0xb0, 0xaa, 0xe5, 0xb5, + 0x49, 0x81, + ]; + + /// SHA-256 of the minimal test image body (32 bytes) with `hash_appended = 1`. + const IMAGE_DIGEST_WITH_HASH_FLAG: [u8; 32] = [ + 0xb2, 0xb7, 0x64, 0x4a, 0x57, 0x62, 0x46, 0x05, 0xf7, 0xe4, 0xb1, 0xc3, 0xbf, 0x96, 0x5a, + 0x20, 0x87, 0x37, 0x3d, 0x7a, 0xc6, 0x2d, 0xf8, 0x6a, 0xcf, 0x2b, 0x1a, 0xcf, 0xe4, 0x8e, + 0xe8, 0xa0, + ]; + + /// SHA-256 of the same minimal image body with `hash_appended = 0`. + const IMAGE_DIGEST_WITHOUT_HASH_FLAG: [u8; 32] = [ + 0x02, 0x50, 0xbb, 0x56, 0xe1, 0x91, 0xf6, 0x6d, 0xde, 0xf1, 0x5e, 0x2d, 0x7c, 0xb4, 0x48, + 0x23, 0x75, 0x36, 0x52, 0x54, 0x7f, 0xc3, 0xd9, 0xd5, 0x83, 0xaa, 0xca, 0x2e, 0xec, 0xfe, + 0x99, 0x00, + ]; + + fn test_flash() -> FlashStorage<'static> { + let mut flash = FlashStorage::new(); + let mut data = [0xffu8; 0x10000]; + data[PARTITION_TABLE_OFFSET as usize..][..PARTITION_TABLE_MAX_LEN] + .copy_from_slice(include_bytes!("../../testdata/single_factory_no_ota.bin")); + flash.write(0, &data).unwrap(); + flash + } + + /// Header-only ESP image (0 segments); body pads to 32 bytes for the checksum. + fn write_minimal_app_image( + flash: &mut FlashStorage<'static>, + offset: u32, + hash_appended: bool, + ) { + let mut image = [0u8; 64]; + image[0] = IMAGE_HEADER_MAGIC; + image[23] = u8::from(hash_appended); + // image[1] = 0 segments; bytes 24..32 are checksum padding + if hash_appended { + image[32..64].copy_from_slice(&IMAGE_DIGEST_WITH_HASH_FLAG); + flash.write(offset, &image).unwrap(); + } else { + flash.write(offset, &image[..32]).unwrap(); + } + } + + #[test] + fn sha256_of_data_partition_matches_known_digest() { + let mut flash = test_flash(); + + let mut buffer = [0u8; PARTITION_TABLE_MAX_LEN]; + let pt = read_partition_table(&mut flash, &mut buffer).unwrap(); + let nvs = pt + .find_partition(PartitionType::Data(DataPartitionSubType::Nvs)) + .unwrap() + .unwrap(); + + nvs.as_flash_region(&mut flash) + .unwrap() + .write(0, &[0xa5u8; 0x6000]) + .unwrap(); + + assert_eq!(nvs.sha256(&mut flash).unwrap(), NVS_DIGEST); + } + + #[test] + fn sha256_of_app_with_appended_hash_returns_validation_digest() { + let mut flash = test_flash(); + + let mut buffer = [0u8; PARTITION_TABLE_MAX_LEN]; + let pt = read_partition_table(&mut flash, &mut buffer).unwrap(); + let factory = pt + .find_partition(PartitionType::App(AppPartitionSubType::Factory)) + .unwrap() + .unwrap(); + + write_minimal_app_image(&mut flash, factory.offset(), true); + + assert_eq!( + factory.sha256(&mut flash).unwrap(), + IMAGE_DIGEST_WITH_HASH_FLAG + ); + } + + #[test] + fn sha256_of_app_without_appended_hash_hashes_image() { + let mut flash = test_flash(); + + let mut buffer = [0u8; PARTITION_TABLE_MAX_LEN]; + let pt = read_partition_table(&mut flash, &mut buffer).unwrap(); + let factory = pt + .find_partition(PartitionType::App(AppPartitionSubType::Factory)) + .unwrap() + .unwrap(); + + write_minimal_app_image(&mut flash, factory.offset(), false); + + assert_eq!( + factory.sha256(&mut flash).unwrap(), + IMAGE_DIGEST_WITHOUT_HASH_FLAG + ); + } + + #[test] + fn sha256_rejects_corrupt_appended_hash() { + let mut flash = test_flash(); + + let mut buffer = [0u8; PARTITION_TABLE_MAX_LEN]; + let pt = read_partition_table(&mut flash, &mut buffer).unwrap(); + let factory = pt + .find_partition(PartitionType::App(AppPartitionSubType::Factory)) + .unwrap() + .unwrap(); + + write_minimal_app_image(&mut flash, factory.offset(), true); + + // Corrupt the appended digest + flash.write(factory.offset() + 32, &[0u8; 32]).unwrap(); + + assert_eq!(factory.sha256(&mut flash), Err(Error::InvalidImage)); + } +} diff --git a/esp-bootloader-esp-idf/src/partitions/mod.rs b/esp-bootloader-esp-idf/src/partitions/mod.rs new file mode 100644 index 00000000000..b9a1b7ccb83 --- /dev/null +++ b/esp-bootloader-esp-idf/src/partitions/mod.rs @@ -0,0 +1,72 @@ +//! # Partition Table Support +//! +//! ## Overview +//! +//! This module allows reading the partition table and conveniently +//! writing/reading partition contents. +//! +//! For more information see + +/// Maximum length of a partition table. +pub const PARTITION_TABLE_MAX_LEN: usize = 0xC00; + +const PARTITION_TABLE_OFFSET: u32 = + esp_config::esp_config_int!(u32, "ESP_BOOTLOADER_ESP_IDF_CONFIG_PARTITION_TABLE_OFFSET"); + +const RAW_ENTRY_LEN: usize = 32; + +mod entry; +mod image; +#[cfg(feature = "embedded-storage")] +mod nor_flash; +mod region; +mod table; +mod types; + +pub use self::{ + entry::PartitionEntry, + region::{AutoFlashRegion, EncryptedFlashRegion, FlashRegion}, + table::{PartitionTable, read_partition_table}, + types::{ + AppPartitionSubType, + BootloaderPartitionSubType, + DataPartitionSubType, + PartitionTablePartitionSubType, + PartitionType, + RawPartitionType, + }, +}; +pub use crate::flash::FlashStorage; + +/// Errors which can be returned. +#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, strum::Display)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[non_exhaustive] +pub enum Error { + /// The partition table is invalid or doesn't contain a needed partition. + Invalid, + /// An operation tries to access data that is out of bounds. + OutOfBounds, + /// The flash driver reported an error. + StorageError, + /// An address or length is not aligned as the operation requires. + NotAligned, + /// The partition is write protected. + WriteProtected, + /// The partition is invalid. + InvalidPartition { + expected_size: usize, + expected_type: PartitionType, + }, + /// Invalid state. + InvalidState, + /// The given argument is invalid. + InvalidArgument, + /// The operation is not supported for this partition (e.g. `as_flash_region` on an encrypted + /// partition). + NotSupported, + /// The partition does not contain a valid application or bootloader image. + InvalidImage, +} + +impl core::error::Error for Error {} diff --git a/esp-bootloader-esp-idf/src/partitions/nor_flash.rs b/esp-bootloader-esp-idf/src/partitions/nor_flash.rs new file mode 100644 index 00000000000..7f8a6f6efc6 --- /dev/null +++ b/esp-bootloader-esp-idf/src/partitions/nor_flash.rs @@ -0,0 +1,141 @@ +use embedded_storage::nor_flash::{ + ErrorType, + MultiwriteNorFlash, + NorFlash, + NorFlashError, + NorFlashErrorKind, + ReadNorFlash, +}; + +use super::{Error, FlashRegion}; +use crate::flash::{SECTOR_SIZE, WORD_SIZE}; + +impl NorFlashError for Error { + fn kind(&self) -> NorFlashErrorKind { + match self { + Error::NotAligned => NorFlashErrorKind::NotAligned, + Error::OutOfBounds => NorFlashErrorKind::OutOfBounds, + _ => NorFlashErrorKind::Other, + } + } +} + +impl ErrorType for FlashRegion<'_, '_> { + type Error = Error; +} + +impl ReadNorFlash for FlashRegion<'_, '_> { + const READ_SIZE: usize = 1; + + fn read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Self::Error> { + FlashRegion::read(self, offset, bytes) + } + + fn capacity(&self) -> usize { + FlashRegion::capacity(self) + } +} + +impl NorFlash for FlashRegion<'_, '_> { + const WRITE_SIZE: usize = WORD_SIZE as usize; + const ERASE_SIZE: usize = SECTOR_SIZE as usize; + + fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> { + FlashRegion::erase(self, from, to) + } + + fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> { + FlashRegion::write(self, offset, bytes) + } +} + +impl MultiwriteNorFlash for FlashRegion<'_, '_> {} + +#[cfg(test)] +mod tests { + use embedded_storage::nor_flash::{ + MultiwriteNorFlash, + NorFlash, + NorFlashError, + NorFlashErrorKind, + ReadNorFlash, + }; + + use super::*; + use crate::partitions::{ + DataPartitionSubType, + FlashStorage, + PARTITION_TABLE_MAX_LEN, + PARTITION_TABLE_OFFSET, + PartitionType, + read_partition_table, + }; + + fn test_flash() -> FlashStorage<'static> { + let mut flash = FlashStorage::new(); + let mut data = [23u8; 0x10000]; + data[PARTITION_TABLE_OFFSET as usize..][..PARTITION_TABLE_MAX_LEN] + .copy_from_slice(include_bytes!("../../testdata/single_factory_no_ota.bin")); + flash.write(0, &data).unwrap(); + flash + } + + #[test] + fn flash_region_implements_multi_write() { + fn assert_multi_write() {} + assert_multi_write::>(); + } + + #[test] + fn nor_flash_sizes() { + assert_eq!( + as ReadNorFlash>::READ_SIZE, + 1 + ); + assert_eq!( as NorFlash>::WRITE_SIZE, 4); + assert_eq!( + as NorFlash>::ERASE_SIZE, + 4096 + ); + } + + #[test] + fn nor_flash_erase_bounds() { + let mut storage = test_flash(); + + let mut buffer = [0u8; PARTITION_TABLE_MAX_LEN]; + let pt = read_partition_table(&mut storage, &mut buffer).unwrap(); + + let nvs = pt + .find_partition(PartitionType::Data(DataPartitionSubType::Nvs)) + .unwrap() + .unwrap(); + let mut nor_flash = nvs.as_flash_region(&mut storage).unwrap(); + let capacity = ReadNorFlash::capacity(&nor_flash) as u32; + + NorFlash::erase(&mut nor_flash, 0, capacity).unwrap(); + let mut buffer = [0u8; 4096]; + ReadNorFlash::read(&mut nor_flash, capacity - 4096, &mut buffer).unwrap(); + assert!(buffer.iter().all(|v| *v == 0xff)); + + assert!(NorFlash::erase(&mut nor_flash, 0, capacity + 4096) == Err(Error::OutOfBounds)); + assert!(NorFlash::erase(&mut nor_flash, 4096, 0) == Err(Error::OutOfBounds)); + } + + #[test] + fn nor_flash_rejects_unaligned_write() { + let mut storage = test_flash(); + + let mut buffer = [0u8; PARTITION_TABLE_MAX_LEN]; + let pt = read_partition_table(&mut storage, &mut buffer).unwrap(); + + let nvs = pt + .find_partition(PartitionType::Data(DataPartitionSubType::Nvs)) + .unwrap() + .unwrap(); + let mut nor_flash = nvs.as_flash_region(&mut storage).unwrap(); + + let error = NorFlash::write(&mut nor_flash, 1, &[0; 4]).unwrap_err(); + assert_eq!(error.kind(), NorFlashErrorKind::NotAligned); + } +} diff --git a/esp-bootloader-esp-idf/src/partitions/region.rs b/esp-bootloader-esp-idf/src/partitions/region.rs new file mode 100644 index 00000000000..91a7b1749b2 --- /dev/null +++ b/esp-bootloader-esp-idf/src/partitions/region.rs @@ -0,0 +1,549 @@ +use super::{Error, FlashStorage, PartitionEntry, PartitionType}; +use crate::flash::{ENCRYPTED_WRITE_SIZE, FlashAccess, SECTOR_SIZE, WORD_SIZE}; + +impl PartitionEntry { + /// Provides a plaintext "view" into the partition allowing to read/write the + /// partition contents using the given [`FlashStorage`]. + /// + /// The partition containing the running application is always read-only. + /// + /// # Errors + /// + /// [`Error::NotSupported`] if the partition is effectively encrypted. Use + /// [`PartitionEntry::as_encrypted_flash_region`] instead. + pub fn as_flash_region<'a, 'd>( + self, + flash: &'a mut FlashStorage<'d>, + ) -> Result, Error> { + if self.is_effectively_encrypted() { + return Err(Error::NotSupported); + } + Ok(FlashRegion { + region: self.region(flash), + }) + } + + /// Provides a "view" into an encrypted partition, which reads decrypted + /// data and writes encrypted data. + /// + /// The partition containing the running application is always read-only. + /// + /// # Errors + /// + /// [`Error::NotSupported`] if the partition is not effectively encrypted, i.e. flash + /// encryption is disabled or the partition type is not encrypted. + pub fn as_encrypted_flash_region<'a, 'd>( + self, + flash: &'a mut FlashStorage<'d>, + ) -> Result, Error> { + if !self.is_effectively_encrypted() { + return Err(Error::NotSupported); + } + Ok(EncryptedFlashRegion { + region: self.region(flash), + }) + } + + /// Provides a "view" into the partition that is plaintext or encrypted, + /// depending on whether the partition is effectively encrypted. + /// + /// The partition containing the running application is always read-only. + pub fn as_auto_flash_region<'a, 'd>( + self, + flash: &'a mut FlashStorage<'d>, + ) -> AutoFlashRegion<'a, 'd> { + let region = self.region(flash); + if self.is_effectively_encrypted() { + AutoFlashRegion::Encrypted(EncryptedFlashRegion { region }) + } else { + AutoFlashRegion::Plain(FlashRegion { region }) + } + } + + fn region<'a, 'd>(self, flash: &'a mut FlashStorage<'d>) -> Region<'a, 'd> { + Region { + offset: self.offset(), + len: self.len(), + partition_type: self.partition_type(), + // Modifying the running application would corrupt code or immutable data. + read_only: self.is_read_only() || self.contains_running_app(), + flash, + } + } + + #[cfg(feature = "std")] + fn contains_running_app(&self) -> bool { + false + } + + #[cfg(not(feature = "std"))] + fn contains_running_app(&self) -> bool { + super::table::booted_app_offset() + .is_some_and(|app| (self.offset()..self.offset() + self.len()).contains(&app)) + } +} + +/// The flash range of a partition. +/// +/// Holds the bounds, write-protection and alignment checks that the public +/// region types share. +#[derive(Debug)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +struct Region<'a, 'd> { + offset: u32, + len: u32, + partition_type: PartitionType, + read_only: bool, + flash: &'a mut FlashStorage<'d>, +} + +impl Region<'_, '_> { + fn capacity(&self) -> usize { + self.len as _ + } + + fn range(&self) -> core::ops::Range { + self.offset..self.offset + self.len + } + + fn in_range(&self, start: u32, len: usize) -> bool { + self.range().contains(&start) && (start + len as u32 <= self.range().end) + } + + fn read(&mut self, offset: u32, bytes: &mut [u8], encrypted: bool) -> Result<(), Error> { + let address = offset + self.offset; + + if !self.in_range(address, bytes.len()) { + return Err(Error::OutOfBounds); + } + + if encrypted { + self.flash.flash_read_encrypted(address, bytes) + } else { + self.flash.flash_read(address, bytes) + } + } + + fn write(&mut self, offset: u32, bytes: &[u8], encrypted: bool) -> Result<(), Error> { + let address = offset + self.offset; + + if self.read_only { + return Err(Error::WriteProtected); + } + + if !self.in_range(address, bytes.len()) { + return Err(Error::OutOfBounds); + } + + let align = if encrypted { + ENCRYPTED_WRITE_SIZE + } else { + WORD_SIZE + }; + if !offset.is_multiple_of(align) || !bytes.len().is_multiple_of(align as usize) { + return Err(Error::NotAligned); + } + + if encrypted { + self.flash.flash_write_encrypted(address, bytes) + } else { + self.flash.flash_write(address, bytes) + } + } + + fn erase(&mut self, from: u32, to: u32) -> Result<(), Error> { + let address_from = from + self.offset; + let address_to = to + self.offset; + + if self.read_only { + return Err(Error::WriteProtected); + } + + if from > to { + return Err(Error::OutOfBounds); + } + + if !self.in_range(address_from, (address_to - address_from) as usize) { + return Err(Error::OutOfBounds); + } + + if !from.is_multiple_of(SECTOR_SIZE) || !to.is_multiple_of(SECTOR_SIZE) { + return Err(Error::NotAligned); + } + + self.flash.flash_erase(address_from, address_to) + } +} + +/// A plaintext "view" into a partition. +/// +/// It allows to read and write to the partition without the need to account for +/// the partition offset. +/// +/// Created by [`PartitionEntry::as_flash_region`]. +#[derive(Debug)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub struct FlashRegion<'a, 'd> { + region: Region<'a, 'd>, +} + +impl FlashRegion<'_, '_> { + /// Returns the size of the partition in bytes. + pub fn partition_size(&self) -> usize { + self.region.capacity() + } + + /// Reads bytes from the partition. + pub fn read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Error> { + self.region.read(offset, bytes, false) + } + + /// Writes bytes to the partition. + /// + /// The target range must be erased first: flash programming can only clear bits. + /// + /// # Errors + /// + /// - [`Error::WriteProtected`] if the partition is read-only or contains the running + /// application. + /// - [`Error::OutOfBounds`] if the range exceeds the partition. + /// - [`Error::NotAligned`] if `offset` or the length is not a multiple of 4. + pub fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Error> { + self.region.write(offset, bytes, false) + } + + /// Returns the size of the partition in bytes. + pub fn capacity(&self) -> usize { + self.region.capacity() + } + + /// Erases flash in the partition from `from` up to but not including `to`. + /// + /// Addresses are relative to the partition start. + /// + /// # Errors + /// + /// - [`Error::WriteProtected`] if the partition is read-only or contains the running + /// application. + /// - [`Error::OutOfBounds`] if `from > to` or the range exceeds the partition. + /// - [`Error::NotAligned`] if `from` or `to` is not a multiple of 4096. + pub fn erase(&mut self, from: u32, to: u32) -> Result<(), Error> { + self.region.erase(from, to) + } +} + +/// A "view" into an encrypted partition. +/// +/// Reads decrypt data, writes encrypt it. Offsets are relative to the partition start. +/// +/// This type does not implement the `embedded-storage` NOR flash traits, erased +/// flash does not read back as `0xFF` after decryption. +/// +/// Created by [`PartitionEntry::as_encrypted_flash_region`]. +#[derive(Debug)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub struct EncryptedFlashRegion<'a, 'd> { + region: Region<'a, 'd>, +} + +impl EncryptedFlashRegion<'_, '_> { + /// Returns the size of the partition in bytes. + pub fn partition_size(&self) -> usize { + self.region.capacity() + } + + /// Returns the size of the partition in bytes. + pub fn capacity(&self) -> usize { + self.region.capacity() + } + + /// Reads and decrypts bytes from the partition. + /// + /// # Errors + /// + /// [`Error::OutOfBounds`] if the range exceeds the partition. + pub fn read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Error> { + self.region.read(offset, bytes, true) + } + + /// Encrypts and writes bytes to the partition. + /// + /// The target range must be erased first: flash programming can only clear bits. + /// + /// # Errors + /// + /// - [`Error::WriteProtected`] if the partition is read-only or contains the running + /// application. + /// - [`Error::OutOfBounds`] if the range exceeds the partition. + /// - [`Error::NotAligned`] if `offset` or the length is not a multiple of 16. + pub fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Error> { + self.region.write(offset, bytes, true) + } + + /// Erases flash in the partition from `from` up to but not including `to`. + /// + /// # Errors + /// + /// - [`Error::WriteProtected`] if the partition is read-only or contains the running + /// application. + /// - [`Error::OutOfBounds`] if `from > to` or the range exceeds the partition. + /// - [`Error::NotAligned`] if `from` or `to` is not a multiple of 4096. + pub fn erase(&mut self, from: u32, to: u32) -> Result<(), Error> { + self.region.erase(from, to) + } +} + +/// A "view" into a partition that is either plaintext or encrypted. +/// +/// Used for partitions that are encrypted only when flash encryption is +/// enabled, such as app and OTA data partitions. All methods forward to the +/// wrapped region. +/// +/// Created by [`PartitionEntry::as_auto_flash_region`]. +#[derive(Debug)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum AutoFlashRegion<'a, 'd> { + /// The partition is not encrypted. + Plain(FlashRegion<'a, 'd>), + /// The partition is encrypted. + Encrypted(EncryptedFlashRegion<'a, 'd>), +} + +impl<'a, 'd> AutoFlashRegion<'a, 'd> { + fn region(&self) -> &Region<'a, 'd> { + match self { + Self::Plain(region) => ®ion.region, + Self::Encrypted(region) => ®ion.region, + } + } + + pub(crate) fn partition_type(&self) -> PartitionType { + self.region().partition_type + } + + /// Returns the size of the partition in bytes. + pub fn partition_size(&self) -> usize { + self.region().capacity() + } + + /// Returns the size of the partition in bytes. + pub fn capacity(&self) -> usize { + self.region().capacity() + } + + /// Returns whether the partition is encrypted. + pub fn is_encrypted(&self) -> bool { + matches!(self, Self::Encrypted(_)) + } + + /// Reads bytes from the partition, see [`FlashRegion::read`] and + /// [`EncryptedFlashRegion::read`]. + pub fn read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Error> { + match self { + Self::Plain(region) => region.read(offset, bytes), + Self::Encrypted(region) => region.read(offset, bytes), + } + } + + /// Writes bytes to the partition, see [`FlashRegion::write`] and + /// [`EncryptedFlashRegion::write`]. + pub fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Error> { + match self { + Self::Plain(region) => region.write(offset, bytes), + Self::Encrypted(region) => region.write(offset, bytes), + } + } + + /// Erases the partition from `from` up to but not including `to`, see + /// [`FlashRegion::erase`]. + pub fn erase(&mut self, from: u32, to: u32) -> Result<(), Error> { + match self { + Self::Plain(region) => region.erase(from, to), + Self::Encrypted(region) => region.erase(from, to), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::partitions::{ + DataPartitionSubType, + PARTITION_TABLE_MAX_LEN, + PARTITION_TABLE_OFFSET, + read_partition_table, + }; + + fn test_flash() -> FlashStorage<'static> { + let mut flash = FlashStorage::new(); + let mut data = [23u8; 0x10000]; + data[PARTITION_TABLE_OFFSET as usize..][..PARTITION_TABLE_MAX_LEN] + .copy_from_slice(include_bytes!("../../testdata/single_factory_no_ota.bin")); + flash.write(0, &data).unwrap(); + flash + } + + #[test] + fn can_read_write_all_of_nvs() { + let mut storage = test_flash(); + + let mut buffer = [0u8; PARTITION_TABLE_MAX_LEN]; + let pt = read_partition_table(&mut storage, &mut buffer).unwrap(); + + let nvs = pt + .find_partition(PartitionType::Data(DataPartitionSubType::Nvs)) + .unwrap() + .unwrap(); + let mut nvs_partition = nvs.as_flash_region(&mut storage).unwrap(); + assert_eq!(nvs_partition.region.offset, 36864); + + assert_eq!(nvs_partition.capacity(), 24576); + + let mut buffer = [0u8; 24576]; + nvs_partition.read(0, &mut buffer).unwrap(); + assert!(buffer.iter().all(|v| *v == 23)); + buffer.fill(42); + nvs_partition.erase(0, 24576).unwrap(); + nvs_partition.write(0, &buffer).unwrap(); + let mut buffer = [0u8; 24576]; + nvs_partition.read(0, &mut buffer).unwrap(); + assert!(buffer.iter().all(|v| *v == 42)); + } + + #[test] + fn cannot_read_write_more_than_partition_size() { + let mut storage = test_flash(); + + let mut buffer = [0u8; PARTITION_TABLE_MAX_LEN]; + let pt = read_partition_table(&mut storage, &mut buffer).unwrap(); + + let nvs = pt + .find_partition(PartitionType::Data(DataPartitionSubType::Nvs)) + .unwrap() + .unwrap(); + let mut nvs_partition = nvs.as_flash_region(&mut storage).unwrap(); + assert_eq!(nvs_partition.region.offset, 36864); + + assert_eq!(nvs_partition.capacity(), 24576); + + let mut buffer = [0u8; 24577]; + assert!(nvs_partition.read(0, &mut buffer) == Err(Error::OutOfBounds)); + } + + #[test] + fn can_erase_up_to_partition_end() { + let mut storage = test_flash(); + + let mut buffer = [0u8; PARTITION_TABLE_MAX_LEN]; + let pt = read_partition_table(&mut storage, &mut buffer).unwrap(); + + let nvs = pt + .find_partition(PartitionType::Data(DataPartitionSubType::Nvs)) + .unwrap() + .unwrap(); + let mut nvs_partition = nvs.as_flash_region(&mut storage).unwrap(); + + let capacity = nvs_partition.capacity() as u32; + assert_eq!(capacity, 24576); + + nvs_partition.write(0, &[42u8; 24576]).unwrap(); + + nvs_partition.erase(capacity - 4096, capacity).unwrap(); + let mut buffer = [0u8; 4096]; + nvs_partition.read(capacity - 4096, &mut buffer).unwrap(); + assert!(buffer.iter().all(|v| *v == 0xff)); + + nvs_partition.erase(0, capacity).unwrap(); + let mut buffer = [0u8; 24576]; + nvs_partition.read(0, &mut buffer).unwrap(); + assert!(buffer.iter().all(|v| *v == 0xff)); + } + + #[test] + fn cannot_erase_out_of_bounds() { + let mut storage = test_flash(); + + let mut buffer = [0u8; PARTITION_TABLE_MAX_LEN]; + let pt = read_partition_table(&mut storage, &mut buffer).unwrap(); + + let nvs = pt + .find_partition(PartitionType::Data(DataPartitionSubType::Nvs)) + .unwrap() + .unwrap(); + let mut nvs_partition = nvs.as_flash_region(&mut storage).unwrap(); + + let capacity = nvs_partition.capacity() as u32; + + assert!(nvs_partition.erase(0, capacity + 4096) == Err(Error::OutOfBounds)); + assert!(nvs_partition.erase(capacity, capacity + 4096) == Err(Error::OutOfBounds)); + assert!(nvs_partition.erase(4096, 0) == Err(Error::OutOfBounds)); + } + + #[test] + fn rejects_unaligned_write_and_erase() { + let mut storage = test_flash(); + + let mut buffer = [0u8; PARTITION_TABLE_MAX_LEN]; + let pt = read_partition_table(&mut storage, &mut buffer).unwrap(); + + let nvs = pt + .find_partition(PartitionType::Data(DataPartitionSubType::Nvs)) + .unwrap() + .unwrap(); + let mut nvs_partition = nvs.as_flash_region(&mut storage).unwrap(); + + assert_eq!(nvs_partition.write(2, &[0; 4]), Err(Error::NotAligned)); + assert_eq!(nvs_partition.write(4, &[0; 6]), Err(Error::NotAligned)); + assert_eq!(nvs_partition.erase(512, 4096), Err(Error::NotAligned)); + assert_eq!(nvs_partition.erase(0, 512), Err(Error::NotAligned)); + } + + #[test] + fn encrypted_write_requires_16_byte_alignment() { + let mut storage = test_flash(); + + let mut buffer = [0u8; PARTITION_TABLE_MAX_LEN]; + let pt = read_partition_table(&mut storage, &mut buffer).unwrap(); + + let nvs = pt + .find_partition(PartitionType::Data(DataPartitionSubType::Nvs)) + .unwrap() + .unwrap(); + // Host tests run without flash encryption, so build the region directly. + let mut region = EncryptedFlashRegion { + region: nvs.region(&mut storage), + }; + + region.erase(0, 4096).unwrap(); + assert_eq!(region.write(4, &[0; 16]), Err(Error::NotAligned)); + assert_eq!(region.write(16, &[0; 20]), Err(Error::NotAligned)); + region.write(16, &[0x5a; 32]).unwrap(); + + let mut buffer = [0u8; 34]; + region.read(15, &mut buffer).unwrap(); + assert_eq!(buffer[0], 0xff); + assert_eq!(buffer[1..33], [0x5a; 32]); + assert_eq!(buffer[33], 0xff); + } + + #[test] + fn encrypted_region_requires_flash_encryption() { + let mut storage = test_flash(); + + let mut buffer = [0u8; PARTITION_TABLE_MAX_LEN]; + let pt = read_partition_table(&mut storage, &mut buffer).unwrap(); + + let nvs = pt + .find_partition(PartitionType::Data(DataPartitionSubType::Nvs)) + .unwrap() + .unwrap(); + + assert!(!nvs.is_effectively_encrypted()); + assert!(nvs.as_flash_region(&mut storage).is_ok()); + assert!(!nvs.as_auto_flash_region(&mut storage).is_encrypted()); + assert!(matches!( + nvs.as_encrypted_flash_region(&mut storage), + Err(Error::NotSupported) + )); + } +} diff --git a/esp-bootloader-esp-idf/src/partitions/table.rs b/esp-bootloader-esp-idf/src/partitions/table.rs new file mode 100644 index 00000000000..81f37aee168 --- /dev/null +++ b/esp-bootloader-esp-idf/src/partitions/table.rs @@ -0,0 +1,376 @@ +use super::{ + Error, + FlashStorage, + PARTITION_TABLE_MAX_LEN, + PARTITION_TABLE_OFFSET, + PartitionEntry, + PartitionType, + RAW_ENTRY_LEN, +}; +use crate::flash::FlashAccess; + +const ENTRY_MAGIC: u16 = 0x50aa; +#[cfg(feature = "validation")] +const MD5_MAGIC: u16 = 0xebeb; + +/// A partition table. +#[derive(Debug)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub struct PartitionTable<'a> { + binary: &'a [[u8; RAW_ENTRY_LEN]], + entries: usize, +} + +impl<'a> PartitionTable<'a> { + fn new(binary: &'a [u8]) -> Result { + if binary.len() > PARTITION_TABLE_MAX_LEN { + return Err(Error::Invalid); + } + + let (binary, rem) = binary.as_chunks::(); + if !rem.is_empty() { + return Err(Error::Invalid); + } + + if binary.is_empty() { + return Ok(Self { + binary: &[], + entries: 0, + }); + } + + let mut raw_table = Self { + binary, + entries: binary.len(), + }; + + #[cfg(feature = "validation")] + { + let index = raw_table + .binary + .iter() + .position(|entry| u16::from_le_bytes([entry[0], entry[1]]) == MD5_MAGIC) + .ok_or(Error::Invalid)?; + let hash = &raw_table.binary[index][16..][..16]; + + let mut hasher = crate::crypto::Md5::new(); + + for entry in &raw_table.binary[..index] { + hasher.update(entry); + } + let calculated_hash = hasher.finalize(); + + if calculated_hash != hash { + return Err(Error::Invalid); + } + } + + let entries = { + let mut i = 0; + loop { + if let Ok(entry) = raw_table.get_partition(i) { + if entry.magic() != ENTRY_MAGIC { + break; + } + + i += 1; + + if i == raw_table.entries { + break; + } + } else { + return Err(Error::Invalid); + } + } + i + }; + + raw_table.entries = entries; + + Ok(raw_table) + } + + /// Returns the number of partitions contained in the partition table. + pub fn len(&self) -> usize { + self.entries + } + + /// Returns whether there are no recognized partitions. + pub fn is_empty(&self) -> bool { + self.entries == 0 + } + + /// Returns a partition entry. + pub fn get_partition(&self, index: usize) -> Result { + if index >= self.entries { + return Err(Error::OutOfBounds); + } + Ok(PartitionEntry::new(&self.binary[index])) + } + + /// Returns the first partition matching the given partition type. + pub fn find_partition(&self, pt: PartitionType) -> Result, Error> { + for i in 0..self.entries { + let entry = self.get_partition(i)?; + if entry.partition_type() == pt { + return Ok(Some(entry)); + } + } + Ok(None) + } + + /// Returns an iterator over the partitions. + pub fn iter(&self) -> impl Iterator { + (0..self.entries).filter_map(|i| self.get_partition(i).ok()) + } + + #[cfg(feature = "std")] + /// Returns the currently booted partition. + pub fn booted_partition(&self) -> Result, Error> { + Err(Error::Invalid) + } + + #[cfg(not(feature = "std"))] + /// Returns the currently booted partition. + pub fn booted_partition(&self) -> Result, Error> { + let Some(paddr) = booted_app_offset() else { + return Ok(None); + }; + + for id in 0..self.len() { + let entry = self.get_partition(id)?; + if entry.offset() == paddr { + return Ok(Some(entry)); + } + } + + Ok(None) + } +} + +/// Returns the flash offset of the running application image, or `None` when no MMU entry maps +/// it. +/// +/// The bootloader maps the app's first page at the last page of the DROM window, so the app can +/// find its partition. The ESP32's bootloader uses the window's first page. +/// See . +#[cfg(not(feature = "std"))] +pub(super) fn booted_app_offset() -> Option { + use esp_hal::flash::{flash_mmu_drom_entries, flash_mmu_entry_offset}; + + let drom = flash_mmu_drom_entries(); + let entry = if cfg!(feature = "esp32") { + drom.start + } else { + drom.end - 1 + }; + let offset = flash_mmu_entry_offset(entry); + // The ESP32-S31 bootloader that espflash 4.6 bundles is built for 32 KB pages, and maps the + // app at entry 511 instead of 1023. + #[cfg(feature = "esp32s31")] + let offset = offset.or_else(|| flash_mmu_entry_offset(511)); + offset +} + +/// Reads the partition table. +/// +/// Pass [`FlashStorage`] and a buffer to read the partition table into. +pub fn read_partition_table<'a, 'd>( + flash: &mut FlashStorage<'d>, + storage: &'a mut [u8], +) -> Result, Error> { + read_partition_table_impl(flash, storage) +} + +fn read_partition_table_impl<'a, F: FlashAccess>( + flash: &mut F, + storage: &'a mut [u8], +) -> Result, Error> { + #[cfg(feature = "std")] + let enabled = false; + + #[cfg(not(feature = "std"))] + let enabled = esp_hal::efuse::flash_encryption(); + + if enabled { + flash.flash_read_encrypted(PARTITION_TABLE_OFFSET, storage)?; + } else { + flash.flash_read(PARTITION_TABLE_OFFSET, storage)?; + } + + PartitionTable::new(storage) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::partitions::{AppPartitionSubType, DataPartitionSubType}; + + static SIMPLE: &[u8] = include_bytes!("../../testdata/single_factory_no_ota.bin"); + static OTA: &[u8] = include_bytes!("../../testdata/factory_app_two_ota.bin"); + + #[test] + fn read_simple() { + let pt = PartitionTable::new(SIMPLE).unwrap(); + + assert_eq!(3, pt.len()); + + assert_eq!(1, pt.get_partition(0).unwrap().raw_type()); + assert_eq!(1, pt.get_partition(1).unwrap().raw_type()); + assert_eq!(0, pt.get_partition(2).unwrap().raw_type()); + + assert_eq!(2, pt.get_partition(0).unwrap().raw_subtype()); + assert_eq!(1, pt.get_partition(1).unwrap().raw_subtype()); + assert_eq!(0, pt.get_partition(2).unwrap().raw_subtype()); + + assert_eq!( + PartitionType::Data(DataPartitionSubType::Nvs), + pt.get_partition(0).unwrap().partition_type() + ); + assert_eq!( + PartitionType::Data(DataPartitionSubType::Phy), + pt.get_partition(1).unwrap().partition_type() + ); + assert_eq!( + PartitionType::App(AppPartitionSubType::Factory), + pt.get_partition(2).unwrap().partition_type() + ); + + assert_eq!(0x9000, pt.get_partition(0).unwrap().offset()); + assert_eq!(0xf000, pt.get_partition(1).unwrap().offset()); + assert_eq!(0x10000, pt.get_partition(2).unwrap().offset()); + + assert_eq!(0x6000, pt.get_partition(0).unwrap().len()); + assert_eq!(0x1000, pt.get_partition(1).unwrap().len()); + assert_eq!(0x100000, pt.get_partition(2).unwrap().len()); + + assert_eq!("nvs", pt.get_partition(0).unwrap().label_as_str()); + assert_eq!("phy_init", pt.get_partition(1).unwrap().label_as_str()); + assert_eq!("factory", pt.get_partition(2).unwrap().label_as_str()); + + assert_eq!(false, pt.get_partition(0).unwrap().is_read_only()); + assert_eq!(false, pt.get_partition(1).unwrap().is_read_only()); + assert_eq!(false, pt.get_partition(2).unwrap().is_read_only()); + + assert_eq!(false, pt.get_partition(0).unwrap().is_encrypted()); + assert_eq!(false, pt.get_partition(1).unwrap().is_encrypted()); + assert_eq!(false, pt.get_partition(2).unwrap().is_encrypted()); + } + + #[test] + fn read_ota() { + let pt = PartitionTable::new(OTA).unwrap(); + + assert_eq!(6, pt.len()); + + assert_eq!(1, pt.get_partition(0).unwrap().raw_type()); + assert_eq!(1, pt.get_partition(1).unwrap().raw_type()); + assert_eq!(1, pt.get_partition(2).unwrap().raw_type()); + assert_eq!(0, pt.get_partition(3).unwrap().raw_type()); + assert_eq!(0, pt.get_partition(4).unwrap().raw_type()); + assert_eq!(0, pt.get_partition(5).unwrap().raw_type()); + + assert_eq!(2, pt.get_partition(0).unwrap().raw_subtype()); + assert_eq!(0, pt.get_partition(1).unwrap().raw_subtype()); + assert_eq!(1, pt.get_partition(2).unwrap().raw_subtype()); + assert_eq!(0, pt.get_partition(3).unwrap().raw_subtype()); + assert_eq!(0x10, pt.get_partition(4).unwrap().raw_subtype()); + assert_eq!(0x11, pt.get_partition(5).unwrap().raw_subtype()); + + assert_eq!( + PartitionType::Data(DataPartitionSubType::Nvs), + pt.get_partition(0).unwrap().partition_type() + ); + assert_eq!( + PartitionType::Data(DataPartitionSubType::Ota), + pt.get_partition(1).unwrap().partition_type() + ); + assert_eq!( + PartitionType::Data(DataPartitionSubType::Phy), + pt.get_partition(2).unwrap().partition_type() + ); + assert_eq!( + PartitionType::App(AppPartitionSubType::Factory), + pt.get_partition(3).unwrap().partition_type() + ); + assert_eq!( + PartitionType::App(AppPartitionSubType::Ota0), + pt.get_partition(4).unwrap().partition_type() + ); + assert_eq!( + PartitionType::App(AppPartitionSubType::Ota1), + pt.get_partition(5).unwrap().partition_type() + ); + + assert_eq!(0x9000, pt.get_partition(0).unwrap().offset()); + assert_eq!(0xd000, pt.get_partition(1).unwrap().offset()); + assert_eq!(0xf000, pt.get_partition(2).unwrap().offset()); + assert_eq!(0x10000, pt.get_partition(3).unwrap().offset()); + assert_eq!(0x110000, pt.get_partition(4).unwrap().offset()); + assert_eq!(0x210000, pt.get_partition(5).unwrap().offset()); + + assert_eq!(0x4000, pt.get_partition(0).unwrap().len()); + assert_eq!(0x2000, pt.get_partition(1).unwrap().len()); + assert_eq!(0x1000, pt.get_partition(2).unwrap().len()); + assert_eq!(0x100000, pt.get_partition(3).unwrap().len()); + assert_eq!(0x100000, pt.get_partition(4).unwrap().len()); + assert_eq!(0x100000, pt.get_partition(5).unwrap().len()); + + assert_eq!("nvs", pt.get_partition(0).unwrap().label_as_str()); + assert_eq!("otadata", pt.get_partition(1).unwrap().label_as_str()); + assert_eq!("phy_init", pt.get_partition(2).unwrap().label_as_str()); + assert_eq!("factory", pt.get_partition(3).unwrap().label_as_str()); + assert_eq!("ota_0", pt.get_partition(4).unwrap().label_as_str()); + assert_eq!("ota_1", pt.get_partition(5).unwrap().label_as_str()); + + assert_eq!(false, pt.get_partition(0).unwrap().is_read_only()); + assert_eq!(false, pt.get_partition(1).unwrap().is_read_only()); + assert_eq!(false, pt.get_partition(2).unwrap().is_read_only()); + assert_eq!(false, pt.get_partition(3).unwrap().is_read_only()); + assert_eq!(false, pt.get_partition(4).unwrap().is_read_only()); + assert_eq!(false, pt.get_partition(5).unwrap().is_read_only()); + + assert_eq!(false, pt.get_partition(0).unwrap().is_encrypted()); + assert_eq!(false, pt.get_partition(1).unwrap().is_encrypted()); + assert_eq!(false, pt.get_partition(2).unwrap().is_encrypted()); + assert_eq!(false, pt.get_partition(3).unwrap().is_encrypted()); + assert_eq!(false, pt.get_partition(4).unwrap().is_encrypted()); + assert_eq!(false, pt.get_partition(5).unwrap().is_encrypted()); + } + + #[test] + fn empty_byte_array() { + let pt = PartitionTable::new(&[]).unwrap(); + + assert_eq!(0, pt.len()); + assert!(matches!(pt.get_partition(0), Err(Error::OutOfBounds))); + } + + #[test] + fn validation_fails_wo_hash() { + assert!(matches!( + PartitionTable::new(&SIMPLE[..RAW_ENTRY_LEN * 3]), + Err(Error::Invalid) + )); + } + + #[test] + fn validation_fails_wo_hash_max_entries() { + let mut data = [0u8; PARTITION_TABLE_MAX_LEN]; + for i in 0..96 { + data[(i * RAW_ENTRY_LEN)..][..RAW_ENTRY_LEN].copy_from_slice(&SIMPLE[..32]); + } + + assert!(matches!(PartitionTable::new(&data), Err(Error::Invalid))); + } + + #[test] + fn validation_succeeds_with_enough_entries() { + assert_eq!( + 3, + PartitionTable::new(&SIMPLE[..RAW_ENTRY_LEN * 4]) + .unwrap() + .len() + ); + } +} diff --git a/esp-bootloader-esp-idf/src/partitions/types.rs b/esp-bootloader-esp-idf/src/partitions/types.rs new file mode 100644 index 00000000000..75469a50584 --- /dev/null +++ b/esp-bootloader-esp-idf/src/partitions/types.rs @@ -0,0 +1,175 @@ +use super::Error; + +const OTA_SUBTYPE_OFFSET: u8 = 0x10; + +/// A partition type including the sub-type. +#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum PartitionType { + /// Application. + App(AppPartitionSubType), + /// Data. + Data(DataPartitionSubType), + /// Bootloader. + Bootloader(BootloaderPartitionSubType), + /// Partition table. + PartitionTable(PartitionTablePartitionSubType), +} + +/// A partition type. +#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[repr(u8)] +pub enum RawPartitionType { + /// Application. + App = 0, + /// Data. + Data, + /// Bootloader. + Bootloader, + /// Partition table. + PartitionTable, +} + +/// Sub-types of an application partition. +#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, strum::FromRepr)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[repr(u8)] +pub enum AppPartitionSubType { + /// Factory image. + Factory = 0, + /// OTA slot 0. + Ota0 = OTA_SUBTYPE_OFFSET, + /// OTA slot 1. + Ota1, + /// OTA slot 2. + Ota2, + /// OTA slot 3. + Ota3, + /// OTA slot 4. + Ota4, + /// OTA slot 5. + Ota5, + /// OTA slot 6. + Ota6, + /// OTA slot 7. + Ota7, + /// OTA slot 8. + Ota8, + /// OTA slot 9. + Ota9, + /// OTA slot 10. + Ota10, + /// OTA slot 11. + Ota11, + /// OTA slot 12. + Ota12, + /// OTA slot 13. + Ota13, + /// OTA slot 14. + Ota14, + /// OTA slot 15. + Ota15, + /// Test image. + Test, +} + +impl AppPartitionSubType { + pub(crate) fn ota_app_number(&self) -> u8 { + *self as u8 - OTA_SUBTYPE_OFFSET + } + + pub(crate) fn from_ota_app_number(number: u8) -> Result { + if number > 16 { + return Err(Error::InvalidArgument); + } + Self::try_from(number + OTA_SUBTYPE_OFFSET) + } +} + +impl TryFrom for AppPartitionSubType { + type Error = Error; + + fn try_from(value: u8) -> Result { + AppPartitionSubType::from_repr(value).ok_or(Error::Invalid) + } +} + +/// Sub-types of the data partition type. +#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, strum::FromRepr)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[repr(u8)] +pub enum DataPartitionSubType { + /// Data partition which stores information about the currently selected OTA + /// app slot. This partition should be 0x2000 bytes in size. Refer to + /// the OTA documentation for more details. + Ota = 0, + /// Phy is for storing PHY initialization data. This allows PHY to be + /// configured per-device, instead of in firmware. + Phy, + /// Used for Non-Volatile Storage (NVS). + Nvs, + /// Used for storing core dumps while using a custom partition table. + Coredump, + /// NvsKeys is used for the NVS key partition. (NVS). + NvsKeys, + /// Used for emulating eFuse bits using Virtual eFuses. + EfuseEm, + /// Implicitly used for data partitions with unspecified (empty) subtype, + /// but it is possible to explicitly mark them as undefined as well. + Undefined, + /// FAT Filesystem Support. + Fat = 0x81, + /// SPIFFS Filesystem. + Spiffs = 0x82, + /// LittleFS filesystem. + LittleFs = 0x83, +} + +impl TryFrom for DataPartitionSubType { + type Error = Error; + + fn try_from(value: u8) -> Result { + DataPartitionSubType::from_repr(value).ok_or(Error::Invalid) + } +} + +/// Sub-type of the bootloader partition type. +#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, strum::FromRepr)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[repr(u8)] +pub enum BootloaderPartitionSubType { + /// It is the so-called 2nd stage bootloader. + Primary = 0, + /// It is a temporary bootloader partition used by the bootloader OTA update + /// functionality for downloading a new image. + Ota = 1, +} + +impl TryFrom for BootloaderPartitionSubType { + type Error = Error; + + fn try_from(value: u8) -> Result { + BootloaderPartitionSubType::from_repr(value).ok_or(Error::Invalid) + } +} + +/// Sub-type of the partition table type. +#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, strum::FromRepr)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[repr(u8)] +pub enum PartitionTablePartitionSubType { + /// It is the primary partition table. + Primary = 0, + /// It is a temporary partition table partition used by the partition table + /// OTA update functionality for downloading a new image. + Ota = 1, +} + +impl TryFrom for PartitionTablePartitionSubType { + type Error = Error; + + fn try_from(value: u8) -> Result { + PartitionTablePartitionSubType::from_repr(value).ok_or(Error::Invalid) + } +} diff --git a/esp-config/Cargo.toml b/esp-config/Cargo.toml index 86fbfbff181..16b54caadef 100644 --- a/esp-config/Cargo.toml +++ b/esp-config/Cargo.toml @@ -20,6 +20,9 @@ check-configs = [ clippy-configs = [ { features = ["tui"] }, ] +host-test-configs = [ + { features = ["build", "tui"] }, +] [lib] bench = false @@ -36,7 +39,7 @@ document-features = "0.2" serde = { version = "1.0", default-features = false, features = ["derive"], optional = true } serde_yaml = { version = "0.9", optional = true } somni-expr = { version = "0.3", optional = true } -esp-metadata-generated = { version = "0.5.0", path = "../esp-metadata-generated", features = ["build-script"], optional = true } +esp-metadata-generated = { version = "0.6.0", path = "../esp-metadata-generated", features = ["build-script"], optional = true } # used by the `tui` feature clap = { version = "4.5", features = ["derive"], optional = true } diff --git a/esp-config/src/bin/esp-config/main.rs b/esp-config/src/bin/esp-config/main.rs index 68111afc5cd..4ed717253fc 100644 --- a/esp-config/src/bin/esp-config/main.rs +++ b/esp-config/src/bin/esp-config/main.rs @@ -30,8 +30,10 @@ struct Args { config_file: Option, } -fn chip_from_str(str: &str) -> Result, String> { - Chip::from_str(str).map(Some) +// `clap` already handles the `Option` wrapper via the struct field type, +// so the value parser should return `Chip` directly instead of `Option`. +fn chip_from_str(str: &str) -> Result { + Chip::from_str(str) } #[derive(Debug, Clone, PartialEq, Eq)] @@ -325,3 +327,15 @@ fn parse_configs( Ok((hint_about_configs, configs)) } + +#[cfg(test)] +mod tests { + use super::*; + + // Regression test to ensure `--chip` argument parsing does not panic + #[test] + fn parses_chip_arg() { + let args = Args::try_parse_from(["esp-config", "--chip", "esp32c6"]).unwrap(); + assert_eq!(args.chip, Some(Chip::Esp32c6)); + } +} diff --git a/esp-config/src/generate/mod.rs b/esp-config/src/generate/mod.rs index d0c64063461..036d3f00c09 100644 --- a/esp-config/src/generate/mod.rs +++ b/esp-config/src/generate/mod.rs @@ -1107,7 +1107,7 @@ options: } #[test] - fn deserialization_fallback_contraint() { + fn deserialization_fallback_constraint() { let yml = r#" crate: esp-bootloader-esp-idf diff --git a/esp-config/src/generate/value.rs b/esp-config/src/generate/value.rs index 6caaec03ef2..b7c64154aa1 100644 --- a/esp-config/src/generate/value.rs +++ b/esp-config/src/generate/value.rs @@ -100,7 +100,7 @@ impl Value { [b'0', b'b', ..] => i128::from_str_radix(&s[2..], 2), _ => s.parse(), } - .map_err(|_| Error::parse(format!("Expected valid intger value, found: '{s}'")))?; + .map_err(|_| Error::parse(format!("Expected valid integer value, found: '{s}'")))?; Value::Integer(inner) } diff --git a/esp-hal-procmacros/Cargo.toml b/esp-hal-procmacros/Cargo.toml index a2417ffff9e..44a3caa3a5c 100644 --- a/esp-hal-procmacros/Cargo.toml +++ b/esp-hal-procmacros/Cargo.toml @@ -20,6 +20,9 @@ check-configs = [ clippy-configs = [ { features = [] }, ] +host-test-configs = [ + { features = ["has-lp-core", "is-lp-core", "rtc-slow", "rtc-fast"] }, +] [package.metadata.docs.rs] features = ["has-ulp-core", "interrupt", "ram", "is-ulp-core"] diff --git a/esp-hal-procmacros/src/doc_replace.rs b/esp-hal-procmacros/src/doc_replace.rs index 2886900e4e1..0592941a6d9 100644 --- a/esp-hal-procmacros/src/doc_replace.rs +++ b/esp-hal-procmacros/src/doc_replace.rs @@ -1,6 +1,6 @@ use std::{collections::HashMap, str::FromStr}; -use proc_macro2::{TokenStream, TokenStream as TokenStream2}; +use proc_macro2::{Literal, TokenStream, TokenStream as TokenStream2, TokenTree}; use quote::quote; use syn::{ AttrStyle, @@ -80,7 +80,7 @@ impl Replacements { } } } else { - for attr_inner in self.inline_attributes(line) { + for attr_inner in self.inline_attributes(line, span) { if outer { attrs.push(syn::parse_quote_spanned! { span => #[ #attr_inner ] }); } else { @@ -130,7 +130,7 @@ impl Replacements { /// A line without placeholders expands to a single attribute. Otherwise, each placeholder /// contributes as many attributes as it has conditional values, so a line is emitted for every /// combination of the values of its placeholders. - fn inline_attributes(&self, line: &str) -> Vec { + fn inline_attributes(&self, line: &str, span: proc_macro2::Span) -> Vec { let pieces = self.split_line(line); // The placeholders of the line, in order of first appearance. A placeholder used multiple @@ -145,7 +145,7 @@ impl Replacements { } if placeholders.is_empty() { - let line = create_raw_string(line); + let line = create_raw_string(line, span); return vec![quote! { doc = #line }]; } @@ -177,10 +177,13 @@ impl Replacements { .filter_map(|placeholder| choice(placeholder).0.as_ref()) .collect::>(); - let doc = quote_doc_line(pieces.iter().map(|piece| match piece { - Piece::Text(text) => Inline::Text((*text).to_string()), - Piece::Replacement(placeholder) => choice(placeholder).1.clone(), - })); + let doc = quote_doc_line( + pieces.iter().map(|piece| match piece { + Piece::Text(text) => Inline::Text((*text).to_string()), + Piece::Replacement(placeholder) => choice(placeholder).1.clone(), + }), + span, + ); attributes.push(match conditions.as_slice() { [] => doc, @@ -198,7 +201,7 @@ impl Replacements { /// Text is concatenated as far as possible, so that a line that is fully known here becomes a /// single string. The rest is left to `concat!`, which runs once the attribute is expanded and the /// remaining pieces are known. -fn quote_doc_line(pieces: impl Iterator) -> TokenStream2 { +fn quote_doc_line(pieces: impl Iterator, span: proc_macro2::Span) -> TokenStream2 { let mut parts: Vec = vec![]; for piece in pieces { match (parts.last_mut(), piece) { @@ -208,19 +211,20 @@ fn quote_doc_line(pieces: impl Iterator) -> TokenStream2 { } if let [Inline::Text(text)] = parts.as_slice() { - let line = create_raw_string(text); + let line = create_raw_string(text, span); return quote! { doc = #line }; } let parts = parts.iter().map(|part| match part { - Inline::Text(text) => create_raw_string(text), + Inline::Text(text) => create_raw_string(text, span), Inline::Expanded(tokens) => tokens.clone(), }); quote! { doc = concat!( #(#parts),* ) } } -fn create_raw_string(line: &str) -> TokenStream2 { +/// Creates a raw string literal with the span of the original doc attribute. +fn create_raw_string(line: &str, span: proc_macro2::Span) -> TokenStream2 { let hash = if line.contains("#\"") { "##" } else if line.contains('"') { @@ -229,7 +233,9 @@ fn create_raw_string(line: &str) -> TokenStream2 { "" }; - TokenStream2::from_str(&format!("r{hash}\"{line}\"{hash}")).unwrap() + let mut literal = Literal::from_str(&format!("r{hash}\"{line}\"{hash}")).unwrap(); + literal.set_span(span); + TokenTree::Literal(literal).into() } impl Parse for Replacements { diff --git a/esp-hal-procmacros/src/lib.rs b/esp-hal-procmacros/src/lib.rs index 2482481ba06..cd1dee03668 100644 --- a/esp-hal-procmacros/src/lib.rs +++ b/esp-hal-procmacros/src/lib.rs @@ -113,7 +113,7 @@ mod unified_main; /// static mut SOME_ZEROED_DATA: [u8; 8] = [0; 8]; /// ``` /// -/// See the `ram` example in the qa-test folder of the esp-hal repository for a full usage example. +/// See the `ram` example in `examples/qa` of the esp-hal repository for a full usage example. /// /// [`bytemuck::AnyBitPattern`]: https://docs.rs/bytemuck/1.9.0/bytemuck/trait.AnyBitPattern.html /// [`bytemuck::Zeroable`]: https://docs.rs/bytemuck/1.9.0/bytemuck/trait.Zeroable.html diff --git a/esp-hal-procmacros/src/ram.rs b/esp-hal-procmacros/src/ram.rs index 1b6368df33a..df2203cb4f0 100644 --- a/esp-hal-procmacros/src/ram.rs +++ b/esp-hal-procmacros/src/ram.rs @@ -144,30 +144,37 @@ pub fn ram(args: TokenStream, input: TokenStream) -> TokenStream { } let is_fn = matches!(item, Item::Fn(_)); - let section_name = match ( - is_fn, - rtc_fast, - rtc_slow, - dram2_uninit, - dcache_reclaimed, - persistent, - zeroed, - ) { - (true, false, false, false, false, false, false) => Ok(".rwtext"), - (true, true, false, false, false, false, false) => Ok(".rtc_fast.text"), - (true, false, true, false, false, false, false) => Ok(".rtc_slow.text"), - - (false, false, false, false, false, false, false) => Ok(".data"), - (false, false, false, true, false, false, false) => Ok(".dram2_uninit"), - (false, false, false, false, true, false, false) => Ok(".dcache_reclaimed_uninit"), - - (false, true, false, false, false, false, false) => Ok(".rtc_fast.data"), - (false, true, false, false, false, true, false) => Ok(".rtc_fast.persistent"), - (false, true, false, false, false, false, true) => Ok(".rtc_fast.bss"), - - (false, false, true, false, false, false, false) => Ok(".rtc_slow.data"), - (false, false, true, false, false, true, false) => Ok(".rtc_slow.persistent"), - (false, false, true, false, false, false, true) => Ok(".rtc_slow.bss"), + + // The memory option comes before the initialization option. + let options = [ + (rtc_fast, "rtc_fast"), + (rtc_slow, "rtc_slow"), + (dram2_uninit, "reclaimed"), + (dcache_reclaimed, "dcache_reclaimed"), + (persistent, "persistent"), + (zeroed, "zeroed"), + ] + .into_iter() + .filter_map(|(set, name)| set.then_some(name)) + .collect::>(); + + let section_name = match (is_fn, options.as_slice()) { + (true, []) => Ok(".rwtext"), + (true, ["rtc_fast"]) => Ok(".rtc_fast.text"), + (true, ["rtc_slow"]) => Ok(".rtc_slow.text"), + + (false, []) => Ok(".data"), + (false, ["reclaimed"]) => Ok(".dram2_uninit"), + (false, ["reclaimed", "zeroed"]) => Ok(".dram2_uninit.bss"), + (false, ["dcache_reclaimed"]) => Ok(".dcache_reclaimed_uninit"), + + (false, ["rtc_fast"]) => Ok(".rtc_fast.data"), + (false, ["rtc_fast", "persistent"]) => Ok(".rtc_fast.persistent"), + (false, ["rtc_fast", "zeroed"]) => Ok(".rtc_fast.bss"), + + (false, ["rtc_slow"]) => Ok(".rtc_slow.data"), + (false, ["rtc_slow", "persistent"]) => Ok(".rtc_slow.persistent"), + (false, ["rtc_slow", "zeroed"]) => Ok(".rtc_slow.bss"), _ => Err(()), }; diff --git a/esp-hal/CHANGELOG.md b/esp-hal/CHANGELOG.md index 9f73c073e32..66537133fa7 100644 --- a/esp-hal/CHANGELOG.md +++ b/esp-hal/CHANGELOG.md @@ -20,6 +20,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Removed +## [v1.2.0] - 2026-09-01 + +### Fixed + +- GPIO: Fixed a breaking change introduced in 1.2.0-rc.0, which prevented writing generic functions for GPIOs. (#6252) +- A pad that is already at its wake level no longer loses its wake configuration. This fixes a regression in 1.2.0-rc.0. (#6250) +- SPI: the maximum bus frequency can be configured using the default clock source. (#6245) +- Power the 32 kHz crystal on ESP32 when it is selected as the RTC slow clock (#6234) +- UART: Fixed an issue that caused UART TX to send a short low pulse when transmitting shorty after changing configuration. (#6233) +- PARL_IO: esp-hal now correctly uses pad clock inputs to sample the received signal. (#6227) +- UART: C2, C3 and S3 now properly synchronize UART register accesses between clock domains. (#6226) +- XTAL32K can no longer be configured without enabling `ESP_HAL_CONFIG_USE_XTAL32K` (#6194) +- ESP32, ESP32-C2: fixed RcFastDivClk calibration on startup (#6193) + ## [v1.2.0-rc.0] - 2026-08-24 ### Added @@ -245,7 +259,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - ESP32 should no longer break its debug interface when running embedded tests. (#5594) - SHA: ESP32 implementation no longer powers down the SHA accelerator while in use (#5592) - SHA: ESP32 no longer tries to use the hardware accelerator when it's held by another SHA operation. (#5592) -- RSA: ESP32 now correctly disables its interrups before disabling the RSA accelerator (#5592) +- RSA: ESP32 now correctly disables its interrupts before disabling the RSA accelerator (#5592) - Add missing import when building SPI with `ESP_HAL_CONFIG_PLACE_SPI_MASTER_DRIVER_IN_RAM = "true"` (#5585) - Xtensa LLD can now link projects again, as long as they don't have GCC linked libraries. Support for linking via LLD with GCC binaries will be possible once https://github.com/espressif/llvm-project/pull/130 lands and is included in the esp toolchain. (#5582) - RMT: allow maximum pulse length on both phases in `PulseCode` (#5514) @@ -635,7 +649,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Support for `rand_core` 0.9 (#3211) - `ESP_HAL_CONFIG_STACK_GUARD_OFFSET` and `ESP_HAL_CONFIG_STACK_GUARD_VALUE` to configure Rust's [Stack smashing protection](https://doc.rust-lang.org/rustc/exploit-mitigations.html#stack-smashing-protection) (#3203) - Experimental metadata in the output `.elf` (#3276) -- `PeripheralInput::connect_input_to_peripheral` and `PeripheralOuptut::{connect_peripheral_to_output, disconnect_from_peripheral_output}` (#3302) +- `PeripheralInput::connect_input_to_peripheral` and `PeripheralOutput::{connect_peripheral_to_output, disconnect_from_peripheral_output}` (#3302) - `ESP_HAL_CONFIG_CRITICAL_SECTION_IMPL` to allow opting out of the default `critical-section` implementation (#3293) - All peripheral singletons (`GpioPin<...>`, `SPIn`, ...) now have a lifetime, as well as `steal`, `reborrow` and `clone_unchecked` methods (#3305) - `i2c::master::Operation` now implements `defmt::Format` (#3348) @@ -896,7 +910,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - The `PeripheralInput` and `PeripheralOutput` traits are now sealed (#2690) - `esp_hal::sync::Lock` has been renamed to RawMutex (#2684) - Updated `esp-pacs` with support for Wi-Fi on the ESP32 and made the peripheral non virtual (#2822) -- `SpiBitOrder`, `SpiDataMode`, `SpiMode` were renamed to `BitOder`, `DataMode` and `Mode` (#2828) +- `SpiBitOrder`, `SpiDataMode`, `SpiMode` were renamed to `BitOrder`, `DataMode` and `Mode` (#2828) - `crate::Mode` was renamed to `crate::DriverMode` (#2828) - `Spi::with_miso` has been overloaded into `Spi::with_miso` and `Spi::with_sio1` (#2557) - Renamed some I2C error variants (#2844) @@ -1083,7 +1097,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Added APIs to allow connecting signals through the GPIO matrix. (#2128) - Allow I8080 transfers to be cancelled on the spot (#2191) - Implement `TryFrom` for `ledc::timer::config::Duty` (#1984) -- Expose `RtcClock::get_xtal_freq` and `RtcClock::get_slow_freq` publically for all chips (#2183) +- Expose `RtcClock::get_xtal_freq` and `RtcClock::get_slow_freq` publicly for all chips (#2183) - TWAI support for ESP32-H2 (#2199) - Make `DmaDescriptor` methods public (#2237) - Added a way to configure watchdogs in `esp_hal::init` (#2180) @@ -1159,7 +1173,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Removed `digest::Digest` implementation from SHA (#2049) - Removed `NoPinType` in favour of `DummyPin`. (#2068) - Removed the `async`, `embedded-hal-02`, `embedded-hal`, `embedded-io`, `embedded-io-async`, and `ufmt` features (#2070) -- Removed the `GpioN` type aliasses. Use `GpioPin` instead. (#2073) +- Removed the `GpioN` type aliases. Use `GpioPin` instead. (#2073) - Removed `Peripherals::take`. Use `esp_hal::init` to obtain `Peripherals` (#1999) - Removed `AnyInputOnlyPin` in favour of `AnyPin`. (#2071) - Removed the following functions from `GpioPin`: `is_high`, `is_low`, `set_high`, `set_low`, `set_state`, `is_set_high`, `is_set_low`, `toggle`. (#2094) @@ -1206,7 +1220,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Improve SYSTIMER API (#1871) - SHA driver now use specific structs for the hashing algorithm instead of a parameter. (#1908) - Remove `fn free(self)` in HMAC which goes against esp-hal API guidelines (#1972) -- `AnyPin`, `AnyInputOnyPin` and `DummyPin` are now accessible from `gpio` module (#1918) +- `AnyPin`, `AnyInputOnlyPin` and `DummyPin` are now accessible from `gpio` module (#1918) - Changed the RSA modular multiplication API to be consistent across devices (#2002) ### Fixed @@ -1348,7 +1362,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Added async support for TWAI (#1320) - Add TWAI support for ESP32-C6 (#1323) - `GpioPin::steal` unsafe API (#1363) -- Inherent implementions of GPIO pin `set_low`, `is_low`, etc. (#1284) +- Inherent implementations of GPIO pin `set_low`, `is_low`, etc. (#1284) - Warn users when attempting to build using the `dev` profile (#1420) - Async uart now reports interrupt errors(overflow, glitch, frame error, parity) back to user of read/write. uart clock decimal part configured for c2,c3,s3 (#1168, #1445) - Add mechanism to configure UART source clock (#1416) @@ -1546,7 +1560,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - ESP32-C3/C6 and ESP32-H2 can now use the `zero-rtc-bss` feature to enable `esp-hal-common/rv-zero-rtc-bss` (#867) - Reuse `ieee802154_clock_enable/disable()` functions for BLE and rename `ble_ieee802154_clock_enable()` (#953) - The `embedded-io` trait implementations are now gated behind the `embedded-io` feature (#964) -- Simplifed RMT channels and channel creators (#958) +- Simplified RMT channels and channel creators (#958) - Reworked construction of I2S driver instances (#983) - ESP32-S2/S3: Don't require GPIO 18 to create a USB peripheral driver instance (#990) - Updated to latest release candidate (`1.0.0-rc.2`) for `embedded-hal{-async,-nb}` (#994) @@ -1876,4 +1890,5 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 [v1.0.0]: https://github.com/esp-rs/esp-hal/compare/esp-hal-v1.0.0-rc.1...esp-hal-v1.0.0 [v1.1.0]: https://github.com/esp-rs/esp-hal/compare/esp-hal-v1.0.0...esp-hal-v1.1.0 [v1.2.0-rc.0]: https://github.com/esp-rs/esp-hal/compare/esp-hal-v1.1.0...esp-hal-v1.2.0-rc.0 -[Unreleased]: https://github.com/esp-rs/esp-hal/compare/esp-hal-v1.2.0-rc.0...HEAD +[v1.2.0]: https://github.com/esp-rs/esp-hal/compare/esp-hal-v1.2.0-rc.0...esp-hal-v1.2.0 +[Unreleased]: https://github.com/esp-rs/esp-hal/compare/esp-hal-v1.2.0...HEAD diff --git a/esp-hal/Cargo.toml b/esp-hal/Cargo.toml index 4b7596425df..8197daccf65 100644 --- a/esp-hal/Cargo.toml +++ b/esp-hal/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "esp-hal" -version = "1.2.0-rc.0" +version = "1.2.0" edition = "2024" rust-version = "1.95.0" description = "Bare-metal HAL for Espressif devices" @@ -26,7 +26,7 @@ check-configs = [ { features = ["unstable", "rt"], env = { ESP_HAL_CONFIG_PLACE_ANON_IN_RAM = "true", ESP_HAL_CONFIG_PLACE_RMT_DRIVER_IN_RAM = "true", ESP_HAL_CONFIG_PLACE_SPI_MASTER_DRIVER_IN_RAM = "true", ESP_HAL_CONFIG_CLEAR_CRYPTO_SECRETS = "false" } }, { features = ["unstable", "rt"], env = { ESP_HAL_CONFIG_ENABLE_PMP = "false" }, if = 'riscv && !esp32c2 && !esp32c3' }, { features = ["unstable", "rt"], env = { ESP_HAL_CONFIG_INIT_STACK_PTR_RANGE_CHECK = "false" } }, - { features = ["unstable", "rt"], env = { ESP_HAL_CONFIG_USE_XTAL32K = "true" }, if = 'soc_has_xtal32k_pads' }, + { features = ["unstable", "rt"], env = { ESP_HAL_CONFIG_USE_XTAL32K = "true" }, if = 'soc_has_clock_node_xtal32k_clk' }, { features = ["unstable", "rt", "__usb_otg"], if = 'usb_otg_driver_supported' }, { features = ["unstable", "rt", "__bluetooth"], if = 'bt_driver_supported' }, { features = ["unstable", "rt", "__sdmmc"], if = 'sdmmc_driver_supported' }, @@ -50,13 +50,14 @@ bench = false test = false [dependencies] -bytemuck = "1.24" +bytemuck = { version = "1.24", features = ["zeroable_maybe_uninit"] } critical-section = { version = "1", features = ["restore-state-u32"], optional = true } embedded-hal = "1.0.0" embedded-hal-async = "1.0.0" enumset = "1.1" paste = "1.0.15" portable-atomic = { version = "1.11", default-features = false } +portable_atomic_enum = { version = "0.3.1", features = ["portable-atomic"] } static_cell = "2" esp-rom-sys = { version = "~0.1", path = "../esp-rom-sys" } @@ -72,7 +73,7 @@ instability = "0.3.12" strum = { version = "0.27.1", default-features = false, features = ["derive"] } esp-config = { version = "0.8.0", path = "../esp-config" } -esp-metadata-generated = { version = "0.5.0", path = "../esp-metadata-generated" } +esp-metadata-generated = { version = "0.6.0", path = "../esp-metadata-generated" } esp-sync = { version = "0.3.0", path = "../esp-sync" } procmacros = { version = "0.23.0", package = "esp-hal-procmacros", path = "../esp-hal-procmacros" } @@ -83,6 +84,7 @@ digest-011 = { package = "digest", version = "0.11", default-fea embassy-usb-driver = { version = "0.2", optional = true } embassy-usb-synopsys-otg = { version = "0.4.0", optional = true, features = ["host"] } embassy-net-driver-02 = { package = "embassy-net-driver", version = "0.2", optional = true } +xarxa-driver = { version = "0.1.0", features = ["async"], optional = true } embedded-can = { version = "0.4.1", optional = true } nb = { version = "1.1", optional = true } sdio = { version = "0.5", optional = true } @@ -111,17 +113,18 @@ ufmt-write = { version = "0.1", optional = true } # IMPORTANT: # Each supported device MUST have its PAC included below along with a # corresponding feature. -esp32 = { version = "0.41", features = ["critical-section"], optional = true } -esp32c2 = { version = "0.30", features = ["critical-section"], optional = true } -esp32c3 = { version = "0.33", features = ["critical-section"], optional = true } -esp32c5 = { version = "0.3", features = ["critical-section"], optional = true } -esp32c6 = { version = "0.24", features = ["critical-section"], optional = true } -esp32c61 = { version = "0.4", features = ["critical-section"], optional = true } -esp32h2 = { version = "0.20", features = ["critical-section"], optional = true } -esp32s2 = { version = "0.32", features = ["critical-section"], optional = true } -esp32s3 = { version = "0.36", features = ["critical-section"], optional = true } -esp32s31 = { version = "0.2", features = ["critical-section"], optional = true } -esp32p4 = { version = "0.3", features = ["critical-section"], optional = true } +esp32 = { version = "0.42", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32c2 = { version = "0.31", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32c3 = { version = "0.34", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32c5 = { version = "0.4", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32c6 = { version = "0.25", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32c61 = { version = "0.5", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32h2 = { version = "0.21", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32h4 = { version = "0.1", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32s2 = { version = "0.33", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32s3 = { version = "0.37", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32s31 = { version = "0.3", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32p4 = { version = "0.4", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } [target.'cfg(target_arch = "riscv32")'.dependencies] riscv = { version = "0.15.0" } @@ -132,13 +135,14 @@ xtensa-lx = { version = "0.13.0", path = "../xtensa-lx" } xtensa-lx-rt = { version = "0.23.0", path = "../xtensa-lx-rt", optional = true } [build-dependencies] -esp-metadata-generated = { version = "0.5.0", path = "../esp-metadata-generated", features = ["build-script"] } +esp-metadata-generated = { version = "0.6.0", path = "../esp-metadata-generated", features = ["build-script"] } esp-config = { version = "0.8.0", path = "../esp-config", features = ["build"] } somni-template = "0.3.1" [dev-dependencies] crypto-bigint = { version = "0.7.5", default-features = false } jiff = { version = "0.2", default-features = false, features = ["static"] } +static_cell = "2" [features] default = ["rt", "exception-handler", "float-save-restore"] @@ -151,6 +155,10 @@ __usb_otg = [ "dep:embassy-usb-driver", "dep:embassy-usb-synopsys-otg", ] +__ethernet = [ + "dep:embassy-net-driver-02", + "dep:xarxa-driver", +] #! ### Runtime support #! These features are meant to be enabled by firmware projects. If you are writing a library that @@ -168,6 +176,7 @@ rt = [ "esp32c61?/rt", "esp32p4?/rt", "esp32h2?/rt", + "esp32h4?/rt", "esp32s2?/rt", "esp32s3?/rt", "esp32s31?/rt", @@ -197,6 +206,7 @@ float-save-restore = ["xtensa-lx-rt/float-save-restore"] esp32 = [ "dep:esp32", "__sdmmc", + "__ethernet", "procmacros/rtc-slow", "procmacros/rtc-fast", "esp-rom-sys/esp32", @@ -204,7 +214,6 @@ esp32 = [ "esp-metadata-generated/esp32", "dep:sha1", "dep:sha2", - "dep:embassy-net-driver-02", ] ## esp32c2 = [ @@ -252,6 +261,7 @@ esp32p4 = [ "dep:esp32p4", "__sdmmc", "__usb_otg", + "__ethernet", "esp-riscv-rt/rtc-ram", "esp-riscv-rt/clic-48", "procmacros/rtc-fast", @@ -259,7 +269,6 @@ esp32p4 = [ "esp-rom-sys/esp32p4", "esp-sync/esp32p4", "esp-metadata-generated/esp32p4", - "dep:embassy-net-driver-02", ] ## esp32c61 = [ @@ -280,13 +289,21 @@ esp32h2 = [ "esp-metadata-generated/esp32h2", ] ## +esp32h4 = [ + "dep:esp32h4", + "esp-riscv-rt/clic-48", + "esp-rom-sys/esp32h4", + "esp-sync/esp32h4", + "esp-metadata-generated/esp32h4", +] +## esp32s2 = [ "dep:esp32s2", + "__usb_otg", "portable-atomic/unsafe-assume-single-core", "procmacros/has-ulp-core", "procmacros/rtc-slow", "procmacros/rtc-fast", - "__usb_otg", "esp-rom-sys/esp32s2", "esp-sync/esp32s2", "esp-metadata-generated/esp32s2", @@ -295,23 +312,24 @@ esp32s2 = [ esp32s3 = [ "dep:esp32s3", "__sdmmc", + "__usb_otg", "procmacros/has-ulp-core", "procmacros/rtc-slow", "procmacros/rtc-fast", "procmacros/dcache-reclaimed", - "__usb_otg", "esp-rom-sys/esp32s3", "esp-sync/esp32s3", "esp-metadata-generated/esp32s3", ] ## esp32s31 = [ - "__sdmmc", "dep:esp32s31", + "__sdmmc", + "__usb_otg", + "__ethernet", "esp-riscv-rt/rtc-ram", "esp-riscv-rt/clic-48", "procmacros/rtc-fast", - "__usb_otg", "esp-rom-sys/esp32s31", "esp-sync/esp32s31", "esp-metadata-generated/esp32s31", @@ -337,12 +355,16 @@ defmt = [ "esp32c6?/defmt", "esp32c61?/defmt", "esp32h2?/defmt", + "esp32h4?/defmt", + "esp32p4?/defmt", "esp32s2?/defmt", "esp32s3?/defmt", + "esp32s31?/defmt", "fugit/defmt", "esp-riscv-rt?/defmt", "xtensa-lx-rt?/defmt", - "esp-sync/defmt" + "esp-sync/defmt", + "xarxa-driver?/defmt" ] #! ### Unstable APIs diff --git a/esp-hal/MIGRATING-1.1.0.md b/esp-hal/MIGRATING-1.1.0.md index 63ed7d979b9..1d8229057e7 100644 --- a/esp-hal/MIGRATING-1.1.0.md +++ b/esp-hal/MIGRATING-1.1.0.md @@ -1,4 +1,4 @@ -# Migration Guide from 1.1.0 to {{currentVersion}} +# Migration Guide from 1.1.0 to 1.2.0 ## `Clocks` struct removed @@ -241,6 +241,73 @@ I2s::new( PDM is I2S0-only and simplex (TX **or** RX). Use `I2s::new_pdm` with `PdmConfig::tx_only(...)` or `PdmConfig::rx_only(...)`, and connect pins via `with_clk` plus `with_dout` / `with_din` (or `with_din_line` on multi-line chips). PDM validation errors are returned as `ConfigError::Pdm(PdmError)` (e.g. `PdmError::InvalidLine` for invalid data line indices). +### I2S DMA now uses the DmaBuffer API + +I2S no longer uses manually passed DMA descriptors or the generic `DmaTransfer*` types. Buffers are +created with the DMA buffer macros, channels are built without descriptors, and transfers are started +by consuming the channel. + +```diff +-use esp_hal::dma_buffers; +-let (mut rx_buffer, rx_descriptors, _, _) = dma_buffers!(4 * 4092, 0); ++use esp_hal::dma_rx_stream_buffer; ++let rx_buffer = dma_rx_stream_buffer!(4 * 4092, 1024); + let i2s_rx = i2s + .i2s_rx + .with_bclk(peripherals.GPIO1) + .with_ws(peripherals.GPIO2) + .with_din(peripherals.GPIO5) +- .build(rx_descriptors); ++ .build(); +``` + +Use `dma_rx_buffer!` / `dma_tx_buffer!` instead of the `*_stream_buffer!` macros when you need a +finite, one-shot transfer rather than continuous streaming. + +#### Starting transfers + +`read` / `write` take ownership of the channel. For async code, call `.into_async()` on `I2s` before +building the RX/TX channel. + +```diff +-let mut transfer = i2s_rx.read_dma_circular(&mut rx_buffer)?; ++let mut transfer = i2s_rx.read(rx_buffer)?; +``` + +On failure, `read` / `write` return `Err((Error, I2sRx, BUF))` (or the TX equivalents), so you can +recover both the channel and the buffer. + +#### Transfer handles and streaming I/O + +The generic `DmaTransferRxCircular` / `DmaTransferTxCircular` (and the old `I2sReadDmaTransferAsync` / +`I2sWriteDmaTransferAsync`) are replaced by `I2sRxDmaTransfer` / `I2sTxDmaTransfer`. These deref to the +buffer view, exposing `available_bytes()`, `pop()`, `push()`, and `push_with()`. + +```diff + loop { +- transfer.wait_for_data().await?; +- let avail = transfer.available()?; ++ transfer.wait_for_available_async().await?; ++ let avail = transfer.available_bytes(); + if avail > 0 { +- transfer.pop(&mut rcv[..avail])?; ++ transfer.pop(&mut rcv[..avail]); + } + } +``` + +#### Finishing a one-shot transfer + +`wait` (and `wait_async` in async code) returns the completion result together with the recovered +peripheral and buffer. + +```rust +let transfer = i2s_rx.read(buffer)?; +let (result, i2s_rx, buffer) = transfer.wait(); +// or, in async code: +let (result, i2s_rx, buffer) = transfer.wait_async().await; +``` + ## DMA memory-to-memory ### `MEM2MEM*` peripherals removed @@ -288,5 +355,3 @@ let erased = channel.into(); `PeripheralDmaChannel`/`PeripheralRxChannel`/`PeripheralTxChannel` type aliases have been removed. Driver channel bounds are now expressed directly as the driver-specific trait (e.g. `SpiDmaChannel`, `I2sDmaChannel`). Update any channel bounds accordingly. - - diff --git a/esp-hal/MIGRATING-1.2.0.md b/esp-hal/MIGRATING-1.2.0.md new file mode 100644 index 00000000000..e41ac790837 --- /dev/null +++ b/esp-hal/MIGRATING-1.2.0.md @@ -0,0 +1 @@ +# Migration Guide from 1.2.0 to {{currentVersion}} diff --git a/esp-hal/README.md b/esp-hal/README.md index 1be6778e7dc..a037fadc938 100644 --- a/esp-hal/README.md +++ b/esp-hal/README.md @@ -32,6 +32,7 @@ For help getting started with this HAL, please refer to [The Rust on ESP Book] a | ESP32-C6 | [Datasheet][esp32c6-datasheet] [TRM][esp32c6-trm] | `riscv32imac-unknown-none-elf` | | | ESP32-C61 | [Datasheet][esp32c61-datasheet] [TRM][esp32c61-trm] | `riscv32imac-unknown-none-elf` | | | ESP32-H2 | [Datasheet][esp32h2-datasheet] [TRM][esp32h2-trm] | `riscv32imac-unknown-none-elf` | | +| ESP32-H4 | [Datasheet][esp32h4-datasheet] [TRM][esp32h4-trm] | `riscv32imafc-unknown-none-elf` | In early stages of development. | | ESP32-P4 | [Datasheet][esp32p4-datasheet] [TRM][esp32p4-trm] | `riscv32imafc-unknown-none-elf` | Revisions below v3.0 are not supported. | | ESP32-S2 | [Datasheet][esp32s2-datasheet] [TRM][esp32s2-trm] | `xtensa-esp32s2-none-elf` | | | ESP32-S3 | [Datasheet][esp32s3-datasheet] [TRM][esp32s3-trm] | `xtensa-esp32s3-none-elf` | | @@ -51,6 +52,8 @@ For help getting started with this HAL, please refer to [The Rust on ESP Book] a [esp32c61-trm]: https://www.espressif.com/sites/default/files/documentation/esp32-c61_technical_reference_manual_en.pdf [esp32h2-datasheet]: https://www.espressif.com/sites/default/files/documentation/esp32-h2_datasheet_en.pdf [esp32h2-trm]: https://www.espressif.com/sites/default/files/documentation/esp32-h2_technical_reference_manual_en.pdf +[esp32h4-datasheet]: https://www.espressif.com/sites/default/files/documentation/esp32-h4_datasheet_en.pdf +[esp32h4-trm]: https://www.espressif.com/sites/default/files/documentation/esp32-h4_technical_reference_manual_en.pdf [esp32p4-datasheet]: https://www.espressif.com/sites/default/files/documentation/esp32-p4_datasheet_en.pdf [esp32p4-trm]: https://www.espressif.com/sites/default/files/documentation/esp32-p4_technical_reference_manual_en.pdf [esp32s2-datasheet]: https://www.espressif.com/sites/default/files/documentation/esp32-s2_datasheet_en.pdf @@ -65,168 +68,142 @@ For help getting started with this HAL, please refer to [The Rust on ESP Book] a - * Empty cell: Not available +For a detailed per-chip support matrix, see the [documentation index](https://docs.espressif.com/projects/rust/esp-hal/main/index.html#peripheral-support). + * ❌: Not supported - * ⚒️: Partial support - * ✔️: Supported - -### GPIO - -| Driver | ESP32 | ESP32-C2 | ESP32-C3 | ESP32-C5 | ESP32-C6 | ESP32-C61 | ESP32-H2 | ESP32-P4 | ESP32-S2 | ESP32-S3 | ESP32-S31 | -| -------------- |:-----:|:--------:|:--------:|:--------:|:--------:|:---------:|:--------:|:--------:|:--------:|:--------:|:---------:| -| GPIO | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | -| Dedicated GPIO | | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | -| IOMUX | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | -| LP IO | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ❌ | - -### Serial interfaces - -| Driver | ESP32 | ESP32-C2 | ESP32-C3 | ESP32-C5 | ESP32-C6 | ESP32-C61 | ESP32-H2 | ESP32-P4 | ESP32-S2 | ESP32-S3 | ESP32-S31 | -| --------------- |:-----:|:--------:|:--------:|:--------:|:--------:|:---------:|:--------:|:--------:|:--------:|:--------:|:---------:| -| UART | [✔️][6138] [^1] | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | -| LP UART | | | | [❌][5155] [^1] | ⚒️ | | | ❌ | | | ❌ | -| UHCI | ❌ | | ⚒️ | ⚒️ | ⚒️ | | ⚒️ | ⚒️ | ❌ | ⚒️ | ⚒️ | -| I2C master | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | -| LP I2C master | ❌ | | | ⚒️ | ⚒️ | | | ⚒️ | ❌ | ⚒️ | ❌ | -| I2C slave | [❌][1909] [^1] | | ⚒️ | [❌][1909] [^1] | ⚒️ | [❌][1909] [^1] | [❌][1909] [^1] | ❌ | [❌][1909] [^1] | [❌][1909] [^1] | ❌ | -| I3C master | | | | | | | | ❌ | | | | -| I3C slave | | | | | | | | ❌ | | | | -| SPI master | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | -| SPI slave | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | -| LP SPI master | | | | | | | | ❌ | | | | -| LP SPI slave | | | | | | | | ❌ | | | | -| I2S | ⚒️ | | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ❌ | -| LP I2S | | | | | | | | ❌ | | | | -| PARL_IO | | | | ⚒️ | ⚒️ | | ⚒️ | ❌ | | | ❌ | -| RMT | ⚒️ | | ⚒️ | ⚒️ | ⚒️ | | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | -| SDMMC/SDIO host | ⚒️ | | | | | | | ⚒️ | | ⚒️ | ⚒️ | -| SDIO slave | ❌ | | | [❌][5169] [^1] | ❌ | [❌][5417] [^1] | | | | | | -| TWAI | ⚒️ | | ⚒️ | | ⚒️ | | ⚒️ | ❌ | ⚒️ | ⚒️ | | -| CANFD | | | | [❌][5163] [^1] | | | | | | | ❌ | -| USB OTG FS | | | | | | | | ⚒️ | ⚒️ | ⚒️ | | -| USB OTG HS | | | | | | | | ⚒️ | | | ⚒️ | -| USB Serial/JTAG | | | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | | ⚒️ | ⚒️ | - -### Wireless and networking - -| Driver | ESP32 | ESP32-C2 | ESP32-C3 | ESP32-C5 | ESP32-C6 | ESP32-C61 | ESP32-H2 | ESP32-P4 | ESP32-S2 | ESP32-S3 | ESP32-S31 | -| ------------- |:-----:|:--------:|:--------:|:--------:|:--------:|:---------:|:--------:|:--------:|:--------:|:--------:|:---------:| -| Bluetooth | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | | | ⚒️ | ❌ | -| WIFI | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | | | ⚒️ | ⚒️ | ❌ | -| IEEE 802.15.4 | | | | ⚒️ | ⚒️ | | ⚒️ | | | | ❌ | -| Ethernet | ⚒️ | | | | | | | ⚒️ | | | ❌ | - -### Display and camera - -| Driver | ESP32 | ESP32-C2 | ESP32-C3 | ESP32-C5 | ESP32-C6 | ESP32-C61 | ESP32-H2 | ESP32-P4 | ESP32-S2 | ESP32-S3 | ESP32-S31 | -| ----------------- |:-----:|:--------:|:--------:|:--------:|:--------:|:---------:|:--------:|:--------:|:--------:|:--------:|:---------:| -| Camera interface | ❌ | | | | | | | ❌ | ❌ | ⚒️ | ❌ | -| MIPI-CSI | | | | | | | | ❌ | | | | -| MIPI-DSI | | | | | | | | ⚒️ | | | | -| RGB display | ⚒️ | | | | | | | ❌ | ❌ | ⚒️ | ❌ | -| SPI LCD interface | | | | | | | | | [❌][5374] [^1] | | | - -### Signal processing - -| Driver | ESP32 | ESP32-C2 | ESP32-C3 | ESP32-C5 | ESP32-C6 | ESP32-C61 | ESP32-H2 | ESP32-P4 | ESP32-S2 | ESP32-S3 | ESP32-S31 | -| ---------------------------- |:-----:|:--------:|:--------:|:--------:|:--------:|:---------:|:--------:|:--------:|:--------:|:--------:|:---------:| -| Bit Scrambler | | | | [❌][5170] [^1] | | | | ❌ | | | ❌ | -| Image Signal Processor | | | | | | | | ❌ | | | | -| Pixel Processing Accelerator | | | | | | | | ❌ | | | ❌ | -| JPEG Codec | | | | | | | | ❌ | | | ❌ | -| H.264 encoder | | | | | | | | ❌ | | | | -| Audio Sample Rate Converter | | | | | | | | | | | ❌ | -| CORDIC accelerator | | | | | | | | | | | ❌ | -| Voice Activity Detection | | | | | | | | ❌ | | | | - -### Analog - -| Driver | ESP32 | ESP32-C2 | ESP32-C3 | ESP32-C5 | ESP32-C6 | ESP32-C61 | ESP32-H2 | ESP32-P4 | ESP32-S2 | ESP32-S3 | ESP32-S31 | -| ------------------------- |:-----:|:--------:|:--------:|:--------:|:--------:|:---------:|:--------:|:--------:|:--------:|:--------:|:---------:| -| ADC | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | -| Analog Voltage Comparator | | | | [❌][5168] [^1] | | [❌][5423] [^1] | ❌ | ❌ | | | ❌ | -| DAC | ⚒️ | | | | | | | | ⚒️ | | ❌ | -| Temperature sensor | ⚒️ | ⚒️ | ⚒️ | [❌][5153] [^1] | ⚒️ | [❌][5421] [^1] | ⚒️ | ❌ | ⚒️ | ⚒️ | ❌ | -| Touch | ⚒️ | | | [❌][5164] [^1] | | | | ❌ | [❌][1905] [^1] | [❌][1905] [^1] | ❌ | - -### Timers and motor control - -| Driver | ESP32 | ESP32-C2 | ESP32-C3 | ESP32-C5 | ESP32-C6 | ESP32-C61 | ESP32-H2 | ESP32-P4 | ESP32-S2 | ESP32-S3 | ESP32-S31 | -| --------------- |:-----:|:--------:|:--------:|:--------:|:--------:|:---------:|:--------:|:--------:|:--------:|:--------:|:---------:| -| LEDC | ⚒️ | ⚒️ | ⚒️ | [❌][5161] [^1] | ⚒️ | [❌][5418] [^1] | ⚒️ | ❌ | ⚒️ | ⚒️ | ❌ | -| MCPWM | ⚒️ | | | [❌][5154] [^1] | ⚒️ | | ⚒️ | ❌ | | ⚒️ | ❌ | -| PCNT | ⚒️ | | | ⚒️ | ⚒️ | | ⚒️ | ❌ | ⚒️ | ⚒️ | ❌ | -| RTC Timekeeping | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | -| SDM | ⚒️ | | ⚒️ | ⚒️ | ⚒️ | | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | -| SYSTIMER | | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | -| Timers | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | - -### Cryptography and security - -| Driver | ESP32 | ESP32-C2 | ESP32-C3 | ESP32-C5 | ESP32-C6 | ESP32-C61 | ESP32-H2 | ESP32-P4 | ESP32-S2 | ESP32-S3 | ESP32-S31 | -| ----------------------- |:-----:|:--------:|:--------:|:--------:|:--------:|:---------:|:--------:|:--------:|:--------:|:--------:|:---------:| -| AES | ⚒️ | | ⚒️ | ⚒️ | ⚒️ | | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | -| RSA Digital Signature | | | [❌][884] [^1] | [❌][884] [^1] | [❌][884] [^1] | | [❌][884] [^1] | ❌ | [❌][884] [^1] | [❌][884] [^1] | ❌ | -| ECDSA Digital Signature | | | | [❌][5444] [^1] | | [❌][5444] [^1] | [❌][5444] [^1] | ❌ | | | ❌ | -| ECC | | ⚒️ | | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | | | [⚒️][5972] [^1] | -| HMAC | | | ⚒️ | [❌][5166] [^1] | ⚒️ | | ⚒️ | ❌ | ⚒️ | ⚒️ | ❌ | -| Key Manager | | | | [❌][5171] [^1] | | | | ❌ | | | ❌ | -| RNG | [⚒️][5979] [^1] | [⚒️][5979] [^1] | [⚒️][5979] [^1] | [⚒️][5980] [^1] | [⚒️][5979] [^1] | [⚒️][5981] [^1] | [⚒️][5979] [^1] | [⚒️][5982] [^1] | [⚒️][5979] [^1] | [⚒️][5979] [^1] | [⚒️][5977] [^1] | -| RSA | ⚒️ | | ⚒️ | ⚒️ | ⚒️ | | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | -| SHA | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | [⚒️][5973] [^1] | - -### Low power - -| Driver | ESP32 | ESP32-C2 | ESP32-C3 | ESP32-C5 | ESP32-C6 | ESP32-C61 | ESP32-H2 | ESP32-P4 | ESP32-S2 | ESP32-S3 | ESP32-S31 | -| ---------------- |:-----:|:--------:|:--------:|:--------:|:--------:|:---------:|:--------:|:--------:|:--------:|:--------:|:---------:| -| Light/deep sleep | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ❌ | -| ULP (FSM) | [❌][376] [^1] | | | | | | | | [❌][376] [^1] | [❌][376] [^1] | | -| ULP (RISC-V) | | | | [❌][5160] [^1] | ⚒️ | | | ❌ | ⚒️ | ⚒️ | ❌ | - -### System - -| Driver | ESP32 | ESP32-C2 | ESP32-C3 | ESP32-C5 | ESP32-C6 | ESP32-C61 | ESP32-H2 | ESP32-P4 | ESP32-S2 | ESP32-S3 | ESP32-S31 | -| ------------ |:-----:|:--------:|:--------:|:--------:|:--------:|:---------:|:--------:|:--------:|:--------:|:--------:|:---------:| -| ASSIST_DEBUG | | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ❌ | | ⚒️ | ❌ | -| DMA | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | -| ETM | | | | [❌][5167] [^1] | ⚒️ | [❌][5419] [^1] | ⚒️ | ❌ | | | ❌ | -| Interrupts | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | ⚒️ | -| PSRAM | ⚒️ | | | ⚒️ | | ⚒️ | | ⚒️ | ⚒️ | ⚒️ | ⚒️ | + * ⚠️: Planned overhaul (unstable, expect major breaking changes) + * 🚧: Unstable (requires the `unstable` feature) + * ✔️: Stable + +### [GPIO](https://docs.espressif.com/projects/rust/esp-hal/main/index.html#gpio) + +| Driver | Status | +| -------------- |:------:| +| GPIO | ✔️ | +| Dedicated GPIO | 🚧 | +| IOMUX | 🚧 | +| LP IO | 🚧 | + +### [Serial interfaces](https://docs.espressif.com/projects/rust/esp-hal/main/index.html#serial-interfaces) + +| Driver | Status | +| --------------- |:------:| +| UART | ✔️ | +| LP UART | 🚧 | +| UHCI | 🚧 | +| I2C master | ✔️ | +| LP I2C master | 🚧 | +| I2C slave | 🚧 | +| I3C master | ❌ | +| I3C slave | ❌ | +| SPI master | ✔️ | +| SPI slave | 🚧 | +| LP SPI master | ❌ | +| LP SPI slave | ❌ | +| I2S | 🚧 | +| LP I2S | ❌ | +| PARL_IO | 🚧 | +| RMT | 🚧 | +| SDMMC/SDIO host | 🚧 | +| SDIO slave | ❌ | +| TWAI | 🚧 | +| CANFD | 🚧 | +| USB OTG FS | 🚧 | +| USB OTG HS | 🚧 | +| USB Serial/JTAG | 🚧 | + +### [Wireless and networking](https://docs.espressif.com/projects/rust/esp-hal/main/index.html#wireless-and-networking) + +| Driver | Status | +| ------------- |:------:| +| Bluetooth | 🚧 | +| WIFI | 🚧 | +| IEEE 802.15.4 | 🚧 | +| Ethernet | 🚧 | + +### [Display and camera](https://docs.espressif.com/projects/rust/esp-hal/main/index.html#display-and-camera) + +| Driver | Status | +| ----------------- |:------:| +| Camera interface | 🚧 | +| MIPI-CSI | ❌ | +| MIPI-DSI | 🚧 | +| RGB display | 🚧 | +| SPI LCD interface | [❌][5374] [^1] | + +### [Signal processing](https://docs.espressif.com/projects/rust/esp-hal/main/index.html#signal-processing) + +| Driver | Status | +| ---------------------------- |:------:| +| Bit Scrambler | ❌ | +| Image Signal Processor | ❌ | +| Pixel Processing Accelerator | ❌ | +| JPEG Codec | ❌ | +| H.264 encoder | ❌ | +| Audio Sample Rate Converter | ❌ | +| CORDIC accelerator | ❌ | +| Voice Activity Detection | ❌ | + +### [Analog](https://docs.espressif.com/projects/rust/esp-hal/main/index.html#analog) + +| Driver | Status | +| ------------------------- |:------:| +| ADC | 🚧 | +| Analog Voltage Comparator | ❌ | +| DAC | 🚧 | +| Temperature sensor | 🚧 | +| Touch | 🚧 | + +### [Timers and motor control](https://docs.espressif.com/projects/rust/esp-hal/main/index.html#timers-and-motor-control) + +| Driver | Status | +| --------------- |:------:| +| LEDC | [⚠️][2286] [^1] | +| MCPWM | 🚧 | +| PCNT | 🚧 | +| RTC Timekeeping | 🚧 | +| SDM | 🚧 | +| SYSTIMER | 🚧 | +| Timers | 🚧 | + +### [Cryptography and security](https://docs.espressif.com/projects/rust/esp-hal/main/index.html#cryptography-and-security) + +| Driver | Status | +| ----------------------- |:------:| +| AES | 🚧 | +| RSA Digital Signature | ❌ | +| ECDSA Digital Signature | ❌ | +| ECC | 🚧 | +| HMAC | 🚧 | +| Key Manager | ❌ | +| RNG | ✔️ | +| RSA | 🚧 | +| SHA | 🚧 | + +### [Low power](https://docs.espressif.com/projects/rust/esp-hal/main/index.html#low-power) + +| Driver | Status | +| ---------------- |:------:| +| Light/deep sleep | 🚧 | +| ULP (FSM) | [❌][376] [^1] | +| ULP (RISC-V) | 🚧 | + +### [System](https://docs.espressif.com/projects/rust/esp-hal/main/index.html#system) + +| Driver | Status | +| ------------ |:------:| +| ASSIST_DEBUG | 🚧 | +| DMA | 🚧 | +| ETM | 🚧 | +| Interrupts | 🚧 | +| Flash | 🚧 | +| PSRAM | 🚧 | [^1]: This cell is clickable and will open the peripheral's issue on GitHub [376]: https://github.com/esp-rs/esp-hal/issues/376 -[884]: https://github.com/esp-rs/esp-hal/issues/884 -[1905]: https://github.com/esp-rs/esp-hal/issues/1905 -[1909]: https://github.com/esp-rs/esp-hal/issues/1909 -[5153]: https://github.com/esp-rs/esp-hal/issues/5153 -[5154]: https://github.com/esp-rs/esp-hal/issues/5154 -[5155]: https://github.com/esp-rs/esp-hal/issues/5155 -[5160]: https://github.com/esp-rs/esp-hal/issues/5160 -[5161]: https://github.com/esp-rs/esp-hal/issues/5161 -[5163]: https://github.com/esp-rs/esp-hal/issues/5163 -[5164]: https://github.com/esp-rs/esp-hal/issues/5164 -[5166]: https://github.com/esp-rs/esp-hal/issues/5166 -[5167]: https://github.com/esp-rs/esp-hal/issues/5167 -[5168]: https://github.com/esp-rs/esp-hal/issues/5168 -[5169]: https://github.com/esp-rs/esp-hal/issues/5169 -[5170]: https://github.com/esp-rs/esp-hal/issues/5170 -[5171]: https://github.com/esp-rs/esp-hal/issues/5171 +[2286]: https://github.com/esp-rs/esp-hal/issues/2286 [5374]: https://github.com/esp-rs/esp-hal/issues/5374 -[5417]: https://github.com/esp-rs/esp-hal/issues/5417 -[5418]: https://github.com/esp-rs/esp-hal/issues/5418 -[5419]: https://github.com/esp-rs/esp-hal/issues/5419 -[5421]: https://github.com/esp-rs/esp-hal/issues/5421 -[5423]: https://github.com/esp-rs/esp-hal/issues/5423 -[5444]: https://github.com/esp-rs/esp-hal/issues/5444 -[5972]: https://github.com/esp-rs/esp-hal/issues/5972 -[5973]: https://github.com/esp-rs/esp-hal/issues/5973 -[5977]: https://github.com/esp-rs/esp-hal/issues/5977 -[5979]: https://github.com/esp-rs/esp-hal/issues/5979 -[5980]: https://github.com/esp-rs/esp-hal/issues/5980 -[5981]: https://github.com/esp-rs/esp-hal/issues/5981 -[5982]: https://github.com/esp-rs/esp-hal/issues/5982 -[6138]: https://github.com/esp-rs/esp-hal/issues/6138 ## `unstable` feature diff --git a/esp-hal/build.rs b/esp-hal/build.rs index ed354f58342..9e2aa8ab907 100644 --- a/esp-hal/build.rs +++ b/esp-hal/build.rs @@ -43,6 +43,10 @@ fn try_main() -> Result<(), Box> { // by metadata for single-I2C chips (e.g. ESP32-C3). Register it here to avoid unexpected_cfgs // warnings on those targets. println!("cargo:rustc-check-cfg=cfg(i2c_slave_i2c1)"); + // HIL rustflags for exercising the ADC self-calibration fallback on boards with eFuse data. + println!("cargo:rustc-check-cfg=cfg(__test_adc_self_cal)"); + // HIL rustflags for encrypted-write tests that run without burned eFuses. + println!("cargo:rustc-check-cfg=cfg(__test_flash)"); if let Ok(level) = std::env::var("OPT_LEVEL") && (level == "0" || level == "1") { diff --git a/esp-hal/esp_config.yml b/esp-hal/esp_config.yml index e679dd11df0..a425eafda7b 100644 --- a/esp-hal/esp_config.yml +++ b/esp-hal/esp_config.yml @@ -235,14 +235,11 @@ options: When disabled (default), XTAL32K stays off so those pins can be used as hi-Z GPIO." default: - value: false - active: "soc_has_xtal32k_pads" + active: "soc_has_clock_node_xtal32k_clk" - name: enable-pmp description: "Protects additional memory regions via Physical Memory Protection (PMP). (Only RISC-V other than ESP32-C2/C3)" default: - # TODO - investigate why it's not working correctly - - value: false - if: "esp32s31" - value: true active: "riscv && !esp32c2 && !esp32c3" diff --git a/esp-hal/ld/esp32h4/esp32h4.x b/esp-hal/ld/esp32h4/esp32h4.x new file mode 100644 index 00000000000..e84e6826655 --- /dev/null +++ b/esp-hal/ld/esp32h4/esp32h4.x @@ -0,0 +1,44 @@ +PROVIDE(_max_hart_id = 1); + +/* The ESP32-C2 and ESP32-C3 have interrupt IDs 1-31, while the ESP32-H4 has + IDs 0-31 (CLIC), so we must define the handler for the one additional + interrupt ID: */ +PROVIDE(interrupt0 = DefaultHandler); + +/* # Multi-processing hook function + fn _mp_hook() -> bool; + This function is called from all the harts and must return true only for one hart, + which will perform memory initialization. For other harts it must return false + and implement wake-up in platform-dependent way (e.g. after waiting for a user interrupt). +*/ +PROVIDE(_mp_hook = default_mp_hook); + +SECTIONS { + /* Shared sections - ordering matters */ + INCLUDE "rwtext.x" + INCLUDE "rwdata.x" + /* End of Shared sections */ +} + +SECTIONS { + /** + * Bootloader really wants to have separate segments for ROTEXT and RODATA + * Thus, we need to force a gap here. + */ + .text_gap (NOLOAD): { + . = . + 8; + . = ALIGN(4) + 0x20; + } > ROM +} +INSERT BEFORE .text; + +/* Shared sections #2 - ordering matters */ +INCLUDE "rodata.x" +INCLUDE "text.x" +INCLUDE "stack.x" +INCLUDE "dram2.x" +INCLUDE "metadata.x" +INCLUDE "eh_frame.x" +/* End of Shared sections #2 */ + +_dram_data_start = ORIGIN(RAM) + SIZEOF(.trap) + SIZEOF(.rwtext); diff --git a/esp-hal/ld/esp32h4/linkall.x b/esp-hal/ld/esp32h4/linkall.x new file mode 100644 index 00000000000..5c5dfa1034b --- /dev/null +++ b/esp-hal/ld/esp32h4/linkall.x @@ -0,0 +1,19 @@ +INCLUDE "memory.x" + +/* esp-hal region aliases */ +REGION_ALIAS("ROTEXT", ROM); +REGION_ALIAS("RODATA", ROM); + +REGION_ALIAS("RWTEXT", RAM); +REGION_ALIAS("RWDATA", RAM); + +/* riscv-rt v0.16+ region aliases (required by upstream riscv-rt link.x) */ +REGION_ALIAS("REGION_TEXT", ROM); +REGION_ALIAS("REGION_RODATA", ROM); +REGION_ALIAS("REGION_DATA", RAM); +REGION_ALIAS("REGION_BSS", RAM); +REGION_ALIAS("REGION_HEAP", RAM); +REGION_ALIAS("REGION_STACK", RAM); + +INCLUDE "esp32h4.x" +INCLUDE "hal-defaults.x" diff --git a/esp-hal/ld/esp32h4/memory.x b/esp-hal/ld/esp32h4/memory.x new file mode 100644 index 00000000000..42a85b1553d --- /dev/null +++ b/esp-hal/ld/esp32h4/memory.x @@ -0,0 +1,40 @@ +MEMORY +{ + /* MEMORY_MAP = [ + [0x00000000, 0x00010000, "PADDING"], + [0x42000000, 0x44000000, "DROM"], + [0x40810000, 0x40860000, "DRAM"], + [0x40810000, 0x40860000, "BYTE_ACCESSIBLE"], + [0x40000000, 0x40050000, "DROM_MASK"], + [0x40000000, 0x40050000, "IROM_MASK"], + [0x42000000, 0x44000000, "IROM"], + [0x40810000, 0x40860000, "IRAM"], + [0x40860000, 0x40868000, "ICACHE1"], + [0x600FE000, 0x60100000, "MEM_INTERNAL2"], + ] */ + + /* 320K of on soc RAM, shared instruction and data memory. It starts at + SOC_IRAM_LOW, see esp-idf components/soc/esp32h4/include/soc/soc.h + 0x4084f350 = 2nd stage bootloader iram_loader_seg start address + see esp-idf components/esp_system/ld/esp32h4/memory.ld.in + */ + RAM : ORIGIN = 0x40810000, LENGTH = 0x3F350 + + /* memory available after the 2nd stage bootloader is finished. + Upper bound is SOC_ROM_STACK_START = 0x4085d350 (pro cpu ROM stack). + see esp-idf components/soc/esp32h4/include/soc/soc.h + */ + dram2_seg ( RW ) : ORIGIN = ORIGIN(RAM) + LENGTH(RAM), len = 0x4085d350 - (ORIGIN(RAM) + LENGTH(RAM)) + + /* External flash + + The 0x20 offset is a convenience for the app binary image generation. + Flash cache has 64KB pages. The .bin file which is flashed to the chip + has a 0x18 byte file header, and each segment has a 0x08 byte segment + header. Setting this offset makes it simple to meet the flash cache MMU's + constraint that (paddr % 64KB == vaddr % 64KB).) + */ + + /* Instruction and Data ROM */ + ROM : ORIGIN = 0x42000000 + 0x20, LENGTH = 0x400000 - 0x20 +} diff --git a/esp-hal/ld/esp32p4/esp32p4.x b/esp-hal/ld/esp32p4/esp32p4.x index 789a032e0d1..0eca4ddd5bd 100644 --- a/esp-hal/ld/esp32p4/esp32p4.x +++ b/esp-hal/ld/esp32p4/esp32p4.x @@ -36,6 +36,7 @@ INCLUDE "rodata.x" INCLUDE "text.x" INCLUDE "rtc_fast.x" INCLUDE "stack.x" +INCLUDE "dram2.x" INCLUDE "metadata.x" INCLUDE "eh_frame.x" /* End of Shared sections */ diff --git a/esp-hal/ld/esp32p4/memory.x b/esp-hal/ld/esp32p4/memory.x index ee756561db0..e33a759212d 100644 --- a/esp-hal/ld/esp32p4/memory.x +++ b/esp-hal/ld/esp32p4/memory.x @@ -26,7 +26,13 @@ RESERVED_L2_CACHE = 0; MEMORY { - RAM : ORIGIN = 0x4FF00000 + RESERVED_L2_CACHE, LENGTH = 0x4FFAE000 - RESERVED_L2_CACHE - 0x4FF00000 + RAM : ORIGIN = 0x4FF00000 + RESERVED_L2_CACHE, LENGTH = 0xADFC0 - RESERVED_L2_CACHE + + /* Memory available after the 2nd stage bootloader finishes. + Upper bound is __stack_app = 0x4ffbefc0. + Source: esp-idf C:\_Espressif\esp-idf\components\bootloader\subproject\main\ld\esp32p4\bootloader.memory.ld.in + */ + dram2_seg ( RW ): ORIGIN = ORIGIN(RAM) + LENGTH(RAM), len = 0x4ffbefc0 - (ORIGIN(RAM) + LENGTH(RAM)) /* External flash (XIP via cache); +0x20 skips the IDF app image header. */ ROM : ORIGIN = 0x40000000 + 0x20, LENGTH = 0x400000 - 0x20 diff --git a/esp-hal/ld/sections/dram2.x b/esp-hal/ld/sections/dram2.x index 1289f781fe9..63778ec69bc 100644 --- a/esp-hal/ld/sections/dram2.x +++ b/esp-hal/ld/sections/dram2.x @@ -1,5 +1,11 @@ /* an uninitialized section of RAM otherwise not useable */ SECTIONS { + .dram2_uninit.bss (NOLOAD) : ALIGN(4) { + _dram2_uninit_bss_start = ABSOLUTE(.); + *(.dram2_uninit.bss) + _dram2_uninit_bss_end = ABSOLUTE(.); + } > dram2_seg + .dram2_uninit (NOLOAD) : ALIGN(4) { *(.dram2_uninit) } > dram2_seg diff --git a/esp-hal/ld/sections/rtc_fast.x b/esp-hal/ld/sections/rtc_fast.x index 16d40e355c6..b532add3924 100644 --- a/esp-hal/ld/sections/rtc_fast.x +++ b/esp-hal/ld/sections/rtc_fast.x @@ -6,7 +6,7 @@ SECTIONS { /* Keep each object's literal pool adjacent to its code (see comment in `text.x`). */ *(.rtc_fast.literal .rtc_fast.text .rtc_fast.literal.* .rtc_fast.text.*) . = ALIGN(4); - } > RTC_FAST_RWTEXT AT > RODATA + } > RTC_FAST_RWTEXT .rtc_fast.data : { @@ -15,10 +15,7 @@ SECTIONS { *(.rtc_fast.data .rtc_fast.data.*) _rtc_fast_data_end = ABSOLUTE(.); . = ALIGN(4); - } > RTC_FAST_RWDATA AT > RODATA - - /* LMA of .data */ - _rtc_fast_sidata = LOADADDR(.rtc_fast.data); + } > RTC_FAST_RWDATA .rtc_fast.bss (NOLOAD) : { diff --git a/esp-hal/ld/sections/rtc_slow.x b/esp-hal/ld/sections/rtc_slow.x index d2f68fce69a..0de97dc6596 100644 --- a/esp-hal/ld/sections/rtc_slow.x +++ b/esp-hal/ld/sections/rtc_slow.x @@ -6,7 +6,7 @@ SECTIONS { /* Keep each object's literal pool adjacent to its code (see comment in `text.x`). */ *(.rtc_slow.literal .rtc_slow.text .rtc_slow.literal.* .rtc_slow.text.*) . = ALIGN(4); - } > rtc_slow_seg AT > RODATA + } > rtc_slow_seg .rtc_slow.data : { @@ -15,10 +15,7 @@ SECTIONS { *(.rtc_slow.data .rtc_slow.data.*) _rtc_slow_data_end = ABSOLUTE(.); . = ALIGN(4); - } > rtc_slow_seg AT > RODATA - - /* LMA of .data */ - _rtc_slow_sidata = LOADADDR(.rtc_slow.data); + } > rtc_slow_seg .rtc_slow.bss (NOLOAD) : { diff --git a/esp-hal/src/aes/cipher_modes.rs b/esp-hal/src/aes/cipher_modes.rs index a56464f57e5..1fa1f8548ae 100644 --- a/esp-hal/src/aes/cipher_modes.rs +++ b/esp-hal/src/aes/cipher_modes.rs @@ -200,7 +200,7 @@ impl Ofb { /// Counter mode. #[derive(Clone)] pub struct Ctr { - /// The nonce + counter. Note that the security of this relies on the nonce being random. + /// The nonce and counter. The security of this mode relies on the nonce being random. pub(super) nonce: [u8; BLOCK_SIZE], /// The key produced by the block cipher. pub(super) buffer: [u8; BLOCK_SIZE], diff --git a/esp-hal/src/aes/mod.rs b/esp-hal/src/aes/mod.rs index 67c1886b4a7..0ee51be3212 100644 --- a/esp-hal/src/aes/mod.rs +++ b/esp-hal/src/aes/mod.rs @@ -50,7 +50,7 @@ use crate::{ aes::cipher_modes::{CryptoBuffers, UnsafeCryptoBuffers}, pac, peripherals::AES, - system::GenericPeripheralGuard, + system::{CryptoClockGuard, GenericPeripheralGuard}, }; pub mod cipher_modes; @@ -138,10 +138,10 @@ for_each_aes_key_length! { #[derive(Clone, Copy, PartialEq, Eq, Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum Operation { - /// Produce ciphertext from plaintext + /// Produces ciphertext from plaintext. Encrypt, - /// Produce plaintext from ciphertext + /// Produces plaintext from ciphertext. Decrypt, } @@ -149,15 +149,21 @@ pub enum Operation { pub struct Aes<'d> { aes: AES<'d>, _guard: GenericPeripheralGuard<{ crate::system::Peripheral::Aes as u8 }>, + _clock_guard: CryptoClockGuard, } impl<'d> Aes<'d> { - /// Constructs a new `Aes` instance. + /// Creates a new `Aes` instance. pub fn new(aes: AES<'d>) -> Self { + let clock_guard = CryptoClockGuard::new(); let guard = GenericPeripheralGuard::new(); #[cfg_attr(not(aes_supports_dma), expect(unused_mut))] - let mut this = Self { aes, _guard: guard }; + let mut this = Self { + aes, + _guard: guard, + _clock_guard: clock_guard, + }; #[cfg(aes_supports_dma)] this.write_dma(false); @@ -169,7 +175,7 @@ impl<'d> Aes<'d> { self.aes.register_block() } - /// Configures how the state matrix would be laid out + /// Configures how the state matrix would be laid out. #[cfg(aes_endianness_configurable)] pub fn write_endianness( &mut self, @@ -283,7 +289,7 @@ impl<'d> Aes<'d> { self.process(block, mode, key) } - /// Encrypts/Decrypts the given buffer based on `mode` parameter + /// Encrypts or decrypts the given buffer based on the `mode` parameter. fn process_work_item(&mut self, work_item: &mut AesOperation) { // Note that we can't just create slices out of the input and output buffers, because they // may alias (when encrypting/decrypting data in place). @@ -430,7 +436,7 @@ pub mod dma { } impl<'d> super::Aes<'d> { - /// Enable DMA for the current instance of the AES driver + /// Enables DMA for the current instance of the AES driver. pub fn with_dma(self, channel: impl AesDmaChannel<'d>) -> AesDma<'d> { let channel = Channel::new(channel.into()); channel.runtime_ensure_compatible(self.aes.dma_peripheral()); @@ -505,9 +511,9 @@ pub mod dma { }) } - /// Perform a DMA transfer. + /// Performs a DMA transfer. /// - /// This will return a [AesTransfer]. + /// Returns an [`AesTransfer`]. pub fn process( mut self, number_of_blocks: usize, @@ -604,7 +610,7 @@ pub mod dma { } impl<'d, RX: DmaRxBuffer, TX: DmaTxBuffer> AesTransfer<'d, RX, TX> { - /// Returns true when [Self::wait] will not block. + /// Returns whether [`Self::wait`] will not block. pub fn is_done(&self) -> bool { self.aes_dma.is_done() } @@ -719,7 +725,7 @@ pub mod dma { /// - When the data is not correctly aligned to the needs of the hardware (e.g. when using a /// stream cipher mode, the data length is not an integer multiple of 16 bytes). /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -780,9 +786,9 @@ pub mod dma { )] /// Creates a new DMA-enabled AES backend. /// - /// The backend needs to be [`start`][Self::start]ed before it can execute AES operations. + /// The backend must be started with [`Self::start`] before it can execute AES operations. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -814,7 +820,7 @@ pub mod dma { /// /// The driver stops operating when the returned object is dropped. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1240,13 +1246,13 @@ use crate::work_queue::{ #[derive(Clone)] #[non_exhaustive] pub enum CipherState { - /// Electronic Codebook Mode + /// Electronic Codebook Mode. Ecb(cipher_modes::Ecb), - /// Cipher Block Chaining Mode + /// Cipher Block Chaining Mode. Cbc(cipher_modes::Cbc), - /// Output Feedback Mode + /// Output Feedback Mode. Ofb(cipher_modes::Ofb), - /// Counter Mode + /// Counter Mode. Ctr(cipher_modes::Ctr), /// Cipher Feedback Mode with 8-bit shifting. Cfb8(cipher_modes::Cfb8), @@ -1378,7 +1384,7 @@ const BLOCKING_AES_VTABLE: VTable = VTable { #[procmacros::doc_replace] /// CPU-driven AES processing backend. /// -/// ## Example +/// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1420,9 +1426,9 @@ impl<'d> AesBackend<'d> { #[procmacros::doc_replace] /// Creates a new AES backend. /// - /// The backend needs to be [`start`][Self::start]ed before it can execute AES operations. + /// The backend must be started with [`Self::start`] before it can execute AES operations. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1443,7 +1449,7 @@ impl<'d> AesBackend<'d> { /// /// The driver stops operating when the returned object is dropped. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1556,11 +1562,11 @@ impl AesContext { /// /// For an example, see the documentation of [`AesBackend`]. /// - /// ## Errors + /// # Errors /// - /// - If the lengths of the input and output buffers don't match, an error is returned. - /// - The ECB and OFB cipher modes require the data length to be a multiple of the block size - /// (16), otherwise an error is returned. + /// - [`Error`] when the lengths of the input and output buffers do not match. + /// - [`Error`] when ECB or OFB cipher modes are used and the data length is not a multiple of + /// the block size (16). pub fn process<'t>( &'t mut self, input: &'t [u8], @@ -1579,13 +1585,15 @@ impl AesContext { #[procmacros::doc_replace] /// Starts transforming the buffer. /// - /// The processed data will be written back to the `buffer`. + /// The processed data is written back to the `buffer`. /// /// The returned Handle must be polled until it returns `true`. Dropping the handle /// before the operation finishes will cancel the operation. /// - /// This function operates similar to [`AesContext::process`], but it overwrites the data buffer - /// with the result of the transformation. + /// Operates similarly to [`AesContext::process`], but overwrites the data buffer with the + /// result of the transformation. + /// + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1618,10 +1626,10 @@ impl AesContext { /// # {after_snippet} /// ``` /// - /// ## Errors + /// # Errors /// - /// The ECB and OFB cipher modes require the data length to be a multiple of the block size - /// (16), otherwise an error is returned. + /// [`Error`] when ECB or OFB cipher modes are used and the data length is not a multiple of the + /// block size (16). pub fn process_in_place<'t>( &'t mut self, buffer: &'t mut [u8], @@ -1649,7 +1657,7 @@ pub struct AesHandle<'t>(Handle<'t, AesOperation>); impl AesHandle<'_> { /// Polls the status of the work item. /// - /// This function returns `true` if the item has been processed. + /// Returns whether the item has been processed. #[inline] pub fn poll(&mut self) -> bool { self.0.poll() @@ -1657,7 +1665,7 @@ impl AesHandle<'_> { /// Polls the work item to completion, by busy-looping. /// - /// This function returns immediately if `poll` returns `true`. + /// Returns immediately if `poll` returns `true`. #[inline] pub fn wait_blocking(self) -> Status { self.0.wait_blocking() diff --git a/esp-hal/src/analog/adc/calibration/basic.rs b/esp-hal/src/analog/adc/calibration/basic.rs index 28e7f4527ed..647481a753c 100644 --- a/esp-hal/src/analog/adc/calibration/basic.rs +++ b/esp-hal/src/analog/adc/calibration/basic.rs @@ -1,30 +1,19 @@ use core::marker::PhantomData; -use crate::analog::adc::{ - AdcCalEfuse, - AdcCalScheme, - AdcCalSource, - AdcConfig, - Attenuation, - CalibrationAccess, -}; +use crate::analog::adc::{AdcCalEfuse, AdcCalScheme, Attenuation, CalibrationAccess, Error}; -/// Basic ADC calibration scheme +/// Basic ADC calibration scheme. /// -/// Basic calibration sets the initial ADC bias value so that a zero voltage -/// gives a reading of zero. The correct bias value is usually stored in efuse, -/// but can also be measured at runtime by connecting the ADC input to ground -/// internally. +/// The zero-voltage bias (`Dout0`) is applied by the driver for every +/// conversion, whether or not a calibration scheme is in use, because the +/// hardware subtracts it before truncating the result. /// -/// Failing to apply basic calibration can substantially reduce the ADC's output -/// range because bias correction is done *before* the ADC's output is truncated -/// to 12 bits. +/// What is left for this scheme is the per-channel correction to that bias, +/// which only some chips characterize in eFuse. On the others this scheme +/// returns readings unchanged. #[derive(Clone, Copy)] pub struct AdcCalBasic { - /// Calibration value to set to ADC unit - cal_val: u16, - - #[cfg(any(esp32c5, esp32c6, esp32c61, esp32h2))] + #[cfg(adc_channel_compensation)] chan_compens: i32, _phantom: PhantomData, @@ -36,34 +25,22 @@ impl AdcCalScheme for AdcCalBasic where ADCX: AdcCalEfuse + CalibrationAccess, { - fn new_cal(atten: Attenuation) -> Self { + fn new_cal(atten: Attenuation) -> Result { Self::new_cal_with_channel(atten, 0) } - fn new_cal_with_channel(atten: Attenuation, _channel: u8) -> Self { - // Try to get init code (Dout0) from efuse - // Dout0 means mean raw ADC value when zero voltage applied to input. - let cal_val = ADCX::init_code(atten).unwrap_or_else(|| { - // As a fallback try to calibrate via connecting input to ground internally. - AdcConfig::::adc_calibrate(atten, AdcCalSource::Gnd) - }); - - #[cfg(any(esp32c5, esp32c6, esp32c61, esp32h2))] - let chan_compens = ADCX::cal_chan_compens(atten, _channel).unwrap_or(0); - - Self { - cal_val, - #[cfg(any(esp32c5, esp32c6, esp32c61, esp32h2))] - chan_compens, + fn new_cal_with_channel(_atten: Attenuation, _channel: u8) -> Result { + Ok(Self { + // A missing per-channel offset means the chip did not characterize this + // channel, so no correction applies. `channel` always comes from a valid + // ADC pin, and unburnt eFuses likewise mean zero correction. + #[cfg(adc_channel_compensation)] + chan_compens: ADCX::cal_chan_compens(_atten, _channel).unwrap_or(0), _phantom: PhantomData, - } - } - - fn adc_cal(&self) -> u16 { - self.cal_val + }) } - #[cfg(any(esp32c5, esp32c6, esp32c61, esp32h2))] + #[cfg(adc_channel_compensation)] fn adc_val(&self, val: u16) -> u16 { (val as i32 - self.chan_compens).clamp(0, ADCX::ADC_VAL_MASK as i32) as u16 } diff --git a/esp-hal/src/analog/adc/calibration/curve.rs b/esp-hal/src/analog/adc/calibration/curve.rs index 33644cb95f3..2071c179478 100644 --- a/esp-hal/src/analog/adc/calibration/curve.rs +++ b/esp-hal/src/analog/adc/calibration/curve.rs @@ -7,6 +7,7 @@ use crate::analog::adc::{ AdcHasLineCal, Attenuation, CalibrationAccess, + Error, }; const COEFF_MUL: i64 = 1 << 52; @@ -15,32 +16,28 @@ const COEFF_MUL: i64 = 1 << 52; /// the type, this is a fixed-point number with 52 fractional bits. type CurveCoeff = i64; -/// Polynomial coefficients for specified attenuation. +/// Polynomial coefficients for a specified attenuation. pub struct CurveCoeffs { - /// Attenuation + /// Attenuation. atten: Attenuation, - /// Polynomial coefficients + /// Polynomial coefficients. coeff: &'static [CurveCoeff], } type CurvesCoeffs = &'static [CurveCoeffs]; -/// Marker trait for ADC which support curve fitting +/// Marker trait for ADCs that support curve fitting. /// /// See also [`AdcCalCurve`]. pub trait AdcHasCurveCal { /// Coefficients for calculating the reading voltage error. /// - /// A sets of coefficients for each attenuation. - const CURVES_COEFFS: CurvesCoeffs; - - /// Coefficients for the eFuse calibration version on this chip. - fn curves_coeffs() -> CurvesCoeffs { - Self::CURVES_COEFFS - } + /// A set of coefficients for each attenuation, selected for the eFuse + /// calibration version on this chip. + fn curves_coeffs() -> CurvesCoeffs; } -/// Curve fitting ADC calibration scheme +/// Curve fitting ADC calibration scheme. /// /// This scheme implements polynomial error correction using predefined /// coefficient sets for each attenuation. It returns readings in mV. @@ -71,48 +68,49 @@ impl AdcCalScheme for AdcCalCurve where ADCX: AdcCalEfuse + AdcHasLineCal + AdcHasCurveCal + CalibrationAccess, { - fn new_cal(atten: Attenuation) -> Self { + fn new_cal(atten: Attenuation) -> Result { Self::new_cal_with_channel(atten, 0) } - fn new_cal_with_channel(atten: Attenuation, channel: u8) -> Self { - let line = AdcCalLine::::new_cal_with_channel(atten, channel); + fn new_cal_with_channel(atten: Attenuation, channel: u8) -> Result { + let line = AdcCalLine::::new_cal_with_channel(atten, channel)?; - let coeff = ADCX::curves_coeffs() + // Every shipped coefficient table covers all four attenuations; a miss + // means the user requested an attenuation the chip never characterized. + let Some(coeff) = ADCX::curves_coeffs() .iter() .find(|item| item.atten == atten) - .expect("No curve coefficients for given attenuation") - .coeff; + else { + return Err(Error::UnsupportedAttenuation(atten)); + }; - Self { + Ok(Self { line, - coeff, + coeff: coeff.coeff, _phantom: PhantomData, - } - } - - fn adc_cal(&self) -> u16 { - self.line.adc_cal() + }) } fn adc_val(&self, val: u16) -> u16 { let val = self.line.adc_val(val); - // Calculate polynomial error using Horner's method to prevent overflow. - // Horner's evaluates: err = coeff[0] + val*(coeff[1] + val*(coeff[2] + ...)) - // This avoids computing val^n which causes overflow when multiplied by coefficients. + // Truncate each polynomial term before summing to match integer division + // in the curve-fitting reference model. + // + // The products need i128: the highest-order term (ESP32-S3, x^4) times its + // coefficient does not fit an i64. let err = if val == 0 || self.coeff.is_empty() { 0 } else { - let val_i64 = val as i64; - let mut poly = 0i64; + let mut var: i128 = 1; // val^i + let mut err: i128 = 0; - // Iterate coefficients in reverse order for Horner's method - for &coeff in self.coeff.iter().rev() { - poly = poly * val_i64 + coeff; + for &coeff in self.coeff { + err += var * i128::from(coeff) / i128::from(COEFF_MUL); + var *= i128::from(val); } - (poly / COEFF_MUL) as i32 + err as i32 }; (val as i32 - err) as u16 @@ -135,30 +133,26 @@ macro_rules! coeff_tables { }; } -#[cfg(any(esp32c3, esp32c5, esp32c6, esp32c61, esp32h2, esp32p4, esp32s3))] +#[cfg(adc_curve_calibration)] mod impls { use super::*; impl AdcHasCurveCal for crate::peripherals::ADC1<'_> { - const CURVES_COEFFS: CurvesCoeffs = CURVES_COEFFS1; - - #[cfg(esp32c6)] fn curves_coeffs() -> CurvesCoeffs { + #[cfg(esp32c6)] if crate::efuse::rtc_calib_version() == 2 { - CURVES_COEFFS1_V2 - } else { - CURVES_COEFFS1 + return CURVES_COEFFS1_V2; } + + CURVES_COEFFS1 } } - #[cfg(any(esp32c3, esp32p4, esp32s3))] + #[cfg(adc_adc2)] impl AdcHasCurveCal for crate::peripherals::ADC2<'_> { - const CURVES_COEFFS: CurvesCoeffs = cfg_select! { - esp32c3 => CURVES_COEFFS1, - esp32p4 => CURVES_COEFFS2, - esp32s3 => CURVES_COEFFS2, - }; + fn curves_coeffs() -> CurvesCoeffs { + CURVES_COEFFS2 + } } coeff_tables! { @@ -218,7 +212,7 @@ mod impls { #[cfg(esp32c6)] CURVES_COEFFS1 [ _0dB => [ - -0.0487166399931449, + -0.487166399931449, 0.0006436483033201, 0.0000030410131806, ], @@ -247,7 +241,7 @@ mod impls { 0.0015630376830615, ], _2p5dB => [ - -0.1090569589734153, + -1.090569589734153, 0.0013859487941542, ], _6dB => [ @@ -390,7 +384,7 @@ mod impls { _6dB => [ -0.9452499397020617, -0.0200996773954387, - 0.00000259011467956, + 0.0000259011467956, ], _11dB => [ 1.2247719764336924, diff --git a/esp-hal/src/analog/adc/calibration/line/esp32.rs b/esp-hal/src/analog/adc/calibration/line/esp32.rs index 408378576a2..62023f06e44 100644 --- a/esp-hal/src/analog/adc/calibration/line/esp32.rs +++ b/esp-hal/src/analog/adc/calibration/line/esp32.rs @@ -2,7 +2,7 @@ use core::marker::PhantomData; use super::AdcHasLineCal; use crate::{ - analog::adc::{AdcCalScheme, Attenuation}, + analog::adc::{AdcCalScheme, Attenuation, Error}, efuse, }; @@ -193,10 +193,12 @@ impl AdcCalScheme for AdcCalLine where ADCX: AdcHasLineCal, { - fn new_cal(atten: Attenuation) -> Self { + fn new_cal(atten: Attenuation) -> Result { let unit = ADCX::UNIT; let atten_idx = atten as usize; + // Unburnt Vref defaults to 1100 mV per the reference model; the scheme + // always produces coefficients, so construction never fails. let vref = if check_efuse_vref() { read_efuse_vref() } else { @@ -211,14 +213,14 @@ where characterize_using_vref(unit, atten_idx, vref) }; - Self { + Ok(Self { coeff_a, coeff_b, vref, use_lut: atten == Attenuation::_11dB, unit, _phantom: PhantomData, - } + }) } fn adc_val(&self, val: u16) -> u16 { diff --git a/esp-hal/src/analog/adc/calibration/line/one_point.rs b/esp-hal/src/analog/adc/calibration/line/one_point.rs index c0cdcbd10ab..aa612b8661c 100644 --- a/esp-hal/src/analog/adc/calibration/line/one_point.rs +++ b/esp-hal/src/analog/adc/calibration/line/one_point.rs @@ -5,30 +5,33 @@ use crate::analog::adc::{ AdcCalBasic, AdcCalEfuse, AdcCalScheme, - AdcCalSource, - AdcConfig, Attenuation, CalibrationAccess, + Error, }; -/// We store the gain as a u32, but it's really a fixed-point number. +/// Gain is stored as a `u32`, but is really a fixed-point number. const GAIN_SCALE: u32 = 1 << 16; -/// Line fitting ADC calibration scheme +/// Line fitting ADC calibration scheme. /// /// This scheme implements gain correction based on reference points, and /// returns readings in mV. /// /// A reference point is a pair of a reference voltage and the corresponding -/// mean raw digital ADC value. Such values are usually stored in efuse bit -/// fields for each supported attenuation. -/// -/// Also it can be measured in runtime by connecting ADC to reference voltage -/// internally but this method is not so good because actual reference voltage -/// may varies in range 1.0..=1.2 V. Currently this method is used as a fallback -/// (with 1.1 V by default) when calibration data is missing. +/// mean raw digital ADC value. Those values are stored in eFuse bit fields for each supported +/// attenuation, and there is no way to establish them at runtime: the ADC can only be switched to +/// internal ground, which gives the zero-voltage offset rather than a second point to derive a +/// gain from. /// /// This scheme also includes basic calibration ([`AdcCalBasic`]). +/// +/// # Errors +/// +/// Returns [`Error::UnsupportedAttenuation`] if the attenuation has no +/// reference point on this chip, or [`Error::MissingCalibrationData`] if the +/// chip carries no line-fitting calibration data or the stored reference +/// point is zero. #[derive(Clone, Copy)] pub struct AdcCalLine { basic: AdcCalBasic, @@ -49,44 +52,42 @@ impl AdcCalScheme for AdcCalLine where ADCX: AdcCalEfuse + AdcHasLineCal + CalibrationAccess, { - fn new_cal(atten: Attenuation) -> Self { + fn new_cal(atten: Attenuation) -> Result { Self::new_cal_with_channel(atten, 0) } - fn new_cal_with_channel(atten: Attenuation, channel: u8) -> Self { - let basic = AdcCalBasic::::new_cal_with_channel(atten, channel); + fn new_cal_with_channel(atten: Attenuation, channel: u8) -> Result { + let basic = AdcCalBasic::::new_cal_with_channel(atten, channel)?; + + // Get the reference point (Dout, Vin) from efuse. Dout means mean raw ADC value when + // specified Vin applied to input. + // `cal_mv` goes first: it rejects attenuations without a reference point on the ESP32-C2. + let Some(mv) = ADCX::cal_mv(atten) else { + return Err(Error::UnsupportedAttenuation(atten)); + }; + let Some(code) = ADCX::cal_code(atten) else { + return Err(Error::MissingCalibrationData); + }; - // Try get the reference point (Dout, Vin) from efuse - // Dout means mean raw ADC value when specified Vin applied to input. - let (code, mv) = ADCX::cal_code(atten) - .map(|code| (code, ADCX::cal_mv(atten))) - .unwrap_or_else(|| { - // As a fallback try to calibrate using reference voltage source. - // This method is not too good because actual reference voltage may varies - // in range 1000..=1200 mV and this value currently cannot be read from efuse. - ( - AdcConfig::::adc_calibrate(atten, AdcCalSource::Ref), - 1100, // use 1100 mV as a middle of typical reference voltage range - ) - }); + // A zero reference point would divide by zero below; it means the eFuse + // field was never burnt. + if code == 0 { + return Err(Error::MissingCalibrationData); + } // Estimate the (assumed) linear relationship between the measured raw value and // the voltage with the previously done measurement when the chip was // manufactured. // - // Note that the constant term is zero because the basic calibration takes care - // of it already. + // Note that the constant term is zero because the driver programs the + // zero-voltage bias for every conversion. let gain = mv as u32 * GAIN_SCALE / code as u32; - Self { + Ok(Self { basic, gain, _phantom: PhantomData, - } - } - - fn adc_cal(&self) -> u16 { - self.basic.adc_cal() + }) } fn adc_val(&self, val: u16) -> u16 { diff --git a/esp-hal/src/analog/adc/calibration/line/s2.rs b/esp-hal/src/analog/adc/calibration/line/s2.rs index 472669f538b..0ce232c66dd 100644 --- a/esp-hal/src/analog/adc/calibration/line/s2.rs +++ b/esp-hal/src/analog/adc/calibration/line/s2.rs @@ -1,14 +1,21 @@ use core::marker::PhantomData; use super::AdcHasLineCal; -use crate::analog::adc::{AdcCalBasic, AdcCalEfuse, AdcCalScheme, Attenuation, CalibrationAccess}; +use crate::analog::adc::{ + AdcCalBasic, + AdcCalEfuse, + AdcCalScheme, + Attenuation, + CalibrationAccess, + Error, +}; const COEFF_A_SCALING: i64 = 65536; const COEFF_B_SCALING: i64 = 1024; const V_HIGH: [i64; 4] = [600, 800, 1000, 2000]; const V_LOW: i64 = 250; -/// Line fitting ADC calibration scheme +/// Line fitting ADC calibration scheme. /// /// ESP32-S2 uses two-point characterization (eFuse calibration v1) or /// one-point characterization (v2). Readings are in mV. @@ -24,12 +31,17 @@ pub struct AdcCalLine { _phantom: PhantomData, } -fn characterize_two_point(atten: Attenuation, high: i64, low: i64) -> (u32, i32) { +fn characterize_two_point(atten: Attenuation, high: i64, low: i64) -> Result<(u32, i32), Error> { let v_high = V_HIGH[atten as usize]; - let denom = (high - low).max(1); + // Valid eFuse data always has high > low; a non-positive denominator means the table is + // corrupt, so report it instead of fabricating coefficients. + let denom = high - low; + if denom <= 0 { + return Err(Error::MissingCalibrationData); + } let coeff_a = (COEFF_A_SCALING * (v_high - V_LOW) / denom) as u32; let coeff_b = (COEFF_B_SCALING * (V_LOW * high - v_high * low) / denom) as i32; - (coeff_a, coeff_b) + Ok((coeff_a, coeff_b)) } impl crate::private::Sealed for AdcCalLine {} @@ -38,12 +50,16 @@ impl AdcCalScheme for AdcCalLine where ADCX: AdcCalEfuse + AdcHasLineCal + CalibrationAccess, { - fn new_cal(atten: Attenuation) -> Self { + fn new_cal(atten: Attenuation) -> Result { Self::new_cal_with_channel(atten, 0) } - fn new_cal_with_channel(atten: Attenuation, channel: u8) -> Self { - let basic = AdcCalBasic::::new_cal_with_channel(atten, channel); + /// # Errors + /// + /// Returns [`Error::MissingCalibrationData`] if the chip carries no RTC + /// calibration block or the stored reference point is zero. + fn new_cal_with_channel(atten: Attenuation, channel: u8) -> Result { + let basic = AdcCalBasic::::new_cal_with_channel(atten, channel)?; let version = crate::efuse::rtc_calib_version(); let (coeff_a, coeff_b) = match version { @@ -60,42 +76,35 @@ where atten, crate::efuse::RtcCalibParam::Vhigh, ); - characterize_two_point(atten, high as i64, low as i64) + characterize_two_point(atten, high as i64, low as i64)? } 2 => { - let high = ADCX::cal_code(atten).unwrap_or(1).max(1) as i64; - let mv = ADCX::cal_mv(atten) as i64; - (((COEFF_A_SCALING * mv) / high) as u32, 0) + // A missing or zero reference point means the eFuse field was + // never burnt; fabricating a gain of `mv/1` would hide that. + let Some(code) = ADCX::cal_code(atten) else { + return Err(Error::MissingCalibrationData); + }; + if code == 0 { + return Err(Error::MissingCalibrationData); + } + let Some(mv) = ADCX::cal_mv(atten) else { + return Err(Error::MissingCalibrationData); + }; + (((COEFF_A_SCALING * mv as i64) / code as i64) as u32, 0) } _ => { - let low = crate::efuse::rtc_calib_reading_inner( - 1, - ADCX::UNIT, - atten, - crate::efuse::RtcCalibParam::Vlow, - true, - ); - let high = crate::efuse::rtc_calib_reading_inner( - 1, - ADCX::UNIT, - atten, - crate::efuse::RtcCalibParam::Vhigh, - true, - ); - characterize_two_point(atten, high as i64, low as i64) + // No RTC calibration block on this chip: report it instead of + // falling back to unburnt table defaults. + return Err(Error::MissingCalibrationData); } }; - Self { + Ok(Self { basic, coeff_a, coeff_b, _phantom: PhantomData, - } - } - - fn adc_cal(&self) -> u16 { - self.basic.adc_cal() + }) } fn adc_val(&self, val: u16) -> u16 { diff --git a/esp-hal/src/analog/adc/calibration/mod.rs b/esp-hal/src/analog/adc/calibration/mod.rs index a486d3f3cb6..d82ea3b7d6e 100644 --- a/esp-hal/src/analog/adc/calibration/mod.rs +++ b/esp-hal/src/analog/adc/calibration/mod.rs @@ -1,21 +1,13 @@ -#[cfg(any( - esp32c2, esp32c3, esp32c5, esp32c6, esp32c61, esp32h2, esp32p4, esp32s2, esp32s3 -))] +#[cfg(adc_basic_calibration)] pub use self::basic::AdcCalBasic; -#[cfg(any(esp32c3, esp32c5, esp32c6, esp32c61, esp32h2, esp32p4, esp32s3))] +#[cfg(adc_curve_calibration)] pub use self::curve::{AdcCalCurve, AdcHasCurveCal}; -#[cfg(any( - esp32, esp32c2, esp32c3, esp32c5, esp32c6, esp32c61, esp32h2, esp32p4, esp32s2, esp32s3 -))] +#[cfg(adc_line_calibration)] pub use self::line::{AdcCalLine, AdcHasLineCal}; -#[cfg(any( - esp32c2, esp32c3, esp32c5, esp32c6, esp32c61, esp32h2, esp32p4, esp32s2, esp32s3 -))] +#[cfg(adc_basic_calibration)] mod basic; -#[cfg(any(esp32c3, esp32c5, esp32c6, esp32c61, esp32h2, esp32p4, esp32s3))] +#[cfg(adc_curve_calibration)] mod curve; -#[cfg(any( - esp32, esp32c2, esp32c3, esp32c5, esp32c6, esp32c61, esp32h2, esp32p4, esp32s2, esp32s3 -))] +#[cfg(adc_line_calibration)] mod line; diff --git a/esp-hal/src/analog/adc/dig_ctrl.rs b/esp-hal/src/analog/adc/dig_ctrl.rs new file mode 100644 index 00000000000..d325ab19582 --- /dev/null +++ b/esp-hal/src/analog/adc/dig_ctrl.rs @@ -0,0 +1,738 @@ +use core::marker::PhantomData; + +cfg_select! { + any(esp32c6, esp32c61) => { + use Interrupt::APB_SARADC as InterruptSource; + } + _ => { + use Interrupt::APB_ADC as InterruptSource; + } +} + +use core::{ + pin::Pin, + task::{Context, Poll}, +}; + +use procmacros::handler; + +pub use self::calibration::*; +use super::{AdcConfig, Attenuation, Error}; +use crate::{ + Async, + Blocking, + asynch::AtomicWaker, + efuse::AdcCalibUnit, + interrupt::{InterruptConfigurable, InterruptHandler}, + peripherals::{APB_SARADC, Interrupt}, + rtc_cntl::WakeLock, + soc::regi2c, + system::{GenericPeripheralGuard, Peripheral}, +}; + +mod calibration; + +// Constants taken from: +// https://github.com/espressif/esp-idf/blob/903af13e8/components/soc/esp32c2/include/soc/regi2c_saradc.h +// https://github.com/espressif/esp-idf/blob/903af13e8/components/soc/esp32c3/include/soc/regi2c_saradc.h +// https://github.com/espressif/esp-idf/blob/903af13e8/components/soc/esp32c6/include/soc/regi2c_saradc.h +// https://github.com/espressif/esp-idf/blob/903af13e8/components/soc/esp32h2/include/soc/regi2c_saradc.h +const ADC_VAL_MASK: u16 = 0xfff; + +pub(super) const NUM_ATTENS: usize = property!("adc.channel_count"); + +impl AdcConfig +where + ADCX: RegisterAccess, +{ + /// Measures the initial code that cancels the unit's zero-voltage offset at `atten`. + pub fn adc_calibrate(atten: Attenuation) -> u16 + where + ADCX: super::CalibrationAccess, + { + // This can be called without an `Adc`, so it cannot rely on `Adc::new` having clocked + // and powered the unit. + let _guard = GenericPeripheralGuard::<{ Peripheral::ApbSarAdc as u8 }>::new(); + let _clock = FunctionClockGuard::new(); + let sar_power = SarPowerGuard::new(); + init_hardware(); + sar_power.force_on(); + + ADCX::enable_vdef(true); + + // Start sampling + ADCX::setup_calibration(atten); + + // Connect calibration source + ADCX::connect_gnd(true); + + ADCX::calibration_init(); + let cal_val = super::search_init_code::(read_cal_channel::); + ADCX::reset(); + + // Disconnect calibration source + ADCX::connect_gnd(false); + + cal_val + } +} + +// Converts the connected calibration source once. +// +// See `read_cal_channel` in +// +fn read_cal_channel() -> u16 { + // Only the done flag - `reset` would disarm the unit `setup_calibration` armed. + ADCX::clear_done(); + + ADCX::set_onetime_start(false); + crate::rom::ets_delay_us(5); + ADCX::set_onetime_start(true); + + while !ADCX::is_done() {} + settle_after_done(); + + ADCX::read_data() & ADC_VAL_MASK +} + +// Configures clocks and powers up the SAR ADC. +// +// See `adc_oneshot_hal_setup` in +// +fn init_hardware() { + // controller_clk = source / (DIV_NUM + DIV_A / DIV_B + 1) + // The ESP32-H2 divides its faster source further, landing at the same 5 MHz as the other chips. + #[cfg(esp32h2)] + const DIV: (u8, u8, u8) = (18, 5, 1); + #[cfg(not(esp32h2))] + const DIV: (u8, u8, u8) = (15, 1, 0); + + let (div_num, div_b, div_a) = DIV; + + // The ESP32-C2 and ESP32-C3 keep the divider in the ADC itself; the other chips configure + // it in PCR. See `adc_ll_digi_controller_clk_div`. + #[cfg(not(adc_pcr_clock))] + APB_SARADC::regs().clkm_conf().modify(|_, w| unsafe { + w.clkm_div_num().bits(div_num); + w.clkm_div_b().bits(div_b); + w.clkm_div_a().bits(div_a) + }); + + #[cfg(adc_pcr_clock)] + crate::peripherals::PCR::regs() + .saradc_clkm_conf() + .modify(|_, w| unsafe { + w.saradc_clkm_div_num().bits(div_num); + w.saradc_clkm_div_b().bits(div_b); + w.saradc_clkm_div_a().bits(div_a) + }); + + APB_SARADC::regs().ctrl().modify(|_, w| unsafe { + // Conversions are triggered through `onetime_start`, so the software start of the + // digital controller has to stay off - a concurrently running controller disturbs the + // sampling and biases the results low. + w.start_force().clear_bit(); + w.start().clear_bit(); + w.sar_clk_gated().set_bit(); + #[cfg(not(adc_pcr_sar_clk_div))] + w.sar_clk_div().bits(1); + w.xpd_sar_force().bits(0b11) + }); + + // The ESP32-C5, ESP32-C61, and ESP32-H2 configure the divider in PCR. + // See `adc_ll_digi_set_clk_div`. + #[cfg(adc_pcr_sar_clk_div)] + crate::peripherals::PCR::regs() + .sar_clk_div() + .modify(|_, w| unsafe { w.sar1_clk_div_num().bits(1) }); +} + +struct FunctionClockGuard; + +impl FunctionClockGuard { + fn new() -> Self { + crate::clock::ll::ClockTree::with(|clocks| { + #[cfg(soc_clock_node_adc_function_clock_is_configurable)] + crate::clock::ll::AdcInstance::ApbSaradc + .configure_function_clock(clocks, Default::default()); + crate::clock::ll::AdcInstance::ApbSaradc.request_function_clock(clocks); + }); + Self + } +} + +impl Drop for FunctionClockGuard { + fn drop(&mut self) { + crate::clock::ll::ClockTree::with(|clocks| { + crate::clock::ll::AdcInstance::ApbSaradc.release_function_clock(clocks); + }); + } +} + +/// Keeps the SAR powered while a radio is running. +/// +/// Radio initialization hands SAR power to the PHY's power detector (PWDET), which powers the SAR +/// down between its own measurements - conversions then saturate. Like ESP-IDF, the driver +/// overrides that through `PWDET_CONF` while the ADC is in use, and hands control back to the +/// power detector when the last guard drops. On the ESP32-C2 and ESP32-C3 the power detector does +/// not control the SAR, so this does nothing there. +/// +/// See `s_sar_power_acquire` in +/// +struct SarPowerGuard; + +cfg_select! { + adc_sar_power_override => { + static SAR_POWER_REFS: esp_sync::NonReentrantMutex = + esp_sync::NonReentrantMutex::new(0); + + impl SarPowerGuard { + fn new() -> Self { + SAR_POWER_REFS.with(|refs| *refs += 1); + Self + } + + /// Forces the SAR on. + /// + /// Radio initialization rewrites `PWDET_CONF`, so this has to run before every + /// conversion rather than once when the guard is created. + fn force_on(&self) { + SAR_POWER_REFS.with(|_| force_sar_power(true)); + } + } + + impl Drop for SarPowerGuard { + fn drop(&mut self) { + SAR_POWER_REFS.with(|refs| { + *refs -= 1; + if *refs == 0 { + force_sar_power(false); + } + }); + } + } + + /// Sets or releases the power detector's override of SAR power. + /// + /// `PWDET_CONF` is clocked by the modem front-end APB clock, which the radio gates while + /// its PHY is off, and writes are dropped while it is gated. The clock is enabled only + /// around the write, so the radio finds it the way it left it. Callers hold + /// `SAR_POWER_REFS`, a critical section, which keeps the radio from reconfiguring the + /// clock in between. + /// + /// See `sar_ctrl_ll_set_power_mode_from_pwdet` in + /// + fn force_sar_power(force: bool) { + // The PACs do not describe the power detector. + const PWDET_CONF: *mut u32 = cfg_select! { + esp32c61 => 0x600A_0808 as *mut u32, + _ => 0x600A_0810 as *mut u32, + }; + const SAR_POWER_FORCE: u32 = 1 << 24; + const SAR_POWER_CNTL: u32 = 1 << 23; + + let clk_conf1 = crate::peripherals::MODEM_SYSCON::regs().clk_conf1(); + let fe_apb_clock_enabled = clk_conf1.read().clk_fe_apb_en().bit(); + clk_conf1.modify(|_, w| w.clk_fe_apb_en().set_bit()); + + unsafe { + let conf = PWDET_CONF.read_volatile(); + let conf = if force { + conf | SAR_POWER_FORCE | SAR_POWER_CNTL + } else { + conf & !SAR_POWER_FORCE + }; + PWDET_CONF.write_volatile(conf); + } + + clk_conf1.modify(|_, w| w.clk_fe_apb_en().bit(fe_apb_clock_enabled)); + } + } + _ => { + impl SarPowerGuard { + fn new() -> Self { + Self + } + + fn force_on(&self) {} + } + } +} + +// Triggers a single conversion. +// +// See `adc_hal_onetime_start` in +// +fn start_onetime_sample(sar_power: &SarPowerGuard) { + sar_power.force_on(); + ADCX::set_onetime_start(true); +} + +/// Waits for the conversion result to become readable after the done flag has come up. +/// +/// The ESP32-H2 needs five SAR clock cycles here or it reports zero. `init_hardware` leaves the SAR +/// at the 5 MHz digital controller clock, which makes that one microsecond per cycle. +/// +/// See `ADC_LL_DELAY_CYCLE_AFTER_DONE_SIGNAL`, which is zero on every other chip here. +#[inline] +fn settle_after_done() { + #[cfg(esp32h2)] + crate::rom::ets_delay_us(5); +} + +#[doc(hidden)] +pub trait RegisterAccess { + /// Configures one-time sampling parameters. + fn config_onetime_sample(channel: u8, attenuation: u8); + + /// Drives the `onetime_start` trigger level. + /// + /// Callers go through [`start_onetime_sample`], which raises it once per conversion; `reset` + /// lowers it again after the read. + fn set_onetime_start(enable: bool); + + /// Returns whether sampling is done. + fn is_done() -> bool; + + /// Reads sample data. + fn read_data() -> u16; + + /// Clears the conversion-done flag. + fn clear_done(); + + /// Clears the done flag and ends the one-shot session. + fn reset(); + + /// Sets up ADC hardware for calibration. + fn calibration_init(); + + /// Sets calibration parameter to ADC hardware. + fn set_init_code(data: u16); +} + +impl RegisterAccess for crate::peripherals::ADC1<'_> { + fn config_onetime_sample(channel: u8, attenuation: u8) { + #[cfg(esp32c6)] + let was_armed = APB_SARADC::regs() + .onetime_sample() + .read() + .saradc1_onetime_sample() + .bit(); + + APB_SARADC::regs().onetime_sample().modify(|_, w| unsafe { + // Disarm ADC2 before configuring ADC1. + // See `adc_oneshot_ll_disable_all_unit`. + w.saradc2_onetime_sample().clear_bit(); + w.saradc1_onetime_sample().set_bit(); + w.onetime_channel().bits(channel); + w.onetime_atten().bits(attenuation) + }); + + // The ESP32-C6 channel selection needs 50 µs to settle after arming ADC1, which is why + // `reset` leaves it armed there. See `adc_oneshot_ll_enable`. + #[cfg(esp32c6)] + if !was_armed { + crate::rom::ets_delay_us(50); + } + } + + fn set_onetime_start(enable: bool) { + APB_SARADC::regs() + .onetime_sample() + .modify(|_, w| w.onetime_start().bit(enable)); + } + + fn is_done() -> bool { + APB_SARADC::regs().int_raw().read().adc1_done().bit() + } + + fn read_data() -> u16 { + APB_SARADC::regs() + .sar1data_status() + .read() + .saradc1_data() + .bits() as u16 + & 0xfff + } + + fn clear_done() { + APB_SARADC::regs() + .int_clr() + .write(|w| w.adc1_done().clear_bit_by_one()); + } + + fn reset() { + Self::clear_done(); + + // Disarm both units along with the trigger - except on the ESP32-C6, which keeps + // ADC1 armed for the whole one-shot session. + // See `adc_oneshot_ll_disable_all_unit`. + APB_SARADC::regs().onetime_sample().modify(|_, w| { + #[cfg(not(esp32c6))] + { + w.saradc2_onetime_sample().clear_bit(); + w.saradc1_onetime_sample().clear_bit(); + } + w.onetime_start().clear_bit() + }); + } + + fn calibration_init() { + // e.g. + // https://github.com/espressif/esp-idf/blob/800f141f94c0f880c162de476512e183df671307/components/hal/esp32c3/include/hal/adc_ll.h#L702 + regi2c::ADC_SAR1_DREF.write_field(1); + } + + fn set_init_code(data: u16) { + let [msb, lsb] = data.to_be_bytes(); + + regi2c::ADC_SAR1_INITIAL_CODE_HIGH.write_field(msb); + regi2c::ADC_SAR1_INITIAL_CODE_LOW.write_field(lsb); + } +} + +impl super::CalibrationAccess for crate::peripherals::ADC1<'_> { + const ADC_VAL_MASK: u16 = ADC_VAL_MASK; + const SUPPORTS_SELF_CALIBRATION: bool = !cfg!(esp32c5); + + fn enable_vdef(enable: bool) { + regi2c::ADC_SAR1_DREF.write_field(enable as _); + } + + fn connect_gnd(enable: bool) { + regi2c::ADC_SAR1_ENCAL_GND.write_field(enable as _); + } + + fn setup_calibration(atten: Attenuation) { + // `adc_oneshot_ll_disable_channel` deselects every pad by writing + // `(unit << 3) | 0xf` to the channel field. The attenuation is shared by all + // channels on these chips, so programming it is enough. + Self::config_onetime_sample(0xf, atten as u8); + } +} + +/// Analog-to-Digital Converter peripheral driver. +pub struct Adc<'d, ADCX, Dm: crate::DriverMode> { + _adc: ADCX, + attenuations: [Option; NUM_ATTENS], + /// Hardware calibration code per attenuation, indexed by [`Attenuation`]. + init_codes: [u16; super::ATTENUATION_COUNT], + active_channel: Option, + _clock: FunctionClockGuard, + _guard: GenericPeripheralGuard<{ Peripheral::ApbSarAdc as u8 }>, + sar_power: SarPowerGuard, + _phantom: PhantomData<(Dm, &'d mut ())>, +} + +impl<'d, ADCX, Dm> Adc<'d, ADCX, Dm> +where + ADCX: RegisterAccess + 'd, + Dm: crate::DriverMode, +{ + // Validate the channel before modifying ADC registers. + // The calibration init code depends on the channel's attenuation. + fn start_sample(&mut self, pin: &mut super::AdcPin) -> Result<(), Error> + where + PIN: super::AdcChannel, + CS: super::AdcCalScheme, + { + let channel = pin.pin.adc_channel(); + let attenuation = super::channel_attenuation(&self.attenuations, channel)?; + + ADCX::calibration_init(); + ADCX::set_init_code(self.init_codes[attenuation as usize]); + + ADCX::config_onetime_sample(channel, attenuation as u8); + start_onetime_sample::(&self.sar_power); + + Ok(()) + } +} + +impl<'d, ADCX> Adc<'d, ADCX, Blocking> +where + ADCX: RegisterAccess + 'd, +{ + /// Creates a new ADC instance with the given configuration. + pub fn new(adc_instance: ADCX, config: AdcConfig) -> Result + where + ADCX: super::AdcCalEfuse + super::CalibrationAccess, + { + let guard = GenericPeripheralGuard::new(); + let clock = FunctionClockGuard::new(); + let sar_power = SarPowerGuard::new(); + + init_hardware(); + + let init_codes = super::hw_init_codes::(&config.attenuations); + + // The bootloader runs conversions of its own to seed the RNG, so the done flag can + // already be set here and would make the first read return a stale result. + ADCX::reset(); + + Ok(Adc { + _adc: adc_instance, + attenuations: config.attenuations, + init_codes, + active_channel: None, + _guard: guard, + _clock: clock, + sar_power, + _phantom: PhantomData, + }) + } + + /// Reconfigures the ADC driver to operate in asynchronous mode. + pub fn into_async(mut self) -> Adc<'d, ADCX, Async> { + self.set_interrupt_handler(adc_interrupt_handler); + + // Reset interrupt flags and disable oneshot reading to normalize state before + // entering async mode, otherwise there can be '0' readings, happening initially + // using ADC2 + ADCX::reset(); + + Adc { + _adc: self._adc, + attenuations: self.attenuations, + init_codes: self.init_codes, + active_channel: self.active_channel, + _guard: self._guard, + _clock: self._clock, + sar_power: self.sar_power, + _phantom: PhantomData, + } + } + + /// Requests that the ADC begin a conversion on the specified pin. + /// + /// Takes an [`AdcPin`](super::AdcPin) reference, as it is + /// expected that the ADC will be able to sample whatever channel + /// underlies the pin. + /// + /// # Errors + /// + /// Returns [`Error::ChannelNotConfigured`] if the channel was not configured in + /// [`AdcConfig`]. + pub fn read_oneshot( + &mut self, + pin: &mut super::AdcPin, + ) -> nb::Result + where + PIN: super::AdcChannel, + CS: super::AdcCalScheme, + { + let channel = pin.pin.adc_channel(); + + if let Some(active_channel) = self.active_channel { + // There is conversion in progress: + // - if it's for a different channel try again later + // - if it's for the given channel, go ahead and check progress + if active_channel != channel { + return Err(nb::Error::WouldBlock); + } + } else { + // If no conversions are in progress, start a new one for given channel + self.start_sample(pin).map_err(nb::Error::Other)?; + self.active_channel = Some(channel); + } + + // Wait for ADC to finish conversion + let conversion_finished = ADCX::is_done(); + if !conversion_finished { + return Err(nb::Error::WouldBlock); + } + settle_after_done(); + + // Get converted value + let converted_value = ADCX::read_data(); + ADCX::reset(); + + // Postprocess converted value according to calibration scheme used for pin + let converted_value = pin.cal_scheme.adc_val(converted_value); + + // Mark that no conversions are currently in progress + self.active_channel = None; + + Ok(converted_value) + } +} + +impl crate::private::Sealed for Adc<'_, ADCX, Blocking> {} + +impl InterruptConfigurable for Adc<'_, ADCX, Blocking> { + fn set_interrupt_handler(&mut self, handler: InterruptHandler) { + for core in crate::system::Cpu::other() { + crate::interrupt::disable(core, InterruptSource); + } + crate::interrupt::bind_handler(InterruptSource, handler); + } +} + +impl super::AdcCalEfuse for crate::peripherals::ADC1<'_> { + fn init_code(atten: Attenuation) -> Option { + crate::efuse::rtc_calib_init_code(AdcCalibUnit::ADC1, atten) + } + + fn cal_mv(atten: Attenuation) -> Option { + crate::efuse::rtc_calib_cal_mv(AdcCalibUnit::ADC1, atten) + } + + fn cal_code(atten: Attenuation) -> Option { + crate::efuse::rtc_calib_cal_code(AdcCalibUnit::ADC1, atten) + } + + #[cfg(adc_channel_compensation)] + fn cal_chan_compens(atten: Attenuation, channel: u8) -> Option { + crate::efuse::rtc_calib_get_chan_compens(AdcCalibUnit::ADC1, channel, atten) + } +} + +impl<'d, ADCX> Adc<'d, ADCX, Async> +where + ADCX: RegisterAccess + 'd, +{ + /// Reconfigures the ADC driver to operate in [`Blocking`] mode. + pub fn into_blocking(self) -> Adc<'d, ADCX, Blocking> { + // Every chip handled by this driver has a single ADC unit, so no other driver can be + // sharing the interrupt and it is always safe to disable it here. + for cpu in crate::system::Cpu::all() { + crate::interrupt::disable(cpu, InterruptSource); + } + Adc { + _adc: self._adc, + attenuations: self.attenuations, + init_codes: self.init_codes, + active_channel: self.active_channel, + _guard: self._guard, + _clock: self._clock, + sar_power: self.sar_power, + _phantom: PhantomData, + } + } + + /// Requests that the ADC begin a conversion on the specified pin. + /// + /// Takes an [`AdcPin`](super::AdcPin) reference, as it is + /// expected that the ADC will be able to sample whatever channel + /// underlies the pin. + /// + /// # Errors + /// + /// Returns [`Error::ChannelNotConfigured`] if the channel was not configured in + /// [`AdcConfig`]. + pub async fn read_oneshot( + &mut self, + pin: &mut super::AdcPin, + ) -> Result + where + ADCX: Instance, + PIN: super::AdcChannel, + CS: super::AdcCalScheme, + { + self.start_sample(pin)?; + + // Wait for ADC to finish conversion and get value + let adc_ready_future = AdcFuture::new(self); + adc_ready_future.await; + settle_after_done(); + + let converted_value = ADCX::read_data(); + + ADCX::reset(); + + // Postprocess converted value according to calibration scheme used for pin + Ok(pin.cal_scheme.adc_val(converted_value)) + } +} + +#[handler] +pub(crate) fn adc_interrupt_handler() { + let saradc = APB_SARADC::regs(); + let interrupt_status = saradc.int_st().read(); + + if interrupt_status.adc1_done().bit_is_set() { + unsafe { handle_async(crate::peripherals::ADC1::steal()) } + } +} + +fn handle_async(_instance: ADCX) { + ADCX::waker().wake(); + ADCX::unlisten(); +} + +/// Enables asynchronous access. +pub trait Instance: crate::private::Sealed { + /// Enables the ADC interrupt. + fn listen(); + + /// Disables the ADC interrupt. + fn unlisten(); + + /// Clears the ADC interrupt. + fn clear_interrupt(); + + /// Obtains the waker for the ADC interrupt. + fn waker() -> &'static AtomicWaker; +} + +impl Instance for crate::peripherals::ADC1<'_> { + fn listen() { + APB_SARADC::regs() + .int_ena() + .modify(|_, w| w.adc1_done().set_bit()); + } + + fn unlisten() { + APB_SARADC::regs() + .int_ena() + .modify(|_, w| w.adc1_done().clear_bit()); + } + + fn clear_interrupt() { + APB_SARADC::regs() + .int_clr() + .write(|w| w.adc1_done().clear_bit_by_one()); + } + + fn waker() -> &'static AtomicWaker { + static WAKER: AtomicWaker = AtomicWaker::new(); + + &WAKER + } +} + +#[must_use = "futures do nothing unless you `.await` or poll them"] +pub(crate) struct AdcFuture { + phantom: PhantomData, + _wake_lock: WakeLock, +} + +impl AdcFuture { + pub fn new(_self: &super::Adc<'_, ADCX, Async>) -> Self { + Self { + phantom: PhantomData, + _wake_lock: WakeLock::new(), + } + } +} + +impl core::future::Future for AdcFuture { + type Output = (); + + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + if ADCX::is_done() { + ADCX::clear_interrupt(); + Poll::Ready(()) + } else { + ADCX::waker().register(cx.waker()); + ADCX::listen(); + Poll::Pending + } + } +} + +impl Drop for AdcFuture { + fn drop(&mut self) { + ADCX::unlisten(); + } +} diff --git a/esp-hal/src/analog/adc/esp32.rs b/esp-hal/src/analog/adc/esp32.rs index e9fa8f0d53b..928c13c778c 100644 --- a/esp-hal/src/analog/adc/esp32.rs +++ b/esp-hal/src/analog/adc/esp32.rs @@ -3,7 +3,7 @@ use core::{ sync::atomic::{AtomicBool, Ordering}, }; -use super::{AdcCalScheme, AdcConfig, Attenuation}; +use super::{AdcCalScheme, AdcConfig, Attenuation, Error}; use crate::{ peripherals::{ADC1, ADC2, SENS}, private, @@ -18,15 +18,8 @@ pub use self::calibration::*; // state to prevent unexpected behaviour static ADC2_IN_USE: AtomicBool = AtomicBool::new(false); -/// ADC Error -#[derive(Debug)] -pub enum Error { - /// `ADC2` is used together with `radio`. - Adc2InUse, -} - #[doc(hidden)] -/// Tries to "claim" `ADC2` peripheral and set its status +/// Tries to "claim" `ADC2` peripheral and sets its status. pub fn try_claim_adc2(_: private::Internal) -> Result<(), Error> { if ADC2_IN_USE.fetch_or(true, Ordering::Relaxed) { Err(Error::Adc2InUse) @@ -36,7 +29,7 @@ pub fn try_claim_adc2(_: private::Internal) -> Result<(), Error> { } #[doc(hidden)] -/// Resets `ADC2` usage status to `Unused` +/// Resets `ADC2` usage status to `Unused`. pub fn release_adc2(_: private::Internal) { ADC2_IN_USE.store(false, Ordering::Relaxed); } @@ -240,6 +233,8 @@ pub struct Adc<'d, ADC, Dm: crate::DriverMode> { attenuations: [Option; NUM_ATTENS], active_channel: Option, resolution_bits: u8, + // Set when this driver claimed ADC2, which it then releases on drop. + adc2_claimed: bool, _phantom: PhantomData<(Dm, &'d mut ())>, } @@ -247,19 +242,24 @@ impl<'d, ADCX> Adc<'d, ADCX, crate::Blocking> where ADCX: RegisterAccess + 'd, { - /// Configure a given ADC instance using the provided configuration, and - /// initialize the ADC for use + /// Configures a given ADC instance using the provided configuration, and + /// initializes the ADC for use. /// - /// # Panics + /// # Errors /// - /// `ADC2` cannot be used simultaneously with `radio` functionalities, otherwise this function - /// will panic. - pub fn new(adc_instance: ADCX, config: AdcConfig) -> Self { - if ADCX::instance_number() == 2 && try_claim_adc2(private::Internal).is_err() { - panic!( - "ADC2 is already in use by Radio. On ESP32, ADC2 cannot be used simultaneously with Wi-Fi or Bluetooth." - ); - } + /// Returns [`Error::Adc2InUse`] if `ADC2` is already in use by the radio. + /// `ADC2` cannot be used simultaneously with `radio` functionalities. + /// The handle is consumed even on failure; pass a reborrowed handle to retry later. + pub fn new(adc_instance: ADCX, config: AdcConfig) -> Result { + // Claim ADC2 for exclusive use; the driver releases it on drop. + let adc2_claimed = if ADCX::instance_number() == 2 { + if try_claim_adc2(private::Internal).is_err() { + return Err(Error::Adc2InUse); + } + true + } else { + false + }; let sensors = SENS::regs(); @@ -312,7 +312,7 @@ where .sar_read_ctrl2() .modify(|_, w| w.sar2_data_inv().set_bit()); - Adc { + Ok(Adc { _adc: adc_instance, attenuations: config.attenuations, active_channel: None, @@ -322,28 +322,32 @@ where Resolution::_11Bit => 11, Resolution::_12Bit => 12, }, + adc2_claimed, _phantom: PhantomData, - } + }) } - /// Request that the ADC begin a conversion on the specified pin + /// Requests that the ADC begin a conversion on the specified pin. /// - /// This method takes an [AdcPin](super::AdcPin) reference, as it is + /// Takes an [`AdcPin`](super::AdcPin) reference, as it is /// expected that the ADC will be able to sample whatever channel /// underlies the pin. + /// + /// # Errors + /// + /// Returns [`Error::ChannelNotConfigured`] if the channel was not configured in + /// [`AdcConfig`]. pub fn read_oneshot( &mut self, pin: &mut super::AdcPin, - ) -> nb::Result + ) -> nb::Result where PIN: super::AdcChannel, CS: AdcCalScheme, { - if self.attenuations[pin.pin.adc_channel() as usize].is_none() { - panic!( - "Channel {} is not configured reading!", - pin.pin.adc_channel() - ); + let channel = pin.pin.adc_channel(); + if self.attenuations[channel as usize].is_none() { + return Err(nb::Error::Other(Error::ChannelNotConfigured(channel))); } if let Some(active_channel) = self.active_channel { @@ -383,8 +387,10 @@ where } } -impl Drop for ADC2<'_> { +impl Drop for Adc<'_, ADC, Dm> { fn drop(&mut self) { - release_adc2(private::Internal); + if self.adc2_claimed { + release_adc2(private::Internal); + } } } diff --git a/esp-hal/src/analog/adc/implementation.rs b/esp-hal/src/analog/adc/implementation.rs new file mode 100644 index 00000000000..257f51da656 --- /dev/null +++ b/esp-hal/src/analog/adc/implementation.rs @@ -0,0 +1,8 @@ +// Fallback target for `mod implementation;` in `mod.rs`. +// +// Shared controllers set `adc.controller` to `rtc` or `digital`. ESP32, ESP32-P4, and ESP32-S31 +// use chip path attrs. This file is only compiled when none of those match. +compile_error!( + "This chip has ADC support enabled in `esp-metadata` but no ADC implementation was selected. \ + Set `adc.controller` to \"rtc\" or \"digital\", or add a chip path attr in `mod.rs`." +); diff --git a/esp-hal/src/analog/adc/mod.rs b/esp-hal/src/analog/adc/mod.rs index 204107b9e80..d6360c330a8 100644 --- a/esp-hal/src/analog/adc/mod.rs +++ b/esp-hal/src/analog/adc/mod.rs @@ -32,7 +32,7 @@ //! # use esp_hal::delay::Delay; //! let mut adc1_config = AdcConfig::new(); //! let mut pin = adc1_config.enable_pin(peripherals.__analog_pin__, Attenuation::_11dB); -//! let mut adc1 = Adc::new(peripherals.ADC1, adc1_config); +//! let mut adc1 = Adc::new(peripherals.ADC1, adc1_config)?; //! //! let mut delay = Delay::new(); //! @@ -47,8 +47,10 @@ //! ## Implementation State //! //! - [ADC calibration is not implemented for all targets]. -//! - The ESP32-S31 has no calibration scheme. ESP-IDF does not define the calibration eFuses or -//! the curve fitting coefficients for this chip yet. +//! - The ESP32-C3 has an ADC2 in silicon, but it is not exposed due to hardware errata in its +//! digital controller. GPIO5 is therefore not an ADC pin on ESP32-C3. +//! - The ESP32-S31 has no calibration scheme: calibration eFuses and curve fitting coefficients +//! are not available for this chip. //! - The ESP32-S31 SAR ADC has one attenuation setting, so the attenuation given to //! [`AdcConfig::enable_pin`] has no effect. //! - The ESP32-S31 SAR is differential and its result is the weighted sum of 17 redundant @@ -61,11 +63,14 @@ use core::marker::PhantomData; use crate::gpio::AnalogPin; +// A chip lands in a file by the ADC controller it has, not by its CPU architecture: the RISC-V +// ESP32-P4 drives the same RTC-style controller as the Xtensa ESP32-S2 and ESP32-S3, while the +// chips in `dig_ctrl.rs` have no RTC controller and convert through the digital one instead. #[cfg_attr(esp32, path = "esp32.rs")] #[cfg_attr(esp32p4, path = "p4.rs")] #[cfg_attr(esp32s31, path = "s31.rs")] -#[cfg_attr(all(riscv, not(any(esp32p4, esp32s31))), path = "riscv.rs")] -#[cfg_attr(any(esp32s2, esp32s3), path = "xtensa.rs")] +#[cfg_attr(adc_controller = "rtc", path = "s2_s3.rs")] +#[cfg_attr(adc_controller = "digital", path = "dig_ctrl.rs")] #[cfg(feature = "unstable")] mod implementation; @@ -75,8 +80,8 @@ pub use self::implementation::*; /// The approximate attenuation of the ADC pin. /// /// The effective measurement range for a given attenuation is dependent on the -/// device being targeted. Please refer to "ADC Characteristics" section of your -/// device's datasheet for more information. +/// device being targeted. Refer to the "ADC Characteristics" section of the +/// device datasheet for more information. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[allow(clippy::enum_variant_names, reason = "unit of measurement")] @@ -91,20 +96,13 @@ pub enum Attenuation { _11dB = 0b11, } -/// Calibration source of the ADC. -#[cfg(not(esp32))] -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "defmt", derive(defmt::Format))] -pub enum AdcCalSource { - /// Use Ground as the calibration source - Gnd, - /// Use Vref as the calibration source - Ref, -} +/// The number of [`Attenuation`] variants, and in turn the length of tables indexed by one. +#[cfg(all(feature = "unstable", adc_calibration_v1_scheme_supported))] +const ATTENUATION_COUNT: usize = 4; /// An I/O pin which can be read using the ADC. pub struct AdcPin { - /// The underlying GPIO pin + /// The underlying GPIO pin. pub pin: PIN, /// Calibration scheme used for the configured ADC pin pub cal_scheme: CS, @@ -143,12 +141,12 @@ pub struct AdcConfig { #[cfg(feature = "unstable")] impl AdcConfig { - /// Create a new configuration struct with its default values + /// Creates a new configuration struct with its default values. pub fn new() -> Self { Self::default() } - /// Enable the specified pin with the given attenuation + /// Enables the specified pin with the given attenuation. pub fn enable_pin(&mut self, pin: PIN, attenuation: Attenuation) -> AdcPin where PIN: AdcChannel + AnalogPin, @@ -159,33 +157,42 @@ impl AdcConfig { AdcPin { pin, - cal_scheme: AdcCalScheme::<()>::new_cal(attenuation), + // The unit scheme never fails; construct it directly to keep this infallible. + cal_scheme: (), _phantom: PhantomData, } } - /// Enable the specified pin with the given attenuation and calibration - /// scheme + /// Enables the specified pin with the given attenuation and calibration + /// scheme. + /// + /// # Errors + /// + /// Returns [`Error::MissingCalibrationData`] if the chip carries no + /// calibration data for the scheme, or [`Error::UnsupportedAttenuation`] + /// if the attenuation has no calibration data on this chip. #[cfg(feature = "unstable")] pub fn enable_pin_with_cal( &mut self, pin: PIN, attenuation: Attenuation, - ) -> AdcPin + ) -> Result, Error> where PIN: AdcChannel + AnalogPin, CS: AdcCalScheme, { + let channel = pin.adc_channel(); + let cal_scheme = CS::new_cal_with_channel(attenuation, channel)?; + // TODO revert this on drop pin.set_analog(crate::private::Internal); - let channel = pin.adc_channel(); self.attenuations[channel as usize] = Some(attenuation); - AdcPin { + Ok(AdcPin { pin, - cal_scheme: CS::new_cal_with_channel(attenuation, channel), + cal_scheme, _phantom: PhantomData, - } + }) } } @@ -205,14 +212,77 @@ impl Default for AdcConfig { #[doc(hidden)] #[cfg(feature = "unstable")] pub trait CalibrationAccess: RegisterAccess { - const ADC_CAL_CNT_MAX: u16; - const ADC_CAL_CHANNEL: u16; const ADC_VAL_MASK: u16; + /// Returns whether the unit can measure a calibration source instead of a pad. + /// + /// Hardware self-calibration is not supported on ESP32-C5, where calibration depends on eFuse + /// data. + const SUPPORTS_SELF_CALIBRATION: bool = true; + fn enable_vdef(enable: bool); - /// Enable internal calibration voltage source - fn connect_cal(source: AdcCalSource, enable: bool); + /// Disconnects the unit from its pad and ties the input to internal ground. + fn connect_gnd(enable: bool); + + /// Configures the unit for calibration at the specified attenuation. + /// + /// See `cal_setup` in + /// . + fn setup_calibration(atten: Attenuation); +} + +/// Number of times the search below is repeated. The extremes are discarded and the rest averaged. +#[cfg(all(feature = "unstable", adc_calibration_v1_scheme_supported))] +const ADC_CAL_TIMES: u32 = 10; + +/// One past the highest initial code. The field is twelve bits wide on every chip. +#[cfg(all(feature = "unstable", adc_calibration_v1_scheme_supported))] +const ADC_CAL_OFFSET_RANGE: u16 = 4096; + +/// Finds the initial code that cancels out the calibration source the unit is currently connected +/// to. +/// +/// The initial code shifts the SAR's transfer curve down, so the reading drops to zero once the +/// code reaches the source, and finding that step is an ordinary bisection. Noise moves the step +/// by a code or two between runs, hence the repetitions. +/// +/// `measure` converts once and returns the result, leaving the initial code alone. +/// +/// See `adc_hal_self_calibration` in +/// . +#[cfg(all(feature = "unstable", adc_calibration_v1_scheme_supported))] +fn search_init_code(mut measure: impl FnMut() -> u16) -> u16 { + let mut sum = 0; + let mut lowest = u16::MAX; + let mut highest = 0; + + for _ in 0..ADC_CAL_TIMES { + // `low` still reads non-zero, `high` already reads zero. + let mut low = 0; + let mut high = ADC_CAL_OFFSET_RANGE; + + while high - low > 1 { + let code = (low + high) / 2; + ADCX::set_init_code(code); + + if measure() == 0 { + high = code; + } else { + low = code; + } + } + + sum += u32::from(high); + lowest = lowest.min(high); + highest = highest.max(high); + } + + let count = ADC_CAL_TIMES - 2; + let trimmed = sum - u32::from(lowest) - u32::from(highest); + + // Round to nearest. + ((trimmed + count / 2) / count) as u16 } /// A helper trait to get the ADC channel of a compatible GPIO pin. @@ -223,27 +293,36 @@ pub trait AdcChannel { /// A trait abstracting over calibration methods. /// -/// The methods in this trait are mostly for internal use. To get -/// calibrated ADC reads, all you need to do is call `enable_pin_with_cal` -/// and specify some implementor of this trait. +/// The methods in this trait are mostly for internal use. Call +/// `enable_pin_with_cal` with an implementor of this trait to get calibrated +/// ADC reads. pub trait AdcCalScheme: Sized + crate::private::Sealed { - /// Create a new calibration scheme for the given attenuation. - fn new_cal(atten: Attenuation) -> Self; + /// Creates a new calibration scheme for the given attenuation. + /// + /// # Errors + /// + /// Returns `Error::MissingCalibrationData` if the chip carries no + /// calibration data for the scheme, or `Error::UnsupportedAttenuation` + /// if the attenuation has no calibration data on this chip. + #[cfg(feature = "unstable")] + fn new_cal(atten: Attenuation) -> Result; - /// Create a new calibration scheme for the given attenuation and ADC + /// Creates a new calibration scheme for the given attenuation and ADC /// channel. /// /// The default implementation ignores `channel` and calls [`Self::new_cal`]. - fn new_cal_with_channel(atten: Attenuation, _channel: u8) -> Self { + /// + /// # Errors + /// + /// Returns `Error::MissingCalibrationData` if the chip carries no + /// calibration data for the scheme, or `Error::UnsupportedAttenuation` + /// if the attenuation has no calibration data on this chip. + #[cfg(feature = "unstable")] + fn new_cal_with_channel(atten: Attenuation, _channel: u8) -> Result { Self::new_cal(atten) } - /// Return the basic ADC bias value. - fn adc_cal(&self) -> u16 { - 0 - } - - /// Convert ADC value. + /// Converts ADC value. fn adc_val(&self, val: u16) -> u16 { val } @@ -252,31 +331,141 @@ pub trait AdcCalScheme: Sized + crate::private::Sealed { impl crate::private::Sealed for () {} impl AdcCalScheme for () { - fn new_cal(_atten: Attenuation) -> Self {} + #[cfg(feature = "unstable")] + fn new_cal(_atten: Attenuation) -> Result { + Ok(()) + } +} + +/// Errors that can occur while using the ADC. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[non_exhaustive] +#[instability::unstable] +#[cfg(feature = "unstable")] +pub enum Error { + /// The ADC channel was not configured for reading. + ChannelNotConfigured(u8), + /// `ADC2` cannot be used together with the radio. + /// + /// Only constructed on ESP32, where `ADC2` shares hardware with Wi-Fi and + /// Bluetooth. + Adc2InUse, + /// The chip carries no eFuse calibration data for the requested scheme. + /// + /// Constructed when line/curve fitting is requested but the calibration + /// eFuses are unburnt, or when the stored reference point is zero and + /// therefore unusable. + MissingCalibrationData, + /// The attenuation has no calibration reference point on this chip. + /// + /// Constructed when the requested attenuation is not characterized for + /// calibration (e.g. ESP32-C2 line fitting at 2.5 dB/6 dB, or a missing + /// curve-fitting coefficient set). + UnsupportedAttenuation(Attenuation), +} + +#[cfg(feature = "unstable")] +impl core::error::Error for Error {} + +#[cfg(feature = "unstable")] +impl core::fmt::Display for Error { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::ChannelNotConfigured(channel) => { + write!(f, "ADC channel {channel} is not configured for reading") + } + Self::Adc2InUse => f.write_str("ADC2 cannot be used together with the radio"), + Self::MissingCalibrationData => { + f.write_str("ADC calibration data is missing from eFuse for the requested scheme") + } + Self::UnsupportedAttenuation(atten) => { + write!( + f, + "ADC attenuation {atten:?} has no calibration data on this chip" + ) + } + } + } +} + +/// Returns the attenuation channel `channel` was configured with. +/// +/// # Errors +/// +/// Returns [`Error::ChannelNotConfigured`] if the channel was not enabled via +/// [`AdcConfig::enable_pin`] or [`AdcConfig::enable_pin_with_cal`]. +#[cfg(all(feature = "unstable", adc_calibration_v1_scheme_supported))] +fn channel_attenuation( + attenuations: &[Option], + channel: u8, +) -> Result { + match attenuations[channel as usize] { + Some(attenuation) => Ok(attenuation), + None => Err(Error::ChannelNotConfigured(channel)), + } +} + +// Returns the hardware calibration code (`Dout0`) for every configured attenuation. +// +// The hardware subtracts this code from the conversion result before truncating it, so it has +// to be programmed regardless of the calibration scheme in use - otherwise the usable output +// range shrinks by the ADC's zero-voltage offset. +// +// Determining a code can involve measuring the ADC, and that measurement programs channel 0's +// attenuation, so the caller has to apply the configured attenuations afterwards. +#[cfg(all(feature = "unstable", adc_calibration_v1_scheme_supported))] +fn hw_init_codes(attenuations: &[Option]) -> [u16; ATTENUATION_COUNT] +where + ADCX: AdcCalEfuse + CalibrationAccess, +{ + let mut init_codes = [0; ATTENUATION_COUNT]; + + for atten in attenuations.iter().flatten() { + // Boards with calibration eFuses never reach the self-calibration fallback, so HIL + // tests ignore the eFuses to exercise it. + #[cfg(not(__test_adc_self_cal))] + let efuse_code = ADCX::init_code(*atten); + #[cfg(__test_adc_self_cal)] + let efuse_code = None; + + init_codes[*atten as usize] = efuse_code.unwrap_or_else(|| { + if ADCX::SUPPORTS_SELF_CALIBRATION { + AdcConfig::::adc_calibrate(*atten) + } else { + 0 + } + }); + } + + init_codes } /// A helper trait to get access to ADC calibration efuses. -#[cfg(not(any(esp32, esp32s31)))] -trait AdcCalEfuse { - /// Get ADC calibration init code +#[cfg(adc_calibration_v1_scheme_supported)] +#[doc(hidden)] +pub trait AdcCalEfuse { + /// Returns the ADC calibration init code. /// - /// Returns digital value for zero voltage for a given attenuation + /// Returns digital value for zero voltage for a given attenuation. fn init_code(atten: Attenuation) -> Option; - /// Get ADC calibration reference point voltage + /// Returns the ADC calibration reference point voltage. /// - /// Returns reference voltage (millivolts) for a given attenuation - fn cal_mv(atten: Attenuation) -> u16; + /// Returns reference voltage (millivolts) for a given attenuation, or + /// `None` when the attenuation has no reference point on this chip + /// (e.g. ESP32-C2 at 2.5 dB/6 dB). + fn cal_mv(atten: Attenuation) -> Option; - /// Get ADC calibration reference point digital value + /// Returns the ADC calibration reference point digital value. /// - /// Returns digital value for reference voltage for a given attenuation + /// Returns digital value for reference voltage for a given attenuation. fn cal_code(atten: Attenuation) -> Option; - /// Get the ADC channel specific calibration + /// Returns the ADC channel specific calibration. /// - /// Returns digital per channel offset from reference voltage - #[cfg(any(esp32c5, esp32c6, esp32c61, esp32h2))] + /// Returns digital per channel offset from reference voltage. + #[cfg(adc_channel_compensation)] fn cal_chan_compens(atten: Attenuation, channel: u8) -> Option; } diff --git a/esp-hal/src/analog/adc/p4.rs b/esp-hal/src/analog/adc/p4.rs index 2da3dc8ce28..cbce8ce33b9 100644 --- a/esp-hal/src/analog/adc/p4.rs +++ b/esp-hal/src/analog/adc/p4.rs @@ -11,7 +11,7 @@ use portable_atomic::{AtomicU32, Ordering}; use procmacros::handler; pub use self::calibration::*; -use super::{AdcCalScheme, AdcCalSource, AdcChannel, AdcConfig, AdcPin, Attenuation}; +use super::{AdcCalScheme, AdcChannel, AdcConfig, AdcPin, Attenuation, Error}; use crate::{ Async, Blocking, @@ -31,68 +31,70 @@ mod calibration; pub(super) const NUM_ATTENS: usize = 8; const ADC_VAL_MASK: u16 = 0xfff; -const ADC_CAL_CNT_MAX: u16 = 32; -const ADC_CAL_CHANNEL: u16 = 15; -/// Power the SAR up by software, instead of leaving it to the FSM. +/// Powers the SAR up by software, instead of leaving it to the FSM. const FORCE_XPD_SAR_PU: u8 = 3; impl AdcConfig where ADCX: RegisterAccess, { - /// Calibrate ADC with specified attenuation and voltage source - pub fn adc_calibrate(atten: Attenuation, source: AdcCalSource) -> u16 + /// Measures the initial code that cancels the unit's zero-voltage offset at `atten`. + pub fn adc_calibrate(atten: Attenuation) -> u16 where ADCX: super::CalibrationAccess, { - let mut adc_max: u16 = 0; - let mut adc_min: u16 = u16::MAX; - let mut adc_sum: u32 = 0; + // This can be called without an `Adc`, so it cannot rely on `Adc::new` having clocked + // and powered the unit. + let _guard = GenericPeripheralGuard::<{ Peripheral::ApbSarAdc as u8 }>::new(); + init_hardware::(); ADCX::enable_vdef(true); // Start sampling - ADCX::set_en_pad(ADCX::ADC_CAL_CHANNEL as u8); - ADCX::set_attenuation(ADCX::ADC_CAL_CHANNEL as usize, atten as u8); + ADCX::setup_calibration(atten); // Connect calibration source - ADCX::connect_cal(source, true); + ADCX::connect_gnd(true); ADCX::calibration_init(); - ADCX::set_init_code(0); - - for _ in 0..ADCX::ADC_CAL_CNT_MAX { - // Trigger ADC sampling + let cal_val = super::search_init_code::(|| { + // Clearing the done flag up front, rather than after the read, keeps a conversion left + // over from the previous code from being mistaken for this one's result. + ADCX::reset(); ADCX::start_sample(); - - // Wait until ADC sampling is done while !ADCX::is_done() {} - let adc = ADCX::read_data() & ADCX::ADC_VAL_MASK; - - ADCX::reset(); - - adc_sum += adc as u32; - adc_max = adc.max(adc_max); - adc_min = adc.min(adc_min); - } - - let cal_val = - (adc_sum - adc_max as u32 - adc_min as u32) as u16 / (ADCX::ADC_CAL_CNT_MAX - 2); + ADCX::read_data() & ADCX::ADC_VAL_MASK + }); + ADCX::reset(); // Disconnect calibration source - ADCX::connect_cal(source, false); + ADCX::connect_gnd(false); cal_val } } +/// Clocks the RTC controller and powers the unit up. +/// +/// Writes nothing that depends on previous state, so it is safe to run more than once. +fn init_hardware() { + // The RTC controller lives in the LP domain and has its own clock gate. + LP_PERI::regs() + .clk_en() + .modify(|_, w| w.ck_en_lp_adc().set_bit()); + + ADCX::set_rtc_controller(); + ADCX::set_sar_clk_div(); + ADCX::power_up(); +} + #[doc(hidden)] pub trait RegisterAccess { fn set_attenuation(channel: usize, attenuation: u8); - /// Route the unit to the RTC controller, driven by software. + /// Routes the unit to the RTC controller, driven by software. fn set_rtc_controller(); fn set_en_pad(channel: u8); @@ -101,22 +103,27 @@ pub trait RegisterAccess { fn start_sample(); - /// Check if sampling is done + /// Returns whether sampling is done. fn is_done() -> bool; - /// Read sample data + /// Reads sample data. fn read_data() -> u16; - /// Power the SAR up + /// Powers the SAR up. fn power_up(); - /// Set up ADC hardware for calibration + /// Configures the SAR clock divider. + /// + /// See `adc_ll_set_sar_clk_div` and `ADC_LL_SAR_CLK_DIV_DEFAULT`. + fn set_sar_clk_div(); + + /// Sets up ADC hardware for calibration. fn calibration_init(); - /// Set calibration parameter to ADC hardware + /// Sets calibration parameter to ADC hardware. fn set_init_code(data: u16); - /// Reset flags + /// Resets flags. fn reset(); } @@ -177,6 +184,12 @@ impl RegisterAccess for crate::peripherals::ADC1<'_> { .modify(|_, w| unsafe { w.force_xpd_sar1().bits(FORCE_XPD_SAR_PU) }); } + fn set_sar_clk_div() { + LP_ADC::regs() + .reader1_ctrl() + .modify(|_, w| unsafe { w.sar1_clk_div().bits(1) }); + } + fn calibration_init() { // https://github.com/espressif/esp-idf/blob/08e0d30a74a/components/esp_hal_ana_conv/esp32p4/include/hal/adc_ll.h#L727 regi2c::ADC_SAR1_DREF.write_field(4); @@ -204,19 +217,24 @@ impl RegisterAccess for crate::peripherals::ADC1<'_> { #[cfg(adc_adc1)] impl super::CalibrationAccess for crate::peripherals::ADC1<'_> { - const ADC_CAL_CNT_MAX: u16 = ADC_CAL_CNT_MAX; - const ADC_CAL_CHANNEL: u16 = ADC_CAL_CHANNEL; const ADC_VAL_MASK: u16 = ADC_VAL_MASK; fn enable_vdef(enable: bool) { regi2c::ADC_SAR1_DREF.write_field(enable as u8); } - fn connect_cal(source: AdcCalSource, enable: bool) { - match source { - AdcCalSource::Gnd => regi2c::ADC_SAR1_ENCAL_GND.write_field(enable as u8), - AdcCalSource::Ref => regi2c::ADC_SAR1_ENCAL_REF.write_field(enable as u8), - } + fn connect_gnd(enable: bool) { + regi2c::ADC_SAR1_ENCAL_GND.write_field(enable as u8); + } + + fn setup_calibration(atten: Attenuation) { + // With no pad selected the hardware falls back to channel 0's attenuation, so + // that is where `cal_setup` programs it. Selecting the pseudo-channel the + // digital controller uses would shift past the register instead. + LP_ADC::regs() + .meas1_ctrl2() + .modify(|_, w| unsafe { w.sar1_en_pad().bits(0) }); + Self::set_attenuation(0, atten as u8); } } @@ -286,6 +304,12 @@ impl RegisterAccess for crate::peripherals::ADC2<'_> { .modify(|_, w| unsafe { w.force_xpd_sar2().bits(FORCE_XPD_SAR_PU) }); } + fn set_sar_clk_div() { + LP_ADC::regs() + .reader2_ctrl() + .modify(|_, w| unsafe { w.sar2_clk_div().bits(1) }); + } + fn calibration_init() { regi2c::ADC_SAR2_DREF.write_field(4); } @@ -312,19 +336,21 @@ impl RegisterAccess for crate::peripherals::ADC2<'_> { #[cfg(adc_adc2)] impl super::CalibrationAccess for crate::peripherals::ADC2<'_> { - const ADC_CAL_CNT_MAX: u16 = ADC_CAL_CNT_MAX; - const ADC_CAL_CHANNEL: u16 = ADC_CAL_CHANNEL; const ADC_VAL_MASK: u16 = ADC_VAL_MASK; fn enable_vdef(enable: bool) { regi2c::ADC_SAR2_DREF.write_field(enable as u8); } - fn connect_cal(source: AdcCalSource, enable: bool) { - match source { - AdcCalSource::Gnd => regi2c::ADC_SAR2_ENCAL_GND.write_field(enable as u8), - AdcCalSource::Ref => regi2c::ADC_SAR2_ENCAL_REF.write_field(enable as u8), - } + fn connect_gnd(enable: bool) { + regi2c::ADC_SAR2_ENCAL_GND.write_field(enable as u8); + } + + fn setup_calibration(atten: Attenuation) { + LP_ADC::regs() + .meas2_ctrl2() + .modify(|_, w| unsafe { w.sar2_en_pad().bits(0) }); + Self::set_attenuation(0, atten as u8); } } @@ -334,13 +360,17 @@ impl super::AdcCalEfuse for crate::peripherals::ADC1<'_> { crate::efuse::rtc_calib_init_code(AdcCalibUnit::ADC1, atten) } - fn cal_mv(atten: Attenuation) -> u16 { + fn cal_mv(atten: Attenuation) -> Option { crate::efuse::rtc_calib_cal_mv(AdcCalibUnit::ADC1, atten) } fn cal_code(atten: Attenuation) -> Option { crate::efuse::rtc_calib_cal_code(AdcCalibUnit::ADC1, atten) } + + fn cal_chan_compens(atten: Attenuation, channel: u8) -> Option { + crate::efuse::rtc_calib_get_chan_compens(AdcCalibUnit::ADC1, channel.into(), atten) + } } #[cfg(adc_adc2)] @@ -349,20 +379,26 @@ impl super::AdcCalEfuse for crate::peripherals::ADC2<'_> { crate::efuse::rtc_calib_init_code(AdcCalibUnit::ADC2, atten) } - fn cal_mv(atten: Attenuation) -> u16 { + fn cal_mv(atten: Attenuation) -> Option { crate::efuse::rtc_calib_cal_mv(AdcCalibUnit::ADC2, atten) } fn cal_code(atten: Attenuation) -> Option { crate::efuse::rtc_calib_cal_code(AdcCalibUnit::ADC2, atten) } + + fn cal_chan_compens(atten: Attenuation, channel: u8) -> Option { + crate::efuse::rtc_calib_get_chan_compens(AdcCalibUnit::ADC2, channel.into(), atten) + } } /// Analog-to-Digital Converter peripheral driver. pub struct Adc<'d, ADC, Dm: crate::DriverMode> { _adc: ADC, + attenuations: [Option; NUM_ATTENS], + /// Hardware calibration code per attenuation, indexed by [`Attenuation`]. + init_codes: [u16; super::ATTENUATION_COUNT], active_channel: Option, - last_init_code: u16, _guard: GenericPeripheralGuard<{ Peripheral::ApbSarAdc as u8 }>, _phantom: PhantomData<(Dm, &'d mut ())>, } @@ -372,23 +408,25 @@ where ADCX: RegisterAccess, Dm: crate::DriverMode, { - fn start_sample(&mut self, pin: &mut AdcPin) + fn start_sample(&mut self, pin: &mut AdcPin) -> Result<(), Error> where PIN: AdcChannel, CS: AdcCalScheme, { - // Set ADC unit calibration according used scheme for pin - let init_code = pin.cal_scheme.adc_cal(); - if self.last_init_code != init_code { - ADCX::calibration_init(); - ADCX::set_init_code(init_code); - self.last_init_code = init_code; - } + let channel = pin.pin.adc_channel(); + let attenuation = super::channel_attenuation(&self.attenuations, channel)?; + + // Reprogrammed for every conversion: the regi2c block is shared with the PHY, + // so the code cannot be assumed to survive between reads. + ADCX::calibration_init(); + ADCX::set_init_code(self.init_codes[attenuation as usize]); - ADCX::set_en_pad(pin.pin.adc_channel()); + ADCX::set_en_pad(channel); ADCX::clear_start_sample(); ADCX::start_sample(); + + Ok(()) } } @@ -396,42 +434,52 @@ impl<'d, ADCX> Adc<'d, ADCX, Blocking> where ADCX: RegisterAccess + 'd, { - /// Configure a given ADC instance using the provided configuration, and - /// initialize the ADC for use - pub fn new(adc_instance: ADCX, config: AdcConfig) -> Self { + /// Creates a new ADC instance with the given configuration. + pub fn new(adc_instance: ADCX, config: AdcConfig) -> Result + where + ADCX: super::AdcCalEfuse + super::CalibrationAccess, + { let guard = GenericPeripheralGuard::new(); - // The RTC controller lives in the LP domain and has its own clock gate. - LP_PERI::regs() - .clk_en() - .modify(|_, w| w.ck_en_lp_adc().set_bit()); + let attenuations = config.attenuations; + + init_hardware::(); - for (channel, attenuation) in config.attenuations.iter().enumerate() { + let init_codes = super::hw_init_codes::(&attenuations); + + for (channel, attenuation) in attenuations.iter().enumerate() { if let Some(attenuation) = attenuation { ADCX::set_attenuation(channel, *attenuation as u8); } } - ADCX::set_rtc_controller(); - ADCX::power_up(); + // The bootloader runs conversions of its own to seed the RNG, so the done flag can + // already be set here and would make the first read return a stale result. + ADCX::reset(); - Adc { + Ok(Adc { _adc: adc_instance, + attenuations, + init_codes, active_channel: None, - last_init_code: 0, _guard: guard, _phantom: PhantomData, - } + }) } - /// Start and wait for a conversion on the specified pin and return the - /// result - pub fn read_blocking(&mut self, pin: &mut AdcPin) -> u16 + /// Starts and waits for a conversion on the specified pin and returns the + /// result. + /// + /// # Errors + /// + /// Returns [`Error::ChannelNotConfigured`] if the channel was not configured in + /// [`AdcConfig`]. + pub fn read_blocking(&mut self, pin: &mut AdcPin) -> Result where PIN: AdcChannel, CS: AdcCalScheme, { - self.start_sample(pin); + self.start_sample(pin)?; // Wait for ADC to finish conversion while !ADCX::is_done() {} @@ -441,18 +489,23 @@ where ADCX::reset(); // Postprocess converted value according to calibration scheme used for pin - pin.cal_scheme.adc_val(converted_value) + Ok(pin.cal_scheme.adc_val(converted_value)) } - /// Request that the ADC begin a conversion on the specified pin + /// Requests that the ADC begin a conversion on the specified pin. /// - /// This method takes an [AdcPin](super::AdcPin) reference, as it is + /// Takes an [`AdcPin`](super::AdcPin) reference, as it is /// expected that the ADC will be able to sample whatever channel /// underlies the pin. + /// + /// # Errors + /// + /// Returns [`Error::ChannelNotConfigured`] if the channel was not configured in + /// [`AdcConfig`]. pub fn read_oneshot( &mut self, pin: &mut super::AdcPin, - ) -> nb::Result + ) -> nb::Result where PIN: super::AdcChannel, CS: super::AdcCalScheme, @@ -466,9 +519,8 @@ where } } else { // If no conversions are in progress, start a new one for given channel + self.start_sample(pin).map_err(nb::Error::Other)?; self.active_channel = Some(pin.pin.adc_channel()); - - self.start_sample(pin); } // Wait for ADC to finish conversion @@ -500,8 +552,9 @@ where Adc { _adc: self._adc, + attenuations: self.attenuations, + init_codes: self.init_codes, active_channel: self.active_channel, - last_init_code: self.last_init_code, _guard: self._guard, _phantom: PhantomData, } @@ -523,7 +576,7 @@ impl<'d, ADCX> Adc<'d, ADCX, Async> where ADCX: RegisterAccess + 'd, { - /// Create a new instance in [crate::Blocking] mode. + /// Reconfigures the ADC driver to operate in [`Blocking`] mode. pub fn into_blocking(self) -> Adc<'d, ADCX, Blocking> { if release_async_adc() { // Disable the ADC interrupt on all cores once the last async instance goes away. @@ -533,25 +586,34 @@ where } Adc { _adc: self._adc, + attenuations: self.attenuations, + init_codes: self.init_codes, active_channel: self.active_channel, - last_init_code: self.last_init_code, _guard: self._guard, _phantom: PhantomData, } } - /// Start a conversion on the specified pin and wait for the result. + /// Starts a conversion on the specified pin and waits for the result. /// - /// This method takes an [AdcPin](super::AdcPin) reference, as it is + /// Takes an [`AdcPin`](super::AdcPin) reference, as it is /// expected that the ADC will be able to sample whatever channel /// underlies the pin. - pub async fn read_oneshot(&mut self, pin: &mut super::AdcPin) -> u16 + /// + /// # Errors + /// + /// Returns [`Error::ChannelNotConfigured`] if the channel was not configured in + /// [`AdcConfig`]. + pub async fn read_oneshot( + &mut self, + pin: &mut super::AdcPin, + ) -> Result where ADCX: Instance, PIN: super::AdcChannel, CS: super::AdcCalScheme, { - self.start_sample(pin); + self.start_sample(pin)?; AdcFuture::::new(self).await; @@ -559,7 +621,7 @@ where ADCX::reset(); // Postprocess converted value according to calibration scheme used for pin - pin.cal_scheme.adc_val(converted_value) + Ok(pin.cal_scheme.adc_val(converted_value)) } } @@ -593,18 +655,18 @@ fn handle_async(_instance: ADCX) { ADCX::unlisten(); } -/// Enable asynchronous access. +/// Enables asynchronous access. pub trait Instance: crate::private::Sealed { - /// Enable the ADC interrupt + /// Enables the ADC interrupt. fn listen(); - /// Disable the ADC interrupt + /// Disables the ADC interrupt. fn unlisten(); - /// Clear the ADC interrupt + /// Clears the ADC interrupt. fn clear_interrupt(); - /// Obtain the waker for the ADC interrupt + /// Obtains the waker for the ADC interrupt. fn waker() -> &'static AtomicWaker; } diff --git a/esp-hal/src/analog/adc/riscv.rs b/esp-hal/src/analog/adc/riscv.rs deleted file mode 100644 index 1161504535b..00000000000 --- a/esp-hal/src/analog/adc/riscv.rs +++ /dev/null @@ -1,676 +0,0 @@ -use core::marker::PhantomData; - -cfg_select! { - any(esp32c6, esp32c61) => { - use Interrupt::APB_SARADC as InterruptSource; - } - _ => { - use Interrupt::APB_ADC as InterruptSource; - } -} - -use core::{ - pin::Pin, - task::{Context, Poll}, -}; - -// We only have to count on devices that have multiple ADCs sharing the same interrupt -#[cfg(all(adc_adc1, adc_adc2))] -use portable_atomic::{AtomicU32, Ordering}; -use procmacros::handler; - -pub use self::calibration::*; -use super::{AdcCalSource, AdcConfig, Attenuation}; -#[cfg(any(esp32c2, esp32c3, esp32c5, esp32c6, esp32c61, esp32h2))] -use crate::efuse::AdcCalibUnit; -use crate::{ - Async, - Blocking, - asynch::AtomicWaker, - interrupt::{InterruptConfigurable, InterruptHandler}, - peripherals::{APB_SARADC, Interrupt}, - rtc_cntl::WakeLock, - soc::regi2c, - system::{GenericPeripheralGuard, Peripheral}, -}; - -mod calibration; - -// Constants taken from: -// https://github.com/espressif/esp-idf/blob/903af13e8/components/soc/esp32c2/include/soc/regi2c_saradc.h -// https://github.com/espressif/esp-idf/blob/903af13e8/components/soc/esp32c3/include/soc/regi2c_saradc.h -// https://github.com/espressif/esp-idf/blob/903af13e8/components/soc/esp32c6/include/soc/regi2c_saradc.h -// https://github.com/espressif/esp-idf/blob/903af13e8/components/soc/esp32h2/include/soc/regi2c_saradc.h -cfg_select! { - adc_adc1 => { - const ADC_VAL_MASK: u16 = 0xfff; - const ADC_CAL_CNT_MAX: u16 = 32; - const ADC_CAL_CHANNEL: u16 = 15; - } - _ => {} -} - -// The number of analog IO pins, and in turn the number of attentuations, -// depends on which chip is being used -cfg_select! { - esp32c6 => { - pub(super) const NUM_ATTENS: usize = 7; - } - esp32c5 => { - pub(super) const NUM_ATTENS: usize = 6; - } - esp32c61 => { - pub(super) const NUM_ATTENS: usize = 4; - } - _ => { - pub(super) const NUM_ATTENS: usize = 5; - } -} - -impl AdcConfig -where - ADCX: RegisterAccess, -{ - /// Calibrate ADC with specified attenuation and voltage source - pub fn adc_calibrate(atten: Attenuation, source: AdcCalSource) -> u16 - where - ADCX: super::CalibrationAccess, - { - let mut adc_max: u16 = 0; - let mut adc_min: u16 = u16::MAX; - let mut adc_sum: u32 = 0; - - ADCX::enable_vdef(true); - - // Start sampling - ADCX::config_onetime_sample(ADC_CAL_CHANNEL as u8, atten as u8); - - // Connect calibration source - ADCX::connect_cal(source, true); - - ADCX::calibration_init(); - for _ in 0..ADC_CAL_CNT_MAX { - ADCX::set_init_code(0); - - // Trigger ADC sampling - ADCX::start_onetime_sample(); - - // Wait until ADC sampling is done - while !ADCX::is_done() {} - - let adc = ADCX::read_data() & ADC_VAL_MASK; - - ADCX::reset(); - - adc_sum += adc as u32; - adc_max = adc.max(adc_max); - adc_min = adc.min(adc_min); - } - - let cal_val = (adc_sum - adc_max as u32 - adc_min as u32) as u16 / (ADC_CAL_CNT_MAX - 2); - - // Disconnect calibration source - ADCX::connect_cal(source, false); - - cal_val - } -} - -#[doc(hidden)] -pub trait RegisterAccess { - /// Configure onetime sampling parameters - fn config_onetime_sample(channel: u8, attenuation: u8); - - /// Start onetime sampling - fn start_onetime_sample(); - - /// Check if sampling is done - fn is_done() -> bool; - - /// Read sample data - fn read_data() -> u16; - - /// Reset flags - fn reset(); - - /// Set up ADC hardware for calibration - fn calibration_init(); - - /// Set calibration parameter to ADC hardware - fn set_init_code(data: u16); -} - -#[cfg(adc_adc1)] -impl RegisterAccess for crate::peripherals::ADC1<'_> { - fn config_onetime_sample(channel: u8, attenuation: u8) { - APB_SARADC::regs().onetime_sample().modify(|_, w| unsafe { - w.saradc1_onetime_sample().set_bit(); - w.onetime_channel().bits(channel); - w.onetime_atten().bits(attenuation) - }); - } - - fn start_onetime_sample() { - APB_SARADC::regs() - .onetime_sample() - .modify(|_, w| w.onetime_start().set_bit()); - } - - fn is_done() -> bool { - APB_SARADC::regs().int_raw().read().adc1_done().bit() - } - - fn read_data() -> u16 { - APB_SARADC::regs() - .sar1data_status() - .read() - .saradc1_data() - .bits() as u16 - & 0xfff - } - - fn reset() { - // Clear ADC1 sampling done interrupt bit - APB_SARADC::regs() - .int_clr() - .write(|w| w.adc1_done().clear_bit_by_one()); - - // Disable ADC sampling - APB_SARADC::regs() - .onetime_sample() - .modify(|_, w| w.onetime_start().clear_bit()); - } - - fn calibration_init() { - // e.g. - // https://github.com/espressif/esp-idf/blob/800f141f94c0f880c162de476512e183df671307/components/hal/esp32c3/include/hal/adc_ll.h#L702 - regi2c::ADC_SAR1_DREF.write_field(1); - } - - fn set_init_code(data: u16) { - let [msb, lsb] = data.to_be_bytes(); - - regi2c::ADC_SAR1_INITIAL_CODE_HIGH.write_field(msb); - regi2c::ADC_SAR1_INITIAL_CODE_LOW.write_field(lsb); - } -} - -#[cfg(adc_adc1)] -impl super::CalibrationAccess for crate::peripherals::ADC1<'_> { - const ADC_CAL_CNT_MAX: u16 = ADC_CAL_CNT_MAX; - const ADC_CAL_CHANNEL: u16 = ADC_CAL_CHANNEL; - const ADC_VAL_MASK: u16 = ADC_VAL_MASK; - - fn enable_vdef(enable: bool) { - regi2c::ADC_SAR1_DREF.write_field(enable as _); - } - - fn connect_cal(source: AdcCalSource, enable: bool) { - match source { - AdcCalSource::Gnd => regi2c::ADC_SAR1_ENCAL_GND.write_field(enable as _), - #[cfg(not(esp32h2))] - AdcCalSource::Ref => regi2c::ADC_SAR1_ENCAL_REF.write_field(enable as _), - // For the ESP32-H2 ground and internal reference voltage are mutually exclusive and - // you can toggle between them. - // - // See: - #[cfg(esp32h2)] - AdcCalSource::Ref => regi2c::ADC_SAR1_ENCAL_GND.write_field(!enable as _), - } - } -} - -#[cfg(adc_adc2)] -impl RegisterAccess for crate::peripherals::ADC2<'_> { - fn config_onetime_sample(channel: u8, attenuation: u8) { - APB_SARADC::regs().onetime_sample().modify(|_, w| unsafe { - w.saradc2_onetime_sample().set_bit(); - w.onetime_channel().bits(channel); - w.onetime_atten().bits(attenuation) - }); - } - - fn start_onetime_sample() { - APB_SARADC::regs() - .onetime_sample() - .modify(|_, w| w.onetime_start().set_bit()); - } - - fn is_done() -> bool { - APB_SARADC::regs().int_raw().read().adc2_done().bit() - } - - fn read_data() -> u16 { - APB_SARADC::regs() - .sar2data_status() - .read() - .saradc2_data() - .bits() as u16 - & 0xfff - } - - fn reset() { - APB_SARADC::regs() - .int_clr() - .write(|w| w.adc2_done().clear_bit_by_one()); - - APB_SARADC::regs() - .onetime_sample() - .modify(|_, w| w.onetime_start().clear_bit()); - } - - fn calibration_init() { - regi2c::ADC_SAR2_DREF.write_field(1); - } - - fn set_init_code(data: u16) { - let [msb, lsb] = data.to_be_bytes(); - - regi2c::ADC_SAR2_INITIAL_CODE_HIGH.write_field(msb as _); - regi2c::ADC_SAR2_INITIAL_CODE_LOW.write_field(lsb as _); - } -} - -#[cfg(adc_adc2)] -impl super::CalibrationAccess for crate::peripherals::ADC2<'_> { - const ADC_CAL_CNT_MAX: u16 = ADC_CAL_CNT_MAX; - const ADC_CAL_CHANNEL: u16 = ADC_CAL_CHANNEL; - const ADC_VAL_MASK: u16 = ADC_VAL_MASK; - - fn enable_vdef(enable: bool) { - regi2c::ADC_SAR2_DREF.write_field(enable as _); - } - - fn connect_cal(source: AdcCalSource, enable: bool) { - match source { - AdcCalSource::Gnd => regi2c::ADC_SAR2_ENCAL_GND.write_field(enable as _), - AdcCalSource::Ref => regi2c::ADC_SAR2_ENCAL_REF.write_field(enable as _), - } - } -} - -/// Analog-to-Digital Converter peripheral driver. -pub struct Adc<'d, ADCX, Dm: crate::DriverMode> { - _adc: ADCX, - attenuations: [Option; NUM_ATTENS], - active_channel: Option, - _guard: GenericPeripheralGuard<{ Peripheral::ApbSarAdc as u8 }>, - _phantom: PhantomData<(Dm, &'d mut ())>, -} - -impl<'d, ADCX> Adc<'d, ADCX, Blocking> -where - ADCX: RegisterAccess + 'd, -{ - /// Configure a given ADC instance using the provided configuration, and - /// initialize the ADC for use - pub fn new(adc_instance: ADCX, config: AdcConfig) -> Self { - let guard = GenericPeripheralGuard::new(); - - APB_SARADC::regs().ctrl().modify(|_, w| unsafe { - w.start_force().set_bit(); - w.start().set_bit(); - w.sar_clk_gated().set_bit(); - w.xpd_sar_force().bits(0b11) - }); - - Adc { - _adc: adc_instance, - attenuations: config.attenuations, - active_channel: None, - _guard: guard, - _phantom: PhantomData, - } - } - - /// Reconfigures the ADC driver to operate in asynchronous mode. - pub fn into_async(mut self) -> Adc<'d, ADCX, Async> { - acquire_async_adc(); - self.set_interrupt_handler(adc_interrupt_handler); - - // Reset interrupt flags and disable oneshot reading to normalize state before - // entering async mode, otherwise there can be '0' readings, happening initially - // using ADC2 - ADCX::reset(); - - Adc { - _adc: self._adc, - attenuations: self.attenuations, - active_channel: self.active_channel, - _guard: self._guard, - _phantom: PhantomData, - } - } - - /// Request that the ADC begin a conversion on the specified pin - /// - /// This method takes an [AdcPin](super::AdcPin) reference, as it is - /// expected that the ADC will be able to sample whatever channel - /// underlies the pin. - pub fn read_oneshot( - &mut self, - pin: &mut super::AdcPin, - ) -> nb::Result - where - PIN: super::AdcChannel, - CS: super::AdcCalScheme, - { - if self.attenuations[pin.pin.adc_channel() as usize].is_none() { - panic!( - "Channel {} is not configured reading!", - pin.pin.adc_channel() - ); - } - - if let Some(active_channel) = self.active_channel { - // There is conversion in progress: - // - if it's for a different channel try again later - // - if it's for the given channel, go ahead and check progress - if active_channel != pin.pin.adc_channel() { - return Err(nb::Error::WouldBlock); - } - } else { - // If no conversions are in progress, start a new one for given channel - self.active_channel = Some(pin.pin.adc_channel()); - - // Set ADC unit calibration according used scheme for pin - ADCX::calibration_init(); - ADCX::set_init_code(pin.cal_scheme.adc_cal()); - - let channel = self.active_channel.unwrap(); - let attenuation = self.attenuations[channel as usize].unwrap() as u8; - ADCX::config_onetime_sample(channel, attenuation); - ADCX::start_onetime_sample(); - - // see https://github.com/espressif/esp-idf/blob/b4268c874a4cf8fcf7c0c4153cffb76ad2ddda4e/components/hal/adc_oneshot_hal.c#L105-L107 - // the delay might be a bit generous but longer delay seem to not cause problems - #[cfg(esp32c6)] - { - crate::rom::ets_delay_us(40); - ADCX::start_onetime_sample(); - } - } - - // Wait for ADC to finish conversion - let conversion_finished = ADCX::is_done(); - if !conversion_finished { - return Err(nb::Error::WouldBlock); - } - - // Get converted value - let converted_value = ADCX::read_data(); - ADCX::reset(); - - // Postprocess converted value according to calibration scheme used for pin - let converted_value = pin.cal_scheme.adc_val(converted_value); - - // There is a hardware limitation. If the APB clock frequency is high, the step - // of this reg signal: ``onetime_start`` may not be captured by the - // ADC digital controller (when its clock frequency is too slow). A rough - // estimate for this step should be at least 3 ADC digital controller - // clock cycle. - // - // This limitation will be removed in hardware future versions. - // We reset ``onetime_start`` in `reset` and assume enough time has passed until - // the next sample is requested. - - // Mark that no conversions are currently in progress - self.active_channel = None; - - Ok(converted_value) - } -} - -impl crate::private::Sealed for Adc<'_, ADCX, Blocking> {} - -impl InterruptConfigurable for Adc<'_, ADCX, Blocking> { - fn set_interrupt_handler(&mut self, handler: InterruptHandler) { - for core in crate::system::Cpu::other() { - crate::interrupt::disable(core, InterruptSource); - } - crate::interrupt::bind_handler(InterruptSource, handler); - } -} - -#[cfg(adc_adc1)] -impl super::AdcCalEfuse for crate::peripherals::ADC1<'_> { - fn init_code(atten: Attenuation) -> Option { - crate::efuse::rtc_calib_init_code(AdcCalibUnit::ADC1, atten) - } - - fn cal_mv(atten: Attenuation) -> u16 { - crate::efuse::rtc_calib_cal_mv(AdcCalibUnit::ADC1, atten) - } - - fn cal_code(atten: Attenuation) -> Option { - crate::efuse::rtc_calib_cal_code(AdcCalibUnit::ADC1, atten) - } - - #[cfg(any(esp32c5, esp32c6, esp32c61, esp32h2))] - fn cal_chan_compens(atten: Attenuation, channel: u8) -> Option { - crate::efuse::rtc_calib_get_chan_compens(AdcCalibUnit::ADC1, channel, atten) - } -} - -#[cfg(adc_adc2)] -impl super::AdcCalEfuse for crate::peripherals::ADC2<'_> { - fn init_code(atten: Attenuation) -> Option { - crate::efuse::rtc_calib_init_code(AdcCalibUnit::ADC2, atten) - } - - fn cal_mv(atten: Attenuation) -> u16 { - crate::efuse::rtc_calib_cal_mv(AdcCalibUnit::ADC2, atten) - } - - fn cal_code(atten: Attenuation) -> Option { - crate::efuse::rtc_calib_cal_code(AdcCalibUnit::ADC2, atten) - } -} - -impl<'d, ADCX> Adc<'d, ADCX, Async> -where - ADCX: RegisterAccess + 'd, -{ - /// Create a new instance in [crate::Blocking] mode. - pub fn into_blocking(self) -> Adc<'d, ADCX, Blocking> { - if release_async_adc() { - // Disable ADC interrupt on all cores if the last async ADC instance is disabled - for cpu in crate::system::Cpu::all() { - crate::interrupt::disable(cpu, InterruptSource); - } - } - Adc { - _adc: self._adc, - attenuations: self.attenuations, - active_channel: self.active_channel, - _guard: self._guard, - _phantom: PhantomData, - } - } - - /// Request that the ADC begin a conversion on the specified pin - /// - /// This method takes an [AdcPin](super::AdcPin) reference, as it is - /// expected that the ADC will be able to sample whatever channel - /// underlies the pin. - pub async fn read_oneshot(&mut self, pin: &mut super::AdcPin) -> u16 - where - ADCX: Instance, - PIN: super::AdcChannel, - CS: super::AdcCalScheme, - { - let channel = pin.pin.adc_channel(); - if self.attenuations[channel as usize].is_none() { - panic!("Channel {} is not configured reading!", channel); - } - - // Set ADC unit calibration according used scheme for pin - ADCX::calibration_init(); - ADCX::set_init_code(pin.cal_scheme.adc_cal()); - - let attenuation = self.attenuations[channel as usize].unwrap() as u8; - ADCX::config_onetime_sample(channel, attenuation); - ADCX::start_onetime_sample(); - - // Wait for ADC to finish conversion and get value - let adc_ready_future = AdcFuture::new(self); - adc_ready_future.await; - let converted_value = ADCX::read_data(); - - // There is a hardware limitation. If the APB clock frequency is high, the step - // of this reg signal: ``onetime_start`` may not be captured by the - // ADC digital controller (when its clock frequency is too slow). A rough - // estimate for this step should be at least 3 ADC digital controller - // clock cycle. - // - // This limitation will be removed in hardware future versions. - // We reset ``onetime_start`` in `reset` and assume enough time has passed until - // the next sample is requested. - - ADCX::reset(); - - // Postprocess converted value according to calibration scheme used for pin - pin.cal_scheme.adc_val(converted_value) - } -} - -#[cfg(all(adc_adc1, adc_adc2))] -static ASYNC_ADC_COUNT: AtomicU32 = AtomicU32::new(0); - -pub(super) fn acquire_async_adc() { - #[cfg(all(adc_adc1, adc_adc2))] - ASYNC_ADC_COUNT.fetch_add(1, Ordering::Relaxed); -} - -pub(super) fn release_async_adc() -> bool { - cfg_select! { - all(adc_adc1, adc_adc2) => ASYNC_ADC_COUNT.fetch_sub(1, Ordering::Relaxed) == 1, - _ => true, - } -} - -#[handler] -pub(crate) fn adc_interrupt_handler() { - let saradc = APB_SARADC::regs(); - let interrupt_status = saradc.int_st().read(); - - #[cfg(adc_adc1)] - if interrupt_status.adc1_done().bit_is_set() { - unsafe { handle_async(crate::peripherals::ADC1::steal()) } - } - - #[cfg(adc_adc2)] - if interrupt_status.adc2_done().bit_is_set() { - unsafe { handle_async(crate::peripherals::ADC2::steal()) } - } -} - -fn handle_async(_instance: ADCX) { - ADCX::waker().wake(); - ADCX::unlisten(); -} - -/// Enable asynchronous access. -pub trait Instance: crate::private::Sealed { - /// Enable the ADC interrupt - fn listen(); - - /// Disable the ADC interrupt - fn unlisten(); - - /// Clear the ADC interrupt - fn clear_interrupt(); - - /// Obtain the waker for the ADC interrupt - fn waker() -> &'static AtomicWaker; -} - -#[cfg(adc_adc1)] -impl Instance for crate::peripherals::ADC1<'_> { - fn listen() { - APB_SARADC::regs() - .int_ena() - .modify(|_, w| w.adc1_done().set_bit()); - } - - fn unlisten() { - APB_SARADC::regs() - .int_ena() - .modify(|_, w| w.adc1_done().clear_bit()); - } - - fn clear_interrupt() { - APB_SARADC::regs() - .int_clr() - .write(|w| w.adc1_done().clear_bit_by_one()); - } - - fn waker() -> &'static AtomicWaker { - static WAKER: AtomicWaker = AtomicWaker::new(); - - &WAKER - } -} - -#[cfg(adc_adc2)] -impl Instance for crate::peripherals::ADC2<'_> { - fn listen() { - APB_SARADC::regs() - .int_ena() - .modify(|_, w| w.adc2_done().set_bit()); - } - - fn unlisten() { - APB_SARADC::regs() - .int_ena() - .modify(|_, w| w.adc2_done().clear_bit()); - } - - fn clear_interrupt() { - APB_SARADC::regs() - .int_clr() - .write(|w| w.adc2_done().clear_bit_by_one()); - } - - fn waker() -> &'static AtomicWaker { - static WAKER: AtomicWaker = AtomicWaker::new(); - - &WAKER - } -} - -#[must_use = "futures do nothing unless you `.await` or poll them"] -pub(crate) struct AdcFuture { - phantom: PhantomData, - _wake_lock: WakeLock, -} - -impl AdcFuture { - pub fn new(_self: &super::Adc<'_, ADCX, Async>) -> Self { - Self { - phantom: PhantomData, - _wake_lock: WakeLock::new(), - } - } -} - -impl core::future::Future for AdcFuture { - type Output = (); - - fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { - if ADCX::is_done() { - ADCX::clear_interrupt(); - Poll::Ready(()) - } else { - ADCX::waker().register(cx.waker()); - ADCX::listen(); - Poll::Pending - } - } -} - -impl Drop for AdcFuture { - fn drop(&mut self) { - ADCX::unlisten(); - } -} diff --git a/esp-hal/src/analog/adc/xtensa.rs b/esp-hal/src/analog/adc/s2_s3.rs similarity index 72% rename from esp-hal/src/analog/adc/xtensa.rs rename to esp-hal/src/analog/adc/s2_s3.rs index 0acc341907c..082f53ac2f9 100644 --- a/esp-hal/src/analog/adc/xtensa.rs +++ b/esp-hal/src/analog/adc/s2_s3.rs @@ -8,7 +8,7 @@ use portable_atomic::{AtomicU32, Ordering}; use procmacros::{handler, ram}; pub use self::calibration::*; -use super::{AdcCalScheme, AdcCalSource, AdcChannel, AdcConfig, AdcPin, Attenuation}; +use super::{AdcCalScheme, AdcChannel, AdcConfig, AdcPin, Attenuation, Error}; use crate::{ Async, Blocking, @@ -28,13 +28,9 @@ pub(super) const NUM_ATTENS: usize = 10; cfg_select! { esp32s2 => { const ADC_VAL_MASK: u16 = 0x1fff; - const ADC_CAL_CNT_MAX: u16 = 32; - const ADC_CAL_CHANNEL: u16 = 15; } esp32s3 => { const ADC_VAL_MASK: u16 = 0xfff; - const ADC_CAL_CNT_MAX: u16 = 32; - const ADC_CAL_CHANNEL: u16 = 15; } } @@ -42,53 +38,97 @@ impl AdcConfig where ADCX: RegisterAccess, { - /// Calibrate ADC with specified attenuation and voltage source - pub fn adc_calibrate(atten: Attenuation, source: AdcCalSource) -> u16 + /// Measures the initial code that cancels the unit's zero-voltage offset at `atten`. + pub fn adc_calibrate(atten: Attenuation) -> u16 where ADCX: super::CalibrationAccess, { - let mut adc_max: u16 = 0; - let mut adc_min: u16 = u16::MAX; - let mut adc_sum: u32 = 0; + // This can be called without an `Adc`, so it cannot rely on `Adc::new` having powered up + // the unit. + let _guard = GenericPeripheralGuard::<{ Peripheral::ApbSarAdc as u8 }>::new(); + init_hardware::(); ADCX::enable_vdef(true); // Start sampling - ADCX::set_en_pad(ADCX::ADC_CAL_CHANNEL as u8); - ADCX::set_attenuation(ADCX::ADC_CAL_CHANNEL as usize, atten as u8); + ADCX::setup_calibration(atten); // Connect calibration source - ADCX::connect_cal(source, true); + ADCX::connect_gnd(true); ADCX::calibration_init(); - ADCX::set_init_code(0); - - for _ in 0..ADCX::ADC_CAL_CNT_MAX { - // Trigger ADC sampling + let cal_val = super::search_init_code::(|| { + // Clearing the done flag up front, rather than after the read, keeps a conversion left + // over from the previous code from being mistaken for this one's result. + ADCX::reset(); ADCX::start_sample(); - - // Wait until ADC sampling is done while !ADCX::is_done() {} - let adc = ADCX::read_data() & ADCX::ADC_VAL_MASK; - - ADCX::reset(); - - adc_sum += adc as u32; - adc_max = adc.max(adc_max); - adc_min = adc.min(adc_min); - } - - let cal_val = - (adc_sum - adc_max as u32 - adc_min as u32) as u16 / (ADCX::ADC_CAL_CNT_MAX - 2); + ADCX::read_data() & ADCX::ADC_VAL_MASK + }); + ADCX::reset(); // Disconnect calibration source - ADCX::connect_cal(source, false); + ADCX::connect_gnd(false); cal_val } } +/// Routes the unit to the RTC controller and powers it up. +/// +/// Writes nothing that depends on previous state, so it is safe to run more than once. +fn init_hardware() { + let sensors = SENS::regs(); + + // Set controller to RTC + ADCX::clear_dig_force(); + ADCX::set_start_force(); + ADCX::set_en_pad_force(); + sensors.sar_hall_ctrl().modify(|_, w| { + w.xpd_hall_force().set_bit(); + w.hall_phase_force().set_bit() + }); + + // Set power to SW power on + cfg_select! { + esp32s2 => { + sensors + .sar_meas1_ctrl1() + .modify(|_, w| w.rtc_saradc_clkgate_en().set_bit()); + } + _ => { + sensors + .sar_peri_clk_gate_conf() + .modify(|_, w| w.saradc_clk_en().set_bit()); + } + } + + sensors.sar_power_xpd_sar().modify(|_, w| unsafe { + w.sarclk_en().set_bit(); + w.force_xpd_sar().bits(0b11) + }); + + ADCX::set_sar_clk_div(); + + // disable AMP + sensors + .sar_meas1_ctrl1() + .modify(|_, w| unsafe { w.force_xpd_amp().bits(0b11) }); + sensors.sar_amp_ctrl3().modify(|_, w| unsafe { + w.amp_rst_fb_fsm().bits(0); + w.amp_short_ref_fsm().bits(0); + w.amp_short_ref_gnd_fsm().bits(0) + }); + sensors.sar_amp_ctrl1().modify(|_, w| unsafe { + w.sar_amp_wait1().bits(1); + w.sar_amp_wait2().bits(1) + }); + sensors + .sar_amp_ctrl2() + .modify(|_, w| unsafe { w.sar_amp_wait3().bits(1) }); +} + #[doc(hidden)] pub trait RegisterAccess { fn set_attenuation(channel: usize, attenuation: u8); @@ -105,19 +145,24 @@ pub trait RegisterAccess { fn start_sample(); - /// Check if sampling is done + /// Returns whether sampling is done. fn is_done() -> bool; - /// Read sample data + /// Reads sample data. fn read_data() -> u16; - /// Set up ADC hardware for calibration + /// Configures the SAR clock divider. + /// + /// See `adc_ll_set_sar_clk_div` and `ADC_LL_SAR_CLK_DIV_DEFAULT`. + fn set_sar_clk_div(); + + /// Sets up ADC hardware for calibration. fn calibration_init(); - /// Set calibration parameter to ADC hardware + /// Sets calibration parameter to ADC hardware. fn set_init_code(data: u16); - /// Reset flags + /// Resets flags. fn reset(); } @@ -187,7 +232,15 @@ impl RegisterAccess for crate::peripherals::ADC1<'_> { .bits() } - #[cfg(any(esp32s2, esp32s3))] + fn set_sar_clk_div() { + SENS::regs().sar_reader1_ctrl().modify(|_, w| unsafe { + cfg_select! { + esp32s2 => w.sar1_clk_div().bits(1), + _ => w.sar_sar1_clk_div().bits(1), + } + }); + } + fn calibration_init() { // https://github.com/espressif/esp-idf/blob/800f141f94c0f880c162de476512e183df671307/components/hal/esp32s3/include/hal/adc_ll.h#L833 // https://github.com/espressif/esp-idf/blob/800f141f94c0f880c162de476512e183df671307/components/hal/esp32s2/include/hal/adc_ll.h#L1145 @@ -225,19 +278,23 @@ fn meas1_busy() -> bool { } impl super::CalibrationAccess for crate::peripherals::ADC1<'_> { - const ADC_CAL_CNT_MAX: u16 = ADC_CAL_CNT_MAX; - const ADC_CAL_CHANNEL: u16 = ADC_CAL_CHANNEL; const ADC_VAL_MASK: u16 = ADC_VAL_MASK; fn enable_vdef(enable: bool) { regi2c::ADC_SAR1_DREF.write_field(enable as u8); } - fn connect_cal(source: AdcCalSource, enable: bool) { - match source { - AdcCalSource::Gnd => regi2c::ADC_SAR1_ENCAL_GND.write_field(enable as u8), - AdcCalSource::Ref => regi2c::ADC_SAR1_ENCAL_REF.write_field(enable as u8), - } + fn connect_gnd(enable: bool) { + regi2c::ADC_SAR1_ENCAL_GND.write_field(enable as u8); + } + + fn setup_calibration(atten: Attenuation) { + // With no pad selected the hardware falls back to channel 0's attenuation, so + // that is where `cal_setup` programs it. + SENS::regs() + .sar_meas1_ctrl2() + .modify(|_, w| unsafe { w.sar1_en_pad().bits(0) }); + Self::set_attenuation(0, atten as u8); } } @@ -307,7 +364,15 @@ impl RegisterAccess for crate::peripherals::ADC2<'_> { .bits() } - #[cfg(any(esp32s2, esp32s3))] + fn set_sar_clk_div() { + SENS::regs().sar_reader2_ctrl().modify(|_, w| unsafe { + cfg_select! { + esp32s2 => w.sar2_clk_div().bits(1), + _ => w.sar_sar2_clk_div().bits(1), + } + }); + } + fn calibration_init() { regi2c::ADC_SAR2_DREF.write_field(4); } @@ -335,27 +400,31 @@ impl RegisterAccess for crate::peripherals::ADC2<'_> { } impl super::CalibrationAccess for crate::peripherals::ADC2<'_> { - const ADC_CAL_CNT_MAX: u16 = ADC_CAL_CNT_MAX; - const ADC_CAL_CHANNEL: u16 = ADC_CAL_CHANNEL; const ADC_VAL_MASK: u16 = ADC_VAL_MASK; fn enable_vdef(enable: bool) { regi2c::ADC_SAR2_DREF.write_field(enable as u8); } - fn connect_cal(source: AdcCalSource, enable: bool) { - match source { - AdcCalSource::Gnd => regi2c::ADC_SAR2_ENCAL_GND.write_field(enable as u8), - AdcCalSource::Ref => regi2c::ADC_SAR2_ENCAL_REF.write_field(enable as u8), - } + fn connect_gnd(enable: bool) { + regi2c::ADC_SAR2_ENCAL_GND.write_field(enable as u8); + } + + fn setup_calibration(atten: Attenuation) { + SENS::regs() + .sar_meas2_ctrl2() + .modify(|_, w| unsafe { w.sar2_en_pad().bits(0) }); + Self::set_attenuation(0, atten as u8); } } /// Analog-to-Digital Converter peripheral driver. pub struct Adc<'d, ADC, Dm: crate::DriverMode> { _adc: ADC, + attenuations: [Option; NUM_ATTENS], + /// Hardware calibration code per attenuation, indexed by [`Attenuation`]. + init_codes: [u16; super::ATTENUATION_COUNT], active_channel: Option, - last_init_code: u16, _guard: GenericPeripheralGuard<{ Peripheral::ApbSarAdc as u8 }>, _phantom: PhantomData<(Dm, &'d mut ())>, } @@ -364,70 +433,37 @@ impl<'d, ADCX> Adc<'d, ADCX, Blocking> where ADCX: RegisterAccess + 'd, { - /// Configure a given ADC instance using the provided configuration, and - /// initialize the ADC for use - pub fn new(adc_instance: ADCX, config: AdcConfig) -> Self { + /// Creates a new ADC instance with the given configuration. + pub fn new(adc_instance: ADCX, config: AdcConfig) -> Result + where + ADCX: super::AdcCalEfuse + super::CalibrationAccess, + { let guard = GenericPeripheralGuard::new(); - let sensors = SENS::regs(); - // Set attenuation for pins let attenuations = config.attenuations; + init_hardware::(); + + let init_codes = super::hw_init_codes::(&attenuations); + for (channel, attenuation) in attenuations.iter().enumerate() { if let Some(attenuation) = attenuation { ADCX::set_attenuation(channel, *attenuation as u8); } } - // Set controller to RTC - ADCX::clear_dig_force(); - ADCX::set_start_force(); - ADCX::set_en_pad_force(); - sensors.sar_hall_ctrl().modify(|_, w| { - w.xpd_hall_force().set_bit(); - w.hall_phase_force().set_bit() - }); - - // Set power to SW power on - #[cfg(esp32s2)] - sensors - .sar_meas1_ctrl1() - .modify(|_, w| w.rtc_saradc_clkgate_en().set_bit()); - - #[cfg(esp32s3)] - sensors - .sar_peri_clk_gate_conf() - .modify(|_, w| w.saradc_clk_en().set_bit()); - - sensors.sar_power_xpd_sar().modify(|_, w| unsafe { - w.sarclk_en().set_bit(); - w.force_xpd_sar().bits(0b11) - }); - - // disable AMP - sensors - .sar_meas1_ctrl1() - .modify(|_, w| unsafe { w.force_xpd_amp().bits(0b11) }); - sensors.sar_amp_ctrl3().modify(|_, w| unsafe { - w.amp_rst_fb_fsm().bits(0); - w.amp_short_ref_fsm().bits(0); - w.amp_short_ref_gnd_fsm().bits(0) - }); - sensors.sar_amp_ctrl1().modify(|_, w| unsafe { - w.sar_amp_wait1().bits(1); - w.sar_amp_wait2().bits(1) - }); - sensors - .sar_amp_ctrl2() - .modify(|_, w| unsafe { w.sar_amp_wait3().bits(1) }); + // The bootloader runs conversions of its own to seed the RNG, so the done flag can + // already be set here and would make the first read return a stale result. + ADCX::reset(); - Adc { + Ok(Adc { _adc: adc_instance, + attenuations, + init_codes, active_channel: None, - last_init_code: 0, _guard: guard, _phantom: PhantomData, - } + }) } /// Reconfigures the ADC driver to operate in asynchronous mode. @@ -441,21 +477,27 @@ where Adc { _adc: self._adc, + attenuations: self.attenuations, + init_codes: self.init_codes, active_channel: self.active_channel, - last_init_code: self.last_init_code, _guard: self._guard, _phantom: PhantomData, } } - /// Start and wait for a conversion on the specified pin and return the - /// result - pub fn read_blocking(&mut self, pin: &mut AdcPin) -> u16 + /// Starts and waits for a conversion on the specified pin and returns the + /// result. + /// + /// # Errors + /// + /// Returns [`Error::ChannelNotConfigured`] if the channel was not configured in + /// [`AdcConfig`]. + pub fn read_blocking(&mut self, pin: &mut AdcPin) -> Result where PIN: AdcChannel, CS: AdcCalScheme, { - self.start_sample(pin); + self.start_sample(pin)?; // Wait for ADC to finish conversion while !ADCX::is_done() {} @@ -465,18 +507,23 @@ where ADCX::reset(); // Postprocess converted value according to calibration scheme used for pin - pin.cal_scheme.adc_val(converted_value) + Ok(pin.cal_scheme.adc_val(converted_value)) } - /// Request that the ADC begin a conversion on the specified pin + /// Requests that the ADC begin a conversion on the specified pin. /// - /// This method takes an [AdcPin](super::AdcPin) reference, as it is + /// Takes an [`AdcPin`](super::AdcPin) reference, as it is /// expected that the ADC will be able to sample whatever channel /// underlies the pin. + /// + /// # Errors + /// + /// Returns [`Error::ChannelNotConfigured`] if the channel was not configured in + /// [`AdcConfig`]. pub fn read_oneshot( &mut self, pin: &mut super::AdcPin, - ) -> nb::Result + ) -> nb::Result where PIN: super::AdcChannel, CS: super::AdcCalScheme, @@ -490,9 +537,8 @@ where } } else { // If no conversions are in progress, start a new one for given channel + self.start_sample(pin).map_err(nb::Error::Other)?; self.active_channel = Some(pin.pin.adc_channel()); - - self.start_sample(pin); } // Wait for ADC to finish conversion @@ -540,23 +586,25 @@ where ADCX: RegisterAccess + 'd, Dm: crate::DriverMode, { - fn start_sample(&mut self, pin: &mut AdcPin) + fn start_sample(&mut self, pin: &mut AdcPin) -> Result<(), Error> where PIN: AdcChannel, CS: AdcCalScheme, { - // Set ADC unit calibration according used scheme for pin - let init_code = pin.cal_scheme.adc_cal(); - if self.last_init_code != init_code { - ADCX::calibration_init(); - ADCX::set_init_code(init_code); - self.last_init_code = init_code; - } + let channel = pin.pin.adc_channel(); + let attenuation = super::channel_attenuation(&self.attenuations, channel)?; + + // Reprogrammed for every conversion: the regi2c block is shared with the PHY, + // so the code cannot be assumed to survive between reads. + ADCX::calibration_init(); + ADCX::set_init_code(self.init_codes[attenuation as usize]); - ADCX::set_en_pad(pin.pin.adc_channel()); + ADCX::set_en_pad(channel); ADCX::clear_start_sample(); ADCX::start_sample(); + + Ok(()) } } @@ -564,7 +612,7 @@ impl<'d, ADCX> Adc<'d, ADCX, Async> where ADCX: RegisterAccess + 'd, { - /// Creates a new instance in [`Blocking`] mode. + /// Reconfigures the ADC driver to operate in [`Blocking`] mode. pub fn into_blocking(self) -> Adc<'d, ADCX, Blocking> { if release_async_adc() { // Disable ADC interrupt on all cores if the last async ADC instance is disabled @@ -576,8 +624,9 @@ where } Adc { _adc: self._adc, + attenuations: self.attenuations, + init_codes: self.init_codes, active_channel: self.active_channel, - last_init_code: self.last_init_code, _guard: self._guard, _phantom: PhantomData, } @@ -585,22 +634,30 @@ where /// Starts a conversion on the specified pin and waits until it completes. /// - /// This method takes an [`AdcPin`] reference, as it is expected that the + /// Takes an [`AdcPin`] reference, as it is expected that the /// ADC will be able to sample whatever channel underlies the pin. - pub async fn read_oneshot(&mut self, pin: &mut AdcPin) -> u16 + /// + /// # Errors + /// + /// Returns [`Error::ChannelNotConfigured`] if the channel was not configured in + /// [`AdcConfig`]. + pub async fn read_oneshot( + &mut self, + pin: &mut AdcPin, + ) -> Result where ADCX: Instance, PIN: AdcChannel, CS: AdcCalScheme, { - self.start_sample(pin); + self.start_sample(pin)?; AdcFuture::new(self).await; let converted_value = ADCX::read_data(); ADCX::reset(); - pin.cal_scheme.adc_val(converted_value) + Ok(pin.cal_scheme.adc_val(converted_value)) } } @@ -635,18 +692,18 @@ fn handle_async(_instance: ADCX) { ADCX::waker().wake(); } -/// Enable asynchronous access. +/// Enables asynchronous access. pub trait Instance: crate::private::Sealed { - /// Enable the ADC interrupt + /// Enables the ADC interrupt. fn listen(); - /// Disable the ADC interrupt + /// Disables the ADC interrupt. fn unlisten(); - /// Clear the ADC interrupt + /// Clears the ADC interrupt. fn clear_interrupt(); - /// Obtain the waker for the ADC interrupt + /// Obtains the waker for the ADC interrupt. fn waker() -> &'static AtomicWaker; } @@ -784,13 +841,12 @@ impl Drop for AdcFuture { } } -#[cfg(any(esp32s2, esp32s3))] impl super::AdcCalEfuse for crate::peripherals::ADC1<'_> { fn init_code(atten: Attenuation) -> Option { crate::efuse::rtc_calib_init_code(AdcCalibUnit::ADC1, atten) } - fn cal_mv(atten: Attenuation) -> u16 { + fn cal_mv(atten: Attenuation) -> Option { crate::efuse::rtc_calib_cal_mv(AdcCalibUnit::ADC1, atten) } @@ -799,13 +855,12 @@ impl super::AdcCalEfuse for crate::peripherals::ADC1<'_> { } } -#[cfg(any(esp32s2, esp32s3))] impl super::AdcCalEfuse for crate::peripherals::ADC2<'_> { fn init_code(atten: Attenuation) -> Option { crate::efuse::rtc_calib_init_code(AdcCalibUnit::ADC2, atten) } - fn cal_mv(atten: Attenuation) -> u16 { + fn cal_mv(atten: Attenuation) -> Option { crate::efuse::rtc_calib_cal_mv(AdcCalibUnit::ADC2, atten) } diff --git a/esp-hal/src/analog/adc/s31.rs b/esp-hal/src/analog/adc/s31.rs index ee9a8dedb2d..ec1e4ec1348 100644 --- a/esp-hal/src/analog/adc/s31.rs +++ b/esp-hal/src/analog/adc/s31.rs @@ -10,7 +10,7 @@ use Interrupt::LP_ADC as InterruptSource; use portable_atomic::{AtomicU32, Ordering}; use procmacros::handler; -use super::{AdcCalScheme, AdcChannel, AdcConfig, AdcPin}; +use super::{AdcCalScheme, AdcChannel, AdcConfig, AdcPin, Error}; use crate::{ Async, Blocking, @@ -55,7 +55,7 @@ const TRIGGER_MODE_SW: u8 = 2; /// Trigger disabled. const TRIGGER_MODE_OFF: u8 = 0; -/// Power the SAR up by software, instead of leaving it to the FSM. +/// Powers the SAR up by software, instead of leaving it to the FSM. const FORCE_XPD_SAR_PU: u8 = 3; /// Clock divider for the digital controller. The divider is `CLK_DIV_NUM + 1`. @@ -67,7 +67,7 @@ const CLK_DIV_NUM: u8 = 4; /// Digital controller clock source select value for XTAL. const CLK_SRC_XTAL: u8 = 1; -/// Enable the reference generator shared by both units. +/// Enables the reference generator shared by both units. fn enable_refgen() { APB_SARADC::regs().ref_control().modify(|_, w| { w.rtc_xpd_refgen().set_bit(); @@ -76,38 +76,74 @@ fn enable_refgen() { }); } +// Powers both SAR units up. +// +// The power bits are shared, so both units come up together. +fn power_on_sar_units() { + enable_refgen(); + + APB_SARADC::regs() + .ctrl0() + .modify(|_, w| unsafe { w.xpd_sar1_force().bits(FORCE_XPD_SAR_PU) }); + APB_SARADC::regs() + .ctrl1() + .modify(|_, w| unsafe { w.xpd_sar2_force().bits(FORCE_XPD_SAR_PU) }); +} + #[doc(hidden)] pub trait RegisterAccess { - /// Power the SAR up and put the unit into single-conversion mode. - fn enable(); + /// Prepares the unit for a one-shot conversion. + fn prepare(); - /// Program the single-entry pattern table with the given channel. + /// Programs the single-entry pattern table with the given channel. fn program_pattern(channel: u8); - /// Trigger one conversion. + /// Triggers one conversion. fn start_sample(); - /// Check if sampling is done + /// Returns whether sampling is done. fn is_done() -> bool; - /// Read sample data + /// Reads sample data. fn read_data() -> u16; - /// Clear the done flag and stop triggering. + /// Clears the done flag and stops triggering. fn reset(); + + /// Starts one conversion on `channel`. + /// + /// The done flag does not have to be cleared first: [`Self::reset`] does that at the end of + /// every conversion, and once more while the driver is built. + fn start(channel: u8) { + Self::prepare(); + Self::program_pattern(channel); + Self::start_sample(); + } + + /// Runs one blocking conversion on `channel`. + fn sample(channel: u8) -> u16 { + Self::start(channel); + + while !Self::is_done() {} + + let converted_value = Self::read_data(); + Self::reset(); + converted_value + } } #[cfg(adc_adc1)] impl RegisterAccess for crate::peripherals::ADC1<'_> { - fn enable() { + fn prepare() { APB_SARADC::regs() .ctrl2() .modify(|_, w| w.timer_en().clear_bit()); - enable_refgen(); + power_on_sar_units(); - APB_SARADC::regs().ctrl0().modify(|_, w| unsafe { - w.xpd_sar1_force().bits(FORCE_XPD_SAR_PU); + // Only this unit's trigger mode is touched, so a driver for the other unit + // keeps its own state - `adc_oneshot_ll_enable` is per unit too. + APB_SARADC::regs().ctrl0().modify(|_, w| { w.sar1_continue_mode_en().clear_bit(); w.sar1_trigger_stop().set_bit() }); @@ -167,15 +203,14 @@ impl RegisterAccess for crate::peripherals::ADC1<'_> { #[cfg(adc_adc2)] impl RegisterAccess for crate::peripherals::ADC2<'_> { - fn enable() { + fn prepare() { APB_SARADC::regs() .ctrl2() .modify(|_, w| w.timer_en().clear_bit()); - enable_refgen(); + power_on_sar_units(); - APB_SARADC::regs().ctrl1().modify(|_, w| unsafe { - w.xpd_sar2_force().bits(FORCE_XPD_SAR_PU); + APB_SARADC::regs().ctrl1().modify(|_, w| { w.sar2_continue_mode_en().clear_bit(); w.sar2_trigger_stop().set_bit() }); @@ -234,23 +269,33 @@ impl RegisterAccess for crate::peripherals::ADC2<'_> { /// Analog-to-Digital Converter peripheral driver. pub struct Adc<'d, ADC, Dm: crate::DriverMode> { _adc: ADC, + configured: [bool; NUM_ATTENS], active_channel: Option, _guard: GenericPeripheralGuard<{ Peripheral::ApbSarAdc as u8 }>, _phantom: PhantomData<(Dm, &'d mut ())>, } +fn check_channel_configured(configured: &[bool; NUM_ATTENS], channel: u8) -> Result<(), Error> { + if configured[channel as usize] { + Ok(()) + } else { + Err(Error::ChannelNotConfigured(channel)) + } +} + impl<'d, ADCX> Adc<'d, ADCX, Blocking> where ADCX: RegisterAccess + 'd, { - /// Configure a given ADC instance using the provided configuration, and - /// initialize the ADC for use + /// Creates a new ADC instance with the given configuration. /// /// The ESP32-S31 SAR ADC has a single attenuation setting, so the /// attenuation given per pin has no effect. - pub fn new(adc_instance: ADCX, _config: AdcConfig) -> Self { + pub fn new(adc_instance: ADCX, config: AdcConfig) -> Result { let guard = GenericPeripheralGuard::new(); + let configured = config.attenuations.map(|attenuation| attenuation.is_some()); + // Select XTAL as the digital controller clock and divide it down. LP_PERI::regs().adc_ctrl().modify(|_, w| unsafe { w.lp_adc_clk_sel().bits(CLK_SRC_XTAL); @@ -262,14 +307,16 @@ where .ctrl_date() .modify(|_, w| w.clk_en().set_bit()); - ADCX::enable(); + ADCX::prepare(); + ADCX::reset(); - Adc { + Ok(Adc { _adc: adc_instance, + configured, active_channel: None, _guard: guard, _phantom: PhantomData, - } + }) } /// Reconfigures the ADC driver to operate in asynchronous mode. @@ -282,62 +329,70 @@ where Adc { _adc: self._adc, + configured: self.configured, active_channel: self.active_channel, _guard: self._guard, _phantom: PhantomData, } } - /// Start and wait for a conversion on the specified pin and return the - /// result + /// Starts and waits for a conversion on the specified pin and returns the + /// result. /// /// The result is in the range 0..=[`FULL_SCALE`], and an input tied to /// ground reads about [`ZERO_DIFF_CODE`]. - pub fn read_blocking(&mut self, pin: &mut AdcPin) -> u16 + /// + /// # Errors + /// + /// Returns [`Error::ChannelNotConfigured`] if the channel was not configured in + /// [`AdcConfig`]. + pub fn read_blocking(&mut self, pin: &mut AdcPin) -> Result where PIN: AdcChannel, CS: AdcCalScheme, { - ADCX::program_pattern(pin.pin.adc_channel()); - ADCX::start_sample(); - - while !ADCX::is_done() {} + let channel = pin.pin.adc_channel(); + check_channel_configured(&self.configured, channel)?; - let converted_value = ADCX::read_data(); - ADCX::reset(); - - converted_value + Ok(ADCX::sample(channel)) } - /// Request that the ADC begin a conversion on the specified pin + /// Requests that the ADC begin a conversion on the specified pin. /// - /// This method takes an [AdcPin](super::AdcPin) reference, as it is + /// Takes an [`AdcPin`](super::AdcPin) reference, as it is /// expected that the ADC will be able to sample whatever channel /// underlies the pin. /// /// The result is in the range 0..=[`FULL_SCALE`], and an input tied to /// ground reads about [`ZERO_DIFF_CODE`]. + /// + /// # Errors + /// + /// Returns [`Error::ChannelNotConfigured`] if the channel was not configured in + /// [`AdcConfig`]. pub fn read_oneshot( &mut self, pin: &mut super::AdcPin, - ) -> nb::Result + ) -> nb::Result where PIN: super::AdcChannel, CS: super::AdcCalScheme, { + let channel = pin.pin.adc_channel(); + check_channel_configured(&self.configured, channel).map_err(nb::Error::Other)?; + if let Some(active_channel) = self.active_channel { // There is conversion in progress: // - if it's for a different channel try again later // - if it's for the given channel, go ahead and check progress - if active_channel != pin.pin.adc_channel() { + if active_channel != channel { return Err(nb::Error::WouldBlock); } } else { // If no conversions are in progress, start a new one for given channel - self.active_channel = Some(pin.pin.adc_channel()); + self.active_channel = Some(channel); - ADCX::program_pattern(pin.pin.adc_channel()); - ADCX::start_sample(); + ADCX::start(channel); } if !ADCX::is_done() { @@ -369,7 +424,7 @@ impl<'d, ADCX> Adc<'d, ADCX, Async> where ADCX: RegisterAccess + 'd, { - /// Create a new instance in [crate::Blocking] mode. + /// Reconfigures the ADC driver to operate in [`Blocking`] mode. pub fn into_blocking(self) -> Adc<'d, ADCX, Blocking> { if release_async_adc() { // Disable the ADC interrupt on all cores once the last async instance goes away. @@ -379,35 +434,46 @@ where } Adc { _adc: self._adc, + configured: self.configured, active_channel: self.active_channel, _guard: self._guard, _phantom: PhantomData, } } - /// Start a conversion on the specified pin and wait for the result. + /// Starts a conversion on the specified pin and waits for the result. /// - /// This method takes an [AdcPin](super::AdcPin) reference, as it is + /// Takes an [`AdcPin`](super::AdcPin) reference, as it is /// expected that the ADC will be able to sample whatever channel /// underlies the pin. /// /// The result is in the range 0..=[`FULL_SCALE`], and an input tied to /// ground reads about [`ZERO_DIFF_CODE`]. - pub async fn read_oneshot(&mut self, pin: &mut super::AdcPin) -> u16 + /// + /// # Errors + /// + /// Returns [`Error::ChannelNotConfigured`] if the channel was not configured in + /// [`AdcConfig`]. + pub async fn read_oneshot( + &mut self, + pin: &mut super::AdcPin, + ) -> Result where ADCX: Instance, PIN: super::AdcChannel, CS: super::AdcCalScheme, { - ADCX::program_pattern(pin.pin.adc_channel()); - ADCX::start_sample(); + let channel = pin.pin.adc_channel(); + check_channel_configured(&self.configured, channel)?; + + ADCX::start(channel); AdcFuture::::new(self).await; let converted_value = ADCX::read_data(); ADCX::reset(); - converted_value + Ok(converted_value) } } @@ -441,18 +507,18 @@ fn handle_async(_instance: ADCX) { ADCX::unlisten(); } -/// Enable asynchronous access. +/// Enables asynchronous access. pub trait Instance: crate::private::Sealed { - /// Enable the ADC interrupt + /// Enables the ADC interrupt. fn listen(); - /// Disable the ADC interrupt + /// Disables the ADC interrupt. fn unlisten(); - /// Clear the ADC interrupt + /// Clears the ADC interrupt. fn clear_interrupt(); - /// Obtain the waker for the ADC interrupt + /// Obtains the waker for the ADC interrupt. fn waker() -> &'static AtomicWaker; } diff --git a/esp-hal/src/analog/dac.rs b/esp-hal/src/analog/dac.rs index 552f19fba3b..f8532a15c51 100644 --- a/esp-hal/src/analog/dac.rs +++ b/esp-hal/src/analog/dac.rs @@ -71,7 +71,7 @@ where T: Instance + 'd, T::Pin: AnalogPin + 'd, { - /// Construct a new instance of [`Dac`]. + /// Creates a new instance of [`Dac`]. pub fn new(dac: T, pin: T::Pin) -> Self { // TODO: Revert on drop. pin.set_analog(crate::private::Internal); diff --git a/esp-hal/src/assist_debug.rs b/esp-hal/src/assist_debug.rs index 633decd9cdd..3f912eda039 100644 --- a/esp-hal/src/assist_debug.rs +++ b/esp-hal/src/assist_debug.rs @@ -8,7 +8,7 @@ //! //! //! ## Configuration -//! While all the targets support program counter (PC) logging it's API is not +//! While all the targets support program counter (PC) logging, its API is not //! exposed here. Instead the ROM bootloader will always enable it and print the //! last seen PC (e.g. _Saved PC:0x42002ff2_). Make sure the reset was triggered //! by a TIMG watchdog. Not an RTC or SWD watchdog. @@ -35,7 +35,7 @@ pub struct DebugAssist<'d> { } impl<'d> DebugAssist<'d> { - /// Create a new instance in [crate::Blocking] mode. + /// Creates a new instance in [crate::Blocking] mode. pub fn new(debug_assist: ASSIST_DEBUG<'d>) -> Self { // NOTE: We should enable the debug assist, however, it's always enabled in ROM // code already. @@ -43,10 +43,9 @@ impl<'d> DebugAssist<'d> { DebugAssist { debug_assist } } - /// Register an interrupt handler for the Debug Assist module. + /// Registers an interrupt handler for the Debug Assist module. /// - /// Note that this will replace any previously registered interrupt - /// handlers. + /// Replaces any previously registered interrupt handlers. #[instability::unstable] pub fn set_interrupt_handler(&mut self, handler: InterruptHandler) { for core in crate::system::Cpu::other() { @@ -71,9 +70,9 @@ impl crate::interrupt::InterruptConfigurable for DebugAssist<'_> { #[cfg(assist_debug_has_sp_monitor)] impl DebugAssist<'_> { - /// Enable SP monitoring on main core. When the SP exceeds the - /// `lower_bound` or `upper_bound` threshold, the module will record the PC - /// pointer and generate an interrupt. + /// Enables SP monitoring on the given CPU. When the SP exceeds the + /// `lower_bound` or `upper_bound` threshold, the module records the PC + /// pointer and generates an interrupt. pub fn internal_sp_monitor(&mut self, cpu: usize, lower_bound: u32, upper_bound: u32) { let regs = self.regs().cpu(cpu); @@ -131,29 +130,29 @@ impl DebugAssist<'_> { self.regs().cpu(cpu).sp_pc().read().sp_pc().bits() } - /// Enable SP monitoring on main core. When the SP exceeds the - /// `lower_bound` or `upper_bound` threshold, the module will record the PC - /// pointer and generate an interrupt. + /// Enables SP monitoring on main core. When the SP exceeds the + /// `lower_bound` or `upper_bound` threshold, the module records the PC + /// pointer and generates an interrupt. pub fn enable_sp_monitor(&mut self, lower_bound: u32, upper_bound: u32) { self.internal_sp_monitor(0, lower_bound, upper_bound); } - /// Disable SP monitoring on main core. + /// Disables SP monitoring on main core. pub fn disable_sp_monitor(&mut self) { self.internal_disable_sp_monitor(0) } - /// Clear SP monitoring interrupt on main core. + /// Clears SP monitoring interrupt on main core. pub fn clear_sp_monitor_interrupt(&mut self) { self.internal_clear_sp_monitor_interrupt(0) } - /// Check, if SP monitoring interrupt is set on main core. + /// Returns whether SP monitoring interrupt is set on main core. pub fn is_sp_monitor_interrupt_set(&self) -> bool { self.internal_is_sp_monitor_interrupt_set(0) } - /// Get SP monitoring PC value on main core. + /// Returns SP monitoring PC value on main core. pub fn sp_monitor_pc(&self) -> u32 { self.internal_sp_monitor_pc(0) } @@ -161,29 +160,29 @@ impl DebugAssist<'_> { #[cfg(all(assist_debug_has_sp_monitor, multi_core))] impl<'d> DebugAssist<'d> { - /// Enable SP monitoring on secondary core. When the SP exceeds the - /// `lower_bound` or `upper_bound` threshold, the module will record the PC - /// pointer and generate an interrupt. + /// Enables SP monitoring on secondary core. When the SP exceeds the + /// `lower_bound` or `upper_bound` threshold, the module records the PC + /// pointer and generates an interrupt. pub fn enable_core1_sp_monitor(&mut self, lower_bound: u32, upper_bound: u32) { self.internal_sp_monitor(1, lower_bound, upper_bound); } - /// Disable SP monitoring on secondary core. + /// Disables SP monitoring on secondary core. pub fn disable_core1_sp_monitor(&mut self) { self.internal_disable_sp_monitor(1) } - /// Clear SP monitoring interrupt on secondary core. + /// Clears SP monitoring interrupt on secondary core. pub fn clear_core1_sp_monitor_interrupt(&mut self) { self.internal_clear_sp_monitor_interrupt(1) } - /// Check, if SP monitoring interrupt is set on secondary core. + /// Returns whether SP monitoring interrupt is set on secondary core. pub fn is_core1_sp_monitor_interrupt_set(&self) -> bool { self.internal_is_sp_monitor_interrupt_set(1) } - /// Get SP monitoring PC value on secondary core. + /// Returns SP monitoring PC value on secondary core. pub fn core1_sp_monitor_pc(&self) -> u32 { self.internal_sp_monitor_pc(1) } @@ -312,10 +311,15 @@ impl DebugAssist<'_> { } fn internal_region_monitor_pc(&self, cpu: usize) -> u32 { - self.regs().cpu(cpu).area_pc().read().area_pc().bits() + let regs = self.regs(); + let reg = cfg_select! { + esp32s3 => [regs.core_0_area_pc(), regs.core_1_area_pc()][cpu], + _ => regs.cpu(cpu).area_pc(), + }; + reg.read().area_pc().bits() } - /// Enable region monitoring of read/write performed by the main CPU in a + /// Enables region monitoring of read/write performed by the main CPU in a /// certain memory region0. Whenever the bus reads or writes in the /// specified memory region, an interrupt will be triggered. Two memory /// regions (region0, region1) can be monitored at the same time. @@ -329,22 +333,22 @@ impl DebugAssist<'_> { self.internal_enable_region0_monitor(0, lower_bound, upper_bound, reads, writes) } - /// Disable region0 monitoring on main core. + /// Disables region0 monitoring on main core. pub fn disable_region0_monitor(&mut self) { self.internal_disable_region0_monitor(0) } - /// Clear region0 monitoring interrupt on main core. + /// Clears region0 monitoring interrupt on main core. pub fn clear_region0_monitor_interrupt(&mut self) { self.internal_clear_region0_monitor_interrupt(0) } - /// Check, if region0 monitoring interrupt is set on main core. + /// Returns whether region0 monitoring interrupt is set on main core. pub fn is_region0_monitor_interrupt_set(&self) -> bool { self.internal_is_region0_monitor_interrupt_set(0) } - /// Enable region monitoring of read/write performed by the main CPU in a + /// Enables region monitoring of read/write performed by the main CPU in a /// certain memory region1. Whenever the bus reads or writes in the /// specified memory region, an interrupt will be triggered. pub fn enable_region1_monitor( @@ -357,22 +361,22 @@ impl DebugAssist<'_> { self.internal_enable_region1_monitor(0, lower_bound, upper_bound, reads, writes) } - /// Disable region1 monitoring on main core. + /// Disables region1 monitoring on main core. pub fn disable_region1_monitor(&mut self) { self.internal_disable_region1_monitor(0) } - /// Clear region1 monitoring interrupt on main core. + /// Clears region1 monitoring interrupt on main core. pub fn clear_region1_monitor_interrupt(&mut self) { self.internal_clear_region1_monitor_interrupt(0) } - /// Check, if region1 monitoring interrupt is set on main core. + /// Returns whether region1 monitoring interrupt is set on main core. pub fn is_region1_monitor_interrupt_set(&self) -> bool { self.internal_is_region1_monitor_interrupt_set(0) } - /// Get region monitoring PC value on main core. + /// Returns the region monitoring PC value on main core. pub fn region_monitor_pc(&self) -> u32 { self.internal_region_monitor_pc(0) } @@ -380,7 +384,7 @@ impl DebugAssist<'_> { #[cfg(all(assist_debug_has_region_monitor, multi_core))] impl DebugAssist<'_> { - /// Enable region monitoring of read/write performed by the secondary CPU in + /// Enables region monitoring of read/write performed by the secondary CPU in /// a certain memory region0. Whenever the bus reads or writes in the /// specified memory region, an interrupt will be triggered. pub fn enable_core1_region0_monitor( @@ -393,22 +397,22 @@ impl DebugAssist<'_> { self.internal_enable_region0_monitor(1, lower_bound, upper_bound, reads, writes) } - /// Disable region0 monitoring on secondary core. + /// Disables region0 monitoring on secondary core. pub fn disable_core1_region0_monitor(&mut self) { self.internal_disable_region0_monitor(1) } - /// Clear region0 monitoring interrupt on secondary core. + /// Clears region0 monitoring interrupt on secondary core. pub fn clear_core1_region0_monitor_interrupt(&mut self) { self.internal_clear_region0_monitor_interrupt(1) } - /// Check, if region0 monitoring interrupt is set on secondary core. + /// Returns whether region0 monitoring interrupt is set on secondary core. pub fn is_core1_region0_monitor_interrupt_set(&self) -> bool { self.internal_is_region0_monitor_interrupt_set(1) } - /// Enable region monitoring of read/write performed by the secondary CPU in + /// Enables region monitoring of read/write performed by the secondary CPU in /// a certain memory region1. Whenever the bus reads or writes in the /// specified memory region, an interrupt will be triggered. pub fn enable_core1_region1_monitor( @@ -421,22 +425,22 @@ impl DebugAssist<'_> { self.internal_enable_region1_monitor(1, lower_bound, upper_bound, reads, writes) } - /// Disable region1 monitoring on secondary core. + /// Disables region1 monitoring on secondary core. pub fn disable_core1_region1_monitor(&mut self) { self.internal_disable_region1_monitor(1) } - /// Clear region1 monitoring interrupt on secondary core. + /// Clears region1 monitoring interrupt on secondary core. pub fn clear_core1_region1_monitor_interrupt(&mut self) { self.internal_clear_region1_monitor_interrupt(1) } - /// Check, if region1 monitoring interrupt is set on secondary core. + /// Returns whether region1 monitoring interrupt is set on secondary core. pub fn is_core1_region1_monitor_interrupt_set(&self) -> bool { self.internal_is_region1_monitor_interrupt_set(1) } - /// Get region monitoring PC value on secondary core. + /// Returns the region monitoring PC value on secondary core. pub fn core1_region_monitor_pc(&self) -> u32 { self.internal_region_monitor_pc(1) } diff --git a/esp-hal/src/asynch.rs b/esp-hal/src/asynch.rs index 827ed031fbe..86d08ab8770 100644 --- a/esp-hal/src/asynch.rs +++ b/esp-hal/src/asynch.rs @@ -10,7 +10,7 @@ pub struct AtomicWaker { } impl AtomicWaker { - /// Create a new `AtomicWaker`. + /// Creates a new `AtomicWaker`. #[allow(clippy::new_without_default)] pub const fn new() -> Self { Self { @@ -18,13 +18,13 @@ impl AtomicWaker { } } - /// Register a waker. Overwrites the previous waker, if any. + /// Registers a waker. Overwrites the previous waker, if any. #[inline] pub fn register(&self, w: &Waker) { self.waker.register(w); } - /// Wake the registered waker, if any. + /// Wakes the registered waker, if any. #[crate::ram] pub fn wake(&self) { self.waker.wake(); diff --git a/esp-hal/src/canfd/asynch.rs b/esp-hal/src/canfd/asynch.rs new file mode 100644 index 00000000000..cc6dabef7f9 --- /dev/null +++ b/esp-hal/src/canfd/asynch.rs @@ -0,0 +1,44 @@ +//! Interrupt handling for the async CAN FD driver. +//! +//! Received frames stay in the hardware RX buffer until a task reads them, so +//! the handler only masks the source that fired and wakes the waiting task. + +use super::{CanFdInterrupt, Info, ll::Driver}; +use crate::asynch::AtomicWaker; + +/// Wakers for the tasks waiting on one controller. +#[doc(hidden)] +#[non_exhaustive] +pub struct State { + pub rx_waker: AtomicWaker, + pub tx_waker: AtomicWaker, +} + +impl State { + pub(super) const fn new() -> Self { + Self { + rx_waker: AtomicWaker::new(), + tx_waker: AtomicWaker::new(), + } + } +} + +const RX_SOURCES: u32 = CanFdInterrupt::RxNotEmpty.bit(); +const TX_SOURCES: u32 = CanFdInterrupt::TxDone.bit(); + +pub(super) fn handle(info: &Info, state: &State) { + let driver = Driver::new(info.register_block); + let status = driver.interrupt_status(); + + // The futures re-enable the sources they still need, so a level-triggered + // source cannot re-enter the handler before the task has run. + driver.disable_interrupts(status); + driver.clear_interrupts(status); + + if status & RX_SOURCES != 0 { + state.rx_waker.wake(); + } + if status & TX_SOURCES != 0 { + state.tx_waker.wake(); + } +} diff --git a/esp-hal/src/canfd/ll.rs b/esp-hal/src/canfd/ll.rs new file mode 100644 index 00000000000..e92885e03e4 --- /dev/null +++ b/esp-hal/src/canfd/ll.rs @@ -0,0 +1,1060 @@ +//! Low-level register access for the CTU CAN FD core. +//! +//! Ported from ESP-IDF's [`twaifd_ll.h`](https://github.com/espressif/esp-idf/blob/96f54947e08c196cf71c0588243dfc8e33807acc/components/esp_hal_twai/esp32c5/include/hal/twaifd_ll.h). +//! "TRM" below means the ESP32-C5 TRM v1.1, chapter 38. + +use embedded_can::{ExtendedId, Id, StandardId}; + +use crate::pac::twai0::{ + RegisterBlock, + mode_settings::{MODE_SETTINGS_SPEC, RTRTH_W}, + tx_priority::{TX_PRIORITY_SPEC, TXT1P_W}, +}; + +/// Words in a frame buffer: 1 format + 1 identifier + 2 timestamp + 16 data. +pub(super) const FRAME_WORDS: usize = 20; +/// Largest data length code of CAN FD. +pub(super) const MAX_DLC: u8 = 15; +/// Largest payload of a CAN FD frame, in bytes. +pub(super) const MAX_DATA_LEN: usize = 64; +/// Largest payload of a classic CAN frame, in bytes. +pub(super) const CLASSIC_MAX_DATA_LEN: usize = 8; + +/// Mask of the 11-bit base identifier. +pub(super) const STD_ID_MASK: u32 = 0x0000_07FF; +/// Mask of the 29-bit extended identifier. +pub(super) const EXT_ID_MASK: u32 = 0x1FFF_FFFF; +/// Bit position of the base identifier inside the identifier word. +const IDENTIFIER_BASE_SHIFT: u32 = 18; + +/// Largest value a register field of `width` bits can hold. +const fn field_max(width: u8) -> u8 { + ((1u16 << width) - 1) as u8 +} + +/// Largest retransmission limit the `RTRTH` field can hold. +pub const MAX_RETRANSMIT_LIMIT: u8 = field_max(>::WIDTH); + +/// Largest TX buffer priority the `TXTnP` fields can hold. +pub const MAX_TX_PRIORITY: u8 = field_max(>::WIDTH); + +/// Hardware limits for one set of bit timing parameters. +/// +/// The maxima are the register field widths from TRM 38.7; the minima come from +/// ESP-IDF's `twaifd_ll.h`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub struct TimingLimits { + /// Smallest value of each parameter, included. + pub min: Timing, + /// Largest value of each parameter, included. + pub max: Timing, +} + +/// Limits for the nominal (arbitration phase) bit timing. +pub const NOMINAL_TIMING_LIMITS: TimingLimits = TimingLimits { + min: Timing { + baud_rate_prescaler: 1, + propagation_segment: 1, + phase_segment_1: 0, + phase_segment_2: 1, + sync_jump_width: 1, + }, + max: Timing { + baud_rate_prescaler: 255, + propagation_segment: 127, + phase_segment_1: 63, + phase_segment_2: 63, + sync_jump_width: 31, + }, +}; + +/// Limits for the data phase bit timing. +pub const FD_TIMING_LIMITS: TimingLimits = TimingLimits { + min: Timing { + baud_rate_prescaler: 1, + propagation_segment: 1, + phase_segment_1: 0, + phase_segment_2: 1, + sync_jump_width: 1, + }, + max: Timing { + baud_rate_prescaler: 255, + propagation_segment: 63, + phase_segment_1: 31, + phase_segment_2: 31, + sync_jump_width: 31, + }, +}; + +/// Bit timing parameters for one phase (nominal or data). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub struct Timing { + /// Bit rate prescaler. Divides the function clock to produce the time quantum. + pub baud_rate_prescaler: u8, + /// Propagation segment, in time quanta. + pub propagation_segment: u8, + /// Phase segment 1, in time quanta. + pub phase_segment_1: u8, + /// Phase segment 2, in time quanta. + pub phase_segment_2: u8, + /// Synchronization jump width, in time quanta. + pub sync_jump_width: u8, +} + +impl Timing { + /// Returns whether every parameter fits the given limits. + /// + /// Also checks the two constraints of TRM 38.3.7.7, which are expressed in + /// system clock periods and therefore include the prescaler. + pub const fn is_valid(&self, limits: &TimingLimits) -> bool { + // Phase_Seg2 >= 2 minimal time quanta. + if (self.baud_rate_prescaler as u32) * (self.phase_segment_2 as u32) < 2 { + return false; + } + // Sync_Seg + Prop_Seg + Phase_Seg1 > 2 minimal time quanta. + if (self.baud_rate_prescaler as u32) + * (1 + self.propagation_segment as u32 + self.phase_segment_1 as u32) + <= 2 + { + return false; + } + + let (min, max) = (&limits.min, &limits.max); + self.baud_rate_prescaler >= min.baud_rate_prescaler + && self.baud_rate_prescaler <= max.baud_rate_prescaler + && self.propagation_segment >= min.propagation_segment + && self.propagation_segment <= max.propagation_segment + && self.phase_segment_1 >= min.phase_segment_1 + && self.phase_segment_1 <= max.phase_segment_1 + && self.phase_segment_2 >= min.phase_segment_2 + && self.phase_segment_2 <= max.phase_segment_2 + && self.sync_jump_width >= min.sync_jump_width + && self.sync_jump_width <= max.sync_jump_width + } + + /// Returns the total bit time in time quanta, including the sync segment. + pub const fn total_quanta(&self) -> u32 { + 1 + self.propagation_segment as u32 + + self.phase_segment_1 as u32 + + self.phase_segment_2 as u32 + } + + /// Returns the bit rate in bits per second for a given function clock. + pub const fn bit_rate(&self, clock_hz: u32) -> u32 { + clock_hz / (self.baud_rate_prescaler as u32 * self.total_quanta()) + } + + /// Returns the sample point in per mille of the bit time. + pub const fn sample_point_permille(&self) -> u32 { + (1 + self.propagation_segment as u32 + self.phase_segment_1 as u32) * 1000 + / self.total_quanta() + } +} + +/// Source used to place the secondary sample point (TRM 38.3.7.3). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[repr(u8)] +pub enum SspSource { + /// Measured transmitter delay plus the configured offset. + MeasuredPlusOffset = 0, + /// Secondary sampling is disabled. + Disabled = 1, + /// The configured offset alone. Not used by the driver. + #[allow(dead_code)] + OffsetOnly = 2, +} + +/// State of a single TX buffer (TRM figure 38.3-8). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum TxBufferState { + /// The buffer is not implemented by this core. + NotExist, + /// Armed for transmission. + Ready, + /// Currently being transmitted. + InProgress, + /// Abort requested while a transmission was in progress. + AbortInProgress, + /// Last transmission succeeded. + Ok, + /// Last transmission failed. + Failed, + /// Last transmission was aborted. + Aborted, + /// Ready to be filled by software. + Empty, + /// Hardware reported a state this driver does not model. + Unknown(u8), +} + +impl TxBufferState { + fn from_bits(bits: u8) -> Self { + // Codes from TRM 38.22; ESP-IDF's header only names 0x4/0x6/0x7. + match bits { + 0x0 => Self::NotExist, + 0x1 => Self::Ready, + 0x2 => Self::InProgress, + 0x3 => Self::AbortInProgress, + 0x4 => Self::Ok, + 0x6 => Self::Failed, + 0x7 => Self::Aborted, + 0x8 => Self::Empty, + other => Self::Unknown(other), + } + } + + /// Returns whether software can write to a buffer in this state (TRM 38.3.8). + pub fn is_writable(self) -> bool { + matches!(self, Self::Empty | Self::Ok | Self::Failed | Self::Aborted) + } +} + +/// Fault confinement state (TRM 38.3.10). +/// +/// The error warning limit is not a state of its own; see +/// [`super::CanFd::error_warning`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum ErrorState { + /// Takes part in the bus normally and signals errors actively. + Active, + /// Still communicates, but signals errors passively. + Passive, + /// Off the bus after TEC passed 255. + BusOff, +} + +/// Point in the frame at which a received frame is timestamped. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[repr(u8)] +pub enum TimestampPoint { + /// Sixth bit of the end-of-frame field, when the frame becomes valid. + EndOfFrame = 0, + /// Start-of-frame bit. + StartOfFrame = 1, +} + +/// Every bit of `MODE_SETTINGS` the driver configures, applied in one write. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] +pub(super) struct ModeSettings { + pub listen_only: bool, + pub self_test: bool, + pub loopback: bool, + pub fd_enabled: bool, + pub protocol_exception: bool, + pub rx_auto_increment: bool, + pub filters_enabled: bool, + pub bus_off_tx_fail: bool, + pub drop_request_frames: bool, + pub time_triggered_tx: bool, + /// Retransmission attempts, or `None` to retry forever. + pub retransmit_limit: Option, +} + +/// One of the three mask filter instances. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum MaskFilter { + /// Filter A. + A, + /// Filter B. + B, + /// Filter C. + C, +} + +/// Frame formats a filter accepts. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum FrameFormats { + /// Classic CAN frames only. + Classic, + /// CAN FD frames only. + Fd, + /// Both classic CAN and CAN FD frames. + #[default] + Both, +} + +/// Which kinds of frame a filter accepts, as the hardware encodes it. +/// +/// A filter with none of these set is disabled (TRM 38.3.9.8). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) struct FrameKinds { + classic_standard: bool, + classic_extended: bool, + fd_standard: bool, + fd_extended: bool, +} + +impl FrameKinds { + /// Accepts every kind of frame. + pub(super) const ALL: Self = Self { + classic_standard: true, + classic_extended: true, + fd_standard: true, + fd_extended: true, + }; + + /// Accepts nothing, which disables the filter. + pub(super) const NONE: Self = Self { + classic_standard: false, + classic_extended: false, + fd_standard: false, + fd_extended: false, + }; + + /// Accepts the given frame formats, with identifiers of one format only. + /// + /// The identifier format decides between base and extended, and only + /// classic and FD vary, as in ESP-IDF's + /// [`twai_hal_configure_mask_filter`](https://github.com/espressif/esp-idf/blob/96f54947e08c196cf71c0588243dfc8e33807acc/components/esp_hal_twai/twai_hal_v2.c#L118-L131). + pub(super) fn new(extended: bool, formats: FrameFormats) -> Self { + let classic = formats != FrameFormats::Fd; + let fd = formats != FrameFormats::Classic; + Self { + classic_standard: classic && !extended, + classic_extended: classic && extended, + fd_standard: fd && !extended, + fd_extended: fd && extended, + } + } + + fn bits(self) -> u32 { + (self.classic_standard as u32) + | ((self.classic_extended as u32) << 1) + | ((self.fd_standard as u32) << 2) + | ((self.fd_extended as u32) << 3) + } +} + +/// Reason the core last flagged a bus error (TRM 38.3.13.1). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum BusErrorKind { + /// The transmitted bit did not match the bit sampled back. + Bit, + /// The frame's CRC did not match. + Crc, + /// A fixed-form field held an illegal value. + Form, + /// No node acknowledged the frame. + Ack, + /// A stuffing rule was violated. + Stuff, + /// Hardware reported a code this driver does not model. + Unknown(u8), +} + +impl BusErrorKind { + fn from_bits(bits: u8) -> Self { + match bits { + 0 => Self::Bit, + 1 => Self::Crc, + 2 => Self::Form, + 3 => Self::Ack, + 4 => Self::Stuff, + other => Self::Unknown(other), + } + } +} + +/// Where in a frame the core last flagged an error (TRM 38.3.13.1). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum ErrorPosition { + /// Start of frame. + StartOfFrame, + /// Arbitration field. + Arbitration, + /// Control field. + Control, + /// Data field. + Data, + /// CRC field. + Crc, + /// CRC delimiter, ACK field or ACK delimiter. + Ack, + /// End-of-frame field. + EndOfFrame, + /// During an error frame. + ErrorFrame, + /// During an overload frame. + OverloadFrame, + /// Somewhere else. Also what the register reads out of reset. + Other, + /// Hardware reported a code this driver does not model. + Unknown(u8), +} + +impl ErrorPosition { + fn from_bits(bits: u8) -> Self { + match bits { + 0 => Self::StartOfFrame, + 1 => Self::Arbitration, + 2 => Self::Control, + 3 => Self::Data, + 4 => Self::Crc, + 5 => Self::Ack, + 6 => Self::EndOfFrame, + 7 => Self::ErrorFrame, + 8 => Self::OverloadFrame, + 31 => Self::Other, + other => Self::Unknown(other), + } + } +} + +/// Details of the last bus error the core captured. +/// +/// The registers behind this are not cleared, so the value is only meaningful +/// after a bus error. Out of reset it reads as [`BusErrorKind::Bit`] at +/// [`ErrorPosition::Other`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub struct ErrorCapture { + /// What went wrong. + pub kind: BusErrorKind, + /// Where in the frame it happened. + pub position: ErrorPosition, +} + +/// The format and identifier fields of a frame to transmit. +#[derive(Debug, Clone, Copy)] +pub(super) struct FrameHeader { + pub id: Id, + pub request: bool, + pub fd: bool, + pub bit_rate_switch: bool, + pub dlc: u8, +} + +/// A frame in the layout the hardware TX and RX buffers use. +/// +/// Word 0 is the format word, word 1 the identifier, words 2 and 3 the +/// timestamp, and words 4..20 the payload. +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) struct FrameBuffer { + words: [u32; FRAME_WORDS], +} + +// The payload is viewed as bytes in place, which relies on the word layout +// matching the wire order. +const _: () = core::assert!(cfg!(target_endian = "little")); + +impl FrameBuffer { + const DATA_WORD_OFFSET: usize = 4; + + pub(super) const fn new() -> Self { + Self { + words: [0; FRAME_WORDS], + } + } + + pub(super) fn dlc(&self) -> u8 { + (self.words[0] & 0xF) as u8 + } + + pub(super) fn is_request(&self) -> bool { + self.words[0] & (1 << 5) != 0 + } + + pub(super) fn is_extended(&self) -> bool { + self.words[0] & (1 << 6) != 0 + } + + pub(super) fn is_fd(&self) -> bool { + self.words[0] & (1 << 7) != 0 + } + + pub(super) fn is_bit_rate_switched(&self) -> bool { + self.words[0] & (1 << 9) != 0 + } + + pub(super) fn error_state_indicator(&self) -> bool { + self.words[0] & (1 << 10) != 0 + } + + /// Number of words that follow word 0 for this frame. + /// + /// The RWCNT field. ESP-IDF's `twaifd_struct.h` mislabels it as a + /// retransmission counter; its own RX loop uses it as a word count. + fn word_count(&self) -> u8 { + ((self.words[0] >> 11) & 0x1F) as u8 + } + + pub(super) fn id(&self) -> Id { + if self.is_extended() { + // Masked to the field width, so the value is always in range. + Id::Extended(unsafe { ExtendedId::new_unchecked(self.words[1] & EXT_ID_MASK) }) + } else { + let raw = (self.words[1] >> IDENTIFIER_BASE_SHIFT) & STD_ID_MASK; + Id::Standard(unsafe { StandardId::new_unchecked(raw as u16) }) + } + } + + pub(super) fn timestamp(&self) -> u64 { + (self.words[2] as u64) | ((self.words[3] as u64) << 32) + } + + /// Returns the payload length in bytes. + /// + /// Only CAN FD frames use the extended data length codes; a classic frame + /// with a DLC above 8 still carries 8 bytes. A request frame carries none. + pub(super) fn data_len(&self) -> usize { + if self.is_request() { + return 0; + } + let len = dlc_to_len(self.dlc()) as usize; + if self.is_fd() { + len + } else { + len.min(CLASSIC_MAX_DATA_LEN) + } + } + + /// Returns the payload length a request frame asks for, in bytes. + pub(super) fn requested_len(&self) -> usize { + (dlc_to_len(self.dlc()) as usize).min(CLASSIC_MAX_DATA_LEN) + } + + /// Returns the payload. + pub(super) fn data(&self) -> &[u8] { + let words = &self.words[Self::DATA_WORD_OFFSET..]; + // Little-endian words hold the payload in wire order, checked above. + let bytes = + unsafe { core::slice::from_raw_parts(words.as_ptr().cast::(), words.len() * 4) }; + &bytes[..self.data_len()] + } + + /// Builds a frame buffer ready to be written to a TX buffer. + pub(super) fn build(header: FrameHeader, data: &[u8]) -> Self { + debug_assert!(header.dlc <= MAX_DLC); + debug_assert!(data.len() <= MAX_DATA_LEN); + + let mut frame = Self::new(); + + let (id, extended) = match header.id { + Id::Standard(id) => ((u32::from(id.as_raw())) << IDENTIFIER_BASE_SHIFT, false), + Id::Extended(id) => (id.as_raw(), true), + }; + + frame.words[0] = (header.dlc as u32 & 0xF) + | ((header.request as u32) << 5) + | ((extended as u32) << 6) + | ((header.fd as u32) << 7) + | ((header.bit_rate_switch as u32) << 9); + frame.words[1] = id; + // Words 2 and 3 are the trigger time; zero transmits as soon as the + // bus is idle (TRM 38.3.8.2). + + for (i, &byte) in data.iter().enumerate() { + frame.words[Self::DATA_WORD_OFFSET + i / 4] |= (byte as u32) << (8 * (i % 4)); + } + + frame + } +} + +/// Converts a data length code to a payload length in bytes. +pub(super) const fn dlc_to_len(dlc: u8) -> u8 { + match dlc { + 0..=8 => dlc, + 9..=12 => (dlc - 8) * 4 + 8, + 13 => 32, + 14 => 48, + _ => 64, + } +} + +/// Converts a payload length in bytes to the smallest data length code that +/// can carry it. +pub(super) const fn len_to_dlc(len: u8) -> u8 { + match len { + 0..=8 => len, + 9..=24 => (len - 8).div_ceil(4) + 8, + 25..=32 => (len - 24).div_ceil(8) + 12, + 33..=64 => (len - 32).div_ceil(16) + 13, + _ => MAX_DLC, + } +} + +/// Register access for one CAN FD controller. +pub(super) struct Driver { + regs: *const RegisterBlock, +} + +// The pointer addresses a memory-mapped register block. +unsafe impl Send for Driver {} +unsafe impl Sync for Driver {} + +impl Driver { + pub(super) fn new(regs: *const RegisterBlock) -> Self { + Self { regs } + } + + fn r(&self) -> &RegisterBlock { + unsafe { &*self.regs } + } + + pub(super) fn device_id(&self) -> u16 { + self.r().device_id_version().read().device_id().bits() + } + + /// IP core version as `(major, minor)`. + pub(super) fn version(&self) -> (u8, u8) { + let r = self.r().device_id_version().read(); + (r.ver_major().bits(), r.ver_minor().bits()) + } + + /// Issues a soft reset. No wait is required afterwards (TRM 38.3.2). + pub(super) fn reset(&self) { + self.r().mode_settings().modify(|_, w| w.rst().set_bit()); + } + + pub(super) fn enable(&self, enable: bool) { + self.r().mode_settings().modify(|_, w| w.ena().bit(enable)); + } + + pub(super) fn is_enabled(&self) -> bool { + self.r().mode_settings().read().ena().bit_is_set() + } + + /// Applies every mode setting in one write. Only valid while disabled. + pub(super) fn apply_mode_settings(&self, settings: &ModeSettings) { + debug_assert!(!self.is_enabled(), "mode may only change while disabled"); + + self.r().mode_settings().modify(|_, w| { + // Listen-only needs `rom` and `acf` alongside `bmm` on the + // ESP32-C5 (errata 0v2 issue 5, esp-idf#17461). + w.bmm().bit(settings.listen_only); + w.rom().bit(settings.listen_only); + w.acf().bit(settings.listen_only); + w.stm().bit(settings.self_test); + w.ilbp().bit(settings.loopback); + w.fde().bit(settings.fd_enabled); + w.pex().bit(settings.protocol_exception); + w.rxbam().bit(settings.rx_auto_increment); + w.afm().bit(settings.filters_enabled); + w.tbfbo().bit(settings.bus_off_tx_fail); + w.fdrf().bit(settings.drop_request_frames); + w.tttm().bit(settings.time_triggered_tx); + match settings.retransmit_limit { + Some(limit) => { + w.rtrle().set_bit(); + unsafe { w.rtrth().bits(limit) } + } + None => w.rtrle().clear_bit(), + } + }); + } + + pub(super) fn set_nominal_timing(&self, timing: &Timing) { + self.r().btr().write(|w| unsafe { + w.brp().bits(timing.baud_rate_prescaler); + w.prop().bits(timing.propagation_segment); + w.ph1().bits(timing.phase_segment_1); + w.ph2().bits(timing.phase_segment_2); + w.sjw().bits(timing.sync_jump_width) + }); + } + + pub(super) fn set_fd_timing(&self, timing: &Timing) { + self.r().btr_fd().write(|w| unsafe { + w.brp_fd().bits(timing.baud_rate_prescaler); + w.prop_fd().bits(timing.propagation_segment); + w.ph1_fd().bits(timing.phase_segment_1); + w.ph2_fd().bits(timing.phase_segment_2); + w.sjw_fd().bits(timing.sync_jump_width) + }); + } + + /// Places the secondary sample point. `offset` is in function clock cycles. + pub(super) fn set_secondary_sample_point(&self, source: SspSource, offset: u8) { + self.r().trv_delay_ssp_cfg().modify(|_, w| unsafe { + w.ssp_src().bits(source as u8); + w.ssp_offset().bits(offset) + }); + } + + /// Transmitter delay measured by the hardware, in function clock cycles. + pub(super) fn transmitter_delay(&self) -> u8 { + self.r().trv_delay_ssp_cfg().read().trv_delay_value().bits() + } + + pub(super) fn tx_buffer_count(&self) -> u8 { + self.r() + .tx_command_txtb_info() + .read() + .txt_buffer_count() + .bits() + } + + /// State of one TX buffer. `index` must be below [`Self::tx_buffer_count`]. + pub(super) fn tx_buffer_state(&self, index: u8) -> TxBufferState { + debug_assert!(index < self.tx_buffer_count()); + + let raw = self.r().tx_status().read().bits(); + TxBufferState::from_bits(((raw >> (4 * index as u32)) & 0xF) as u8) + } + + /// Writes a frame into a TX buffer, which must be writable. + pub(super) fn write_tx_buffer(&self, index: u8, frame: &FrameBuffer) { + debug_assert!(index < 4, "the PAC models four TX buffers"); + let regs = self.r(); + for (i, &word) in frame.words.iter().enumerate() { + match index { + 0 => regs.txtb1_data(i).write(|w| unsafe { w.data().bits(word) }), + 1 => regs.txtb2_data(i).write(|w| unsafe { w.data().bits(word) }), + 2 => regs.txtb3_data(i).write(|w| unsafe { w.data().bits(word) }), + _ => regs.txtb4_data(i).write(|w| unsafe { w.data().bits(word) }), + }; + } + } + + pub(super) fn set_tx_ready(&self, index: u8) { + self.tx_command(index, |w| w.txcr().set_bit()); + } + + pub(super) fn set_tx_abort(&self, index: u8) { + self.tx_command(index, |w| w.txca().set_bit()); + } + + pub(super) fn set_tx_empty(&self, index: u8) { + self.tx_command(index, |w| w.txce().set_bit()); + } + + fn tx_command(&self, index: u8, cmd: F) + where + F: FnOnce( + &mut crate::pac::twai0::tx_command_txtb_info::W, + ) -> &mut crate::pac::twai0::tx_command_txtb_info::W, + { + self.r().tx_command_txtb_info().write(|w| { + cmd(w); + match index { + 0 => w.txb1().set_bit(), + 1 => w.txb2().set_bit(), + 2 => w.txb3().set_bit(), + 3 => w.txb4().set_bit(), + 4 => w.txb5().set_bit(), + 5 => w.txb6().set_bit(), + 6 => w.txb7().set_bit(), + _ => w.txb8().set_bit(), + } + }); + } + + pub(super) fn set_tx_priority(&self, index: u8, priority: u8) { + self.r().tx_priority().modify(|_, w| unsafe { + match index { + 0 => w.txt1p().bits(priority), + 1 => w.txt2p().bits(priority), + 2 => w.txt3p().bits(priority), + 3 => w.txt4p().bits(priority), + 4 => w.txt5p().bits(priority), + 5 => w.txt6p().bits(priority), + 6 => w.txt7p().bits(priority), + _ => w.txt8p().bits(priority), + } + }); + } + + /// Size of the RX buffer, in 32-bit words. + pub(super) fn rx_buffer_size(&self) -> u16 { + self.r().rx_mem_info().read().rx_buff_size().bits() + } + + /// Free space in the RX buffer, in 32-bit words. + pub(super) fn rx_free_words(&self) -> u16 { + self.r().rx_mem_info().read().rx_free().bits() + } + + pub(super) fn rx_frame_count(&self) -> u16 { + self.r().rx_status_rx_settings().read().rxfrc().bits() + } + + /// Whether the RX buffer has dropped a frame for lack of space (TRM 38.3.9.4). + pub(super) fn rx_overrun(&self) -> bool { + self.r().status().read().dor().bit_is_set() + } + + /// Whether an error counter has reached the error warning limit. + pub(super) fn error_warning(&self) -> bool { + self.r().status().read().ewl().bit_is_set() + } + + pub(super) fn set_timestamp_point(&self, point: TimestampPoint) { + self.r() + .rx_status_rx_settings() + .modify(|_, w| w.rtsop().bit(point == TimestampPoint::StartOfFrame)); + } + + /// Reads one frame out of the RX buffer. Requires RX auto-increment mode. + pub(super) fn read_rx_frame(&self) -> FrameBuffer { + let mut frame = FrameBuffer::new(); + let rx_data = self.r().rx_data(); + + frame.words[0] = rx_data.read().bits(); + let remaining = (frame.word_count() as usize).min(FRAME_WORDS - 1); + for word in frame.words[1..=remaining].iter_mut() { + *word = rx_data.read().bits(); + } + + frame + } + + pub(super) fn flush_rx(&self) { + self.r().command().write(|w| w.rrb().set_bit()); + } + + pub(super) fn clear_overrun(&self) { + self.r().command().write(|w| w.cdo().set_bit()); + } + + /// Requests error counter reset, which is how a bus-off node rejoins. + /// + /// TRM register 38.3 says this has no effect outside bus-off. Measured on an + /// ESP32-C5, a request made while error-active is remembered and + /// reintegrates the controller the next time it goes bus-off, so callers + /// must check the state themselves. + pub(super) fn request_bus_off_recovery(&self) { + self.r().command().write(|w| w.ercrst().set_bit()); + } + + pub(super) fn reset_traffic_counters(&self) { + self.r() + .command() + .write(|w| w.rxfcrst().set_bit().txfcrst().set_bit()); + } + + pub(super) fn rec(&self) -> u16 { + self.r().rec_tec().read().rec_val().bits() + } + + pub(super) fn tec(&self) -> u16 { + self.r().rec_tec().read().tec_val().bits() + } + + pub(super) fn error_state(&self) -> ErrorState { + let r = self.r().ewl_erp_fault_state().read(); + // More than one bit can be set while a transition settles. + if r.bof().bit_is_set() { + ErrorState::BusOff + } else if r.erp().bit_is_set() { + ErrorState::Passive + } else { + ErrorState::Active + } + } + + /// Sets the error warning limit. Only writable in test mode (TRM 38.3.10). + pub(super) fn set_error_warning_limit(&self, limit: u8) { + debug_assert!(self.r().mode_settings().read().tstm().bit_is_set()); + self.r() + .ewl_erp_fault_state() + .modify(|_, w| unsafe { w.ew_limit().bits(limit) }); + } + + /// Enables test mode. Only valid while the controller is disabled. + pub(super) fn enable_test_mode(&self, enable: bool) { + debug_assert!(!self.is_enabled()); + self.r().mode_settings().modify(|_, w| w.tstm().bit(enable)); + } + + pub(super) fn enable_interrupts(&self, mask: u32) { + self.r().int_ena_set().write(|w| unsafe { w.bits(mask) }); + } + + pub(super) fn disable_interrupts(&self, mask: u32) { + self.r().int_ena_clr().write(|w| unsafe { w.bits(mask) }); + } + + pub(super) fn interrupt_status(&self) -> u32 { + self.r().int_stat().read().bits() + } + + pub(super) fn clear_interrupts(&self, mask: u32) { + self.r().int_stat().write(|w| unsafe { w.bits(mask) }); + } + + pub(super) fn rx_traffic_counter(&self) -> u32 { + self.r().rx_fr_ctr().read().val().bits() + } + + pub(super) fn tx_traffic_counter(&self) -> u32 { + self.r().tx_fr_ctr().read().tx_ctr_val().bits() + } + + /// Sets a mask filter's acceptance code and mask. + /// + /// The identifier word holds a base identifier in bits 28..18 and an + /// extended one in bits 28..0 (TRM 38.3.9.9). + pub(super) fn set_mask_filter(&self, filter: MaskFilter, extended: bool, code: u32, mask: u32) { + let (code, mask) = if extended { + (code & EXT_ID_MASK, mask & EXT_ID_MASK) + } else { + ( + (code & STD_ID_MASK) << IDENTIFIER_BASE_SHIFT, + (mask & STD_ID_MASK) << IDENTIFIER_BASE_SHIFT, + ) + }; + + match filter { + MaskFilter::A => { + self.r() + .filter_a_mask() + .write(|w| unsafe { w.bit_mask_a_val().bits(mask) }); + self.r() + .filter_a_val() + .write(|w| unsafe { w.bit_val_a_val().bits(code) }); + } + MaskFilter::B => { + self.r() + .filter_b_mask() + .write(|w| unsafe { w.bit_mask_b_val().bits(mask) }); + self.r() + .filter_b_val() + .write(|w| unsafe { w.bit_val_b_val().bits(code) }); + } + MaskFilter::C => { + self.r() + .filter_c_mask() + .write(|w| unsafe { w.bit_mask_c_val().bits(mask) }); + self.r() + .filter_c_val() + .write(|w| unsafe { w.bit_val_c_val().bits(code) }); + } + } + } + + /// Sets the identifier range the range filter accepts. + /// + /// For a base identifier range the low 18 bits of the upper bound are set, + /// so the whole base identifier is covered (TRM 38.3.9.10). + pub(super) fn set_range_filter(&self, extended: bool, low: u32, high: u32) { + let (low, high) = if extended { + (low & EXT_ID_MASK, high & EXT_ID_MASK) + } else { + ( + (low & STD_ID_MASK) << IDENTIFIER_BASE_SHIFT, + ((high & STD_ID_MASK) << IDENTIFIER_BASE_SHIFT) | 0x3FFFF, + ) + }; + self.r() + .filter_ran_low() + .write(|w| unsafe { w.bit_ran_low_val().bits(low) }); + self.r() + .filter_ran_high() + .write(|w| unsafe { w.bit_ran_high_val().bits(high) }); + } + + /// Sets which frame kinds each filter accepts. + pub(super) fn set_filter_kinds( + &self, + a: FrameKinds, + b: FrameKinds, + c: FrameKinds, + range: FrameKinds, + ) { + let bits = a.bits() | (b.bits() << 4) | (c.bits() << 8) | (range.bits() << 12); + // The upper half of the register is read-only status. + self.r() + .filter_control_filter_status() + .write(|w| unsafe { w.bits(bits) }); + } + + pub(super) fn error_capture(&self) -> ErrorCapture { + let r = self.r().err_capt_retr_ctr_alc_ts_info().read(); + ErrorCapture { + kind: BusErrorKind::from_bits(r.err_type().bits()), + position: ErrorPosition::from_bits(r.err_pos().bits()), + } + } + + pub(super) fn retransmit_count(&self) -> u8 { + self.r() + .err_capt_retr_ctr_alc_ts_info() + .read() + .retr_ctr_val() + .bits() + } + + pub(super) fn nominal_error_count(&self) -> u16 { + self.r().err_norm_err_fd().read().err_norm_val().bits() + } + + pub(super) fn fd_error_count(&self) -> u16 { + self.r().err_norm_err_fd().read().err_fd_val().bits() + } + + pub(super) fn timer_bit_width(&self) -> u8 { + self.r() + .err_capt_retr_ctr_alc_ts_info() + .read() + .ts_bits() + .bits() + + 1 + } + + pub(super) fn timer_enable_config_clock(&self, enable: bool) { + self.r() + .timer_clk_en() + .modify(|_, w| w.clk_en().bit(enable)); + } + + pub(super) fn timer_enable(&self, enable: bool) { + self.r().timer_cfg().modify(|_, w| w.timer_ce().bit(enable)); + } + + pub(super) fn timer_count_up(&self, up: bool) { + self.r().timer_cfg().modify(|_, w| w.timer_up_dn().bit(up)); + } + + /// Sets the timer prescaler to `divider` function clock cycles per tick. + /// + /// TRM 38.13 describes `TIMER_STEP` as a count step; measured on an + /// ESP32-C5 it is a divider of `TIMER_STEP + 1`. + pub(super) fn timer_set_divider(&self, divider: u16) { + debug_assert!(divider >= 1); + self.r() + .timer_cfg() + .modify(|_, w| unsafe { w.timer_step().bits(divider - 1) }); + } + + pub(super) fn timer_clear(&self) { + self.r().timer_cfg().modify(|_, w| w.timer_clr().set_bit()); + } + + /// Makes the counter free-running over its whole width (TRM 38.14 to 38.17). + pub(super) fn timer_set_free_running(&self) { + self.r() + .timer_ld_val_l() + .write(|w| unsafe { w.timer_ld_val_l().bits(0) }); + self.r() + .timer_ld_val_h() + .write(|w| unsafe { w.timer_ld_val_h().bits(0) }); + self.r() + .timer_ct_val_l() + .write(|w| unsafe { w.timer_ct_val_l().bits(u32::MAX) }); + self.r() + .timer_ct_val_h() + .write(|w| unsafe { w.timer_ct_val_h().bits(u32::MAX) }); + } + + pub(super) fn timer_count(&self) -> u64 { + // Re-read the high word if the low word wrapped between the reads. + loop { + let high = self.r().timestamp_high().read().bits(); + let low = self.r().timestamp_low().read().bits(); + if self.r().timestamp_high().read().bits() == high { + return ((high as u64) << 32) | low as u64; + } + } + } +} diff --git a/esp-hal/src/canfd/mod.rs b/esp-hal/src/canfd/mod.rs new file mode 100644 index 00000000000..6d409a58102 --- /dev/null +++ b/esp-hal/src/canfd/mod.rs @@ -0,0 +1,2335 @@ +//! # Controller Area Network Flexible Data-Rate (CAN FD) +//! +//! ## Overview +//! +//! The CAN FD controller is a CTU CAN FD core. It is a different peripheral +//! from the classic two-wire automotive interface (TWAI) controller. It +//! supports classic CAN 2.0 frames and CAN FD frames. A CAN FD frame carries up +//! to 64 bytes of payload and can switch to a faster bit rate for its data +//! phase. +//! +//! The peripheral needs an external transceiver to drive a real bus. +#![doc = concat!("[ESP-IDF documentation](https://docs.espressif.com/projects/esp-idf/en/latest/", chip!(), "/api-reference/peripherals/twai.html)")] +//! ## Configuration +//! +//! [`Config`] selects the bus participation [`Mode`], the function +//! [`ClockSource`], and the bit [`Timing`] of the arbitration and data phases. +//! The controller stays off the bus until [`CanFd::start`] is called, so the +//! pins can be assigned first. +//! +//! Received frames pass through three mask filters and one range filter; see +//! [`MaskFilterConfig`] and [`RangeFilterConfig`]. Each filter matches either +//! standard or extended identifiers, and accepts classic CAN frames, CAN FD +//! frames or both, as set by [`FrameFormats`]. +//! +//! ## Usage +//! +//! [`CanFd::into_async`] converts the driver into an async driver. Received +//! frames stay in the hardware RX buffer until they are read, so +//! [`CanFd::receive_async`] is cancel-safe and the driver needs no software +//! frame queue. +//! +//! Identifiers are the [`embedded_can`] types. [`ClassicFrame`] implements +//! [`embedded_can::Frame`] and [`BusErrorKind`] implements +//! [`embedded_can::Error`], for code written against those traits. +//! +//! ## Examples +//! +//! ### Sending a CAN FD frame +//! +//! ```rust, no_run +#![doc = crate::before_snippet!()] +//! use esp_hal::canfd::{CanFd, Config, Frame, StandardId}; +//! +//! let mut canfd = CanFd::new(peripherals.TWAI0, Config::default())? +//! .with_rx(peripherals.GPIO9) +//! .with_tx(peripherals.GPIO8); +//! canfd.start()?; +//! +//! // A 64-byte frame, sent with the data phase at the FD bit rate. +//! let id = StandardId::new(0x123).unwrap(); +//! let frame = Frame::new_fd(id, &[0xAA; 64])?.with_bit_rate_switch(true); +//! canfd.transmit(&frame)?; +//! # Ok(()) +//! # } +//! ``` +//! +//! ### Receiving a range of identifiers +//! +//! Filter A accepts every frame out of reset. Configure it to accept only +//! CAN FD frames with the standard identifiers 0x120–0x12F. +//! ```rust, no_run +#![doc = crate::before_snippet!()] +//! use esp_hal::canfd::{ +//! CanFd, +//! Config, +//! FrameFormats, +//! MaskFilter, +//! MaskFilterConfig, +//! StandardId, +//! }; +//! +//! let mut canfd = CanFd::new(peripherals.TWAI0, Config::default())? +//! .with_rx(peripherals.GPIO9) +//! .with_tx(peripherals.GPIO8); +//! +//! let id = StandardId::new(0x120).unwrap(); +//! let mask = StandardId::new(0x7F0).unwrap(); +//! canfd.set_mask_filter( +//! MaskFilter::A, +//! &MaskFilterConfig::standard(id, mask).with_formats(FrameFormats::Fd), +//! ); +//! canfd.start()?; +//! # Ok(()) +//! # } +//! ``` +//! +//! ## Implementation State +//! +//! - Time-triggered transmission is not exposed. +//! - TX buffer backup mode and RAM parity protection are not exposed. +//! +//! "TRM" in this module means the ESP32-C5 TRM v1.1, chapter 38. +#![doc = crate::trm_markdown_link!("#canfd")] + +use core::marker::PhantomData; + +pub use embedded_can::{ExtendedId, Id, StandardId}; +use enumset::{EnumSet, EnumSetType}; + +use crate::{ + Async, + Blocking, + DriverMode, + clock::ll::{ClockTree, TwaiInstance}, + gpio::{ + DriveMode, + InputConfig, + InputSignal, + OutputConfig, + OutputSignal, + Pull, + interconnect::{PeripheralInput, PeripheralOutput}, + }, + interrupt::InterruptHandler, + peripherals::Interrupt, + rtc_cntl::WakeLock, + system::{Cpu, Peripheral, PeripheralGuard}, + time::{Duration, Instant}, +}; + +mod asynch; +mod ll; + +pub use ll::{ + BusErrorKind, + ErrorCapture, + ErrorPosition, + ErrorState, + FD_TIMING_LIMITS, + FrameFormats, + MAX_RETRANSMIT_LIMIT, + MAX_TX_PRIORITY, + MaskFilter, + NOMINAL_TIMING_LIMITS, + Timing, + TimingLimits, + TxBufferState, +}; +use ll::{ + CLASSIC_MAX_DATA_LEN, + Driver, + FrameBuffer, + FrameHeader, + FrameKinds, + MAX_DATA_LEN, + SspSource, + TimestampPoint, + len_to_dlc, +}; + +/// Clock source for the CAN FD peripheral. +pub use crate::soc::clocks::TwaiFunctionClockConfig as ClockSource; + +/// The device ID every CTU CAN FD core reports. +const CTU_CAN_FD_DEVICE_ID: u16 = 0xCAFD; + +/// An interrupt source of the controller (TRM 38.4). +#[derive(Debug, EnumSetType)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum CanFdInterrupt { + /// A frame was received. + RxFrame, + /// A frame was transmitted. + TxFrame, + /// The error warning limit was reached. + ErrorWarning, + /// The RX buffer overran. + DataOverrun, + /// The fault confinement state changed. + FaultStateChanged, + /// Arbitration was lost. + ArbitrationLost, + /// A bus error was detected. + BusError, + /// An overload frame was seen. + Overload, + /// The RX buffer is full. + RxFull, + /// A frame switched to the data bit rate, on either side of the transfer. + BitRateShifted, + /// The RX buffer is no longer empty. + RxNotEmpty, + /// A TX buffer finished, successfully or not. + TxDone, +} + +impl CanFdInterrupt { + const fn bit(self) -> u32 { + 1 << match self { + Self::RxFrame => 0, + Self::TxFrame => 1, + Self::ErrorWarning => 2, + Self::DataOverrun => 3, + Self::FaultStateChanged => 4, + Self::ArbitrationLost => 5, + Self::BusError => 6, + Self::Overload => 7, + Self::RxFull => 8, + Self::BitRateShifted => 9, + Self::RxNotEmpty => 10, + Self::TxDone => 11, + } + } + + fn mask(set: EnumSet) -> u32 { + set.iter().fold(0, |acc, source| acc | source.bit()) + } + + fn from_mask(bits: u32) -> EnumSet { + EnumSet::all() + .iter() + .filter(|source: &Self| bits & source.bit() != 0) + .collect() + } +} + +/// Identity of a CAN FD controller, read out of the hardware. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub struct Identity { + /// Device ID. Reads `0xCAFD` on a working core. + pub device_id: u16, + /// IP core major version. + pub version_major: u8, + /// IP core minor version. + pub version_minor: u8, +} + +impl Identity { + /// Returns whether the device ID is the one a CTU CAN FD core reports. + pub fn is_ctu_can_fd(&self) -> bool { + self.device_id == CTU_CAN_FD_DEVICE_ID + } +} + +/// How the controller participates on the bus. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum Mode { + /// Transmits and receives normally. + #[default] + Normal, + /// Receives only, never driving a dominant bit (TRM 38.3.12.4). + ListenOnly, + /// Treats a frame as transmitted even without an ACK (TRM 38.3.12.2). + /// + /// Needed to transmit as the only node on a bus. + SelfTest, + /// Routes transmitted frames back into the RX buffer (TRM 38.3.12.1). + /// + /// Also enables self test, because loopback alone still requires an ACK. + LoopbackSelfTest, +} + +/// Errors that can occur when the configuration is applied. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[non_exhaustive] +pub enum ConfigError { + /// The nominal bit timing is outside the limits of the hardware. + UnsupportedNominalTiming, + /// The data phase bit timing is outside the limits of the hardware. + UnsupportedFdTiming, + /// The timestamp resolution cannot be reached from the function clock. + UnsupportedTimestampResolution, + /// The timestamp counter did not start ticking. + TimestampTimerStalled, + /// The retransmission limit is larger than [`MAX_RETRANSMIT_LIMIT`]. + UnsupportedRetransmitLimit, + /// The secondary sample point cannot be placed where it was asked for. + /// + /// The final position must stay inside four data bit times and inside the + /// eight-bit offset field (TRM 38.3.7.3). + UnsupportedSecondarySamplePoint, + /// A transmission was still in flight and did not settle, so the + /// configuration was not applied. + BusBusy, + /// The transceiver setting cannot change after a pin is assigned, because + /// it decides how that pin is driven. + TransceiverModeLocked, +} + +impl core::error::Error for ConfigError {} + +impl core::fmt::Display for ConfigError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let message = match self { + Self::UnsupportedNominalTiming => { + "The nominal bit timing is outside the hardware limits" + } + Self::UnsupportedFdTiming => "The data phase bit timing is outside the hardware limits", + Self::UnsupportedTimestampResolution => { + "The timestamp resolution cannot be reached from the function clock" + } + Self::TimestampTimerStalled => "The timestamp counter did not start ticking", + Self::UnsupportedRetransmitLimit => { + "The retransmission limit is larger than the hardware field can hold" + } + Self::UnsupportedSecondarySamplePoint => { + "The secondary sample point cannot be placed where it was asked for" + } + Self::BusBusy => "A transmission was still in flight and did not settle", + Self::TransceiverModeLocked => { + "Whether a transceiver is in the way cannot be changed once a pin is assigned" + } + }; + f.write_str(message) + } +} + +/// Errors that can occur while the driver operates. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[non_exhaustive] +pub enum Error { + /// Every TX buffer holds a frame that is not yet finished. + NoFreeTxBuffer, + /// The RX buffer holds no complete frame. + RxBufferEmpty, + /// The controller did not become error-active in time. + /// + /// The bus must be idle-recessive for 11 bit times before the controller + /// can join it. + BusIntegrationTimeout, + /// The controller gave up on the frame after its retransmission limit. + TransmitFailed, + /// The transmission was aborted. + TransmitAborted, + /// The operation needs the controller to be off the bus first. + ControllerRunning, + /// The operation needs the controller to be on the bus; see + /// [`CanFd::start`]. + ControllerStopped, + /// A transmission did not settle in time after being aborted. + AbortTimeout, +} + +impl core::error::Error for Error {} + +impl core::fmt::Display for Error { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let message = match self { + Self::NoFreeTxBuffer => "Every TX buffer holds a frame that is not yet finished", + Self::RxBufferEmpty => "The RX buffer holds no complete frame", + Self::BusIntegrationTimeout => "The controller did not become error-active in time", + Self::TransmitFailed => "The controller gave up on the frame", + Self::TransmitAborted => "The transmission was aborted", + Self::ControllerRunning => "The operation needs the controller to be off the bus", + Self::ControllerStopped => "The operation needs the controller to be on the bus", + Self::AbortTimeout => "A transmission did not settle in time after being aborted", + }; + f.write_str(message) + } +} + +/// Errors that can occur when a frame is created. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[non_exhaustive] +pub enum FrameError { + /// The payload is longer than the frame format can carry. + /// + /// Classic CAN frames carry up to 8 bytes, CAN FD frames up to 64. + PayloadTooLong, + /// The frame is a CAN FD frame, which a [`ClassicFrame`] cannot hold. + NotClassic, +} + +impl core::error::Error for FrameError {} + +impl core::fmt::Display for FrameError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let message = match self { + Self::PayloadTooLong => "The payload is longer than the frame format can carry", + Self::NotClassic => "The frame is a CAN FD frame", + }; + f.write_str(message) + } +} + +/// CAN FD driver configuration. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, procmacros::BuilderLite)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[non_exhaustive] +pub struct Config { + /// Bus participation mode. + /// + /// Default value: [`Mode::Normal`]. + mode: Mode, + + /// Function clock source. + /// + /// The TRM recommends [`ClockSource::Xtal`] up to 5 Mbit/s and + /// [`ClockSource::PllF80m`] above that. + /// + /// Default value: [`ClockSource::PllF80m`]. + clock_source: ClockSource, + + /// Bit timing of the arbitration phase. + /// + /// Default value: 500 kbit/s from an 80 MHz function clock. + nominal_timing: Timing, + + /// Bit timing of the data phase, used by bit-rate-switched frames. + /// + /// Default value: 2 Mbit/s from an 80 MHz function clock. + fd_timing: Timing, + + /// Number of retransmission attempts, or `None` to retry forever. + /// + /// The first attempt is not a retransmission. The hardware holds at most + /// [`MAX_RETRANSMIT_LIMIT`]. + /// + /// Default value: `Some(3)`. + retransmit_limit: Option, + + /// Secondary sample point offset in time quanta, or `None` to disable it. + /// + /// Default value: `None`. + secondary_sample_point_offset: Option, + + /// Whether received request frames are dropped instead of stored. + /// + /// Default value: `false`. + drop_request_frames: bool, + + /// Whether protocol exception handling is enabled. + /// + /// Default value: `false`. + protocol_exception: bool, + + /// Whether the TX pin is driven open-drain with a pull-up. + /// + /// Lets two nodes be wired together directly, without transceivers. Binding + /// the RX and TX signals to the same pin then forms a single-node bus. + /// + /// Default value: `false`. + no_transceiver: bool, +} + +impl Default for Config { + fn default() -> Self { + // 500 kbit/s nominal and 2 Mbit/s data from 80 MHz, sampling at 81.2% + // and 75%. + Self { + mode: Mode::Normal, + clock_source: ClockSource::PllF80m, + nominal_timing: Timing { + baud_rate_prescaler: 10, + propagation_segment: 7, + phase_segment_1: 5, + phase_segment_2: 3, + sync_jump_width: 3, + }, + fd_timing: Timing { + baud_rate_prescaler: 10, + propagation_segment: 1, + phase_segment_1: 1, + phase_segment_2: 1, + sync_jump_width: 1, + }, + retransmit_limit: Some(3), + secondary_sample_point_offset: None, + drop_request_frames: false, + protocol_exception: false, + no_transceiver: false, + } + } +} + +impl Config { + fn validate(&self) -> Result<(), ConfigError> { + if !self.nominal_timing.is_valid(&NOMINAL_TIMING_LIMITS) { + return Err(ConfigError::UnsupportedNominalTiming); + } + if !self.fd_timing.is_valid(&FD_TIMING_LIMITS) { + return Err(ConfigError::UnsupportedFdTiming); + } + if self + .retransmit_limit + .is_some_and(|limit| limit > MAX_RETRANSMIT_LIMIT) + { + return Err(ConfigError::UnsupportedRetransmitLimit); + } + + if let Some(offset) = self.secondary_sample_point_offset { + // The hardware counts the offset in function clock periods. + let cycles = u32::from(offset) * u32::from(self.fd_timing.baud_rate_prescaler); + + // The field is eight bits; the hardware would saturate silently. + if cycles > u32::from(u8::MAX) { + return Err(ConfigError::UnsupportedSecondarySamplePoint); + } + + // TRM 38.3.7.3 limits the final position, offset plus measured + // delay, to four data bit times. The core adds at least two cycles + // of delay on its own, so an offset that only fits with zero delay + // cannot fit in practice. + let data_bit_cycles = + u32::from(self.fd_timing.baud_rate_prescaler) * self.fd_timing.total_quanta(); + if cycles + MIN_TRANSMITTER_DELAY_CYCLES > data_bit_cycles * 4 { + return Err(ConfigError::UnsupportedSecondarySamplePoint); + } + + // Below three cycles the core flags bit errors against its own + // output. + if cycles <= MIN_TRANSMITTER_DELAY_CYCLES { + return Err(ConfigError::UnsupportedSecondarySamplePoint); + } + } + + Ok(()) + } +} + +/// Configuration of one mask filter; see [`CanFd::set_mask_filter`]. +/// +/// A frame is accepted when its identifier has the filter's format and matches +/// the filter's identifier in every bit set in the mask. A mask of +/// [`StandardId::MAX`] or [`ExtendedId::MAX`] compares every bit, and a mask of +/// zero accepts every identifier of the format. +/// +/// The filter accepts classic CAN and CAN FD frames by default; see +/// [`MaskFilterConfig::with_formats`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub struct MaskFilterConfig { + id: u32, + mask: u32, + extended: bool, + formats: FrameFormats, +} + +impl MaskFilterConfig { + /// Matches standard identifiers against `id`, in the bits set in `mask`. + pub fn standard(id: StandardId, mask: StandardId) -> Self { + Self { + id: id.as_raw() as u32, + mask: mask.as_raw() as u32, + extended: false, + formats: FrameFormats::Both, + } + } + + /// Matches extended identifiers against `id`, in the bits set in `mask`. + pub fn extended(id: ExtendedId, mask: ExtendedId) -> Self { + Self { + id: id.as_raw(), + mask: mask.as_raw(), + extended: true, + formats: FrameFormats::Both, + } + } + + /// Sets which frame formats the filter accepts. + pub fn with_formats(self, formats: FrameFormats) -> Self { + Self { formats, ..self } + } + + fn kinds(&self) -> FrameKinds { + FrameKinds::new(self.extended, self.formats) + } +} + +/// Configuration of the range filter; see [`CanFd::set_range_filter`]. +/// +/// A frame is accepted when its identifier has the filter's format and lies in +/// `low..=high`. A `low` above `high` is an empty range, which accepts nothing. +/// +/// The filter accepts classic CAN and CAN FD frames by default; see +/// [`RangeFilterConfig::with_formats`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub struct RangeFilterConfig { + low: u32, + high: u32, + extended: bool, + formats: FrameFormats, +} + +impl RangeFilterConfig { + /// Matches standard identifiers in `low..=high`. + pub fn standard(low: StandardId, high: StandardId) -> Self { + Self { + low: low.as_raw() as u32, + high: high.as_raw() as u32, + extended: false, + formats: FrameFormats::Both, + } + } + + /// Matches extended identifiers in `low..=high`. + pub fn extended(low: ExtendedId, high: ExtendedId) -> Self { + Self { + low: low.as_raw(), + high: high.as_raw(), + extended: true, + formats: FrameFormats::Both, + } + } + + /// Sets which frame formats the filter accepts. + pub fn with_formats(self, formats: FrameFormats) -> Self { + Self { formats, ..self } + } + + fn kinds(&self) -> FrameKinds { + FrameKinds::new(self.extended, self.formats) + } +} + +/// A CAN FD frame. +#[derive(Clone, Copy)] +pub struct Frame { + id: Id, + request: bool, + fd: bool, + bit_rate_switch: bool, + error_state_indicator: bool, + data: [u8; MAX_DATA_LEN], + /// Bytes carried. Always zero for a request frame. + len: usize, + /// Bytes a request frame asks for. Zero for a data frame. + requested_len: usize, + timestamp: u64, +} + +impl Frame { + /// Creates a new classic CAN data frame. + /// + /// # Errors + /// + /// [`FrameError::PayloadTooLong`] when `payload` is longer than 8 bytes. + pub fn new(id: impl Into, payload: &[u8]) -> Result { + if payload.len() > CLASSIC_MAX_DATA_LEN { + return Err(FrameError::PayloadTooLong); + } + Ok(Self::build(id.into(), false, false, payload)) + } + + /// Creates a new classic CAN request frame. + /// + /// A request frame carries no payload. `len` is the payload length that the + /// frame asks for. + /// + /// # Errors + /// + /// [`FrameError::PayloadTooLong`] when `len` is greater than 8. + pub fn new_request(id: impl Into, len: usize) -> Result { + if len > CLASSIC_MAX_DATA_LEN { + return Err(FrameError::PayloadTooLong); + } + let mut frame = Self::build(id.into(), true, false, &[]); + frame.requested_len = len; + Ok(frame) + } + + /// Creates a new CAN FD data frame. + /// + /// The data phase uses the nominal bit rate unless + /// [`Frame::with_bit_rate_switch`] is set. + /// + /// # Errors + /// + /// [`FrameError::PayloadTooLong`] when `payload` is longer than 64 bytes. + pub fn new_fd(id: impl Into, payload: &[u8]) -> Result { + if payload.len() > MAX_DATA_LEN { + return Err(FrameError::PayloadTooLong); + } + Ok(Self::build(id.into(), false, true, payload)) + } + + /// Sets whether the data phase is sent at the FD bit rate. + /// + /// Only a CAN FD frame can switch bit rate; the setting is ignored on a + /// classic frame. + pub fn with_bit_rate_switch(mut self, bit_rate_switch: bool) -> Self { + self.bit_rate_switch = bit_rate_switch && self.fd; + self + } + + fn build(id: Id, request: bool, fd: bool, payload: &[u8]) -> Self { + let mut data = [0u8; MAX_DATA_LEN]; + data[..payload.len()].copy_from_slice(payload); + Self { + id, + request, + fd, + bit_rate_switch: false, + error_state_indicator: false, + data, + len: payload.len(), + requested_len: 0, + timestamp: 0, + } + } + + /// Returns the payload the frame carries. + pub fn payload(&self) -> &[u8] { + &self.data[..self.len] + } + + /// Returns the payload length in bytes. + pub fn len(&self) -> usize { + self.len + } + + /// Returns whether the frame carries no payload. + pub fn is_empty(&self) -> bool { + self.len == 0 + } + + /// Returns the payload length a request frame asks for, in bytes. + /// + /// Zero for a data frame, whose length is [`Frame::len`]. + pub fn requested_len(&self) -> usize { + self.requested_len + } + + /// Returns the data length code the frame is sent with. + /// + /// A payload length that no code expresses is padded up to the next one, + /// so a received copy of the frame can be longer than [`Frame::len`]. + pub fn dlc(&self) -> u8 { + if self.request { + len_to_dlc(self.requested_len as u8) + } else { + len_to_dlc(self.len as u8) + } + } + + /// Returns the arbitration identifier. + pub fn id(&self) -> Id { + self.id + } + + /// Returns whether the identifier is a 29-bit extended one. + pub fn is_extended(&self) -> bool { + matches!(self.id, Id::Extended(_)) + } + + /// Returns whether this is a request frame, which carries no payload. + pub fn is_request(&self) -> bool { + self.request + } + + /// Returns whether the frame uses the CAN FD format. + pub fn is_fd(&self) -> bool { + self.fd + } + + /// Returns whether the data phase uses the FD bit rate. + pub fn is_bit_rate_switched(&self) -> bool { + self.bit_rate_switch + } + + /// Returns the error state indicator of the transmitting node. + pub fn error_state_indicator(&self) -> bool { + self.error_state_indicator + } + + /// Returns the timestamp captured when the frame was received. + /// + /// Zero for a frame that was not received; see + /// [`CanFd::start_timestamp_timer`]. + pub fn timestamp(&self) -> u64 { + self.timestamp + } + + fn to_buffer(self) -> FrameBuffer { + FrameBuffer::build( + FrameHeader { + id: self.id, + request: self.request, + fd: self.fd, + bit_rate_switch: self.bit_rate_switch, + dlc: self.dlc(), + }, + self.payload(), + ) + } + + fn from_buffer(buffer: &FrameBuffer) -> Self { + let payload = buffer.data(); + let mut data = [0u8; MAX_DATA_LEN]; + data[..payload.len()].copy_from_slice(payload); + let request = buffer.is_request(); + Self { + id: buffer.id(), + request, + fd: buffer.is_fd(), + bit_rate_switch: buffer.is_bit_rate_switched(), + error_state_indicator: buffer.error_state_indicator(), + data, + len: payload.len(), + requested_len: if request { buffer.requested_len() } else { 0 }, + timestamp: buffer.timestamp(), + } + } + + fn raw_id(&self) -> u32 { + match self.id { + Id::Standard(id) => u32::from(id.as_raw()), + Id::Extended(id) => id.as_raw(), + } + } +} + +impl core::fmt::Debug for Frame { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("Frame") + .field("id", &format_args!("{:#x}", self.raw_id())) + .field("extended", &self.is_extended()) + .field("request", &self.request) + .field("fd", &self.fd) + .field("bit_rate_switch", &self.bit_rate_switch) + .field("error_state_indicator", &self.error_state_indicator) + .field("dlc", &self.dlc()) + .field("len", &self.len) + .field("timestamp", &self.timestamp) + .field("data", &self.payload()) + .finish() + } +} + +#[cfg(feature = "defmt")] +impl defmt::Format for Frame { + fn format(&self, f: defmt::Formatter<'_>) { + defmt::write!( + f, + "Frame {{ id: {=u32:#x}, extended: {}, request: {}, fd: {}, brs: {}, esi: {}, dlc: {=u8}, len: {=usize}, timestamp: {=u64}, data: {=[u8]:#x} }}", + self.raw_id(), + self.is_extended(), + self.request, + self.fd, + self.bit_rate_switch, + self.error_state_indicator, + self.dlc(), + self.len, + self.timestamp, + self.payload() + ) + } +} + +/// A frame that is known to be classic CAN, for code written against +/// `embedded-can`. +/// +/// [`embedded_can::Frame`] promises at most 8 bytes of data, which a [`Frame`] +/// cannot keep: a 64-byte FD frame is a `Frame` too. The trait is therefore +/// implemented on this type, which the trait constructors build directly and +/// which `TryFrom` refuses to make from an FD frame. +/// +/// The type dereferences to the [`Frame`] it wraps and converts back into one +/// for [`CanFd::transmit`]. +#[derive(Clone, Copy, Debug)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub struct ClassicFrame(Frame); + +impl ClassicFrame { + /// Returns the frame this wraps. + pub fn into_frame(self) -> Frame { + self.0 + } +} + +impl core::ops::Deref for ClassicFrame { + type Target = Frame; + + fn deref(&self) -> &Frame { + &self.0 + } +} + +impl TryFrom for ClassicFrame { + type Error = FrameError; + + /// # Errors + /// + /// [`FrameError::NotClassic`] when the frame uses the CAN FD format. + fn try_from(frame: Frame) -> Result { + if frame.fd { + return Err(FrameError::NotClassic); + } + Ok(Self(frame)) + } +} + +impl From for Frame { + fn from(frame: ClassicFrame) -> Self { + frame.0 + } +} + +#[instability::unstable] +impl embedded_can::Frame for ClassicFrame { + fn new(id: impl Into, data: &[u8]) -> Option { + Frame::new(id, data).ok().map(Self) + } + + fn new_remote(id: impl Into, dlc: usize) -> Option { + Frame::new_request(id, dlc).ok().map(Self) + } + + fn is_extended(&self) -> bool { + self.0.is_extended() + } + + fn is_remote_frame(&self) -> bool { + self.0.request + } + + fn id(&self) -> Id { + self.0.id + } + + fn dlc(&self) -> usize { + // The trait defines this as the payload length of a data frame and the + // requested length of a remote frame. + if self.0.request { + self.0.requested_len + } else { + self.0.len + } + } + + fn data(&self) -> &[u8] { + self.0.payload() + } +} + +#[instability::unstable] +impl From for embedded_can::ErrorKind { + fn from(kind: BusErrorKind) -> Self { + match kind { + BusErrorKind::Bit => Self::Bit, + BusErrorKind::Crc => Self::Crc, + BusErrorKind::Form => Self::Form, + BusErrorKind::Ack => Self::Acknowledge, + BusErrorKind::Stuff => Self::Stuff, + BusErrorKind::Unknown(_) => Self::Other, + } + } +} + +#[instability::unstable] +impl embedded_can::Error for BusErrorKind { + fn kind(&self) -> embedded_can::ErrorKind { + (*self).into() + } +} + +impl core::error::Error for BusErrorKind {} + +impl core::fmt::Display for BusErrorKind { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::Bit => f.write_str("The transmitted bit did not match the bit sampled back"), + Self::Crc => f.write_str("The CRC of the frame did not match"), + Self::Form => f.write_str("A fixed-form field held an illegal value"), + Self::Ack => f.write_str("No node acknowledged the frame"), + Self::Stuff => f.write_str("A stuffing rule was violated"), + Self::Unknown(code) => write!(f, "Unknown bus error code {code}"), + } + } +} + +/// A CAN FD controller. +pub struct CanFd<'d, Dm: DriverMode = Blocking> { + // Drop order matters: the controller leaves the bus before its clocks are + // released, and the function clock goes before the register clock. + bus: BusGuard, + config: Config, + _mode: PhantomData, + /// Accepted frame kinds for filters A, B, C and the range filter. They + /// share one register. + filter_kinds: [FrameKinds; 4], + /// Whether a pin has been assigned, which commits `no_transceiver`. + pins_bound: bool, + twai: AnyCanFd<'d>, + _function_clock: FunctionClockGuard, + _peripheral: PeripheralGuard, +} + +impl core::fmt::Debug for CanFd<'_, Dm> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("CanFd") + .field("twai", &self.twai) + .field("config", &self.config) + .field("started", &self.is_started()) + .finish_non_exhaustive() + } +} + +#[cfg(feature = "defmt")] +impl defmt::Format for CanFd<'_, Dm> { + fn format(&self, f: defmt::Formatter<'_>) { + defmt::write!( + f, + "CanFd {{ twai: {:?}, config: {:?}, started: {} }}", + self.twai, + self.config, + self.is_started() + ) + } +} + +/// Receiving half of a split controller. +/// +/// Borrows the driver, which keeps the configuration and the teardown. See +/// [`CanFd::split`]. +pub struct CanFdRx<'a, Dm: DriverMode> { + driver: Driver, + state: &'static asynch::State, + _driver: PhantomData<&'a mut ()>, + _mode: PhantomData, +} + +/// Transmitting half of a split controller. +/// +/// See [`CanFd::split`]. +pub struct CanFdTx<'a, Dm: DriverMode> { + driver: Driver, + state: &'static asynch::State, + tx_buffers: u8, + _driver: PhantomData<&'a mut ()>, + _mode: PhantomData, +} + +impl core::fmt::Debug for CanFdRx<'_, Dm> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("CanFdRx") + .field("rx_frame_count", &self.rx_frame_count()) + .finish_non_exhaustive() + } +} + +impl core::fmt::Debug for CanFdTx<'_, Dm> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("CanFdTx") + .field("tx_buffers", &self.tx_buffers) + .finish_non_exhaustive() + } +} + +#[cfg(feature = "defmt")] +impl defmt::Format for CanFdRx<'_, Dm> { + fn format(&self, f: defmt::Formatter<'_>) { + defmt::write!( + f, + "CanFdRx {{ rx_frame_count: {=u16} }}", + self.rx_frame_count() + ) + } +} + +#[cfg(feature = "defmt")] +impl defmt::Format for CanFdTx<'_, Dm> { + fn format(&self, f: defmt::Formatter<'_>) { + defmt::write!(f, "CanFdTx {{ tx_buffers: {=u8} }}", self.tx_buffers) + } +} + +impl CanFdRx<'_, Dm> { + /// Returns the number of complete frames waiting in the RX buffer. + pub fn rx_frame_count(&self) -> u16 { + self.driver.rx_frame_count() + } + + /// Reads one frame from the RX buffer. + /// + /// # Errors + /// + /// [`Error::RxBufferEmpty`] when no complete frame is waiting. + pub fn receive(&mut self) -> Result { + if self.driver.rx_frame_count() == 0 { + return Err(Error::RxBufferEmpty); + } + Ok(Frame::from_buffer(&self.driver.read_rx_frame())) + } + + /// Discards everything in the RX buffer. + pub fn flush_rx(&mut self) { + self.driver.flush_rx(); + } + + /// Returns the size of the RX buffer in 32-bit words. + pub fn rx_buffer_size_words(&self) -> u16 { + self.driver.rx_buffer_size() + } + + /// Returns the free space in the RX buffer in 32-bit words. + pub fn rx_buffer_free_words(&self) -> u16 { + self.driver.rx_free_words() + } + + /// Returns whether the RX buffer has overrun and dropped a frame + /// (TRM 38.3.9.4). + pub fn rx_overrun(&self) -> bool { + self.driver.rx_overrun() + } + + /// Clears the RX buffer overrun flag. + pub fn clear_rx_overrun(&mut self) { + self.driver.clear_overrun(); + } + + /// Returns the current fault confinement state; see [`CanFd::error_state`]. + pub fn error_state(&self) -> ErrorState { + self.driver.error_state() + } + + /// Returns the receive error counter. + pub fn receive_error_count(&self) -> u16 { + self.driver.rec() + } + + /// Returns the transmit error counter. + pub fn transmit_error_count(&self) -> u16 { + self.driver.tec() + } +} + +impl CanFdRx<'_, Async> { + /// Waits until a frame is received, then reads it. + /// + /// # Cancellation Safety + /// + /// This future is cancel-safe. A frame stays in the hardware RX buffer + /// until it is read, so dropping the future loses nothing. + pub async fn receive_async(&mut self) -> Frame { + core::future::poll_fn(|cx| { + self.state.rx_waker.register(cx.waker()); + // Armed before the check, so a frame arriving in between still + // raises the interrupt. + self.driver + .enable_interrupts(CanFdInterrupt::RxNotEmpty.bit()); + + if self.driver.rx_frame_count() > 0 { + self.driver + .disable_interrupts(CanFdInterrupt::RxNotEmpty.bit()); + return core::task::Poll::Ready(()); + } + + core::task::Poll::Pending + }) + .await; + + Frame::from_buffer(&self.driver.read_rx_frame()) + } +} + +impl CanFdTx<'_, Dm> { + /// Returns the number of TX buffers the hardware provides. + pub fn tx_buffer_count(&self) -> u8 { + self.tx_buffers + } + + /// Queues a frame in the first free TX buffer and arms it. + /// + /// Returns the index of the buffer used. Up to [`CanFdTx::tx_buffer_count`] + /// frames can be queued at once. + /// + /// The hardware picks the next frame to send among the armed buffers by + /// priority, and among equal priorities by the lower buffer index; see + /// [`CanFdTx::set_tx_priority`]. The order in which frames were queued + /// plays no part in that choice. With equal priorities a frame queued into + /// a buffer that a finished frame freed up is sent before frames still + /// waiting in higher-numbered buffers. To keep frames in the order they + /// were queued, wait for each buffer to leave [`TxBufferState::Ready`] + /// before queueing the next frame, or give later frames lower priorities. + /// + /// # Errors + /// + /// [`Error::ControllerStopped`] when the controller is not on the bus. A + /// stopped controller ignores the command that arms a buffer, so the frame + /// would be lost. + /// + /// [`Error::NoFreeTxBuffer`] when every TX buffer is occupied. + pub fn transmit(&mut self, frame: &Frame) -> Result { + if !self.driver.is_enabled() { + return Err(Error::ControllerStopped); + } + + let index = (0..self.tx_buffers) + .find(|&i| self.driver.tx_buffer_state(i).is_writable()) + .ok_or(Error::NoFreeTxBuffer)?; + + self.driver.write_tx_buffer(index, &frame.to_buffer()); + self.driver.set_tx_ready(index); + Ok(index) + } + + /// Returns the state of one TX buffer. + /// + /// Returns [`TxBufferState::NotExist`] for an index the hardware does not + /// have. + pub fn tx_buffer_state(&self, index: u8) -> TxBufferState { + if index >= self.tx_buffers { + return TxBufferState::NotExist; + } + self.driver.tx_buffer_state(index) + } + + /// Requests that a queued transmission be aborted. + /// + /// Does nothing for an index the hardware does not have. + pub fn abort_transmit(&mut self, index: u8) { + if index < self.tx_buffers { + self.driver.set_tx_abort(index); + } + } + + /// Returns a TX buffer to the empty state, releasing it for reuse. + /// + /// Does nothing for an index the hardware does not have. + pub fn release_tx_buffer(&mut self, index: u8) { + if index < self.tx_buffers { + self.driver.set_tx_empty(index); + } + } + + /// Sets a TX buffer's arbitration priority. + /// + /// Higher values win. Equal priorities are resolved in favor of the lower + /// buffer index (TRM 38.3.8.1). A value above [`MAX_TX_PRIORITY`] counts as + /// that maximum. Does nothing for an index the hardware does not have. + /// + /// The priority belongs to the buffer, not to the frame in it, and all + /// buffers start out equal. Set it before arming the buffer with + /// [`CanFdTx::transmit`], or right after, while the frame is still + /// [`TxBufferState::Ready`]. + pub fn set_tx_priority(&mut self, index: u8, priority: u8) { + if index < self.tx_buffers { + self.driver + .set_tx_priority(index, priority.min(MAX_TX_PRIORITY)); + } + } + + /// Returns the current fault confinement state; see [`CanFd::error_state`]. + /// + /// On bus-off every armed TX buffer fails, so a transmission that ends in + /// [`Error::TransmitFailed`] can be told apart from an exhausted + /// retransmission limit here. + pub fn error_state(&self) -> ErrorState { + self.driver.error_state() + } + + /// Returns the receive error counter. + pub fn receive_error_count(&self) -> u16 { + self.driver.rec() + } + + /// Returns the transmit error counter. + pub fn transmit_error_count(&self) -> u16 { + self.driver.tec() + } + + /// Requests that a bus-off controller rejoin the bus. + /// + /// Does nothing unless the controller is bus-off. Rejoining takes 128 + /// occurrences of 11 recessive bits, as ISO 11898-1 requires. Leaving the + /// bus with [`CanFd::stop`] and joining it again with [`CanFd::start`] also + /// clears the bus-off state, after ordinary integration. + /// + /// The state is checked here because the hardware remembers a request made + /// while error-active and then rejoins on its own the next time it goes + /// bus-off (measured on an ESP32-C5; TRM register 38.3 says otherwise). + pub fn request_bus_off_recovery(&mut self) { + if self.driver.error_state() == ErrorState::BusOff { + self.driver.request_bus_off_recovery(); + } + } +} + +impl CanFdTx<'_, Async> { + /// Queues a frame and waits until the hardware finishes with it. + /// + /// # Errors + /// + /// [`Error::ControllerStopped`] when the controller is not on the bus, and + /// [`Error::NoFreeTxBuffer`] when every TX buffer is occupied; see + /// [`CanFdTx::transmit`]. + /// + /// [`Error::TransmitFailed`] when the controller gave up on the frame. + /// + /// [`Error::TransmitAborted`] when the transmission was aborted. + /// + /// # Cancellation Safety + /// + /// This future is not cancel-safe. Dropping it leaves the frame queued, and + /// the hardware may still transmit it. + pub async fn transmit_async(&mut self, frame: &Frame) -> Result<(), Error> { + let index = self.transmit(frame)?; + + core::future::poll_fn(|cx| { + self.state.tx_waker.register(cx.waker()); + // Armed before the check, so a transmission finishing in between + // still raises the interrupt. + self.driver.enable_interrupts(CanFdInterrupt::TxDone.bit()); + + let state = self.driver.tx_buffer_state(index); + if !matches!( + state, + TxBufferState::Ready | TxBufferState::InProgress | TxBufferState::AbortInProgress + ) { + self.driver.disable_interrupts(CanFdInterrupt::TxDone.bit()); + } + + match state { + TxBufferState::Ready + | TxBufferState::InProgress + | TxBufferState::AbortInProgress => core::task::Poll::Pending, + TxBufferState::Ok => core::task::Poll::Ready(Ok(())), + TxBufferState::Failed => core::task::Poll::Ready(Err(Error::TransmitFailed)), + TxBufferState::Aborted => core::task::Poll::Ready(Err(Error::TransmitAborted)), + _ => core::task::Poll::Ready(Err(Error::NoFreeTxBuffer)), + } + }) + .await + } +} + +/// Owns the controller's participation in the bus, so that a dropped driver +/// leaves the bus cleanly instead of cutting a frame short. +struct BusGuard { + driver: Driver, + tx_buffers: u8, + interrupt: Interrupt, + /// How long a frame in flight is given to finish at the configured bit + /// rate. + abort_timeout: Duration, + /// Held while the controller is on the bus: light sleep gates the function + /// clock, and a frame keeps going after the future that queued it is + /// dropped. + wake_lock: Option, +} + +impl BusGuard { + fn enable(&mut self) { + self.driver.enable(true); + if self.wake_lock.is_none() { + self.wake_lock = Some(WakeLock::new()); + } + } + + fn disable(&mut self) { + self.driver.enable(false); + self.wake_lock = None; + } + + /// Aborts anything queued and waits for the wire to be free (TRM 38.3.6 + /// step 1). + fn quiesce(&self) -> Result<(), Error> { + for index in 0..self.tx_buffers { + self.driver.set_tx_abort(index); + } + + let deadline = Instant::now() + self.abort_timeout; + for index in 0..self.tx_buffers { + while matches!( + self.driver.tx_buffer_state(index), + TxBufferState::Ready | TxBufferState::InProgress | TxBufferState::AbortInProgress + ) { + if Instant::now() > deadline { + return Err(Error::AbortTimeout); + } + } + } + + Ok(()) + } +} + +impl Drop for BusGuard { + fn drop(&mut self) { + // An interrupt source left armed keeps the request line asserted after + // the clocks are gone, and the handler could no longer retire it. + self.driver.disable_interrupts(u32::MAX); + self.driver.clear_interrupts(u32::MAX); + crate::interrupt::disable(Cpu::current(), self.interrupt); + + // Best effort: a wedged transmission must not hang teardown. + let _ = self.quiesce(); + self.disable(); + } +} + +impl crate::private::Sealed for CanFd<'_, Blocking> {} + +#[instability::unstable] +impl crate::interrupt::InterruptConfigurable for CanFd<'_, Blocking> { + fn set_interrupt_handler(&mut self, handler: InterruptHandler) { + self.bind_interrupt_handler(handler); + } +} + +impl<'d> CanFd<'d, Blocking> { + /// Registers an interrupt handler for this controller. + /// + /// Replaces any previously registered handler. The handler runs for the + /// sources enabled with [`CanFd::listen`]. It must clear them with + /// [`CanFd::clear_interrupts`], or it runs again as soon as it returns. + #[instability::unstable] + pub fn set_interrupt_handler(&mut self, handler: InterruptHandler) { + self.bind_interrupt_handler(handler); + } + + /// Enables the given interrupt sources. + /// + /// Without a handler from [`CanFd::set_interrupt_handler`] this only makes + /// [`CanFd::interrupts`] record what happened. + pub fn listen(&mut self, interrupts: impl Into>) { + self.bus + .driver + .enable_interrupts(CanFdInterrupt::mask(interrupts.into())); + } + + /// Disables the given interrupt sources. + pub fn unlisten(&mut self, interrupts: impl Into>) { + self.bus + .driver + .disable_interrupts(CanFdInterrupt::mask(interrupts.into())); + } + + /// Returns the interrupt sources that are currently asserted. + pub fn interrupts(&self) -> EnumSet { + CanFdInterrupt::from_mask(self.bus.driver.interrupt_status()) + } + + /// Clears the given interrupt sources. + pub fn clear_interrupts(&mut self, interrupts: impl Into>) { + self.bus + .driver + .clear_interrupts(CanFdInterrupt::mask(interrupts.into())); + } + + /// Creates a new CAN FD driver in [`Blocking`] mode. + /// + /// The controller is configured but stays off the bus. Assign the pins with + /// [`CanFd::with_rx`] and [`CanFd::with_tx`], then call [`CanFd::start`]. + /// + /// # Errors + /// + /// [`ConfigError`] when the configuration does not fit the hardware. + pub fn new(twai: impl Instance + 'd, config: Config) -> Result { + let twai = twai.degrade(); + let info = twai.info(); + let peripheral = PeripheralGuard::new(info.peripheral); + let function_clock = FunctionClockGuard::new(info.clock_instance, config.clock_source); + + let driver = Driver::new(info.register_block); + driver.reset(); + let tx_buffers = driver.tx_buffer_count(); + + let abort_timeout = abort_timeout( + &config.nominal_timing, + &config.fd_timing, + info.clock_instance.function_clock_frequency(), + ); + + let mut this = Self { + bus: BusGuard { + driver, + tx_buffers, + abort_timeout, + interrupt: info.interrupt, + wake_lock: None, + }, + config, + filter_kinds: RESET_FILTER_KINDS, + pins_bound: false, + _mode: PhantomData, + twai, + _function_clock: function_clock, + _peripheral: peripheral, + }; + this.configure()?; + + Ok(this) + } + + /// Converts the driver into an async driver. + pub fn into_async(self) -> CanFd<'d, Async> { + let mut this = CanFd { + bus: self.bus, + config: self.config, + filter_kinds: self.filter_kinds, + pins_bound: self.pins_bound, + _mode: PhantomData, + twai: self.twai, + _function_clock: self._function_clock, + _peripheral: self._peripheral, + }; + let handler = this.twai.info().async_handler; + this.bind_interrupt_handler(handler); + + this + } +} + +impl<'d> CanFd<'d, Async> { + /// Waits until a frame is received, then reads it. + /// + /// # Cancellation Safety + /// + /// This future is cancel-safe. A frame stays in the hardware RX buffer + /// until it is read, so dropping the future loses nothing. + pub async fn receive_async(&mut self) -> Frame { + self.rx_half().receive_async().await + } + + /// Queues a frame and waits until the hardware finishes with it. + /// + /// # Errors + /// + /// [`Error::ControllerStopped`] when the controller is not on the bus, and + /// [`Error::NoFreeTxBuffer`] when every TX buffer is occupied; see + /// [`CanFdTx::transmit`]. + /// + /// [`Error::TransmitFailed`] when the controller gave up on the frame. + /// + /// [`Error::TransmitAborted`] when the transmission was aborted. + /// + /// # Cancellation Safety + /// + /// This future is not cancel-safe. Dropping it leaves the frame queued, and + /// the hardware may still transmit it. + pub async fn transmit_async(&mut self, frame: &Frame) -> Result<(), Error> { + self.tx_half().transmit_async(frame).await + } + + /// Converts the driver back into a blocking driver. + pub fn into_blocking(self) -> CanFd<'d, Blocking> { + self.bus.driver.disable_interrupts(u32::MAX); + crate::interrupt::disable(Cpu::current(), self.twai.info().interrupt); + + CanFd { + bus: self.bus, + config: self.config, + filter_kinds: self.filter_kinds, + pins_bound: self.pins_bound, + _mode: PhantomData, + twai: self.twai, + _function_clock: self._function_clock, + _peripheral: self._peripheral, + } + } +} + +impl<'d, Dm: DriverMode> CanFd<'d, Dm> { + fn bind_interrupt_handler(&mut self, handler: InterruptHandler) { + let interrupt = self.twai.info().interrupt; + crate::interrupt::disable(Cpu::current(), interrupt); + self.bus.driver.disable_interrupts(u32::MAX); + self.bus.driver.clear_interrupts(u32::MAX); + crate::interrupt::bind_handler(interrupt, handler); + crate::interrupt::enable(interrupt, handler.priority()); + } + + /// Assigns the RX pin. + /// + /// The pin is driven according to [`Config::with_no_transceiver`]. That + /// setting is committed to the hardware here and cannot change afterwards. + pub fn with_rx(mut self, rx: impl PeripheralInput<'d>) -> Self { + let rx = rx.into(); + rx.apply_input_config(&InputConfig::default().with_pull(self.pin_pull())); + rx.set_input_enable(true); + self.twai.info().rx_signal.connect_to(&rx); + self.pins_bound = true; + + self + } + + /// Assigns the TX pin. + /// + /// With [`Config::with_no_transceiver`] set, the pin is driven open-drain + /// with a pull-up. Assigning the same pin to [`CanFd::with_rx`] then forms + /// a single-node bus that needs no external wiring. That setting is + /// committed to the hardware here and cannot change afterwards. + pub fn with_tx(mut self, tx: impl PeripheralOutput<'d>) -> Self { + let tx = tx.into(); + let mut output = OutputConfig::default(); + if self.config.no_transceiver { + output = output + .with_drive_mode(DriveMode::OpenDrain) + .with_pull(Pull::Up); + } + tx.apply_output_config(&output); + tx.set_output_enable(true); + self.twai.info().tx_signal.connect_to(&tx); + self.pins_bound = true; + + self + } + + fn pin_pull(&self) -> Pull { + if self.config.no_transceiver { + Pull::Up + } else { + Pull::None + } + } + + /// Applies a new configuration. + /// + /// The controller leaves the bus while the configuration is applied. A + /// running driver must be started again with [`CanFd::start`] afterwards. + /// A change of clock source also stops a running timestamp counter, + /// because its resolution is derived from that clock. Start it again with + /// [`CanFd::start_timestamp_timer`] and use the resolution that it returns. + /// + /// # Errors + /// + /// [`ConfigError`] when the configuration does not fit the hardware. + /// + /// [`ConfigError::TransceiverModeLocked`] when the configuration changes + /// [`Config::with_no_transceiver`] after a pin has been assigned. + pub fn apply_config(&mut self, config: &Config) -> Result<(), ConfigError> { + config.validate()?; + + if self.pins_bound && config.no_transceiver != self.config.no_transceiver { + return Err(ConfigError::TransceiverModeLocked); + } + + // The prescaler divides the function clock, so a new source would + // silently rescale a running counter. + if config.clock_source != self.config.clock_source { + self.stop_timestamp_timer(); + } + + // `configure` refuses before writing anything, so `config()` keeps + // describing the hardware. + let previous = self.config; + self.config = *config; + self.configure().inspect_err(|_| self.config = previous) + } + + /// Returns the current configuration. + pub fn config(&self) -> &Config { + &self.config + } + + /// Writes the stored configuration to the hardware, leaving the bus. + fn configure(&mut self) -> Result<(), ConfigError> { + self.config.validate()?; + + if self.bus.driver.is_enabled() { + self.bus.quiesce().map_err(|_| ConfigError::BusBusy)?; + } + + // Mode bits can only be changed while the controller is disabled. + self.bus.disable(); + + // The timing below is expressed in periods of the function clock + // (TRM 38.3.1), so the mux is switched first. + self._function_clock.set_source(self.config.clock_source); + + let config = self.config; + let (listen_only, self_test, loopback) = match config.mode { + Mode::Normal => (false, false, false), + Mode::ListenOnly => (true, false, false), + Mode::SelfTest => (false, true, false), + Mode::LoopbackSelfTest => (false, true, true), + }; + + self.bus.driver.apply_mode_settings(&ll::ModeSettings { + listen_only, + self_test, + loopback, + fd_enabled: true, + protocol_exception: config.protocol_exception, + rx_auto_increment: true, + filters_enabled: true, + bus_off_tx_fail: true, + drop_request_frames: config.drop_request_frames, + time_triggered_tx: false, + retransmit_limit: config.retransmit_limit, + }); + + self.bus + .driver + .set_timestamp_point(TimestampPoint::EndOfFrame); + + self.bus.driver.set_nominal_timing(&config.nominal_timing); + self.bus.driver.set_fd_timing(&config.fd_timing); + + self.bus.abort_timeout = abort_timeout( + &config.nominal_timing, + &config.fd_timing, + self.function_clock_frequency(), + ); + + match config.secondary_sample_point_offset { + // The hardware counts the offset in function clock cycles. + Some(offset) => self.bus.driver.set_secondary_sample_point( + SspSource::MeasuredPlusOffset, + offset.saturating_mul(config.fd_timing.baud_rate_prescaler), + ), + None => self + .bus + .driver + .set_secondary_sample_point(SspSource::Disabled, 0), + } + + Ok(()) + } + + /// Joins the bus and waits for the controller to become error-active. + /// + /// Follows the initialization sequence in TRM 38.3.5. + /// + /// # Errors + /// + /// [`Error::BusIntegrationTimeout`] when the bus does not go idle-recessive + /// long enough for the controller to join it. The controller stays off the + /// bus in that case, unless it was on the bus before the call. + pub fn start(&mut self) -> Result<(), Error> { + let timeout = integration_timeout( + &self.config.nominal_timing, + &self.config.fd_timing, + self.function_clock_frequency(), + ); + + let was_enabled = self.bus.driver.is_enabled(); + self.bus.enable(); + + // Integration finishes when the controller becomes error-active, after + // 11 consecutive recessive bits. + let deadline = Instant::now() + timeout; + loop { + if self.bus.driver.error_state() == ErrorState::Active { + return Ok(()); + } + if Instant::now() > deadline { + if !was_enabled { + self.bus.disable(); + } + return Err(Error::BusIntegrationTimeout); + } + } + } + + /// Leaves the bus, following the de-initialization sequence in TRM 38.3.6. + /// + /// Every TX buffer returns to the empty state without its memory being + /// cleared, and the RX buffer is flushed. + /// + /// While the controller is on the bus, the driver holds a [`WakeLock`], + /// because Light-sleep mode gates the function clock. Leaving the bus + /// releases the lock. A running timestamp counter does not advance during + /// sleep. + /// + /// # Errors + /// + /// [`Error::AbortTimeout`] when a transmission does not settle. The + /// controller stays on the bus in that case. + pub fn stop(&mut self) -> Result<(), Error> { + self.bus.quiesce()?; + self.bus.disable(); + Ok(()) + } + + /// Returns whether the controller is on the bus. + /// + /// This is true between a successful [`CanFd::start`] and the next + /// [`CanFd::stop`] or [`CanFd::apply_config`]. + pub fn is_started(&self) -> bool { + self.bus.driver.is_enabled() + } + + /// Returns the identity of the core. + pub fn identity(&self) -> Identity { + let (major, minor) = self.bus.driver.version(); + Identity { + device_id: self.bus.driver.device_id(), + version_major: major, + version_minor: minor, + } + } + + /// Returns the frequency of the controller's function clock, in Hz. + pub fn function_clock_frequency(&self) -> u32 { + self.twai.info().clock_instance.function_clock_frequency() + } + + /// Splits the controller into a receiving and a transmitting half. + /// + /// The two halves can be used at the same time, for example to wait for a + /// frame while a transmission is in flight. They arm different interrupt + /// sources, so neither disturbs the other. + /// + /// The halves borrow the driver, which keeps the configuration and the + /// teardown: everything that reconfigures the controller or takes it off + /// the bus stays on [`CanFd`] and is unavailable while a half is alive. For + /// two independent tasks, split a driver that lives in a `static`. + pub fn split(&mut self) -> (CanFdRx<'_, Dm>, CanFdTx<'_, Dm>) { + let (info, state) = self.twai.parts(); + ( + CanFdRx { + driver: Driver::new(info.register_block), + state, + _driver: PhantomData, + _mode: PhantomData, + }, + CanFdTx { + driver: Driver::new(info.register_block), + state, + tx_buffers: self.bus.tx_buffers, + _driver: PhantomData, + _mode: PhantomData, + }, + ) + } + + fn rx_half(&mut self) -> CanFdRx<'_, Dm> { + self.split().0 + } + + fn tx_half(&mut self) -> CanFdTx<'_, Dm> { + self.split().1 + } + + /// Returns the number of TX buffers the hardware provides. + pub fn tx_buffer_count(&self) -> u8 { + self.bus.tx_buffers + } + + /// Queues a frame in the first free TX buffer and arms it. + /// + /// Returns the index of the buffer used. The hardware chooses the order in + /// which armed buffers are sent, not the order in which they were queued; + /// see [`CanFdTx::transmit`]. + /// + /// # Errors + /// + /// [`Error::ControllerStopped`] when the controller is not on the bus, and + /// [`Error::NoFreeTxBuffer`] when every TX buffer is occupied; see + /// [`CanFdTx::transmit`]. + pub fn transmit(&mut self, frame: &Frame) -> Result { + self.tx_half().transmit(frame) + } + + /// Returns the state of one TX buffer. + /// + /// Returns [`TxBufferState::NotExist`] for an index the hardware does not + /// have. + pub fn tx_buffer_state(&self, index: u8) -> TxBufferState { + if index >= self.bus.tx_buffers { + return TxBufferState::NotExist; + } + self.bus.driver.tx_buffer_state(index) + } + + /// Requests that a queued transmission be aborted. + /// + /// The buffer moves to "aborted", or to "abort in progress" if the frame is + /// already on the wire. Does nothing for an index the hardware does not + /// have. + pub fn abort_transmit(&mut self, index: u8) { + if index < self.bus.tx_buffers { + self.bus.driver.set_tx_abort(index); + } + } + + /// Returns a TX buffer to the empty state, releasing it for reuse. + /// + /// Does nothing for an index the hardware does not have. + pub fn release_tx_buffer(&mut self, index: u8) { + if index < self.bus.tx_buffers { + self.bus.driver.set_tx_empty(index); + } + } + + /// Sets a TX buffer's arbitration priority. + /// + /// Higher values win, and a value above [`MAX_TX_PRIORITY`] counts as that + /// maximum; see [`CanFdTx::set_tx_priority`]. + pub fn set_tx_priority(&mut self, index: u8, priority: u8) { + self.tx_half().set_tx_priority(index, priority); + } + + /// Returns the number of complete frames waiting in the RX buffer. + pub fn rx_frame_count(&self) -> u16 { + self.bus.driver.rx_frame_count() + } + + /// Reads one frame from the RX buffer. + /// + /// # Errors + /// + /// [`Error::RxBufferEmpty`] when no complete frame is waiting. + pub fn receive(&mut self) -> Result { + self.rx_half().receive() + } + + /// Discards everything in the RX buffer. + pub fn flush_rx(&mut self) { + self.bus.driver.flush_rx(); + } + + /// Returns the size of the RX buffer in 32-bit words. + pub fn rx_buffer_size_words(&self) -> u16 { + self.bus.driver.rx_buffer_size() + } + + /// Returns the free space in the RX buffer in 32-bit words. + pub fn rx_buffer_free_words(&self) -> u16 { + self.bus.driver.rx_free_words() + } + + /// Returns whether the RX buffer has overrun and dropped a frame + /// (TRM 38.3.9.4). + pub fn rx_overrun(&self) -> bool { + self.bus.driver.rx_overrun() + } + + /// Clears the RX buffer overrun flag. + pub fn clear_rx_overrun(&mut self) { + self.bus.driver.clear_overrun(); + } + + /// Returns the current fault confinement state. + /// + /// Returns [`ErrorState::BusOff`] while the controller is off the bus, both + /// before the first [`CanFd::start`] and after [`CanFd::stop`]; that is how + /// the hardware reports a disabled controller. [`CanFd::is_started`] tells + /// the two apart. + pub fn error_state(&self) -> ErrorState { + self.bus.driver.error_state() + } + + /// Returns whether an error counter has reached the error warning limit. + /// + /// A node at the limit is still [`ErrorState::Active`] (TRM 38.3.10). + pub fn error_warning(&self) -> bool { + self.bus.driver.error_warning() + } + + /// Returns the receive error counter. + pub fn receive_error_count(&self) -> u16 { + self.bus.driver.rec() + } + + /// Returns the transmit error counter. + pub fn transmit_error_count(&self) -> u16 { + self.bus.driver.tec() + } + + /// Requests that a bus-off controller rejoin the bus; see + /// [`CanFdTx::request_bus_off_recovery`]. + pub fn request_bus_off_recovery(&mut self) { + self.tx_half().request_bus_off_recovery(); + } + + /// Sets the error warning limit, which defaults to 96. + /// + /// The hardware only accepts the write in test mode (TRM 38.3.10), which + /// is entered for the write and left again. + /// + /// # Errors + /// + /// [`Error::ControllerRunning`] when the controller is still on the bus. + pub fn set_error_warning_limit(&mut self, limit: u8) -> Result<(), Error> { + if self.bus.driver.is_enabled() { + return Err(Error::ControllerRunning); + } + self.bus.driver.enable_test_mode(true); + self.bus.driver.set_error_warning_limit(limit); + self.bus.driver.enable_test_mode(false); + Ok(()) + } + + /// Resets the received and transmitted frame counters. + pub fn reset_traffic_counters(&mut self) { + self.bus.driver.reset_traffic_counters(); + } + + /// Returns the number of frames received since the traffic counters were + /// last reset. + pub fn rx_traffic_count(&self) -> u32 { + self.bus.driver.rx_traffic_counter() + } + + /// Returns the number of frames transmitted since the traffic counters + /// were last reset. + pub fn tx_traffic_count(&self) -> u32 { + self.bus.driver.tx_traffic_counter() + } + + /// Configures one mask filter and enables it. + /// + /// A frame reaches the RX buffer if it passes at least one enabled filter + /// (TRM 38.3.9.8). Out of reset, filter A accepts every frame; see + /// [`CanFd::accept_all`]. + pub fn set_mask_filter(&mut self, filter: MaskFilter, config: &MaskFilterConfig) { + self.bus + .driver + .set_mask_filter(filter, config.extended, config.id, config.mask); + self.filter_kinds[Self::mask_filter_index(filter)] = config.kinds(); + self.apply_filter_kinds(); + } + + /// Disables one mask filter. + pub fn disable_mask_filter(&mut self, filter: MaskFilter) { + self.filter_kinds[Self::mask_filter_index(filter)] = FrameKinds::NONE; + self.apply_filter_kinds(); + } + + /// Configures the range filter and enables it. + pub fn set_range_filter(&mut self, config: &RangeFilterConfig) { + self.bus + .driver + .set_range_filter(config.extended, config.low, config.high); + self.filter_kinds[RANGE_FILTER_INDEX] = config.kinds(); + self.apply_filter_kinds(); + } + + /// Disables the range filter. + pub fn disable_range_filter(&mut self) { + self.filter_kinds[RANGE_FILTER_INDEX] = FrameKinds::NONE; + self.apply_filter_kinds(); + } + + /// Accepts every frame, by giving filter A a zero mask and disabling the rest. + /// + /// This is the one filter setting that matches standard and extended + /// identifiers at once. + pub fn accept_all(&mut self) { + // A zero mask passes any identifier word, so the format only decides + // how the zeros are shifted. + self.bus.driver.set_mask_filter(MaskFilter::A, false, 0, 0); + self.filter_kinds = RESET_FILTER_KINDS; + self.apply_filter_kinds(); + } + + fn mask_filter_index(filter: MaskFilter) -> usize { + match filter { + MaskFilter::A => 0, + MaskFilter::B => 1, + MaskFilter::C => 2, + } + } + + fn apply_filter_kinds(&mut self) { + let [a, b, c, range] = self.filter_kinds; + self.bus.driver.set_filter_kinds(a, b, c, range); + } + + /// Returns details of the last bus error the core captured. + /// + /// Only meaningful after the core has reported a bus error; see + /// [`ErrorCapture`]. + pub fn error_capture(&self) -> ErrorCapture { + self.bus.driver.error_capture() + } + + /// Returns the number of retransmission attempts made for the frame + /// currently being sent. + pub fn retransmit_count(&self) -> u8 { + self.bus.driver.retransmit_count() + } + + /// Returns the number of errors detected at the nominal bit rate. + pub fn nominal_error_count(&self) -> u16 { + self.bus.driver.nominal_error_count() + } + + /// Returns the number of errors detected at the data bit rate, in the data + /// phase of bit-rate-switched frames. + pub fn fd_error_count(&self) -> u16 { + self.bus.driver.fd_error_count() + } + + /// Returns the transmitter delay the core measured, in function clock + /// periods. + /// + /// The core measures the delay during every FD frame it sends + /// (TRM 38.3.7.2), so the value reads zero until the first one. The + /// secondary sample point sits at this delay plus the configured offset, + /// and the four-bit-time limit of TRM 38.3.7.3 applies to that sum. + pub fn transmitter_delay(&self) -> u8 { + self.bus.driver.transmitter_delay() + } + + /// Starts the timestamp counter from zero, at the requested resolution. + /// + /// Received frames are stamped at the sixth bit of their end-of-frame + /// field, which is when a frame becomes valid. The achievable resolution is + /// the function clock divided by an integer, so the returned value is the + /// resolution actually programmed, in Hz. + /// + /// # Errors + /// + /// [`ConfigError::UnsupportedTimestampResolution`] when the resolution + /// cannot be reached from the function clock. + /// + /// [`ConfigError::TimestampTimerStalled`] when the counter does not start. + pub fn start_timestamp_timer(&mut self, resolution_hz: u32) -> Result { + let clock = self.function_clock_frequency(); + if resolution_hz == 0 || resolution_hz > clock { + return Err(ConfigError::UnsupportedTimestampResolution); + } + + let divider = clock / resolution_hz; + let divider = + u16::try_from(divider).map_err(|_| ConfigError::UnsupportedTimestampResolution)?; + + self.bus.driver.timer_enable(false); + self.bus.driver.timer_enable_config_clock(true); + + self.bus.driver.timer_set_divider(divider); + self.bus.driver.timer_count_up(true); + self.bus.driver.timer_set_free_running(); + self.bus.driver.timer_enable(true); + self.bus.driver.timer_clear(); + + // The prescaler keeps its phase across a reprogram and compares + // against the divider instead of reloading, so a divider below the + // phase it holds is missed until the 16-bit prescaler wraps. Measured + // on an ESP32-C5; nothing resets that phase. Wait it out rather than + // hand back a counter that stands still for up to 819 us. + let cycles = u64::from(PRESCALER_PERIOD) + 2 * u64::from(divider); + let deadline = Instant::now() + + Duration::from_micros(cycles * 1_000_000 / u64::from(clock)) + + Duration::from_millis(1); + while self.bus.driver.timer_count() == 0 { + if Instant::now() > deadline { + return Err(ConfigError::TimestampTimerStalled); + } + } + + Ok(clock / u32::from(divider)) + } + + /// Stops the timestamp counter. + pub fn stop_timestamp_timer(&mut self) { + self.bus.driver.timer_enable(false); + self.bus.driver.timer_enable_config_clock(false); + } + + /// Returns the current value of the timestamp counter. + pub fn timestamp(&self) -> u64 { + self.bus.driver.timer_count() + } + + /// Returns the width of the timestamp counter in bits. + pub fn timestamp_bit_width(&self) -> u8 { + self.bus.driver.timer_bit_width() + } +} + +crate::any_peripheral! { + /// Any CAN FD peripheral. + pub peripheral AnyCanFd<'d> { + Twai0(crate::peripherals::TWAI0<'d>), + Twai1(crate::peripherals::TWAI1<'d>), + } +} + +/// Peripheral data describing one CAN FD controller. +#[doc(hidden)] +#[non_exhaustive] +pub struct Info { + pub register_block: *const crate::pac::twai0::RegisterBlock, + pub peripheral: Peripheral, + pub clock_instance: TwaiInstance, + pub interrupt: Interrupt, + pub async_handler: InterruptHandler, + pub rx_signal: InputSignal, + pub tx_signal: OutputSignal, +} + +unsafe impl Sync for Info {} + +/// A peripheral singleton compatible with the CAN FD driver. +pub trait Instance: crate::private::Sealed + any::Degrade { + /// Returns the peripheral data and state describing this controller. + #[doc(hidden)] + fn parts(&self) -> (&'static Info, &'static asynch::State); + + /// Returns the peripheral data describing this controller. + #[doc(hidden)] + #[inline(always)] + fn info(&self) -> &'static Info { + self.parts().0 + } + + /// Returns the peripheral state of this controller. + #[doc(hidden)] + #[inline(always)] + fn state(&self) -> &'static asynch::State { + self.parts().1 + } +} + +for_each_canfd! { + ($instance:ident, $sys:ident, $rx:ident, $tx:ident) => { + impl Instance for crate::peripherals::$instance<'_> { + fn parts(&self) -> (&'static Info, &'static asynch::State) { + #[crate::handler] + fn irq_handler() { + asynch::handle(&INFO, &STATE); + } + + static STATE: asynch::State = asynch::State::new(); + + static INFO: Info = Info { + register_block: crate::peripherals::$instance::ptr(), + peripheral: Peripheral::$sys, + clock_instance: TwaiInstance::$sys, + interrupt: Interrupt::$instance, + async_handler: irq_handler, + rx_signal: InputSignal::$rx, + tx_signal: OutputSignal::$tx, + }; + + (&INFO, &STATE) + } + } + }; +} + +impl Instance for AnyCanFd<'_> { + #[inline] + fn parts(&self) -> (&'static Info, &'static asynch::State) { + any::delegate!(self, twai => { twai.parts() }) + } +} + +/// Index of the range filter in `CanFd::filter_kinds`. +const RANGE_FILTER_INDEX: usize = 3; + +/// The reset value of `CanFd::filter_kinds`: filter A accepts everything, the +/// rest are off. +const RESET_FILTER_KINDS: [FrameKinds; 4] = [ + FrameKinds::ALL, + FrameKinds::NONE, + FrameKinds::NONE, + FrameKinds::NONE, +]; + +/// Function clock periods the timestamp prescaler takes to wrap, measured on +/// an ESP32-C5. +const PRESCALER_PERIOD: u32 = 1 << 16; + +/// Transmitter delay the core adds on its own, in function clock periods +/// (TRM 38.3.7.3). +const MIN_TRANSMITTER_DELAY_CYCLES: u32 = 2; + +/// Bit times allowed for joining the bus: a frame already in flight (under 800 +/// bit times at most), then the 11 recessive bits of integration. +const INTEGRATION_TIMEOUT_BITS: u64 = 2048; + +/// Shortest wait for bus integration, so the bound at megabit rates is not +/// about the speed of the polling loop. +const INTEGRATION_TIMEOUT_FLOOR: Duration = Duration::from_millis(50); + +/// Bit times allowed for a transmission to settle: an abort only takes effect +/// once the frame in flight has finished. +const ABORT_TIMEOUT_BITS: u64 = 1024; + +/// How long a transmission may take to finish or abort while leaving the bus. +/// +/// Derived from the slower of the two phases: a bit rate switched frame +/// spends its data field at the FD timing, and nothing requires that to be the +/// faster one. +fn abort_timeout(nominal: &Timing, fd: &Timing, function_clock_hz: u32) -> Duration { + // The added millisecond covers the polling loop at fast bit rates. + bit_times( + slowest_cycles_per_bit(nominal, fd), + ABORT_TIMEOUT_BITS, + function_clock_hz, + ) + Duration::from_millis(1) +} + +/// How long the controller may take to join the bus. +fn integration_timeout(nominal: &Timing, fd: &Timing, function_clock_hz: u32) -> Duration { + let derived = bit_times( + slowest_cycles_per_bit(nominal, fd), + INTEGRATION_TIMEOUT_BITS, + function_clock_hz, + ); + + if derived < INTEGRATION_TIMEOUT_FLOOR { + INTEGRATION_TIMEOUT_FLOOR + } else { + derived + } +} + +/// Function clock periods one bit takes in the slower of the two phases. +fn slowest_cycles_per_bit(nominal: &Timing, fd: &Timing) -> u64 { + let cycles_per_bit = + |timing: &Timing| u64::from(timing.baud_rate_prescaler) * u64::from(timing.total_quanta()); + cycles_per_bit(nominal).max(cycles_per_bit(fd)) +} + +/// How long `bits` bit times last, given the clock periods one bit takes. +fn bit_times(cycles_per_bit: u64, bits: u64, function_clock_hz: u32) -> Duration { + // Scaled before dividing: a bit at 2 Mbit/s is half a microsecond. + let micros = cycles_per_bit + .saturating_mul(bits) + .saturating_mul(1_000_000) + / u64::from(function_clock_hz).max(1); + + Duration::from_micros(micros) +} + +struct FunctionClockGuard { + instance: TwaiInstance, +} + +impl FunctionClockGuard { + fn new(instance: TwaiInstance, clock_source: ClockSource) -> Self { + ClockTree::with(|clocks| { + // The mux must be configured before the clock is requested. + instance.configure_function_clock(clocks, clock_source); + instance.request_function_clock(clocks); + }); + Self { instance } + } + + fn set_source(&self, clock_source: ClockSource) { + ClockTree::with(|clocks| { + self.instance.configure_function_clock(clocks, clock_source); + }); + } +} + +impl Drop for FunctionClockGuard { + fn drop(&mut self) { + ClockTree::with(|clocks| self.instance.release_function_clock(clocks)); + } +} diff --git a/esp-hal/src/clock/mod.rs b/esp-hal/src/clock/mod.rs index d25cee45351..f6ce356f7ab 100644 --- a/esp-hal/src/clock/mod.rs +++ b/esp-hal/src/clock/mod.rs @@ -21,11 +21,11 @@ //! The `CPU clock` is responsible for defining the speed at which the central //! processing unit (CPU) operates. This driver provides predefined options for //! different CPU clock speeds, such as -#![cfg_attr(not(esp32h2), doc = "* 80MHz")] -#![cfg_attr(esp32h2, doc = "* 96MHz")] -#![cfg_attr(esp32c2, doc = "* 120MHz")] -#![cfg_attr(not(any(esp32c2, esp32h2)), doc = "* 160MHz")] -#![cfg_attr(any(esp32c5, xtensa), doc = "* 240MHz")] +#![cfg_attr(not(esp32h2), doc = "* 80 MHz")] +#![cfg_attr(esp32h2, doc = "* 96 MHz")] +#![cfg_attr(esp32c2, doc = "* 120 MHz")] +#![cfg_attr(not(any(esp32c2, esp32h2)), doc = "* 160 MHz")] +#![cfg_attr(any(esp32c5, xtensa), doc = "* 240 MHz")] //! ### Frozen Clock Frequencies //! //! Once the clock configuration is applied, the clock frequencies become @@ -47,11 +47,10 @@ #[cfg(soc_has_clock_node_lp_slow_clk)] use clocks::LpSlowClkConfig; -#[cfg(all(not(esp32s2), soc_has_clock_node_rtc_slow_clk))] +#[cfg(soc_has_clock_node_rtc_slow_clk)] use clocks::RtcSlowClkConfig; #[cfg(soc_has_clock_node_timg_function_clock)] use clocks::TimgFunctionClockConfig; -use portable_atomic::AtomicU32; pub(crate) mod dividers; @@ -59,7 +58,7 @@ pub(crate) mod dividers; /// ///
/// This module provides experimental low-level clock control functionality. These functions -/// can render your device temporarily unusable. Use with caution. +/// can render the device temporarily unusable. Use with caution. ///
#[doc = ""] #[instability::unstable] @@ -99,9 +98,9 @@ cfg_select! { impl CpuClock { #[procmacros::doc_replace] - /// Use the highest possible frequency for a particular chip. + /// Returns the highest possible CPU clock frequency for this chip. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -114,7 +113,7 @@ impl CpuClock { cfg_select! { esp32c2 => Self::_120MHz, any(esp32c3, esp32c6, esp32c61) => Self::_160MHz, - esp32h2 => Self::_96MHz, + any(esp32h2, esp32h4) => Self::_96MHz, esp32p4 => Self::_400MHz, esp32s31 => Self::_320MHz, _ => Self::_240MHz, @@ -133,7 +132,7 @@ use crate::soc::clocks::TimgCalibrationClockConfig; impl RtcClock { pub(crate) const CAL_FRACT: u32 = 19; - /// Get the nominal value of the RTC_SLOW_CLK source. + /// Returns the nominal value of the RTC_SLOW_CLK source. #[instability::unstable] #[cfg(any(soc_has_clock_node_lp_slow_clk, soc_has_clock_node_rtc_slow_clk))] pub fn slow_freq() -> Rate { @@ -145,17 +144,16 @@ impl RtcClock { Rate::from_hz(freq) } - /// Measure the frequency of one of the TIMG0 calibration clocks, + /// Measures the frequency of one of the TIMG0 calibration clocks, /// using XTAL_CLK as the reference clock. /// - /// This function will time out and return 0 if the time for the given - /// number of cycles to be counted exceeds the expected time twice. This - /// may happen if 32k XTAL is being calibrated, but the oscillator has - /// not started up (due to incorrect loading capacitance, board design - /// issue, or lack of 32 XTAL on board). + /// Times out and returns 0 if the time for the given number of cycles to be + /// counted exceeds the expected time twice. This may happen if 32k XTAL is + /// being calibrated, but the oscillator has not started up (due to incorrect + /// loading capacitance, board design issue, or lack of 32 XTAL on board). #[cfg(soc_has_clock_node_timg_calibration_clock)] pub(crate) fn calibrate(cal_clk: TimgCalibrationClockConfig, slowclk_cycles: u32) -> u32 { - #[cfg(not(esp32c2))] + #[cfg(use_xtal32k)] if cal_clk == TimgCalibrationClockConfig::Xtal32kClk { debug!("Assuming Xtal32k has precisely 32.768kHz instead of calibrating"); let freq_hz: u64 = 32_768; @@ -231,6 +229,8 @@ pub(crate) fn init(cpu_clock_config: ClockConfig) { clocks::request_pll_f240m(clocks); #[cfg(soc_has_clock_node_rc_fast_div_clk)] clocks::request_rc_fast_div_clk(clocks); + #[cfg(soc_has_clock_node_rtc_slow_clk)] + clocks::request_rtc_slow_clk(clocks); }); calibrate_rtc_slow_clock(); @@ -238,10 +238,10 @@ pub(crate) fn init(cpu_clock_config: ClockConfig) { } impl RtcClock { - /// Uses a TIMG0 feature to count clock cycles of a high-frequency clock, for a period of time - /// that is measured by a low-frequency clock. This function can be used to calibrate two - /// clocks to each other, e.g. to determine a rough value of the XTAL clock, or to determine - /// the current frequency of a low-precision RC oscillator. + /// Counts clock cycles of a high-frequency clock for a period of time measured + /// by a low-frequency clock. Calibrates two clocks to each other, e.g. to + /// determine a rough value of the XTAL clock, or to determine the current + /// frequency of a low-precision RC oscillator. #[cfg(soc_has_clock_node_timg_calibration_clock)] pub(crate) fn measure_rtc_clock( clocks: &mut ClockTree, @@ -411,6 +411,13 @@ impl RtcClock { } }; + #[cfg(esp32h4)] + let cali_value = if rtc_clock == TimgCalibrationClockConfig::RcSlowClk { + cali_value * property!("timergroup.rc_slow_calibration_multiplier") + } else { + cali_value + }; + TIMG0::regs() .rtccalicfg() .modify(|_, w| w.rtc_cali_start().clear_bit()); @@ -457,22 +464,31 @@ pub(crate) fn calibrate_rtc_slow_clock() { esp32s2 => { // Can directly measure output of the RTC_SLOW mux let slow_clk = TimgCalibrationClockConfig::RtcClk; + let rc_slow_selected = + unwrap!(ClockTree::with(clocks::rtc_slow_clk_config)) == RtcSlowClkConfig::RcSlow; } soc_has_clock_node_rtc_slow_clk => { - let slow_clk = match unwrap!(ClockTree::with(clocks::rtc_slow_clk_config)) { + let slow_clk_config = unwrap!(ClockTree::with(clocks::rtc_slow_clk_config)); + let rc_slow_selected = slow_clk_config == RtcSlowClkConfig::RcSlow; + let slow_clk = match slow_clk_config { RtcSlowClkConfig::RcFast => TimgCalibrationClockConfig::RcFastDivClk, RtcSlowClkConfig::RcSlow => TimgCalibrationClockConfig::RcSlowClk, - #[cfg(not(esp32c2))] + #[cfg(use_xtal32k)] RtcSlowClkConfig::Xtal32k => TimgCalibrationClockConfig::Xtal32kClk, #[cfg(esp32c2)] RtcSlowClkConfig::OscSlow => TimgCalibrationClockConfig::Osc32kClk, }; } soc_has_clock_node_lp_slow_clk => { - let slow_clk = match unwrap!(ClockTree::with(clocks::lp_slow_clk_config)) { + let slow_clk_config = unwrap!(ClockTree::with(clocks::lp_slow_clk_config)); + let rc_slow_selected = slow_clk_config == LpSlowClkConfig::RcSlow; + let slow_clk = match slow_clk_config { // on S31, clock can not be calibrated to get OSC_SLOW actual frequency - #[cfg(not(esp32s31))] + #[cfg(all(not(esp32s31), use_xtal32k))] LpSlowClkConfig::OscSlow => TimgCalibrationClockConfig::Xtal32kClk, //? + #[cfg(all(not(esp32s31), not(use_xtal32k)))] + LpSlowClkConfig::OscSlow => TimgCalibrationClockConfig::RcSlowClk, + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => TimgCalibrationClockConfig::Xtal32kClk, LpSlowClkConfig::RcSlow => TimgCalibrationClockConfig::RcSlowClk, }; @@ -484,6 +500,10 @@ pub(crate) fn calibrate_rtc_slow_clock() { const SLOW_CLK_SRC_CAL_CYCLES: u32 = 16; let cal_val = RtcClock::calibrate(slow_clk, SLOW_CLK_SRC_CAL_CYCLES); + if cal_val == 0 { + panic!("{:?} calibration failed.", slow_clk); + } + let reg = cfg_select! { esp32s31 => LP_AON::regs().lp_store(1), esp32p4 => LP_AON::regs().lp_store1(), @@ -491,21 +511,45 @@ pub(crate) fn calibrate_rtc_slow_clock() { }; reg.write(|w| unsafe { w.bits(cal_val) }); -} -static RC_FAST_CAL_VAL: AtomicU32 = AtomicU32::new(0); + if rc_slow_selected { + let frequency = ((1_000_000u64 << RtcClock::CAL_FRACT) / cal_val as u64) as u32; + + // On some chips, the calibrated clock is RC_SLOW_CLK divided down. + let divider = clocks::rc_slow_clk_frequency() + / clocks::timg_calibration_clock_source_frequency(slow_clk); + + ClockTree::with(|clocks| clocks::set_rc_slow_clk_frequency(clocks, frequency * divider)); + } +} #[cfg(soc_has_clock_node_timg_calibration_clock)] pub(crate) fn calibrate_rtc_fast_clock() { // Clock is in order of 10 MHz const FAST_CLK_SRC_CAL_CYCLES: u32 = 128; - let cal_val = RtcClock::calibrate( - TimgCalibrationClockConfig::RcFastDivClk, - FAST_CLK_SRC_CAL_CYCLES, - ); + ClockTree::with(|clocks| { + let (xtal_cycles, calibration_clock_frequency) = RtcClock::measure_rtc_clock( + clocks, + TimgCalibrationClockConfig::RcFastDivClk, + #[cfg(soc_has_clock_node_timg_function_clock)] + TimgFunctionClockConfig::XtalClk, + FAST_CLK_SRC_CAL_CYCLES, + ); + + if xtal_cycles == 0 { + warn!("RC_FAST_CLK calibration failed"); + return; + } + + // On some chips, the calibration input is RC_FAST_CLK divided by 256. + let divider = clocks::rc_fast_clk_frequency() / calibration_clock_frequency.as_hz(); + let frequency = + (clocks::xtal_clk_frequency() as u64 * FAST_CLK_SRC_CAL_CYCLES as u64 * divider as u64 + / xtal_cycles as u64) as u32; - RC_FAST_CAL_VAL.store(cal_val, core::sync::atomic::Ordering::Relaxed); + clocks::set_rc_fast_clk_frequency(clocks, frequency); + }); } #[cfg(not(soc_has_clock_node_timg_calibration_clock))] @@ -523,7 +567,7 @@ pub fn xtal_clock() -> Rate { Rate::from_hz(ll::xtal_clk_frequency()) } -/// Read the calibrated RTC slow clock period from the STORE1 register. +/// Reads the calibrated RTC slow clock period from the STORE1 register. /// /// The period is in unit of microseconds, represented as a fixed-point number /// with `RtcClock::CAL_FRACT` fractional bits. @@ -539,14 +583,7 @@ pub(crate) fn rtc_slow_cal_period() -> u32 { reg.read().bits() } -/// Read the calibrated RTC fast clock period from memory. -#[cfg_attr(not(soc_has_pmu), expect(dead_code))] -#[cfg_attr(esp32s31, expect(dead_code))] -pub(crate) fn rtc_fast_cal_period() -> u32 { - RC_FAST_CAL_VAL.load(core::sync::atomic::Ordering::Relaxed) -} - -/// Convert RTC slow clock ticks to microseconds using the calibrated period. +/// Converts RTC slow clock ticks to microseconds using the calibrated period. #[cfg(lp_timer_driver_supported)] pub(crate) fn rtc_ticks_to_us(ticks: u64) -> u64 { let period = rtc_slow_cal_period() as u64; @@ -565,7 +602,7 @@ pub(crate) fn rtc_ticks_to_us(ticks: u64) -> u64 { upper * period + ((lower * period) >> RtcClock::CAL_FRACT) } -/// Convert microseconds to RTC slow clock ticks using the calibrated period. +/// Converts microseconds to RTC slow clock ticks using the calibrated period. pub(crate) fn us_to_rtc_ticks(time_in_us: u64) -> u64 { let period = rtc_slow_cal_period() as u64; diff --git a/esp-hal/src/debugger.rs b/esp-hal/src/debugger.rs index da0b1b79d42..314a48fcdd6 100644 --- a/esp-hal/src/debugger.rs +++ b/esp-hal/src/debugger.rs @@ -1,6 +1,6 @@ //! Debugger utilities -/// Checks if a debugger is connected. +/// Returns whether a debugger is connected. pub fn debugger_connected() -> bool { cfg_select! { xtensa => xtensa_lx::is_debugger_attached(), @@ -14,7 +14,7 @@ pub fn debugger_connected() -> bool { } } -/// Set a word-sized data breakpoint at the given address. +/// Sets a word-sized data breakpoint at the given address. /// No breakpoint will be set when a debugger is currently attached if /// the `stack_guard_monitoring_with_debugger_connected` option is false. /// @@ -63,22 +63,22 @@ bitfield::bitfield! { #[derive(Clone, Copy, Default)] pub(crate) struct Tdata1(u32); - /// Set this for configuring the selected trigger to fire right before a load operation with matching + /// Sets this for configuring the selected trigger to fire right before a load operation with matching /// data address is executed by the CPU. pub bool, load, set_load: 0; - /// Set this for configuring the selected trigger to fire right before a store operation with matching + /// Sets this for configuring the selected trigger to fire right before a store operation with matching /// data address is executed by the CPU. pub bool, store, set_store: 1; - /// Set this for configuring the selected trigger to fire right before an instruction with matching + /// Sets this for configuring the selected trigger to fire right before an instruction with matching /// virtual address is executed by the CPU. pub bool, execute, set_execute: 2; - /// Set this for enabling selected trigger to operate in user mode. + /// Sets this for enabling selected trigger to operate in user mode. pub bool, u, set_u: 3; - /// Set this for enabling selected trigger to operate in machine mode. + /// Sets this for enabling selected trigger to operate in machine mode. pub bool, m, set_m: 6; /// Configures the selected trigger to perform one of the available matching operations on a @@ -87,14 +87,14 @@ bitfield::bitfield! { /// the value of maddress exactly. /// 0x1: NAPOT match, i.e. at least one of the bytes of an access must lie in the NAPOT region /// specified in maddress. - /// Note: Writing a larger value will clip it to the largest possible value 0x1. + /// Writing a larger value clips it to the largest possible value 0x1. pub u8, _match, set_match: 10, 7; /// Configures the selected trigger to perform one of the available actions when firing. Valid /// options are: /// 0x0: cause breakpoint exception. /// 0x1: enter debug mode (only valid when dmode = 1) - /// Note: Writing an invalid value will set this to the default value 0x0. + /// Writing an invalid value sets this to the default value 0x0. pub u8, action, set_action: 15, 12; /// This is found to be 1 if the selected trigger had fired previously. This bit is to be cleared manually. @@ -103,7 +103,7 @@ bitfield::bitfield! { /// 0: Both Debug and M mode can write the tdata1 and tdata2 registers at the selected tselect. /// 1: Only Debug Mode can write the tdata1 and tdata2 registers at the selected tselect. Writes from /// other modes are ignored. - /// Note: Only writable from debug mode. + /// Only writable from debug mode. pub bool, dmode, set_dmode: 27; } @@ -127,7 +127,7 @@ pub(crate) struct WatchPoint { tdata2: u32, } -/// Clear the watchpoint +/// Clears the watchpoint. #[cfg(riscv)] pub(crate) unsafe fn clear_watchpoint(id: u8) -> WatchPoint { assert!(id < 4); @@ -151,7 +151,7 @@ pub(crate) unsafe fn clear_watchpoint(id: u8) -> WatchPoint { WatchPoint { tdata1, tdata2 } } -/// Clear the watchpoint +/// Clears the watchpoint. #[cfg(riscv)] pub(crate) unsafe fn restore_watchpoint(id: u8, watchpoint: WatchPoint) { DEBUGGER_LOCK.lock(|| unsafe { @@ -167,7 +167,7 @@ pub(crate) unsafe fn restore_watchpoint(id: u8, watchpoint: WatchPoint) { }); } -/// Clear the watchpoint +/// Clears the watchpoint. #[cfg(all(riscv, feature = "exception-handler"))] pub(crate) unsafe fn watchpoint_hit(id: u8) -> bool { assert!(id < 4); @@ -186,7 +186,7 @@ pub(crate) unsafe fn watchpoint_hit(id: u8) -> bool { tdata.hit() } -/// Set watchpoint and enable triggers. +/// Sets the watchpoint and enables triggers. #[cfg(riscv)] pub(crate) unsafe fn set_watchpoint(id: u8, addr: usize, len: usize) { assert!(id < 4); diff --git a/esp-hal/src/delay.rs b/esp-hal/src/delay.rs index e5a3d2a161c..357ab50ef4b 100644 --- a/esp-hal/src/delay.rs +++ b/esp-hal/src/delay.rs @@ -32,7 +32,7 @@ use crate::time::{Duration, Instant}; -/// Delay driver, using [`Instant`]. +/// Delay driver that uses [`Instant`]. #[derive(Clone, Copy, Default)] #[non_exhaustive] pub struct Delay; @@ -49,24 +49,24 @@ impl Delay { Self {} } - /// Delay for the specified time + /// Delays for the specified time. pub fn delay(&self, delay: Duration) { let start = Instant::now(); while start.elapsed() < delay {} } - /// Delay for the specified number of milliseconds + /// Delays for the specified number of milliseconds. pub fn delay_millis(&self, ms: u32) { self.delay(Duration::from_millis(ms as u64)); } - /// Delay for the specified number of microseconds + /// Delays for the specified number of microseconds. pub fn delay_micros(&self, us: u32) { self.delay(Duration::from_micros(us as u64)); } - /// Delay for the specified number of nanoseconds + /// Delays for the specified number of nanoseconds. pub fn delay_nanos(&self, ns: u32) { self.delay(Duration::from_micros(ns.div_ceil(1000) as u64)); } diff --git a/esp-hal/src/dma/aligned.rs b/esp-hal/src/dma/aligned.rs index fb52933f7e0..21d75d7885e 100644 --- a/esp-hal/src/dma/aligned.rs +++ b/esp-hal/src/dma/aligned.rs @@ -76,7 +76,7 @@ impl InternalMemory { /// `addr` is not in a DMA-capable region. /// /// Both the address and size of a DMA buffer must be a multiple of this value -/// so that cache maintenance on the buffer cannot corrupt neighbouring data. +/// so that cache maintenance on the buffer cannot corrupt neighboring data. pub(crate) fn region_dma_alignment(addr: usize) -> Option { if is_valid_ram_address(addr) { return Some(core::mem::align_of::>()); @@ -92,7 +92,7 @@ pub(crate) fn region_dma_alignment(addr: usize) -> Option { // available. soc_internal_memory_cached => 128, esp32s31 => 64, - any(esp32, esp32c5, esp32c61) => 32, /* TODO: fixed 32-bytes, metadata-ify */ + any(esp32, esp32c5, esp32c61) => 32, // TODO: fixed 32-bytes, metadata-ify _ => crate::soc::CONFIG_DATA_CACHE_LINE_SIZE, }); } @@ -122,7 +122,7 @@ fn validate_dma_alignment(addr: usize, size: usize) -> Result<(), DmaBufError> { Ok(()) } -/// Returns `true` if the value at `addr` spanning `size` bytes occupies a +/// Returns whether the value at `addr` spanning `size` bytes occupies a /// cached memory region and therefore needs explicit cache maintenance. #[cfg(any(soc_internal_memory_cached, dma_can_access_psram))] fn region_needs_cache_op(addr: usize, size: usize) -> bool { @@ -158,7 +158,7 @@ impl<'a, T: ?Sized> DmaAlignedMut<'a, T> { cfg(soc_internal_memory_cached) => "64", _ => "4" })] - /// Creates a new [`DmaAlignedMut`] from a mutable variable, if it's + /// Creates a new [`DmaAlignedMut`] from a mutable variable, if it is /// provably compatible. /// /// In internal memory, the address and size of the variable @@ -276,7 +276,7 @@ impl<'a, T: ?Sized> DmaAlignedRef<'a, T> { cfg(soc_internal_memory_cached) => "64", _ => "4" })] - /// Creates a new [`DmaAlignedRef`] from a shared reference, if it's + /// Creates a new [`DmaAlignedRef`] from a shared reference, if it is /// provably compatible. /// /// In internal memory, the address and size of the value diff --git a/esp-hal/src/dma/buffers/mod.rs b/esp-hal/src/dma/buffers/mod.rs index 7a8923eb3df..e6341f68110 100644 --- a/esp-hal/src/dma/buffers/mod.rs +++ b/esp-hal/src/dma/buffers/mod.rs @@ -421,7 +421,7 @@ pub struct Preparation { /// and alignment in each descriptor is compatible with the burst /// transfer configuration. /// - /// For details on alignment requirements, refer to your chip's + /// For details on alignment requirements, refer to the chip's #[doc = crate::trm_markdown_link!()] pub burst_transfer: BurstConfig, @@ -433,24 +433,24 @@ pub struct Preparation { /// operating and fires /// [DmaRxInterrupt::DescriptorError]/[DmaTxInterrupt::DescriptorError]. /// - /// This field allows buffer implementation to configure this behaviour. + /// This field allows buffer implementation to configure this behavior. /// - `Some(true)`: DMA channel must check the owner bit. /// - `Some(false)`: DMA channel must NOT check the owner bit. /// - `None`: DMA channel should check the owner bit if it is supported. /// /// Some buffer implementations may require that the DMA channel performs /// this check before consuming the descriptor to ensure correct - /// behaviour. e.g. To prevent wrap-around in a circular transfer. + /// behavior. e.g. To prevent wrap-around in a circular transfer. /// /// Some buffer implementations may require that the DMA channel does NOT /// perform this check as the ownership bit will not be set before the /// channel tries to consume the descriptor. /// - /// Most implementations won't have any such requirements and will work + /// Most implementations do not have any such requirements and work /// correctly regardless of whether the DMA channel checks or not. /// - /// Note: If the DMA channel doesn't support the provided option, - /// preparation will fail. + /// If the DMA channel does not support the provided option, preparation + /// fails. pub check_owner: Option, /// Configures whether the DMA channel automatically clears the @@ -460,12 +460,12 @@ pub struct Preparation { /// For RX transfers, this is always true and the value specified here is /// ignored. /// - /// Note: SPI_DMA on the ESP32 does not support this and will panic if set + /// SPI_DMA on the ESP32 does not support this and panics if set /// to true. pub auto_write_back: bool, } -/// [DmaTxBuffer] is a DMA descriptor + memory combo that can be used for +/// [`DmaTxBuffer`] is a DMA descriptor + memory combo that can be used for /// transmitting data from a DMA channel to a peripheral's FIFO. /// /// # Safety @@ -474,18 +474,18 @@ pub struct Preparation { /// point to valid while the buffer is being transferred. pub unsafe trait DmaTxBuffer { /// A type providing operations that are safe to perform on the buffer - /// whilst the DMA is actively using it. + /// while the DMA is actively using it. type View; - /// The type returned to the user when a transfer finishes. + /// The type returned when a transfer finishes. /// - /// Some buffers don't need to be reconstructed. + /// Some buffers do not need to be reconstructed. type Final; /// Prepares the buffer for an imminent transfer and returns /// information required to use this buffer. /// - /// Note: This operation is idempotent. + /// This operation is idempotent. fn prepare(&mut self) -> Preparation; /// This is called before the DMA starts using the buffer. @@ -495,10 +495,10 @@ pub unsafe trait DmaTxBuffer { fn from_view(view: Self::View) -> Self::Final; } -/// [DmaRxBuffer] is a DMA descriptor + memory combo that can be used for +/// [`DmaRxBuffer`] is a DMA descriptor + memory combo that can be used for /// receiving data from a peripheral's FIFO to a DMA channel. /// -/// Note: Implementations of this trait may only support having a single EOF bit +/// Implementations of this trait may only support having a single EOF bit /// which resides in the last descriptor. There will be a separate trait in /// future to support multiple EOFs. /// @@ -508,18 +508,18 @@ pub unsafe trait DmaTxBuffer { /// point to valid while the buffer is being transferred. pub unsafe trait DmaRxBuffer { /// A type providing operations that are safe to perform on the buffer - /// whilst the DMA is actively using it. + /// while the DMA is actively using it. type View; - /// The type returned to the user when a transfer finishes. + /// The type returned when a transfer finishes. /// - /// Some buffers don't need to be reconstructed. + /// Some buffers do not need to be reconstructed. type Final; /// Prepares the buffer for an imminent transfer and returns /// information required to use this buffer. /// - /// Note: This operation is idempotent. + /// This operation is idempotent. fn prepare(&mut self) -> Preparation; /// This is called before the DMA starts using the buffer. @@ -529,7 +529,7 @@ pub unsafe trait DmaRxBuffer { fn from_view(view: Self::View) -> Self::Final; } -/// An in-progress view into [DmaRxBuf]/[DmaTxBuf]. +/// An in-progress view into [`DmaRxBuf`]/[`DmaTxBuf`]. /// /// In the future, this could support peeking into state of the /// descriptors/buffers. @@ -539,13 +539,13 @@ pub struct BufView(T); /// /// This is a contiguous buffer linked together by DMA descriptors of length /// 4095 at most. It can only be used for transmitting data to a peripheral's -/// FIFO. See [DmaRxBuf] for receiving data. +/// FIFO. See [`DmaRxBuf`] for receiving data. #[derive(Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub struct DmaTxBuf(ScopedDmaTxBuf<'static>); impl DmaTxBuf { - /// Creates a new [DmaTxBuf] from some descriptors and a buffer. + /// Creates a new [`DmaTxBuf`] from some descriptors and a buffer. pub fn new( descriptors: DmaAlignedMut<'static, [DmaDescriptor]>, buffer: DmaAlignedMut<'static, [u8]>, @@ -553,7 +553,7 @@ impl DmaTxBuf { ScopedDmaTxBuf::new(descriptors, buffer).map(Self) } - /// Creates a new [DmaTxBuf] from some descriptors and a buffer. + /// Creates a new [`DmaTxBuf`] from some descriptors and a buffer. /// /// There must be enough descriptors for the provided buffer. /// Depending on alignment requirements, each descriptor can handle at most @@ -574,7 +574,7 @@ impl DmaTxBuf { self.0.set_burst_config(burst) } - /// Consume the buf, returning the descriptors and buffer. + /// Consumes the buf, returning the descriptors and buffer. pub fn split( self, ) -> ( @@ -584,18 +584,18 @@ impl DmaTxBuf { self.0.split() } - /// Returns the size of the underlying buffer + /// Returns the size of the underlying buffer. pub fn capacity(&self) -> usize { self.0.capacity() } - /// Return the number of bytes that would be transmitted by this buf. + /// Returns the number of bytes that would be transmitted by this buf. #[allow(clippy::len_without_is_empty)] pub fn len(&self) -> usize { self.0.len() } - /// Reset the descriptors to only transmit `len` amount of bytes from this + /// Resets the descriptors to only transmit `len` amount of bytes from this /// buf. /// /// The number of bytes in data must be less than or equal to the buffer @@ -613,12 +613,12 @@ impl DmaTxBuf { self.0.fill(data); } - /// Returns the buf as a mutable slice than can be written. + /// Returns the buf as a mutable slice that can be written. pub fn as_mut_slice(&mut self) -> &mut [u8] { self.0.as_mut_slice() } - /// Returns the buf as a slice than can be read. + /// Returns the buf as a slice that can be read. pub fn as_slice(&self) -> &[u8] { self.0.as_slice() } @@ -650,13 +650,13 @@ unsafe impl DmaTxBuffer for DmaTxBuf { /// /// This is a contiguous buffer linked together by DMA descriptors of length /// 4092. It can only be used for receiving data from a peripheral's FIFO. -/// See [DmaTxBuf] for transmitting data. +/// See [`DmaTxBuf`] for transmitting data. #[derive(Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub struct DmaRxBuf(ScopedDmaRxBuf<'static>); impl DmaRxBuf { - /// Creates a new [DmaRxBuf] from some descriptors and a buffer. + /// Creates a new [`DmaRxBuf`] from some descriptors and a buffer. pub fn new( descriptors: DmaAlignedMut<'static, [DmaDescriptor]>, buffer: DmaAlignedMut<'static, [u8]>, @@ -664,7 +664,7 @@ impl DmaRxBuf { ScopedDmaRxBuf::new(descriptors, buffer).map(Self) } - /// Creates a new [DmaRxBuf] from some descriptors and a buffer. + /// Creates a new [`DmaRxBuf`] from some descriptors and a buffer. /// /// There must be enough descriptors for the provided buffer. /// Depending on alignment requirements, each descriptor can handle at most @@ -685,7 +685,7 @@ impl DmaRxBuf { self.0.set_burst_config(burst) } - /// Consume the buf, returning the descriptors and buffer. + /// Consumes the buf, returning the descriptors and buffer. pub fn split( self, ) -> ( @@ -695,7 +695,7 @@ impl DmaRxBuf { self.0.split() } - /// Returns the size of the underlying buffer + /// Returns the size of the underlying buffer. pub fn capacity(&self) -> usize { self.0.capacity() } @@ -707,7 +707,7 @@ impl DmaRxBuf { self.0.len() } - /// Reset the descriptors to only receive `len` amount of bytes into this + /// Resets the descriptors to only receive `len` amount of bytes into this /// buf. /// /// The number of bytes in data must be less than or equal to the buffer @@ -716,17 +716,17 @@ impl DmaRxBuf { self.0.set_length(len) } - /// Returns the entire underlying buffer as a slice than can be read. + /// Returns the entire underlying buffer as a slice that can be read. pub fn as_slice(&self) -> &[u8] { self.0.as_slice() } - /// Returns the entire underlying buffer as a slice than can be written. + /// Returns the entire underlying buffer as a slice that can be written. pub fn as_mut_slice(&mut self) -> &mut [u8] { self.0.as_mut_slice() } - /// Return the number of bytes that was received by this buf. + /// Returns the number of bytes that was received by this buf. pub fn number_of_received_bytes(&self) -> usize { self.0.number_of_received_bytes() } @@ -736,7 +736,7 @@ impl DmaRxBuf { /// If `buf.len()` is less than the amount of received data then only the /// first `buf.len()` bytes of received data is written into `buf`. /// - /// Returns the number of bytes in written to `buf`. + /// Returns the number of bytes written to `buf`. pub fn read_received_data(&self, buf: &mut [u8]) -> usize { self.0.read_received_data(buf) } @@ -830,7 +830,7 @@ impl DmaRxTxBuf { self.configure(burst, len) } - /// Consume the buf, returning the rx descriptors, tx descriptors and + /// Consumes the buf, returning the rx descriptors, tx descriptors and /// buffer. #[allow(clippy::type_complexity)] pub fn split( @@ -847,12 +847,12 @@ impl DmaRxTxBuf { ) } - /// Return the size of the underlying buffer. + /// Returns the size of the underlying buffer. pub fn capacity(&self) -> usize { self.buffer.len() } - /// Return the number of bytes that would be transmitted by this buf. + /// Returns the number of bytes that would be transmitted by this buf. #[allow(clippy::len_without_is_empty)] pub fn len(&self) -> usize { self.tx_descriptors @@ -861,12 +861,12 @@ impl DmaRxTxBuf { .sum::() } - /// Returns the entire buf as a slice than can be read. + /// Returns the entire buf as a slice that can be read. pub fn as_slice(&self) -> &[u8] { &self.buffer } - /// Returns the entire buf as a slice than can be written. + /// Returns the entire buf as a slice that can be written. pub fn as_mut_slice(&mut self) -> &mut [u8] { &mut self.buffer } @@ -886,7 +886,7 @@ impl DmaRxTxBuf { Ok(()) } - /// Reset the descriptors to only transmit/receive `len` amount of bytes + /// Resets the descriptors to only transmit/receive `len` amount of bytes /// with this buf. /// /// `len` must be less than or equal to the buffer size. @@ -982,8 +982,8 @@ unsafe impl DmaRxBuffer for DmaRxTxBuf { /// /// It is used for continuously streaming data from a peripheral's FIFO. /// -/// It does so by maintaining sliding window of descriptors that progresses when -/// you call [DmaRxStreamBufView::consume]. +/// It maintains a sliding window of descriptors that progresses when +/// [DmaRxStreamBufView::consume] is called. /// /// The list starts out like so `A (empty) -> B (empty) -> C (empty) -> D /// (empty) -> NULL`. @@ -994,7 +994,7 @@ unsafe impl DmaRxBuffer for DmaRxTxBuf { /// - `A (full) -> B (full) -> C (empty) -> D (empty) -> NULL` /// - `A (full) -> B (full) -> C (full) -> D (empty) -> NULL` /// -/// As you call [DmaRxStreamBufView::consume] the list (approximately) +/// As [DmaRxStreamBufView::consume] is called, the list (approximately) /// progresses like so: /// - `A (full) -> B (full) -> C (full) -> D (empty) -> NULL` /// - `B (full) -> C (full) -> D (empty) -> A (empty) -> NULL` @@ -1002,18 +1002,18 @@ unsafe impl DmaRxBuffer for DmaRxTxBuf { /// - `D (empty) -> A (empty) -> B (empty) -> C (empty) -> NULL` /// /// If all the descriptors fill up, the [DmaRxInterrupt::DescriptorEmpty] -/// interrupt will fire and the DMA will stop writing, at which point it is up -/// to you to resume/restart the transfer. +/// interrupt fires and the DMA stops writing. The transfer must then be resumed +/// or restarted. /// -/// Note: This buffer will not tell you when this condition occurs, you should -/// check with the driver to see if the DMA has stopped. +/// This buffer does not indicate when this condition occurs. Check with the +/// driver to see if the DMA has stopped. /// -/// When constructing this buffer, it is important to tune the ratio between the -/// chunk size and buffer size appropriately. Smaller chunk sizes means you -/// receive data more frequently but this means the DMA interrupts -/// ([DmaRxInterrupt::Done]) also fire more frequently (if you use them). +/// When constructing this buffer, tune the ratio between the chunk size and +/// buffer size appropriately. Smaller chunk sizes mean data is received more +/// frequently, but the DMA interrupts ([DmaRxInterrupt::Done]) also fire more +/// frequently when they are used. /// -/// See [DmaRxStreamBufView] for APIs available whilst a transfer is in +/// See [DmaRxStreamBufView] for APIs available while a transfer is in /// progress. #[derive(Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] @@ -1024,7 +1024,7 @@ pub struct DmaRxStreamBuf { } impl DmaRxStreamBuf { - /// Creates a new [DmaRxStreamBuf] evenly distributing the buffer between + /// Creates a new [`DmaRxStreamBuf`] evenly distributing the buffer between /// the provided descriptors. pub fn new( mut descriptors: DmaAlignedMut<'static, [DmaDescriptor]>, @@ -1066,7 +1066,7 @@ impl DmaRxStreamBuf { }) } - /// Consume the buf, returning the descriptors and buffer. + /// Consumes the buf, returning the descriptors and buffer. pub fn split( self, ) -> ( @@ -1122,7 +1122,7 @@ unsafe impl DmaRxBuffer for DmaRxStreamBuf { } } -/// A view into a [DmaRxStreamBuf] +/// A view into a [DmaRxStreamBuf]. pub struct DmaRxStreamBufView { buf: DmaRxStreamBuf, descriptor_idx: usize, @@ -1180,8 +1180,7 @@ impl DmaRxStreamBufView { /// This will be the longest possible contiguous slice into the buffer that /// contains data that is available to read. /// - /// Note: This function ignores EOFs, see [Self::peek_until_eof] if you need - /// EOF support. + /// Ignores EOFs. See [Self::peek_until_eof] for EOF support. pub fn peek(&mut self) -> &[u8] { let (slice, _) = self.peek_internal(false); slice @@ -1350,14 +1349,14 @@ impl DmaRxStreamBufView { /// - `A(empty) -> B(empty) -> C(full) -> D(full) -> NULL` /// - `A(empty) -> B(empty) -> C(empty) -> D(full) -> NULL` /// -/// As you call [DmaTxStreamBufView::push] the list (approximately) progresses like so: +/// As [DmaTxStreamBufView::push] is called, the list (approximately) progresses like so: /// - `A(empty) -> B(empty) -> C(empty) -> D(full) -> NULL` /// - `B(empty) -> C(empty) -> D(full) -> A(full) -> NULL` /// - `C(empty) -> D(full) -> A(full) -> B(full) -> NULL` /// - `D(full) -> A(full) -> B(full) -> C(full) -> NULL` /// -/// If all the descriptors run out, the [DmaTxInterrupt::TotalEof] interrupt will fire and DMA -/// will stop writing, at which point it is up to you to resume/restart the transfer. +/// If all the descriptors run out, the [DmaTxInterrupt::TotalEof] interrupt fires and the DMA +/// stops writing. The transfer must then be resumed or restarted. #[derive(Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub struct DmaTxStreamBuf { @@ -1370,7 +1369,7 @@ pub struct DmaTxStreamBuf { } impl DmaTxStreamBuf { - /// Creates a new [DmaTxStreamBuf] evenly distributing the buffer between + /// Creates a new [`DmaTxStreamBuf`] evenly distributing the buffer between /// the provided descriptors. pub fn new( mut descriptors: DmaAlignedMut<'static, [DmaDescriptor]>, @@ -1415,7 +1414,7 @@ impl DmaTxStreamBuf { }) } - /// Consume the buf, returning the descriptors and buffer. + /// Consumes the buf, returning the descriptors and buffer. pub fn split( self, ) -> ( @@ -1425,10 +1424,14 @@ impl DmaTxStreamBuf { (self.descriptors, self.buffer) } - /// Push the buffer with the given data before DMA transfer starts. + /// Pushes the buffer with the given data before DMA transfer starts. /// - /// It's expected to pre-fill at least enough data to fill the first two descriptors' buffers. + /// It is expected to pre-fill at least enough data to fill the first two descriptors' buffers. /// The more data is pre-filled, the more head-room is left to push more data. + /// + /// Pre-filled data only applies to the next transfer: a buffer returned from a + /// transfer starts with nothing pre-filled. If nothing is pushed before a + /// transfer starts, the entire buffer is transmitted with its current contents. pub fn push(&mut self, data: &[u8]) -> usize { self.push_with(|buf| { let len = buf.len().min(data.len()); @@ -1437,11 +1440,15 @@ impl DmaTxStreamBuf { }) } - /// Push the buffer with the given data before DMA transfer starts. + /// Pushes the buffer with the given data before DMA transfer starts. /// - /// It's expected to pre-fill at least enough data to fill the first two descriptors' buffers. + /// It is expected to pre-fill at least enough data to fill the first two descriptors' buffers. /// The more data is pre-filled, the more head-room is left to push more data. /// + /// Pre-filled data only applies to the next transfer: a buffer returned from a + /// transfer starts with nothing pre-filled. If nothing is pushed before a + /// transfer starts, the entire buffer is transmitted with its current contents. + /// /// Returns the number of bytes filled. pub fn push_with(&mut self, f: impl FnOnce(&mut [u8]) -> usize) -> usize { let start = self.pre_filled.unwrap_or(0); @@ -1626,11 +1633,12 @@ unsafe impl DmaTxBuffer for DmaTxStreamBuf { } = view; buf.view_descriptor_idx = descriptor_idx; buf.view_descriptor_offset = descriptor_offset; + buf.pre_filled = None; buf } } -/// A view into a [DmaTxStreamBuf] +/// A view into a [DmaTxStreamBuf]. pub struct DmaTxStreamBufView { buf: DmaTxStreamBuf, descriptor_idx: usize, @@ -1683,7 +1691,7 @@ impl DmaTxStreamBufView { bytes_pushed } - /// Advances the first `n` bytes from the available data + /// Advances the first `n` bytes from the available data. pub fn advance(&mut self, bytes_pushed: usize) { advance_tx_stream_descriptors( &mut self.buf.descriptors, @@ -1717,7 +1725,7 @@ impl DmaTxStreamBufView { static mut EMPTY: InternalMemory<[DmaDescriptor; 1]> = InternalMemory::new([DmaDescriptor::EMPTY]); -/// An empty buffer that can be used when you don't need to transfer any data. +/// An empty buffer for transfers that carry no data. pub struct EmptyBuf; unsafe impl DmaTxBuffer for EmptyBuf { @@ -1794,8 +1802,8 @@ unsafe impl DmaRxBuffer for EmptyBuf { /// single buffer, resulting in the buffer being transmitted over and over /// again, indefinitely. /// -/// Note: A DMA descriptor is 12 bytes. If your buffer is significantly shorter -/// than this, the DMA channel will spend more time reading the descriptor than +/// A DMA descriptor is 12 bytes. If the buffer is significantly shorter +/// than this, the DMA channel spends more time reading the descriptor than /// it does reading the buffer, which may leave it unable to keep up with the /// bandwidth requirements of some peripherals at high frequencies. pub struct DmaLoopBuf { @@ -1804,7 +1812,7 @@ pub struct DmaLoopBuf { } impl DmaLoopBuf { - /// Create a new [DmaLoopBuf]. + /// Creates a new [DmaLoopBuf]. pub fn new( mut descriptors: DmaAlignedMut<'static, [DmaDescriptor]>, mut buffer: DmaAlignedMut<'static, [u8]>, @@ -1827,7 +1835,7 @@ impl DmaLoopBuf { }) } - /// Consume the buf, returning the descriptor and buffer. + /// Consumes the buf, returning the descriptor and buffer. pub fn split( self, ) -> ( @@ -1881,9 +1889,9 @@ impl DerefMut for DmaLoopBuf { /// A Preparation that masks itself as a DMA buffer. /// -/// Fow low level use, where none of the pre-made buffers really fit. +/// For low-level use, where none of the pre-made buffers really fit. /// -/// This type likely never should be visible outside of esp-hal. +/// Intended for low-level use inside esp-hal only. pub(crate) struct NoBuffer(pub(crate) Preparation); impl NoBuffer { fn prep(&self) -> Preparation { @@ -1999,7 +2007,7 @@ pub(crate) unsafe fn prepare_for_tx( )) } -/// Prepare buffers to receive data from DMA. +/// Prepares buffers to receive data from DMA. /// /// The function returns the DMA buffer, and the number of bytes that will be transferred. /// @@ -2102,7 +2110,7 @@ fn build_descriptor_list_for_psram( let min_alignment = ExternalBurstConfig::DEFAULT.min_psram_alignment(TransferDirection::In); let chunk_size = 4096 - min_alignment; - let mut desciptor_iter = DescriptorChainingIter::new(&mut descriptors.descriptors); + let mut descriptor_iter = DescriptorChainingIter::new(&mut descriptors.descriptors); let mut copy_buffer_iter = copy_buffers.iter_mut(); // MIN_LAST_DMA_LEN could make this really annoying, so we're just allocating a bit larger @@ -2111,9 +2119,10 @@ fn build_descriptor_list_for_psram( // MIN_LAST_DMA_LEN data to work with. let has_aligned_data = data_len > BUF_LEN; - // Calculate byte offset to the start of the buffer + // Calculate byte offset to the start of the buffer. An already-aligned + // buffer needs no head at all. let offset = data_addr % min_alignment; - let head_to_copy = min_alignment - offset; + let head_to_copy = (min_alignment - offset) % min_alignment; let head_to_copy = if !has_aligned_data { BUF_LEN } else if head_to_copy > 0 && head_to_copy < MIN_LAST_DMA_LEN { @@ -2140,7 +2149,7 @@ fn build_descriptor_list_for_psram( copy_buffer.insert(ManualWritebackBuffer::new(get_range(data, 0..head_to_copy))); buffer.prepare_for_dma(); - let Some(descriptor) = desciptor_iter.next() else { + let Some(descriptor) = descriptor_iter.next() else { return consumed; }; descriptor.set_size(head_to_copy); @@ -2151,7 +2160,7 @@ fn build_descriptor_list_for_psram( // Chain up descriptors for the main aligned data part. let mut aligned_data = get_range(data, head_to_copy..data.len() - tail_to_copy); while !aligned_data.is_empty() { - let Some(descriptor) = desciptor_iter.next() else { + let Some(descriptor) = descriptor_iter.next() else { return consumed; }; let chunk = aligned_data.len().min(chunk_size); @@ -2171,7 +2180,7 @@ fn build_descriptor_list_for_psram( ))); buffer.prepare_for_dma(); - let Some(descriptor) = desciptor_iter.next() else { + let Some(descriptor) = descriptor_iter.next() else { return consumed; }; descriptor.set_size(tail_to_copy); diff --git a/esp-hal/src/dma/buffers/scoped.rs b/esp-hal/src/dma/buffers/scoped.rs index 571000fbfd6..66317d0c8ba 100644 --- a/esp-hal/src/dma/buffers/scoped.rs +++ b/esp-hal/src/dma/buffers/scoped.rs @@ -69,17 +69,17 @@ impl<'a> ScopedDmaTxBuf<'a> { self.configure(burst, len) } - /// Consume the buf, returning the descriptors and buffer. + /// Consumes the buf, returning the descriptors and buffer. pub fn split(self) -> (DmaAlignedMut<'a, [DmaDescriptor]>, DmaAlignedMut<'a, [u8]>) { (self.descriptors.descriptors, self.buffer) } - /// Returns the size of the underlying buffer + /// Returns the size of the underlying buffer. pub fn capacity(&self) -> usize { self.buffer.len() } - /// Return the number of bytes that would be transmitted by this buf. + /// Returns the number of bytes that would be transmitted by this buf. #[allow(clippy::len_without_is_empty)] pub fn len(&self) -> usize { self.descriptors @@ -108,7 +108,7 @@ impl<'a> ScopedDmaTxBuf<'a> { Ok(()) } - /// Reset the descriptors to only transmit `len` amount of bytes from this + /// Resets the descriptors to only transmit `len` amount of bytes from this /// buf. /// /// The number of bytes in data must be less than or equal to the buffer @@ -127,12 +127,12 @@ impl<'a> ScopedDmaTxBuf<'a> { self.as_mut_slice()[..data.len()].copy_from_slice(data); } - /// Returns the buf as a mutable slice than can be written. + /// Returns the buf as a mutable slice that can be written. pub fn as_mut_slice(&mut self) -> &mut [u8] { &mut self.buffer } - /// Returns the buf as a slice than can be read. + /// Returns the buf as a slice that can be read. pub fn as_slice(&self) -> &[u8] { &self.buffer } @@ -239,12 +239,12 @@ impl<'a> ScopedDmaRxBuf<'a> { self.configure(burst, len) } - /// Consume the buf, returning the descriptors and buffer. + /// Consumes the buf, returning the descriptors and buffer. pub fn split(self) -> (DmaAlignedMut<'a, [DmaDescriptor]>, DmaAlignedMut<'a, [u8]>) { (self.descriptors.descriptors, self.buffer) } - /// Returns the size of the underlying buffer + /// Returns the size of the underlying buffer. pub fn capacity(&self) -> usize { self.buffer.len() } @@ -271,7 +271,7 @@ impl<'a> ScopedDmaRxBuf<'a> { ) } - /// Reset the descriptors to only receive `len` amount of bytes into this + /// Resets the descriptors to only receive `len` amount of bytes into this /// buf. /// /// The number of bytes in data must be less than or equal to the buffer @@ -280,17 +280,17 @@ impl<'a> ScopedDmaRxBuf<'a> { unwrap!(self.set_length_fallible(len, self.burst)); } - /// Returns the entire underlying buffer as a slice than can be read. + /// Returns the entire underlying buffer as a slice that can be read. pub fn as_slice(&self) -> &[u8] { &self.buffer } - /// Returns the entire underlying buffer as a slice than can be written. + /// Returns the entire underlying buffer as a slice that can be written. pub fn as_mut_slice(&mut self) -> &mut [u8] { &mut self.buffer } - /// Return the number of bytes that was received by this buf. + /// Returns the number of bytes that was received by this buf. pub fn number_of_received_bytes(&self) -> usize { self.sync_received_from_dma(); self.descriptors @@ -304,7 +304,7 @@ impl<'a> ScopedDmaRxBuf<'a> { /// If `buf.len()` is less than the amount of received data then only the /// first `buf.len()` bytes of received data is written into `buf`. /// - /// Returns the number of bytes in written to `buf`. + /// Returns the number of bytes written to `buf`. pub fn read_received_data(&self, mut buf: &mut [u8]) -> usize { // Note that due to an ESP32 quirk, the last received descriptor may not get // updated. @@ -333,7 +333,7 @@ impl<'a> ScopedDmaRxBuf<'a> { }) } - /// Read DMA-written RX data from memory on cached SoCs. + /// Reads DMA-written RX data from memory on cached SoCs. fn sync_received_from_dma(&self) { #[cfg(any(soc_internal_memory_cached, dma_can_access_psram))] { diff --git a/esp-hal/src/dma/engine/gdma/ahb_v3.rs b/esp-hal/src/dma/engine/gdma/ahb_v3.rs index 2095bdc2820..6c7a0f22331 100644 --- a/esp-hal/src/dma/engine/gdma/ahb_v3.rs +++ b/esp-hal/src/dma/engine/gdma/ahb_v3.rs @@ -1,8 +1,15 @@ -use pac::ahb_dma as gdma_pac; - use super::*; use crate::RegisterToggle; +cfg_select! { + esp32s31 => { + use pac::ahb_dma as gdma_pac; + } + esp32h4 => { + use pac::dma as gdma_pac; + } +} + impl AhbGdmaTxChannel<'_> { #[inline(always)] pub(super) fn ch(&self) -> &gdma_pac::ch::CH { diff --git a/esp-hal/src/dma/engine/gdma/mod.rs b/esp-hal/src/dma/engine/gdma/mod.rs index 3d71ed900bc..ea4e497f1aa 100644 --- a/esp-hal/src/dma/engine/gdma/mod.rs +++ b/esp-hal/src/dma/engine/gdma/mod.rs @@ -57,7 +57,7 @@ pub(crate) struct ChannelState { pub(crate) rx_is_async: portable_atomic::AtomicBool, } -/// An arbitrary GDMA channel +/// An arbitrary GDMA channel. pub struct AhbGdmaChannel<'d> { info: &'static ChannelInfo, state: &'static ChannelState, @@ -107,12 +107,12 @@ impl<'d> DmaChannel for AhbGdmaChannel<'d> { } } -/// An arbitrary GDMA RX channel +/// An arbitrary GDMA RX channel. #[derive(Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub struct AhbGdmaRxChannel<'d>(AhbGdmaChannel<'d>); -/// An arbitrary GDMA TX channel +/// An arbitrary GDMA TX channel. #[derive(Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub struct AhbGdmaTxChannel<'d>(AhbGdmaChannel<'d>); diff --git a/esp-hal/src/dma/engine/mod.rs b/esp-hal/src/dma/engine/mod.rs index a97a35f84d3..22af51412d9 100644 --- a/esp-hal/src/dma/engine/mod.rs +++ b/esp-hal/src/dma/engine/mod.rs @@ -71,14 +71,14 @@ pub trait RegisterAccess: Sealed { #[allow(private_interfaces)] fn enable(&self) -> Option; - /// Reset the state machine of the channel and FIFO pointer. + /// Resets the state machine of the channel and FIFO pointer. fn reset(&self); - /// Enable/Disable INCR burst transfer for channel reading + /// Enables or disables INCR burst transfer for channel reading /// accessing data in internal RAM. fn set_burst_mode(&self, burst_mode: BurstConfig); - /// Enable/Disable burst transfer for channel reading + /// Enables or disables burst transfer for channel reading /// descriptors in internal RAM. fn set_descr_burst_mode(&self, burst_mode: bool); @@ -87,22 +87,22 @@ pub trait RegisterAccess: Sealed { #[cfg(dma_max_priority_is_set)] fn set_priority(&self, priority: crate::dma::DmaPriority); - /// Select a peripheral for the channel. + /// Selects a peripheral for the channel. fn set_peripheral(&self, _peripheral: u8) {} - /// Set the address of the first descriptor. + /// Sets the address of the first descriptor. fn set_link_addr(&self, address: u32); - /// Enable the channel for data transfer. + /// Enables the channel for data transfer. fn start(&self); - /// Stop the channel from transferring data. + /// Stops the channel from transferring data. fn stop(&self); - /// Mount a new descriptor. + /// Mounts a new descriptor. fn restart(&self); - /// Configure the bit to enable checking the owner attribute of the + /// Configures the bit to enable checking the owner attribute of the /// descriptor. fn set_check_owner(&self, check_owner: Option); @@ -138,7 +138,7 @@ pub trait TxRegisterAccess: RegisterAccess { /// Returns whether the DMA's FIFO is empty. fn is_fifo_empty(&self) -> bool; - /// Enable/disable outlink-writeback + /// Enables or disables outlink-writeback. fn set_auto_write_back(&self, enable: bool); /// Outlink descriptor address when EOF occurs of Tx channel. @@ -186,7 +186,7 @@ pub trait DmaChannel: Sized + crate::private::Sealed { type Tx: DmaTxChannel + From; /// Splits the DMA channel into its RX and TX halves. - #[cfg(any(esp32c5, esp32c6, esp32h2, esp32s3))] // TODO relax this to allow splitting on all chips + #[cfg(dma_separate_in_out_interrupts)] // TODO relax this to allow splitting on all chips fn split(self) -> (Self::Rx, Self::Tx) { // This function is exposed safely on chips that have separate IN and OUT // interrupt handlers. @@ -198,8 +198,7 @@ pub trait DmaChannel: Sized + crate::private::Sealed { /// /// # Safety /// - /// This function must only be used if the separate halves are used by the - /// same peripheral. + /// Must only be used if the separate halves are used by the same peripheral. unsafe fn split_internal(self, _: Internal) -> (Self::Rx, Self::Tx); } diff --git a/esp-hal/src/dma/m2m.rs b/esp-hal/src/dma/m2m.rs index 65abc712d09..fb555613a17 100644 --- a/esp-hal/src/dma/m2m.rs +++ b/esp-hal/src/dma/m2m.rs @@ -215,7 +215,7 @@ where } impl<'d> Mem2Mem<'d, Blocking> { - /// Create a new [`Mem2Mem`] instance. + /// Creates a new [`Mem2Mem`] instance. pub fn new( channel: CH, #[cfg(dma_mem2mem_requires_peripheral)] peripheral: impl DmaEligiblePeripheral, @@ -230,13 +230,13 @@ impl<'d> Mem2Mem<'d, Blocking> { Self::new_inner(channel, dma_peri) } - /// Create a new [`Mem2Mem`] instance. + /// Creates a new [`Mem2Mem`] instance. /// /// # Safety /// - /// You must ensure that you're not using DMA for the same peripheral and - /// that you're the only one using the peripheral. You must also ensure that - /// the peripheral is compatible with the channel. + /// The caller must ensure that DMA is not used for the same peripheral, + /// that this is the only user of the peripheral, and that the peripheral is + /// compatible with the channel. #[cfg(dma_mem2mem_requires_peripheral)] pub unsafe fn new_unsafe(channel: CH, peripheral: DmaPeripheral) -> Self where @@ -245,7 +245,7 @@ impl<'d> Mem2Mem<'d, Blocking> { Self::new_inner(channel, peripheral) } - /// Convert Mem2Mem to an async Mem2Mem. + /// Converts Mem2Mem to an async Mem2Mem. pub fn into_async(self) -> Mem2Mem<'d, Async> { Mem2Mem { rx: self.rx.into_async(), @@ -297,7 +297,7 @@ where } impl<'d> Mem2MemRx<'d, Blocking> { - /// Convert Mem2MemRx to an async Mem2MemRx. + /// Converts Mem2MemRx to an async Mem2MemRx. pub fn into_async(self) -> Mem2MemRx<'d, Async> { Mem2MemRx { channel: self.channel.into_async(), @@ -310,7 +310,7 @@ impl<'d, Dm> Mem2MemRx<'d, Dm> where Dm: DriverMode, { - /// Start the RX half of a memory to memory transfer. + /// Starts the RX half of a memory to memory transfer. pub fn receive( mut self, mut buf: BUF, @@ -351,7 +351,7 @@ where BUF: DmaRxBuffer, Dm: DriverMode, { - /// Returns true when [Self::wait] will not block. + /// Returns whether [`Self::wait`] will not block. pub fn is_done(&self) -> bool { let done_interrupts = DmaRxInterrupt::DescriptorError | DmaRxInterrupt::DescriptorEmpty; !self @@ -448,7 +448,7 @@ where } impl<'d> Mem2MemTx<'d, Blocking> { - /// Convert Mem2MemTx to an async Mem2MemTx. + /// Converts Mem2MemTx to an async Mem2MemTx. pub fn into_async(self) -> Mem2MemTx<'d, Async> { Mem2MemTx { channel: self.channel.into_async(), @@ -461,7 +461,7 @@ impl<'d, Dm> Mem2MemTx<'d, Dm> where Dm: DriverMode, { - /// Start the TX half of a memory to memory transfer. + /// Starts the TX half of a memory to memory transfer. pub fn send( mut self, mut buf: BUF, @@ -502,7 +502,7 @@ where BUF: DmaTxBuffer, Dm: DriverMode, { - /// Returns true when [Self::wait] will not block. + /// Returns whether [`Self::wait`] will not block. pub fn is_done(&self) -> bool { let done_interrupts = DmaTxInterrupt::DescriptorError | DmaTxInterrupt::TotalEof; !self @@ -745,7 +745,7 @@ impl SimpleMem2MemTransfer<'_, '_, Dm> where Dm: DriverMode, { - /// Returns true when [Self::wait] will not block. + /// Returns whether [`Self::wait`] will not block. pub fn is_done(&self) -> bool { let State::Active(rx, tx) = &self.0.state else { unreachable!() @@ -761,7 +761,7 @@ where .contains(DmaRxInterrupt::SuccessfulEof) } - /// Wait for the transfer to finish. + /// Waits for the transfer to finish. pub fn wait(self) -> Result<(), DmaError> { while !self.is_done() {} Ok(()) diff --git a/esp-hal/src/dma/mod.rs b/esp-hal/src/dma/mod.rs index 8d73123f313..379b083ed97 100644 --- a/esp-hal/src/dma/mod.rs +++ b/esp-hal/src/dma/mod.rs @@ -188,12 +188,12 @@ impl DmaDescriptor { self.set_suc_eof(set_eof); } - /// Set the size of the buffer. See [DmaDescriptorFlags::size]. + /// Sets the size of the buffer. See [DmaDescriptorFlags::size]. pub fn set_size(&mut self, len: usize) { self.flags.set_size(len as u16) } - /// Set the length of the descriptor. See [DmaDescriptorFlags::length]. + /// Sets the length of the descriptor. See [DmaDescriptorFlags::length]. pub fn set_length(&mut self, len: usize) { self.flags.set_length(len as u16) } @@ -209,12 +209,12 @@ impl DmaDescriptor { self.flags.length() as usize } - /// Set the suc_eof bit. See [DmaDescriptorFlags::suc_eof]. + /// Sets the suc_eof bit. See [DmaDescriptorFlags::suc_eof]. pub fn set_suc_eof(&mut self, suc_eof: bool) { self.flags.set_suc_eof(suc_eof) } - /// Set the owner. See [DmaDescriptorFlags::owner]. + /// Sets the owner. See [DmaDescriptorFlags::owner]. pub fn set_owner(&mut self, owner: Owner) { let owner = match owner { Owner::Cpu => false, @@ -241,9 +241,9 @@ unsafe impl Send for DmaDescriptor {} #[derive(Debug, EnumSetType)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum DmaInterrupt { - /// RX is done + /// RX is done. RxDone, - /// TX is done + /// TX is done. TxDone, } @@ -302,7 +302,8 @@ pub const CHUNK_SIZE: usize = 4092; #[procmacros::doc_replace] /// Convenience macro to create DMA buffers and descriptors. /// -/// ## Usage +/// # Examples +/// /// ```rust,no_run /// # {before_snippet} /// use esp_hal::dma_buffers; @@ -327,7 +328,8 @@ macro_rules! dma_buffers { #[procmacros::doc_replace] /// Convenience macro to create DMA descriptors. /// -/// ## Usage +/// # Examples +/// /// ```rust,no_run /// # {before_snippet} /// use esp_hal::dma_descriptors; @@ -354,7 +356,8 @@ macro_rules! dma_descriptors { /// Convenience macro to create DMA buffers and descriptors with specific chunk /// size. /// -/// ## Usage +/// # Examples +/// /// ```rust,no_run /// # {before_snippet} /// use esp_hal::dma_buffers_chunk_size; @@ -386,9 +389,10 @@ macro_rules! dma_buffers_chunk_size { } #[procmacros::doc_replace] -/// Convenience macro to create DMA descriptors with specific chunk size +/// Convenience macro to create DMA descriptors with specific chunk size. +/// +/// # Examples /// -/// ## Usage /// ```rust,no_run /// # {before_snippet} /// use esp_hal::dma_descriptors_chunk_size; @@ -499,7 +503,8 @@ macro_rules! dma_descriptor_count { /// Convenience macro to create a DmaRxBuf from buffer size. The buffer and /// descriptors are statically allocated and used to create the `DmaRxBuf`. /// -/// ## Usage +/// # Examples +/// /// ```rust,no_run /// # {before_snippet} /// use esp_hal::dma_rx_buffer; @@ -523,7 +528,8 @@ macro_rules! dma_rx_buffer { /// Convenience macro to create a DmaTxBuf from buffer size. The buffer and /// descriptors are statically allocated and used to create the `DmaTxBuf`. /// -/// ## Usage +/// # Examples +/// /// ```rust,no_run /// # {before_snippet} /// use esp_hal::dma_tx_buffer; @@ -551,7 +557,8 @@ macro_rules! dma_tx_buffer { /// /// Smaller chunk sizes are recommended for lower latency. /// -/// ## Usage +/// # Examples +/// /// ```rust,no_run /// # {before_snippet} /// use esp_hal::dma_rx_stream_buffer; @@ -582,7 +589,8 @@ macro_rules! dma_rx_stream_buffer { /// /// Smaller chunk sizes are recommended for lower latency. /// -/// ## Usage +/// # Examples +/// /// ```rust,no_run /// # {before_snippet} /// use esp_hal::dma_tx_stream_buffer; @@ -608,7 +616,8 @@ macro_rules! dma_tx_stream_buffer { #[procmacros::doc_replace] /// Convenience macro to create a [DmaLoopBuf] from a buffer size. /// -/// ## Usage +/// # Examples +/// /// ```rust,no_run /// # {before_snippet} /// use esp_hal::dma_loop_buffer; @@ -632,25 +641,25 @@ macro_rules! dma_loop_buffer { }}; } -/// DMA Errors +/// DMA Errors. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum DmaError { - /// The alignment of data is invalid + /// The alignment of data is invalid. InvalidAlignment(DmaAlignmentError), - /// More descriptors are needed for the buffer size + /// More descriptors are needed for the buffer size. OutOfDescriptors, /// DescriptorError the DMA rejected the descriptor configuration. This /// could be because the source address of the data is not in RAM. Ensure - /// your source data is in a valid address space. + /// the source data is in a valid address space. DescriptorError, - /// The available free buffer is less than the amount of data to push + /// The available free buffer is less than the amount of data to push. Overflow, - /// The given buffer is too small + /// The given buffer is too small. BufferTooSmall, - /// Descriptors or buffers are not located in a supported memory region + /// Descriptors or buffers are not located in a supported memory region. UnsupportedMemoryRegion, - /// Invalid DMA chunk size + /// Invalid DMA chunk size. InvalidChunkSize, } @@ -667,7 +676,7 @@ impl From for DmaError { } } -/// DMA Priorities +/// DMA Priorities. #[cfg(dma_max_priority_is_set)] #[derive(Debug, Clone, Copy, PartialEq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] @@ -719,9 +728,9 @@ pub enum DmaPriority { /// The owner bit of a DMA descriptor. #[derive(PartialEq, PartialOrd)] pub enum Owner { - /// Owned by CPU + /// Owned by CPU. Cpu = 0, - /// Owned by DMA + /// Owned by DMA. Dma = 1, } @@ -815,9 +824,9 @@ impl<'a> DescriptorSet<'a> { }) } - /// Associate each descriptor with a chunk of the buffer. + /// Associates each descriptor with a chunk of the buffer. /// - /// This function checks the alignment and location of the buffer. + /// Checks the alignment and location of the buffer. /// /// See [`Self::set_up_buffer_ptrs`] for more details. fn link_with_buffer( @@ -906,16 +915,15 @@ impl<'a> DescriptorSet<'a> { Ok(()) } - /// Associate each descriptor with a chunk of the buffer. + /// Associates each descriptor with a chunk of the buffer. /// - /// This function does not check the alignment and location of the buffer, - /// because some callers may not have enough information currently. + /// Does not check the alignment and location of the buffer, because some + /// callers may not have enough information currently. /// - /// This function does not set up descriptor lengths or states. + /// Does not set up descriptor lengths or states. /// - /// This function also does not link descriptors into a linked list. This is - /// intentional, because it is done in `set_up_descriptors` to support - /// changing length without requiring buffer pointers to be set + /// Does not link descriptors into a linked list. This is intentional, because it is done in + /// `set_up_descriptors` to support changing length without requiring buffer pointers to be set /// repeatedly. fn set_up_buffer_ptrs( buffer: &mut [u8], @@ -934,7 +942,7 @@ impl<'a> DescriptorSet<'a> { } } -/// Block size for transfers to/from PSRAM +/// Blocks size for transfers to/from PSRAM. #[cfg(dma_ext_mem_configurable_block_size)] #[derive(Copy, Clone, Debug, PartialEq)] pub enum DmaExtMemBKSize { @@ -1012,7 +1020,7 @@ where } } - fn set_interrupt_handler(&mut self, handler: InterruptHandler) { + pub(crate) fn set_interrupt_handler(&mut self, handler: InterruptHandler) { self.unlisten_in(EnumSet::all()); self.clear_in(EnumSet::all()); @@ -1048,7 +1056,7 @@ where Dm: DriverMode, CH: DmaRxChannel, { - /// Configure the channel. + /// Configures the channel. #[cfg(dma_max_priority_is_set)] pub fn set_priority(&mut self, priority: DmaPriority) { self.rx_impl.set_priority(priority); @@ -1184,7 +1192,7 @@ where } } -/// DMA transmit channel +/// DMA transmit channel. #[doc(hidden)] pub struct ChannelTx where @@ -1230,7 +1238,7 @@ where } } - fn set_interrupt_handler(&mut self, handler: InterruptHandler) { + pub(crate) fn set_interrupt_handler(&mut self, handler: InterruptHandler) { self.unlisten_out(EnumSet::all()); self.clear_out(EnumSet::all()); @@ -1272,7 +1280,7 @@ where self.tx_impl.runtime_ensure_compatible(peripheral); } - /// Configure the channel priority. + /// Configures the channel priority. #[cfg(dma_max_priority_is_set)] pub fn set_priority(&mut self, priority: DmaPriority) { self.tx_impl.set_priority(priority); @@ -1395,16 +1403,16 @@ where } } -/// DMA Channel +/// DMA Channel. #[non_exhaustive] pub struct Channel where Dm: DriverMode, CH: DmaChannel, { - /// RX half of the channel + /// RX half of the channel. pub rx: ChannelRx, - /// TX half of the channel + /// TX half of the channel. pub tx: ChannelTx, } @@ -1431,7 +1439,7 @@ where self.tx.set_interrupt_handler(handler); } - /// Listen for the given interrupts + /// Listens for the given interrupts. pub fn listen(&mut self, interrupts: impl Into>) { for interrupt in interrupts.into() { match interrupt { @@ -1441,7 +1449,7 @@ where } } - /// Unlisten the given interrupts + /// Unlistens from the given interrupts. pub fn unlisten(&mut self, interrupts: impl Into>) { for interrupt in interrupts.into() { match interrupt { @@ -1451,7 +1459,7 @@ where } } - /// Gets asserted interrupts + /// Returns the asserted interrupts. pub fn interrupts(&mut self) -> EnumSet { let mut res = EnumSet::new(); if self.rx.is_done() { @@ -1463,7 +1471,7 @@ where res } - /// Resets asserted interrupts + /// Resets asserted interrupts. pub fn clear_interrupts(&mut self, interrupts: impl Into>) { for interrupt in interrupts.into() { match interrupt { @@ -1473,7 +1481,7 @@ where } } - /// Configure the channel priorities. + /// Configures the channel priorities. #[cfg(dma_max_priority_is_set)] pub fn set_priority(&mut self, priority: DmaPriority) { self.tx.set_priority(priority); @@ -1604,7 +1612,7 @@ pub(crate) mod asynch { return Poll::Pending; }; - self.tx.clear_interrupts(); + self.tx.clear_out(interrupts); Poll::Ready(result) } @@ -1690,7 +1698,7 @@ pub(crate) mod asynch { return Poll::Pending; }; - self.rx.clear_interrupts(); + self.rx.clear_in(interrupts); Poll::Ready(result) } diff --git a/esp-hal/src/ecc.rs b/esp-hal/src/ecc.rs index bb672e73183..27d0445f736 100644 --- a/esp-hal/src/ecc.rs +++ b/esp-hal/src/ecc.rs @@ -23,7 +23,7 @@ use crate::{ pac::{self, ecc::mult_conf::KEY_LENGTH}, peripherals::{ECC, Interrupt}, private::Sealed, - system::{self, GenericPeripheralGuard}, + system::{self, CryptoClockGuard, GenericPeripheralGuard}, work_queue::{Handle, Poll, Status, VTable, WorkQueue, WorkQueueDriver, WorkQueueFrontend}, }; @@ -105,18 +105,18 @@ macro_rules! define_operations { $(#[doc = $lines])* #[doc = r" -## Errors +# Errors -This function will return an error if the bitlength of the parameters is different -from the bitlength of the prime fields of the curve."] +[`OperationError::ParameterLengthMismatch`] if an input does not match the curve's size."] + #[cfg_attr(ecc_has_curve_sm2, doc = "\n[`OperationError::UnsupportedCurve`] if SM2 is disabled by eFuse.")] #[inline] pub fn $function<'op>( &'op mut self, curve: EllipticCurve, $(#[cfg($is_modular)] modulus: EccModBase,)? $($input: &[u8],)* - ) -> Result, KeyLengthMismatch> { - curve.size_check([$($input),*])?; + ) -> Result, OperationError> { + curve.check_parameters([$($input),*])?; paste::paste! { $( @@ -151,12 +151,17 @@ from the bitlength of the prime fields of the curve."] #[doc = concat!("Configures a new ", $first_line, " operation with the given inputs, to be executed on [`EccBackend`].")] /// /// Outputs need to be assigned separately before executing the operation. + /// + /// # Errors + /// + /// [`OperationError::ParameterLengthMismatch`] if an input does not match the curve's size. + #[cfg_attr(ecc_has_curve_sm2, doc = "\n[`OperationError::UnsupportedCurve`] if SM2 is disabled by eFuse.")] pub fn $function<'op>( self, $(#[cfg($is_modular)] modulus: EccModBase,)? $($input: &'op [u8],)* - ) -> Result, KeyLengthMismatch> { - self.size_check([&$($input,)*])?; + ) -> Result, OperationError> { + self.check_parameters([&$($input,)*])?; #[cfg(ecc_has_modular_arithmetic)] let mod_base = $crate::if_set! { @@ -367,13 +372,13 @@ const MEM_BLOCK_SIZE: usize = property!("ecc.mem_block_size"); /// The ECC Accelerator driver. /// -/// Note that as opposed to commonly used standards, this driver operates on -/// **little-endian** data. +/// Unlike commonly used standards, this driver operates on **little-endian** data. pub struct Ecc<'d, Dm: DriverMode> { _ecc: ECC<'d>, phantom: PhantomData, _memory_guard: EccMemoryPowerGuard, _guard: GenericPeripheralGuard<{ system::Peripheral::Ecc as u8 }>, + _clock_guard: CryptoClockGuard, } struct EccMemoryPowerGuard; @@ -409,14 +414,14 @@ impl Drop for EccMemoryPowerGuard { #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, BuilderLite)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub struct Config { - /// Force enable register clock. + /// Force-enables the register clock. force_enable_reg_clock: bool, - /// Force enable memory clock. + /// Force-enables the memory clock. #[cfg(ecc_has_memory_clock_gate)] force_enable_mem_clock: bool, - /// Enable constant time operation and minimized power consumption variation for + /// Enables constant time operation and minimized power consumption variation for /// point-multiplication operations. #[cfg_attr( esp32h2, @@ -428,10 +433,6 @@ Only available on chip revision 1.2 and above." enhanced_security: bool, } -/// The length of the arguments do not match the length required by the curve. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct KeyLengthMismatch; - /// ECC operation error. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum OperationError { @@ -440,6 +441,9 @@ pub enum OperationError { /// Point verification failed. PointNotOnCurve, + + /// The selected curve is not supported. + UnsupportedCurve, } /// Modulus base. @@ -453,12 +457,6 @@ pub enum EccModBase { PrimeModulus = 1, } -impl From for OperationError { - fn from(_: KeyLengthMismatch) -> Self { - OperationError::ParameterLengthMismatch - } -} - for_each_ecc_curve! { (all $(( $id:literal, $name:ident, $bits:literal )),*) => { /// Represents supported elliptic curves for cryptographic operations. @@ -473,6 +471,17 @@ for_each_ecc_curve! { )* } impl EllipticCurve { + /// Returns whether the curve is available for hardware operations. + #[cfg_attr(ecc_has_curve_sm2, doc = "\nSM2 is disabled when the `DIS_SM_CRYPT` eFuse is set.")] + #[instability::unstable] + pub fn is_supported(self) -> bool { + match self { + #[cfg(ecc_has_curve_sm2)] + Self::Sm2 => !crate::efuse::read_bit(crate::efuse::DIS_SM_CRYPT), + _ => true, + } + } + /// Returns the size of the elliptic curve in bytes. pub const fn size(self) -> usize { match self { @@ -488,11 +497,19 @@ for_each_ecc_curve! { for_each_ecc_working_mode! { (all $(($wm_id:literal, $op:tt)),*) => { impl EllipticCurve { - fn size_check(&self, params: [&[u8]; N]) -> Result<(), KeyLengthMismatch> { + fn check_parameters(&self, params: [&[u8]; N]) -> Result<(), OperationError> { + if !self.is_supported() { + return Err(OperationError::UnsupportedCurve); + } + + self.size_check(params) + } + + fn size_check(&self, params: [&[u8]; N]) -> Result<(), OperationError> { let bytes = self.size(); if params.iter().any(|p| p.len() != bytes) { - return Err(KeyLengthMismatch); + return Err(OperationError::ParameterLengthMismatch); } Ok(()) @@ -507,13 +524,15 @@ for_each_ecc_working_mode! { } impl<'d> Ecc<'d, Blocking> { - /// Create a new instance in [Blocking] mode. + /// Creates a new instance in [Blocking] mode. pub fn new(ecc: ECC<'d>, config: Config) -> Self { + let clock_guard = CryptoClockGuard::new(); let this = Self { _ecc: ecc, phantom: PhantomData, _memory_guard: EccMemoryPowerGuard::new(), _guard: GenericPeripheralGuard::new(), + _clock_guard: clock_guard, }; this.info().apply_config(&config); @@ -649,7 +668,7 @@ impl Info { self.read_mem(self.qz_mem(), qz); } - /// Clears all peripheral memory blocks + /// Clears all peripheral memory blocks. #[cfg(clear_crypto_secrets)] fn clear_secrets(&self) { self.zero_mem(self.k_mem()); @@ -763,10 +782,9 @@ for_each_ecc_working_mode! { self.info().reset() } - /// Register an interrupt handler for the ECC peripheral. + /// Registers an interrupt handler for the ECC peripheral. /// - /// Note that this will replace any previously registered interrupt - /// handlers. + /// Replaces any previously registered interrupt handlers. #[instability::unstable] pub fn set_interrupt_handler(&mut self, handler: InterruptHandler) { for core in crate::system::Cpu::other() { @@ -821,9 +839,9 @@ pub trait OperationVerifiesPoint: EccOperation {} /// The result of an ECC operation. /// -/// This struct can be used to read the result of an ECC operation. The methods which can be used -/// depend on the operation. An operation can compute multiple values, such as an affine point and -/// a Jacobian point at the same time. +/// Used to read the result of an ECC operation. The available methods depend on +/// the operation. An operation can compute multiple values, such as an affine point +/// and a Jacobian point at the same time. #[must_use] pub struct EccResultHandle<'op, O> where @@ -867,11 +885,11 @@ where } } - /// Retrieve the scalar result of the operation. + /// Retrieves the scalar result of the operation. /// - /// ## Errors + /// # Errors /// - /// Returns an error if point verification failed, or if `out` is not the correct size. + /// [`OperationError`] when point verification failed, or when `out` is not the correct size. pub fn read_scalar_result(&self, out: &mut [u8]) -> Result<(), OperationError> where O: OperationReturnsScalar, @@ -887,11 +905,12 @@ where Ok(()) } - /// Retrieve the affine point result of the operation. + /// Retrieves the affine point result of the operation. /// - /// ## Errors + /// # Errors /// - /// Returns an error if point verification failed, or if `x` or `y` are not the correct size. + /// [`OperationError`] when point verification failed, or when `x` or `y` are not the correct + /// size. pub fn read_affine_point_result(&self, x: &mut [u8], y: &mut [u8]) -> Result<(), OperationError> where O: OperationReturnsAffinePoint, @@ -901,12 +920,12 @@ where Ok(()) } - /// Retrieve the Jacobian point result of the operation. + /// Retrieves the Jacobian point result of the operation. /// - /// ## Errors + /// # Errors /// - /// Returns an error if point verification failed, or if `x`, `y`, or `z` are not the correct - /// size. + /// [`OperationError`] when point verification failed, or when `x`, `y`, or `z` are not the + /// correct size. pub fn read_jacobian_point_result( &self, x: &mut [u8], @@ -1046,7 +1065,7 @@ enum DriverState<'d> { /// ECC processing backend. /// -/// This struct enables shared access to the device's ECC hardware using a work queue. +/// Enables shared access to the device's ECC hardware using a work queue. pub struct EccBackend<'d> { driver: DriverState<'d>, config: Config, @@ -1055,7 +1074,7 @@ pub struct EccBackend<'d> { impl<'d> EccBackend<'d> { /// Creates a new ECC backend. /// - /// The backend needs to be [`start`][Self::start]ed before it can execute ECC operations. + /// The backend must be started with [`Self::start`] before it can execute ECC operations. pub fn new(ecc: ECC<'d>, config: Config) -> Self { Self { driver: DriverState::Uninitialized(ecc), @@ -1228,10 +1247,10 @@ impl<'op, O: EccOperation> EccBackendOperation<'op, O> { /// /// Once the operation is processed, the result can be retrieved from the designated buffer. /// - /// ## Errors + /// # Errors /// - /// Returns an error if `out` is not the correct size. - pub fn with_scalar_result(mut self, out: &'op mut [u8]) -> Result + /// [`OperationError::ParameterLengthMismatch`] when `out` is not the correct size. + pub fn with_scalar_result(mut self, out: &'op mut [u8]) -> Result where O: OperationReturnsScalar, { @@ -1249,14 +1268,14 @@ impl<'op, O: EccOperation> EccBackendOperation<'op, O> { /// /// Once the operation is processed, the result can be retrieved from the designated buffers. /// - /// ## Errors + /// # Errors /// - /// Returns an error if `x` or `y` are not the correct size. + /// [`OperationError::ParameterLengthMismatch`] when `x` or `y` are not the correct size. pub fn with_affine_point_result( mut self, px: &'op mut [u8], py: &'op mut [u8], - ) -> Result + ) -> Result where O: OperationReturnsAffinePoint, { @@ -1272,15 +1291,15 @@ impl<'op, O: EccOperation> EccBackendOperation<'op, O> { /// /// Once the operation is processed, the result can be retrieved from the designated buffers. /// - /// ## Errors + /// # Errors /// - /// Returns an error if `x`, `y`, or `z` are not the correct size. + /// [`OperationError::ParameterLengthMismatch`] when `x`, `y`, or `z` are not the correct size. pub fn with_jacobian_point_result( mut self, qx: &'op mut [u8], qy: &'op mut [u8], qz: &'op mut [u8], - ) -> Result + ) -> Result where O: OperationReturnsJacobianPoint, { @@ -1293,7 +1312,7 @@ impl<'op, O: EccOperation> EccBackendOperation<'op, O> { Ok(self) } - /// Returns `true` if the input point is on the curve. + /// Returns whether the input point is on the curve. /// /// The operation must be processed before this method returns a meaningful value. pub fn point_on_curve(&self) -> bool @@ -1319,7 +1338,7 @@ pub struct EccHandle<'t>(Handle<'t, EccWorkItem>); impl EccHandle<'_> { /// Polls the status of the work item. /// - /// This function returns `true` if the item has been processed. + /// Returns whether the item has been processed. #[inline] pub fn poll(&mut self) -> bool { self.0.poll() @@ -1327,7 +1346,7 @@ impl EccHandle<'_> { /// Polls the work item to completion, by busy-looping. /// - /// This function returns immediately if `poll` returns `true`. + /// Returns immediately if `poll` returns `true`. #[inline] pub fn wait_blocking(self) -> Status { self.0.wait_blocking() diff --git a/esp-hal/src/efuse/esp32/mod.rs b/esp-hal/src/efuse/esp32/mod.rs index 3e80c581862..88fe37db823 100644 --- a/esp-hal/src/efuse/esp32/mod.rs +++ b/esp-hal/src/efuse/esp32/mod.rs @@ -41,8 +41,8 @@ pub fn core_count() -> u32 { /// Returns the maximum rated clock of the CPU in MHz. /// -/// Note that the actual clock may be lower, depending on the current power -/// configuration of the chip, clock source, and other settings. +/// The actual clock may be lower, depending on the current power configuration of the chip, clock +/// source, and other settings. #[instability::unstable] pub fn max_cpu_frequency() -> Rate { let has_rating = super::read_bit(CHIP_CPU_FREQ_RATED); @@ -78,7 +78,7 @@ pub fn chip_type() -> ChipType { } } -/// Get status of SPI boot encryption. +/// Returns whether SPI boot encryption is enabled. #[instability::unstable] pub fn flash_encryption() -> bool { !super::read_field_le::(FLASH_CRYPT_CNT) @@ -86,7 +86,7 @@ pub fn flash_encryption() -> bool { .is_multiple_of(2) } -/// Returns the major hardware revision +/// Returns the major hardware revision. #[instability::unstable] pub fn major_chip_version() -> u8 { let eco_bit0 = super::read_field_le::(CHIP_VER_REV1); @@ -101,7 +101,7 @@ pub fn major_chip_version() -> u8 { } } -/// Returns the minor hardware revision +/// Returns the minor hardware revision. #[instability::unstable] pub fn minor_chip_version() -> u8 { super::read_field_le(WAFER_VERSION_MINOR) diff --git a/esp-hal/src/efuse/esp32c2/fields.rs b/esp-hal/src/efuse/esp32c2/fields.rs index cd92a284493..9db35a5bd25 100644 --- a/esp-hal/src/efuse/esp32c2/fields.rs +++ b/esp-hal/src/efuse/esp32c2/fields.rs @@ -25,7 +25,7 @@ pub const DIS_DOWNLOAD_MANUAL_ENCRYPT: EfuseField = EfuseField::new(0, 1, 38, 1) pub const SPI_BOOT_CRYPT_CNT: EfuseField = EfuseField::new(0, 1, 39, 3); /// Flash encryption key length pub const XTS_KEY_LENGTH_256: EfuseField = EfuseField::new(0, 1, 42, 1); -/// Set the default UARTboot message output mode +/// Set the default UART boot message output mode pub const UART_PRINT_CONTROL: EfuseField = EfuseField::new(0, 1, 43, 2); /// Set this bit to force ROM code to send a resume command during SPI boot pub const FORCE_SEND_RESUME: EfuseField = EfuseField::new(0, 1, 45, 1); diff --git a/esp-hal/src/efuse/esp32c2/mod.rs b/esp-hal/src/efuse/esp32c2/mod.rs index 95dd575fe5d..a2f9e93b8fd 100644 --- a/esp-hal/src/efuse/esp32c2/mod.rs +++ b/esp-hal/src/efuse/esp32c2/mod.rs @@ -5,14 +5,14 @@ mod fields; #[instability::unstable] pub use fields::*; -/// Selects which ADC we are interested in the efuse calibration data for +/// Selects which ADC the eFuse calibration data applies to. #[instability::unstable] pub enum AdcCalibUnit { - /// Select efuse calibration data for ADC1 + /// Selects efuse calibration data for ADC1. ADC1, } -/// Get status of SPI boot encryption. +/// Returns whether SPI boot encryption is enabled. #[instability::unstable] pub fn flash_encryption() -> bool { !super::read_field_le::(SPI_BOOT_CRYPT_CNT) @@ -20,13 +20,13 @@ pub fn flash_encryption() -> bool { .is_multiple_of(2) } -/// Get the multiplier for the timeout value of the RWDT STAGE 0 register. +/// Returns the multiplier for the timeout value of the RWDT STAGE 0 register. #[instability::unstable] pub fn rwdt_multiplier() -> u8 { super::read_field_le::(WDT_DELAY_SEL) } -/// Get efuse block version +/// Returns the eFuse block version. /// /// see #[instability::unstable] @@ -39,7 +39,7 @@ pub fn block_version() -> (u8, u8) { ) } -/// Get version of RTC calibration block +/// Returns the version of RTC calibration block. /// /// see #[instability::unstable] @@ -48,7 +48,7 @@ pub fn rtc_calib_version() -> u8 { if major == 0 { 1 } else { 0 } } -/// Get ADC initial code for specified attenuation from efuse +/// Returns the ADC initial code for specified attenuation from efuse. /// /// see #[instability::unstable] @@ -59,13 +59,15 @@ pub fn rtc_calib_init_code(_unit: AdcCalibUnit, atten: Attenuation) -> Option let diff_code0: u16 = super::read_field_le(ADC1_INIT_CODE_ATTEN0); - let code0 = if diff_code0 & (1 << 7) != 0 { - 2160 - (diff_code0 & 0x7f) - } else { - 2160 + diff_code0 - }; + let code0 = (2160 + super::sign_magnitude(diff_code0 as u32, 7)) as u16; if matches!(atten, Attenuation::_0dB) { return Some(code0); @@ -78,19 +80,22 @@ pub fn rtc_calib_init_code(_unit: AdcCalibUnit, atten: Attenuation) -> Option #[instability::unstable] -pub fn rtc_calib_cal_mv(_unit: AdcCalibUnit, atten: Attenuation) -> u16 { +pub fn rtc_calib_cal_mv(_unit: AdcCalibUnit, atten: Attenuation) -> Option { match atten { - Attenuation::_0dB => 400, - Attenuation::_11dB => 1370, - _ => panic!("Unsupported attenuation"), + Attenuation::_0dB => Some(400), + Attenuation::_11dB => Some(1370), + _ => None, } } -/// Get ADC reference point digital code for specified attenuation +/// Returns the ADC reference point digital code for specified attenuation. /// /// see #[instability::unstable] @@ -101,13 +106,14 @@ pub fn rtc_calib_cal_code(_unit: AdcCalibUnit, atten: Attenuation) -> Option let diff_code0: u16 = super::read_field_le(ADC1_CAL_VOL_ATTEN0); - let code0 = if diff_code0 & (1 << 7) != 0 { - 1540 - (diff_code0 & 0x7f) - } else { - 1540 + diff_code0 - }; + let code0 = (1540 + super::sign_magnitude(diff_code0 as u32, 7)) as u16; if matches!(atten, Attenuation::_0dB) { return Some(code0); @@ -115,22 +121,20 @@ pub fn rtc_calib_cal_code(_unit: AdcCalibUnit, atten: Attenuation) -> Option let diff_code11: u16 = super::read_field_le(ADC1_CAL_VOL_ATTEN3); - let code11 = if diff_code0 & (1 << 5) != 0 { - code0 - (diff_code11 & 0x1f) - } else { - code0 + diff_code11 - } - 123; + // The diff is subtracted from the attenuation-0 reference point, so a negative diff raises + // the code. + let code11 = (code0 as i32 - super::sign_magnitude(diff_code11 as u32, 5) - 123) as u16; Some(code11) } -/// Returns the major hardware revision +/// Returns the major hardware revision. #[instability::unstable] pub fn major_chip_version() -> u8 { super::read_field_le(WAFER_VERSION_MAJOR) } -/// Returns the minor hardware revision +/// Returns the minor hardware revision. #[instability::unstable] pub fn minor_chip_version() -> u8 { super::read_field_le(WAFER_VERSION_MINOR) diff --git a/esp-hal/src/efuse/esp32c3/fields.rs b/esp-hal/src/efuse/esp32c3/fields.rs index 46c807e3567..d12be2a3f88 100644 --- a/esp-hal/src/efuse/esp32c3/fields.rs +++ b/esp-hal/src/efuse/esp32c3/fields.rs @@ -104,7 +104,7 @@ pub const FLASH_ECC_MODE: EfuseField = EfuseField::new(0, 4, 131, 1); pub const DIS_USB_SERIAL_JTAG_DOWNLOAD_MODE: EfuseField = EfuseField::new(0, 4, 132, 1); /// Set this bit to enable secure UART download mode pub const ENABLE_SECURITY_DOWNLOAD: EfuseField = EfuseField::new(0, 4, 133, 1); -/// Set the default UARTboot message output mode +/// Set the default UART boot message output mode pub const UART_PRINT_CONTROL: EfuseField = EfuseField::new(0, 4, 134, 2); /// GPIO33-GPIO37 power supply selection in ROM code pub const PIN_POWER_SELECTION: EfuseField = EfuseField::new(0, 4, 136, 1); diff --git a/esp-hal/src/efuse/esp32c3/mod.rs b/esp-hal/src/efuse/esp32c3/mod.rs index 3d640310abd..9e0b092961d 100644 --- a/esp-hal/src/efuse/esp32c3/mod.rs +++ b/esp-hal/src/efuse/esp32c3/mod.rs @@ -5,16 +5,14 @@ mod fields; #[instability::unstable] pub use fields::*; -/// Selects which ADC we are interested in the efuse calibration data for +/// Selects which ADC the eFuse calibration data applies to. #[instability::unstable] pub enum AdcCalibUnit { - /// Select efuse calibration data for ADC1 + /// Selects efuse calibration data for ADC1. ADC1, - /// Select efuse calibration data for ADC2 - ADC2, } -/// Get status of SPI boot encryption. +/// Returns whether SPI boot encryption is enabled. #[instability::unstable] pub fn flash_encryption() -> bool { !super::read_field_le::(SPI_BOOT_CRYPT_CNT) @@ -22,13 +20,13 @@ pub fn flash_encryption() -> bool { .is_multiple_of(2) } -/// Get the multiplier for the timeout value of the RWDT STAGE 0 register. +/// Returns the multiplier for the timeout value of the RWDT STAGE 0 register. #[instability::unstable] pub fn rwdt_multiplier() -> u8 { super::read_field_le::(WDT_DELAY_SEL) } -/// Get efuse block version +/// Returns the eFuse block version. /// /// see #[instability::unstable] @@ -42,7 +40,7 @@ pub fn block_version() -> (u8, u8) { ) } -/// Get version of RTC calibration block +/// Returns the version of RTC calibration block. /// /// see #[instability::unstable] @@ -51,7 +49,7 @@ pub fn rtc_calib_version() -> u8 { if major == 1 { 1 } else { 0 } } -/// Get ADC initial code for specified attenuation from efuse +/// Returns the ADC initial code for specified attenuation from efuse. /// /// see #[instability::unstable] @@ -73,20 +71,20 @@ pub fn rtc_calib_init_code(_unit: AdcCalibUnit, atten: Attenuation) -> Option #[instability::unstable] -pub fn rtc_calib_cal_mv(_unit: AdcCalibUnit, atten: Attenuation) -> u16 { - match atten { +pub fn rtc_calib_cal_mv(_unit: AdcCalibUnit, atten: Attenuation) -> Option { + Some(match atten { Attenuation::_0dB => 400, Attenuation::_2p5dB => 550, Attenuation::_6dB => 750, Attenuation::_11dB => 1370, - } + }) } -/// Get ADC reference point digital code for specified attenuation +/// Returns the ADC reference point digital code for specified attenuation. /// /// see #[instability::unstable] @@ -105,22 +103,18 @@ pub fn rtc_calib_cal_code(_unit: AdcCalibUnit, atten: Attenuation) -> Option ADC1_CAL_VOL_ATTEN3, }); - let cal_code = if cal_code & (1 << 9) != 0 { - 2000 - (cal_code & !(1 << 9)) - } else { - 2000 + cal_code - }; + let cal_code = (2000 + super::sign_magnitude(cal_code as u32, 9)) as u16; Some(cal_code) } -/// Returns the major hardware revision +/// Returns the major hardware revision. #[instability::unstable] pub fn major_chip_version() -> u8 { super::read_field_le(WAFER_VERSION_MAJOR) } -/// Returns the minor hardware revision +/// Returns the minor hardware revision. #[instability::unstable] pub fn minor_chip_version() -> u8 { super::read_field_le::(WAFER_VERSION_MINOR_HI) << 3 diff --git a/esp-hal/src/efuse/esp32c5/fields.rs b/esp-hal/src/efuse/esp32c5/fields.rs index 0eda80c06d9..1f986edff04 100644 --- a/esp-hal/src/efuse/esp32c5/fields.rs +++ b/esp-hal/src/efuse/esp32c5/fields.rs @@ -17,10 +17,10 @@ pub const BOOTLOADER_ANTI_ROLLBACK_SECURE_VERSION_HI: EfuseField = EfuseField::n /// Represents whether cache is disabled pub const DIS_ICACHE: EfuseField = EfuseField::new(0, 1, 40, 1); /// Represents whether the USB-to-JTAG function in USB Serial/JTAG is disabled. -/// Note that EFUSE_DIS_USB_JTAG is available only when -/// EFUSE_DIS_USB_SERIAL_JTAG is configured to 0 +/// `EFUSE_DIS_USB_JTAG` is available only when `EFUSE_DIS_USB_SERIAL_JTAG` is +/// configured to 0. pub const DIS_USB_JTAG: EfuseField = EfuseField::new(0, 1, 41, 1); -/// Represents whether the ani-rollback check for the 2nd stage bootloader is +/// Represents whether the anti-rollback check for the 2nd stage bootloader is /// enabled pub const BOOTLOADER_ANTI_ROLLBACK_EN: EfuseField = EfuseField::new(0, 1, 42, 1); /// Represents whether USB Serial/JTAG is disabled @@ -80,7 +80,7 @@ pub const FORCE_USE_KEY_MANAGER_KEY: EfuseField = EfuseField::new(0, 2, 74, 4); /// Represents whether to disable the use of the initialization key written by /// software and instead force use efuse_init_key pub const FORCE_DISABLE_SW_INIT_KEY: EfuseField = EfuseField::new(0, 2, 78, 1); -/// Represents whether the ani-rollback SECURE_VERSION will be updated from the +/// Represents whether the anti-rollback SECURE_VERSION will be updated from the /// ROM bootloader pub const BOOTLOADER_ANTI_ROLLBACK_UPDATE_IN_ROM: EfuseField = EfuseField::new(0, 2, 79, 1); /// Enables flash encryption when 1 or 3 bits are set and disables otherwise @@ -241,11 +241,11 @@ pub const TEMPERATURE_SENSOR: EfuseField = EfuseField::new(2, 4, 128, 9); pub const OCODE: EfuseField = EfuseField::new(2, 4, 137, 8); /// Average initcode of ADC1 atten0 pub const ADC1_AVE_INITCODE_ATTEN0: EfuseField = EfuseField::new(2, 4, 145, 10); -/// Average initcode of ADC1 atten0 +/// Average initcode of ADC1 atten1 pub const ADC1_AVE_INITCODE_ATTEN1: EfuseField = EfuseField::new(2, 4, 155, 10); -/// Average initcode of ADC1 atten0 +/// Average initcode of ADC1 atten2 pub const ADC1_AVE_INITCODE_ATTEN2: EfuseField = EfuseField::new(2, 5, 165, 10); -/// Average initcode of ADC1 atten0 +/// Average initcode of ADC1 atten3 pub const ADC1_AVE_INITCODE_ATTEN3: EfuseField = EfuseField::new(2, 5, 175, 10); /// HI DOUT of ADC1 atten0 pub const ADC1_HI_DOUT_ATTEN0: EfuseField = EfuseField::new(2, 5, 185, 10); diff --git a/esp-hal/src/efuse/esp32c5/mod.rs b/esp-hal/src/efuse/esp32c5/mod.rs index 938931a215c..3a1bc807217 100644 --- a/esp-hal/src/efuse/esp32c5/mod.rs +++ b/esp-hal/src/efuse/esp32c5/mod.rs @@ -5,14 +5,14 @@ mod fields; #[instability::unstable] pub use fields::*; -/// Selects which ADC we are interested in the efuse calibration data for +/// Selects which ADC the eFuse calibration data applies to. #[instability::unstable] pub enum AdcCalibUnit { - /// Select efuse calibration data for ADC1 + /// Selects efuse calibration data for ADC1. ADC1, } -/// Get status of SPI boot encryption. +/// Returns whether SPI boot encryption is enabled. #[instability::unstable] pub fn flash_encryption() -> bool { !super::read_field_le::(SPI_BOOT_CRYPT_CNT) @@ -20,13 +20,13 @@ pub fn flash_encryption() -> bool { .is_multiple_of(2) } -/// Get the multiplier for the timeout value of the RWDT STAGE 0 register. +/// Returns the multiplier for the timeout value of the RWDT STAGE 0 register. #[instability::unstable] pub fn rwdt_multiplier() -> u8 { super::read_field_le::(WDT_DELAY_SEL) } -/// Get efuse block version +/// Returns the eFuse block version. /// /// see #[instability::unstable] @@ -39,18 +39,7 @@ pub fn block_version() -> (u8, u8) { ) } -/// Get a signed value from the raw data from eFuse. Sign bit is the index of the sign bit, starting -/// from 0. see -fn get_signed_val(data: u32, sign_bit: u32) -> i32 { - let sign_mask = 1u32 << sign_bit; - if data & sign_mask != 0 { - -((data & !sign_mask) as i32) - } else { - data as i32 - } -} - -/// Get version of RTC calibration block +/// Returns the version of RTC calibration block. /// /// see #[instability::unstable] @@ -59,7 +48,7 @@ pub fn rtc_calib_version() -> u8 { if minor >= 1 { 1 } else { 0 } } -/// Get ADC initial code for specified attenuation from efuse +/// Returns the ADC initial code for specified attenuation from efuse. /// /// see #[instability::unstable] @@ -80,7 +69,7 @@ pub fn rtc_calib_init_code(_unit: AdcCalibUnit, atten: Attenuation) -> Option #[instability::unstable] @@ -99,23 +88,23 @@ pub fn rtc_calib_get_chan_compens( _ => return None, }); - Some(get_signed_val(chan_diff, 3) * (4 - atten as i32)) + Some(super::sign_magnitude(chan_diff, 3) * (4 - atten as i32)) } -/// Get ADC calibration coefficients +/// Returns the ADC calibration coefficients. /// /// see #[instability::unstable] -pub fn rtc_calib_cal_mv(_unit: AdcCalibUnit, atten: Attenuation) -> u16 { - match atten { +pub fn rtc_calib_cal_mv(_unit: AdcCalibUnit, atten: Attenuation) -> Option { + Some(match atten { Attenuation::_0dB => 600, Attenuation::_2p5dB => 800, Attenuation::_6dB => 1200, Attenuation::_11dB => 2300, - } + }) } -/// Get ADC calibration code +/// Returns the ADC calibration code. /// /// see #[instability::unstable] @@ -138,24 +127,24 @@ pub fn rtc_calib_cal_code(_unit: AdcCalibUnit, atten: Attenuation) -> Option 2300, }; - let out = chk_offset + get_signed_val(cal_vol as u32, 9); + let out = chk_offset + super::sign_magnitude(cal_vol as u32, 9); Some(out as u16) } -/// Returns the major hardware revision +/// Returns the major hardware revision. #[instability::unstable] pub fn major_chip_version() -> u8 { super::read_field_le(WAFER_VERSION_MAJOR) } -/// Returns the minor hardware revision +/// Returns the minor hardware revision. #[instability::unstable] pub fn minor_chip_version() -> u8 { super::read_field_le(WAFER_VERSION_MINOR) } -/// Returns the frequency of the crystal oscillator in MHz +/// Returns the frequency of the crystal oscillator in MHz. #[instability::unstable] pub fn xtal_frequency_mhz() -> u32 { let sel = super::read_field_le::(XTAL_48M_SEL); diff --git a/esp-hal/src/efuse/esp32c6/fields.rs b/esp-hal/src/efuse/esp32c6/fields.rs index 703da90396b..d6b1e38de70 100644 --- a/esp-hal/src/efuse/esp32c6/fields.rs +++ b/esp-hal/src/efuse/esp32c6/fields.rs @@ -125,7 +125,7 @@ pub const DIS_USB_SERIAL_JTAG_DOWNLOAD_MODE: EfuseField = EfuseField::new(0, 4, /// Represents whether security download is enabled or disabled. 1: enabled. 0: /// disabled pub const ENABLE_SECURITY_DOWNLOAD: EfuseField = EfuseField::new(0, 4, 133, 1); -/// Set the default UARTboot message output mode +/// Set the default UART boot message output mode pub const UART_PRINT_CONTROL: EfuseField = EfuseField::new(0, 4, 134, 2); /// Reserved pub const RPT4_RESERVED3_4: EfuseField = EfuseField::new(0, 4, 136, 1); diff --git a/esp-hal/src/efuse/esp32c6/mod.rs b/esp-hal/src/efuse/esp32c6/mod.rs index 1ca9286db14..9bbc4a92134 100644 --- a/esp-hal/src/efuse/esp32c6/mod.rs +++ b/esp-hal/src/efuse/esp32c6/mod.rs @@ -5,16 +5,14 @@ mod fields; #[instability::unstable] pub use fields::*; -/// Selects which ADC we are interested in the efuse calibration data for +/// Selects which ADC the eFuse calibration data applies to. #[instability::unstable] pub enum AdcCalibUnit { - /// Select efuse calibration data for ADC1 + /// Selects efuse calibration data for ADC1. ADC1, - /// Select efuse calibration data for ADC2 - ADC2, } -/// Get status of SPI boot encryption. +/// Returns whether SPI boot encryption is enabled. #[instability::unstable] pub fn flash_encryption() -> bool { !super::read_field_le::(SPI_BOOT_CRYPT_CNT) @@ -22,13 +20,13 @@ pub fn flash_encryption() -> bool { .is_multiple_of(2) } -/// Get the multiplier for the timeout value of the RWDT STAGE 0 register. +/// Returns the multiplier for the timeout value of the RWDT STAGE 0 register. #[instability::unstable] pub fn rwdt_multiplier() -> u8 { super::read_field_le::(WDT_DELAY_SEL) } -/// Get efuse block version +/// Returns the eFuse block version. /// /// see #[instability::unstable] @@ -41,19 +39,7 @@ pub fn block_version() -> (u8, u8) { ) } -/// Get a signed value from the raw data from eFuse. -/// -/// `sign_bit` is the index of the sign bit, starting from 0. -fn get_signed_val(data: u32, sign_bit: u32) -> i32 { - let sign_mask = 1u32 << sign_bit; - if data & sign_mask != 0 { - -((data & !sign_mask) as i32) - } else { - data as i32 - } -} - -/// Get version of RTC calibration block +/// Returns the version of RTC calibration block. /// /// See #[instability::unstable] @@ -68,7 +54,7 @@ pub fn rtc_calib_version() -> u8 { } } -/// Get ADC initial code for specified attenuation from efuse +/// Returns the ADC initial code for specified attenuation from efuse. /// /// See #[instability::unstable] @@ -90,7 +76,7 @@ pub fn rtc_calib_init_code(_unit: AdcCalibUnit, atten: Attenuation) -> Option #[instability::unstable] @@ -109,24 +95,24 @@ pub fn rtc_calib_get_chan_compens( _ => ADC1_INIT_CODE_ATTEN0_CH6, }); - Some(get_signed_val(chan_diff, 3) * (4 - atten as i32)) + Some(super::sign_magnitude(chan_diff, 3) * (4 - atten as i32)) } -/// Get ADC reference point voltage for specified attenuation in millivolts +/// Returns the ADC reference point voltage for specified attenuation in millivolts. /// /// See #[instability::unstable] -pub fn rtc_calib_cal_mv(_unit: AdcCalibUnit, atten: Attenuation) -> u16 { +pub fn rtc_calib_cal_mv(_unit: AdcCalibUnit, atten: Attenuation) -> Option { let version = rtc_calib_version(); let input_vout_mv = match version { 2 => [750, 1000, 1500, 2800], _ => [400, 550, 750, 1370], }; - input_vout_mv[atten as usize] + Some(input_vout_mv[atten as usize]) } -/// Get ADC reference point digital code for specified attenuation +/// Returns the ADC reference point digital code for specified attenuation. /// /// See #[instability::unstable] @@ -153,16 +139,16 @@ pub fn rtc_calib_cal_code(_unit: AdcCalibUnit, atten: Attenuation) -> Option u8 { super::read_field_le(WAFER_VERSION_MAJOR) } -/// Returns the minor hardware revision +/// Returns the minor hardware revision. #[instability::unstable] pub fn minor_chip_version() -> u8 { super::read_field_le(WAFER_VERSION_MINOR) diff --git a/esp-hal/src/efuse/esp32c61/fields.rs b/esp-hal/src/efuse/esp32c61/fields.rs index 99930701ad1..facf97e4c3e 100644 --- a/esp-hal/src/efuse/esp32c61/fields.rs +++ b/esp-hal/src/efuse/esp32c61/fields.rs @@ -127,10 +127,10 @@ pub const ECC_FORCE_CONST_TIME: EfuseField = EfuseField::new(0, 3, 127, 1); /// Represents the anti-rollback secure version of the 2nd stage bootloader used /// by the ROM bootloader pub const BOOTLOADER_ANTI_ROLLBACK_SECURE_VERSION: EfuseField = EfuseField::new(0, 4, 128, 4); -/// Represents whether the ani-rollback check for the 2nd stage bootloader is +/// Represents whether the anti-rollback check for the 2nd stage bootloader is /// enabled.1: Enabled0: Disabled pub const BOOTLOADER_ANTI_ROLLBACK_EN: EfuseField = EfuseField::new(0, 4, 132, 1); -/// Represents whether the ani-rollback SECURE_VERSION will be updated from the +/// Represents whether the anti-rollback SECURE_VERSION will be updated from the /// ROM bootloader.1: Enable0: Disable pub const BOOTLOADER_ANTI_ROLLBACK_UPDATE_IN_ROM: EfuseField = EfuseField::new(0, 4, 133, 1); /// Represents the starting flash sector (flash sector size is 0x1000) of the diff --git a/esp-hal/src/efuse/esp32c61/mod.rs b/esp-hal/src/efuse/esp32c61/mod.rs index 40bc2118ba1..423b9a01ce2 100644 --- a/esp-hal/src/efuse/esp32c61/mod.rs +++ b/esp-hal/src/efuse/esp32c61/mod.rs @@ -5,7 +5,7 @@ mod fields; #[instability::unstable] pub use fields::*; -/// Get status of SPI boot encryption. +/// Returns whether SPI boot encryption is enabled. #[instability::unstable] pub fn flash_encryption() -> bool { !super::read_field_le::(SPI_BOOT_CRYPT_CNT) @@ -13,13 +13,13 @@ pub fn flash_encryption() -> bool { .is_multiple_of(2) } -/// Get the multiplier for the timeout value of the RWDT STAGE 0 register. +/// Returns the multiplier for the timeout value of the RWDT STAGE 0 register. #[instability::unstable] pub fn rwdt_multiplier() -> u8 { super::read_field_le::(WDT_DELAY_SEL) } -/// Get efuse block version +/// Returns the eFuse block version. /// /// see #[instability::unstable] @@ -32,7 +32,7 @@ pub fn block_version() -> (u8, u8) { ) } -/// Get version of RTC calibration block +/// Returns the version of RTC calibration block. /// /// see #[instability::unstable] @@ -41,13 +41,13 @@ pub fn rtc_calib_version() -> u8 { if minor >= 1 { 1 } else { 0 } } -/// Returns the major hardware revision +/// Returns the major hardware revision. #[instability::unstable] pub fn major_chip_version() -> u8 { super::read_field_le(WAFER_VERSION_MAJOR) } -/// Returns the minor hardware revision +/// Returns the minor hardware revision. #[instability::unstable] pub fn minor_chip_version() -> u8 { super::read_field_le(WAFER_VERSION_MINOR) @@ -88,25 +88,14 @@ impl EfuseBlock { } } -/// Selects which ADC we are interested in the efuse calibration data for +/// Selects which ADC the eFuse calibration data applies to. #[instability::unstable] pub enum AdcCalibUnit { - /// Select efuse calibration data for ADC1 + /// Selects efuse calibration data for ADC1. ADC1, } -/// Get a signed value from the raw data from eFuse. Sign bit is the index of the sign bit, starting -/// from 0. see -fn get_signed_val(data: u32, sign_bit: u32) -> i32 { - let sign_mask = 1u32 << sign_bit; - if data & sign_mask != 0 { - -((data & !sign_mask) as i32) - } else { - data as i32 - } -} - -/// Get ADC initial code for specified attenuation from efuse +/// Returns the ADC initial code for specified attenuation from efuse. /// /// see #[instability::unstable] @@ -127,7 +116,7 @@ pub fn rtc_calib_init_code(_unit: AdcCalibUnit, atten: Attenuation) -> Option #[instability::unstable] @@ -144,23 +133,23 @@ pub fn rtc_calib_get_chan_compens( _ => return None, }); - Some(get_signed_val(chan_diff, 3) * (4 - atten as i32)) + Some(super::sign_magnitude(chan_diff, 3) * (4 - atten as i32)) } -/// Get ADC calibration coefficients +/// Returns the ADC calibration coefficients. /// /// see #[instability::unstable] -pub fn rtc_calib_cal_mv(_unit: AdcCalibUnit, atten: Attenuation) -> u16 { - match atten { +pub fn rtc_calib_cal_mv(_unit: AdcCalibUnit, atten: Attenuation) -> Option { + Some(match atten { Attenuation::_0dB => 600, Attenuation::_2p5dB => 800, Attenuation::_6dB => 1200, Attenuation::_11dB => 2300, - } + }) } -/// Get ADC calibration code +/// Returns the ADC calibration code. /// /// see #[instability::unstable] @@ -183,7 +172,7 @@ pub fn rtc_calib_cal_code(_unit: AdcCalibUnit, atten: Attenuation) -> Option 2300, }; - let out = chk_offset + get_signed_val(cal_vol as u32, 9); + let out = chk_offset + super::sign_magnitude(cal_vol as u32, 9); Some(out as u16) } diff --git a/esp-hal/src/efuse/esp32h2/fields.rs b/esp-hal/src/efuse/esp32h2/fields.rs index fe4bed5c052..05276a7fa62 100644 --- a/esp-hal/src/efuse/esp32h2/fields.rs +++ b/esp-hal/src/efuse/esp32h2/fields.rs @@ -127,7 +127,7 @@ pub const DIS_USB_SERIAL_JTAG_DOWNLOAD_MODE: EfuseField = EfuseField::new(0, 4, /// Represents whether security download is enabled or disabled. 1: enabled. 0: /// disabled pub const ENABLE_SECURITY_DOWNLOAD: EfuseField = EfuseField::new(0, 4, 133, 1); -/// Set the default UARTboot message output mode +/// Set the default UART boot message output mode pub const UART_PRINT_CONTROL: EfuseField = EfuseField::new(0, 4, 134, 2); /// Represents whether ROM code is forced to send a resume command during SPI /// boot. 1: forced. 0:not forced diff --git a/esp-hal/src/efuse/esp32h2/mod.rs b/esp-hal/src/efuse/esp32h2/mod.rs index 94e1bbcb186..ab403f33bcf 100644 --- a/esp-hal/src/efuse/esp32h2/mod.rs +++ b/esp-hal/src/efuse/esp32h2/mod.rs @@ -5,14 +5,14 @@ mod fields; #[instability::unstable] pub use fields::*; -/// Selects which ADC we are interested in the efuse calibration data for +/// Selects which ADC the eFuse calibration data applies to. #[instability::unstable] pub enum AdcCalibUnit { - /// Select efuse calibration data for ADC1 + /// Selects efuse calibration data for ADC1. ADC1, } -/// Get status of SPI boot encryption. +/// Returns whether SPI boot encryption is enabled. #[instability::unstable] pub fn flash_encryption() -> bool { !super::read_field_le::(SPI_BOOT_CRYPT_CNT) @@ -20,13 +20,13 @@ pub fn flash_encryption() -> bool { .is_multiple_of(2) } -/// Get the multiplier for the timeout value of the RWDT STAGE 0 register. +/// Returns the multiplier for the timeout value of the RWDT STAGE 0 register. #[instability::unstable] pub fn rwdt_multiplier() -> u8 { super::read_field_le::(WDT_DELAY_SEL) } -/// Get efuse block version +/// Returns the eFuse block version. /// /// See: #[instability::unstable] @@ -37,19 +37,7 @@ pub fn block_version() -> (u8, u8) { ) } -/// Get a signed value from the raw data from eFuse. -/// -/// `sign_bit` is the index of the sign bit, starting from 0. -fn get_signed_val(data: u32, sign_bit: u32) -> i32 { - let sign_mask = 1u32 << sign_bit; - if data & sign_mask != 0 { - -((data & !sign_mask) as i32) - } else { - data as i32 - } -} - -/// Get version of RTC calibration block +/// Returns the version of RTC calibration block. /// /// See: #[instability::unstable] @@ -58,7 +46,7 @@ pub fn rtc_calib_version() -> u8 { if minor >= 2 { 1 } else { 0 } } -/// Get ADC initial code for specified attenuation from efuse +/// Returns the ADC initial code for specified attenuation from efuse. /// /// See: #[instability::unstable] @@ -80,7 +68,7 @@ pub fn rtc_calib_init_code(_unit: AdcCalibUnit, atten: Attenuation) -> Option #[instability::unstable] @@ -97,28 +85,28 @@ pub fn rtc_calib_get_chan_compens( _ => ADC1_CH4_ATTEN0_INITCODE_DIFF, }); - Some(get_signed_val(chan_diff, 3) * (4 - atten as i32)) + Some(super::sign_magnitude(chan_diff, 3) * (4 - atten as i32)) } -/// Get ADC reference point voltage for specified attenuation in millivolts +/// Returns the ADC reference point voltage for specified attenuation in millivolts. /// /// See: #[instability::unstable] -pub fn rtc_calib_cal_mv(_unit: AdcCalibUnit, atten: Attenuation) -> u16 { +pub fn rtc_calib_cal_mv(_unit: AdcCalibUnit, atten: Attenuation) -> Option { let version = rtc_calib_version(); let input_vout_mv = match version { 1 => [750, 1000, 1500, 2800], _ => { // The required efuse bits for this chip are not burnt. // 1100 is the middle of the reference voltage range. - return 1100; + return Some(1100); } }; - input_vout_mv[atten as usize] + Some(input_vout_mv[atten as usize]) } -/// Returns the calibration code +/// Returns the calibration code. /// /// See: #[instability::unstable] @@ -140,16 +128,16 @@ pub fn rtc_calib_cal_code(_unit: AdcCalibUnit, atten: Attenuation) -> Option u8 { super::read_field_le(WAFER_VERSION_MAJOR) } -/// Returns the minor hardware revision +/// Returns the minor hardware revision. #[instability::unstable] pub fn minor_chip_version() -> u8 { super::read_field_le(WAFER_VERSION_MINOR) diff --git a/esp-hal/src/efuse/esp32h4/fields.rs b/esp-hal/src/efuse/esp32h4/fields.rs new file mode 100644 index 00000000000..7a3af8d065d --- /dev/null +++ b/esp-hal/src/efuse/esp32h4/fields.rs @@ -0,0 +1,342 @@ +//! eFuse fields for the ESP32-H4. +//! +//! This file was generated from espefuse/efuse_defs/esp32h4.yaml +//! (via espflash/espflash/src/target/efuse/esp32h4.rs). +//! +//! For information on how to regenerate these files, please refer to the +//! `xtask` package's `README.md` file. +use crate::efuse::EfuseField; +/// Disable programming of individual eFuses +pub const WR_DIS: EfuseField = EfuseField::new(0, 0, 0, 32); +/// Disable reading from BlOCK4-10 +pub const RD_DIS: EfuseField = EfuseField::new(0, 1, 32, 7); +/// Represents whether the function of usb switch to jtag is disabled or +/// enabled. 1: disabled 0: enabled +pub const DIS_USB_JTAG: EfuseField = EfuseField::new(0, 1, 39, 1); +/// Represents whether USB-Serial-JTAG is disabled or enabled. 1: disabled 0: +/// enabled +pub const DIS_USB_SERIAL_JTAG: EfuseField = EfuseField::new(0, 1, 40, 1); +/// Represents whether the function that forces chip into download mode is +/// disabled or enabled. 1: disabled 0: enabled +pub const DIS_FORCE_DOWNLOAD: EfuseField = EfuseField::new(0, 1, 41, 1); +/// Represents whether SPI0 controller during boot_mode_download is disabled or +/// enabled. 1: disabled 0: enabled +pub const SPI_DOWNLOAD_MSPI_DIS: EfuseField = EfuseField::new(0, 1, 42, 1); +/// Represents whether TWAI function is disabled or enabled. 1: disabled 0: +/// enabled +pub const DIS_TWAI: EfuseField = EfuseField::new(0, 1, 43, 1); +/// Represents whether the selection between usb_to_jtag and pad_to_jtag through +/// strapping gpio15 when both EFUSE_DIS_PAD_JTAG and EFUSE_DIS_USB_JTAG are +/// equal to 0 is enabled or disabled. 1: enabled 0: disabled +pub const JTAG_SEL_ENABLE: EfuseField = EfuseField::new(0, 1, 44, 1); +/// Represents whether JTAG is disabled in the hard way(permanently). 1: +/// disabled 0: enabled +pub const DIS_PAD_JTAG: EfuseField = EfuseField::new(0, 1, 45, 1); +/// Represents whether flash encrypt function is disabled or enabled(except in +/// SPI boot mode). 1: disabled 0: enabled +pub const DIS_DOWNLOAD_MANUAL_ENCRYPT: EfuseField = EfuseField::new(0, 1, 46, 1); +/// Reserved; it was created by set_missed_fields_in_regs func +pub const RESERVE_0_47: EfuseField = EfuseField::new(0, 1, 47, 3); +/// Represents whether to enable PVT power glitch monitor function.1:Enable. +/// 0:Disable +pub const PVT_GLITCH_EN: EfuseField = EfuseField::new(0, 1, 50, 1); +/// Reserved; it was created by set_missed_fields_in_regs func +pub const RESERVE_0_51: EfuseField = EfuseField::new(0, 1, 51, 1); +/// Use to configure glitch mode +pub const PVT_GLITCH_MODE: EfuseField = EfuseField::new(0, 1, 52, 2); +/// Represents whether the CPU-Core1 is disabled. 1: Disabled. 0: Not disable +pub const DIS_CORE1: EfuseField = EfuseField::new(0, 1, 54, 1); +/// Enables flash encryption when 1 or 3 bits are set and disables otherwise +pub const SPI_BOOT_CRYPT_CNT: EfuseField = EfuseField::new(0, 1, 55, 3); +/// Revoke 1st secure boot key +pub const SECURE_BOOT_KEY_REVOKE0: EfuseField = EfuseField::new(0, 1, 58, 1); +/// Revoke 2nd secure boot key +pub const SECURE_BOOT_KEY_REVOKE1: EfuseField = EfuseField::new(0, 1, 59, 1); +/// Revoke 3rd secure boot key +pub const SECURE_BOOT_KEY_REVOKE2: EfuseField = EfuseField::new(0, 1, 60, 1); +/// Reserved; it was created by set_missed_fields_in_regs func +pub const RESERVE_0_61: EfuseField = EfuseField::new(0, 1, 61, 3); +/// Represents the purpose of Key0 +pub const KEY_PURPOSE_0: EfuseField = EfuseField::new(0, 2, 64, 5); +/// Represents the purpose of Key1 +pub const KEY_PURPOSE_1: EfuseField = EfuseField::new(0, 2, 69, 5); +/// Represents the purpose of Key2 +pub const KEY_PURPOSE_2: EfuseField = EfuseField::new(0, 2, 74, 5); +/// Represents the purpose of Key3 +pub const KEY_PURPOSE_3: EfuseField = EfuseField::new(0, 2, 79, 5); +/// Represents the purpose of Key4 +pub const KEY_PURPOSE_4: EfuseField = EfuseField::new(0, 2, 84, 5); +/// Represents the purpose of Key5 +pub const KEY_PURPOSE_5: EfuseField = EfuseField::new(0, 2, 89, 5); +/// Represents the spa secure level by configuring the clock random divide mode +pub const SEC_DPA_LEVEL: EfuseField = EfuseField::new(0, 2, 94, 2); +/// Represents the pseudo round level of xts-aes anti-dpa attack. 3: High. 2: +/// Moderate 1. Low 0: Disabled +pub const XTS_DPA_PSEUDO_LEVEL: EfuseField = EfuseField::new(0, 3, 96, 2); +/// Represents whether xts-aes anti-dpa attack clock is enabled. 1. Enable. 0: +/// Disable. +pub const XTS_DPA_CLK_ENABLE: EfuseField = EfuseField::new(0, 3, 98, 1); +/// Represents whether to force ecc to use const-time calculation mode. 1: +/// Enable. 0: Disable +pub const ECC_FORCE_CONST_TIME: EfuseField = EfuseField::new(0, 3, 99, 1); +/// Represents if the chip supports Secure Boot using SHA-384 +pub const SECURE_BOOT_SHA384_EN: EfuseField = EfuseField::new(0, 3, 100, 1); +/// Represents whether secure boot is enabled or disabled. 1: enabled 0: +/// disabled +pub const SECURE_BOOT_EN: EfuseField = EfuseField::new(0, 3, 101, 1); +/// Represents whether revoking aggressive secure boot is enabled or disabled. +/// 1: enabled. 0: disabled +pub const SECURE_BOOT_AGGRESSIVE_REVOKE: EfuseField = EfuseField::new(0, 3, 102, 1); +/// Represents whether the new key deployment of key manager is disabled. Bit0: +/// Represents whether the new ECDSA key deployment is disabled0: Enabled1: +/// DisabledBit1: Represents whether the new XTS-AES (flash and PSRAM) key +/// deployment is disabled0: Enabled1: DisabledBit2: Represents whether the new +/// HMAC key deployment is disabled0: Enabled1: DisabledBit3: Represents whether +/// the new DS key deployment is disabled0: Enabled1: Disabled +pub const KM_DISABLE_DEPLOY_MODE: EfuseField = EfuseField::new(0, 3, 103, 5); +/// Represents the cycle at which the Key Manager switches random numbers.0: +/// Controlled by the +/// \hyperref\[fielddesc:KEYMNGRNDSWITCHCYCLE\]{KEYMNG\_RND\_SWITCH\_CYCLE} +/// register. For more information; please refer to Chapter \ref{mod:keymng} +/// \textit{\nameref{mod:keymng}}1: 8 Key Manager clock cycles2: 16 Key Manager +/// clock cycles3: 32 Key Manager clock cycles +pub const KM_RND_SWITCH_CYCLE: EfuseField = EfuseField::new(0, 3, 108, 2); +/// Represents whether the corresponding key can be deployed only once.Bit0: +/// Represents whether the ECDSA key can be deployed only once0: The key can be +/// deployed multiple times1: The key can be deployed only onceBit1: Represents +/// whether the XTS-AES (flash and PSRAM) key can be deployed only once0: The +/// key can be deployed multiple times1: The key can be deployed only onceBit2: +/// Represents whether the HMAC key can be deployed only once0: The key can be +/// deployed multiple times1: The key can be deployed only onceBit3: Represents +/// whether the DS key can be deployed only once0: The key can be deployed +/// multiple times1: The key can be deployed only once +pub const KM_DEPLOY_ONLY_ONCE: EfuseField = EfuseField::new(0, 3, 110, 5); +/// Represents whether the corresponding key must come from Key Manager. Bit0: +/// Represents whether the ECDSA key must come from Key Manager.0: The key does +/// not need to come from Key Manager1: The key must come from Key ManagerBit1: +/// Represents whether the XTS-AES (flash and PSRAM) key must come from Key +/// Manager.0: The key does not need to come from Key Manager1: The key must +/// come from Key ManagerBit2: Represents whether the HMAC key must come from +/// Key Manager.0: The key does not need to come from Key Manager1: The key must +/// come from Key ManagerBit3: Represents whether the DS key must come from Key +/// Manager.0: The key does not need to come from Key Manager1: The key must +/// come from Key Manager +pub const FORCE_USE_KEY_MANAGER_KEY: EfuseField = EfuseField::new(0, 3, 115, 5); +/// Represents whether to disable the use of the initialization key written by +/// software and instead force use efuse\_init\_key.0: Enable1: Disable +pub const FORCE_DISABLE_SW_INIT_KEY: EfuseField = EfuseField::new(0, 3, 120, 1); +/// Represents which key flash encryption uses.0: XTS-AES-256 key1: XTS-AES-128 +/// key +pub const KM_XTS_KEY_LENGTH_256: EfuseField = EfuseField::new(0, 3, 121, 1); +/// Represents whether the keys in the Key Manager are locked after +/// deployment.0: Not locked1: Locked +pub const LOCK_KM_KEY: EfuseField = EfuseField::new(0, 3, 122, 1); +/// Represents the flash waiting time after power-up; in unit of ms. When the +/// value less than 15; the waiting time is the programmed value. Otherwise; the +/// waiting time is 2 times the programmed value +pub const FLASH_TPUW: EfuseField = EfuseField::new(0, 3, 123, 3); +/// Reserved; it was created by set_missed_fields_in_regs func +pub const RESERVE_0_126: EfuseField = EfuseField::new(0, 3, 126, 1); +/// Represents whether Download mode is disabled or enabled. 1: disabled 0: +/// enabled +pub const DIS_DOWNLOAD_MODE: EfuseField = EfuseField::new(0, 3, 127, 1); +/// Represents whether direct boot mode is disabled or enabled. 1: disabled 0: +/// enabled +pub const DIS_DIRECT_BOOT: EfuseField = EfuseField::new(0, 4, 128, 1); +/// Represents whether print from USB-Serial-JTAG is disabled or enabled. 1: +/// disabled 0: enabled +pub const DIS_USB_SERIAL_JTAG_ROM_PRINT: EfuseField = EfuseField::new(0, 4, 129, 1); +/// Represents whether the USB-Serial-JTAG download function is disabled or +/// enabled. 1: Disable 0: Enable +pub const DIS_USB_SERIAL_JTAG_DOWNLOAD_MODE: EfuseField = EfuseField::new(0, 4, 130, 1); +/// Represents whether security download is enabled or disabled. 1: enabled 0: +/// disabled +pub const ENABLE_SECURITY_DOWNLOAD: EfuseField = EfuseField::new(0, 4, 131, 1); +/// Represents the type of UART printing. 00: force enable printing 01: enable +/// printing when GPIO8 is reset at low level 10: enable printing when GPIO8 is +/// reset at high level 11: force disable printing +pub const UART_PRINT_CONTROL: EfuseField = EfuseField::new(0, 4, 132, 2); +/// Represents whether ROM code is forced to send a resume command during SPI +/// boot. 1: forced 0:not forced +pub const FORCE_SEND_RESUME: EfuseField = EfuseField::new(0, 4, 134, 1); +/// Represents the version used by ESP-IDF anti-rollback feature +pub const SECURE_VERSION: EfuseField = EfuseField::new(0, 4, 135, 16); +/// Represents whether the HUK generate mode is valid.Odd count of bits with a +/// value of 1: InvalidEven count of bits with a value of 1: Valid +pub const HUK_GEN_STATE: EfuseField = EfuseField::new(0, 4, 151, 5); +/// Represents whether to select efuse control flash ldo default voltage. 1 : +/// efuse 0 : strapping +pub const FLASH_LDO_EFUSE_SEL: EfuseField = EfuseField::new(0, 4, 156, 1); +/// Reserved; it was created by set_missed_fields_in_regs func +pub const RESERVE_0_157: EfuseField = EfuseField::new(0, 4, 157, 3); +/// Represents the single-end input threshold vrefh of USB_SERIAL_JTAG PHY; 1.76 +/// V to 2 V with step of 80 mV +pub const USB_DREFH: EfuseField = EfuseField::new(0, 5, 160, 2); +/// Represents the single-end input threshold vrefl of USB_SERIAL_JTAG PHY; 1.76 +/// V to 2 V with step of 80 mV +pub const USB_DREFL: EfuseField = EfuseField::new(0, 5, 162, 2); +/// Represents the single-end input threshold vrefh of USB_OTG_FS PHY; 1.76 V to +/// 2 V with step of 80 mV +pub const USB_OTG_FS_DREFH: EfuseField = EfuseField::new(0, 5, 164, 2); +/// Represents the single-end input threshold vrefl of USB_OTG_FS PHY; 1.76 V to +/// 2 V with step of 80 mV +pub const USB_OTG_FS_DREFL: EfuseField = EfuseField::new(0, 5, 166, 2); +/// Represents whether the D+ and D- pins of USB_SERIAL_JTAG PHY is exchanged. +/// 1: exchanged 0: not exchanged +pub const USB_EXCHG_PINS: EfuseField = EfuseField::new(0, 5, 168, 1); +/// Represents whether the D+ and D- pins of USB_OTG_FS PHY is exchanged. 1: +/// exchanged 0: not exchanged +pub const USB_OTG_FS_EXCHG_PINS: EfuseField = EfuseField::new(0, 5, 169, 1); +/// Represents whether to exchange the USB_SERIAL_JTAG PHY with USB_OTG_FS PHY. +/// 1: exchanged. 0: not exchanged +pub const USB_PHY_SEL: EfuseField = EfuseField::new(0, 5, 170, 1); +/// Represents whether JTAG is disabled in soft way. Odd number: disabled Even +/// number: enabled +pub const SOFT_DIS_JTAG: EfuseField = EfuseField::new(0, 5, 171, 3); +/// Represents configuration of IO LDO mode and voltage. +pub const IO_LDO_ADJUST: EfuseField = EfuseField::new(0, 5, 174, 8); +/// Represents select IO LDO voltage to 1.8V or 3.3V. 1: 1.8V 0: 3.3V +pub const IO_LDO_1P8: EfuseField = EfuseField::new(0, 5, 182, 1); +/// Represents whether change DCDC to CCM mode +pub const DCDC_CCM_EN: EfuseField = EfuseField::new(0, 5, 183, 1); +/// Reserved; it was created by set_missed_fields_in_regs func +pub const RESERVE_0_184: EfuseField = EfuseField::new(0, 5, 184, 8); +/// MAC address +pub const MAC0: EfuseField = EfuseField::new(1, 0, 0, 32); +/// MAC address +pub const MAC1: EfuseField = EfuseField::new(1, 1, 32, 16); +/// Represents the extended bits of MAC address +pub const MAC_EXT: EfuseField = EfuseField::new(1, 1, 48, 16); +/// Power glitch monitor threthold +pub const PVT_LIMIT: EfuseField = EfuseField::new(1, 2, 64, 16); +/// Power glitch monitor PVT cell select +pub const PVT_CELL_SELECT: EfuseField = EfuseField::new(1, 2, 80, 7); +/// Use to configure voltage monitor limit for charge pump +pub const PVT_PUMP_LIMIT: EfuseField = EfuseField::new(1, 2, 87, 8); +/// Reserved; it was created by set_missed_fields_in_regs func +pub const RESERVE_1_95: EfuseField = EfuseField::new(1, 2, 95, 1); +/// Use to configure charge pump voltage gain +pub const PUMP_DRV: EfuseField = EfuseField::new(1, 3, 96, 4); +/// Represents the threshold level of the RTC watchdog STG0 timeout. 0: Original +/// threshold configuration value of STG0 *2 1: Original threshold configuration +/// value of STG0 *4 2: Original threshold configuration value of STG0 *8 3: +/// Original threshold configuration value of STG0 *16 +pub const WDT_DELAY_SEL: EfuseField = EfuseField::new(1, 3, 100, 2); +/// Represents whether the hysteresis function of corresponding PAD is enabled. +/// 1: enabled 0:disabled +pub const HYS_EN_PAD: EfuseField = EfuseField::new(1, 3, 102, 1); +/// Represents whether to trigger reset or charge pump when PVT power glitch +/// happened.1:Trigger charge pump. 0:Trigger reset +pub const PVT_GLITCH_CHARGE_RESET: EfuseField = EfuseField::new(1, 3, 103, 1); +/// Reserved; it was created by set_missed_fields_in_regs func +pub const RESERVE_1_104: EfuseField = EfuseField::new(1, 3, 104, 1); +/// Represents configuration of FLASH LDO mode and voltage. +pub const VDD_SPI_LDO_ADJUST: EfuseField = EfuseField::new(1, 3, 105, 8); +/// Represents which flash ldo be select: 1: FLASH LDO 1P2 0 : FLASH LDO 1P8 +pub const FLASH_LDO_POWER_SEL: EfuseField = EfuseField::new(1, 3, 113, 1); +/// Minor chip version +pub const WAFER_VERSION_MINOR: EfuseField = EfuseField::new(1, 3, 114, 4); +/// Major chip version +pub const WAFER_VERSION_MAJOR: EfuseField = EfuseField::new(1, 3, 118, 2); +/// Disables check of wafer version major +pub const DISABLE_WAFER_VERSION_MAJOR: EfuseField = EfuseField::new(1, 3, 120, 1); +/// Disables check of blk version major +pub const DISABLE_BLK_VERSION_MAJOR: EfuseField = EfuseField::new(1, 3, 121, 1); +/// BLK_VERSION_MINOR of BLOCK2 +pub const BLK_VERSION_MINOR: EfuseField = EfuseField::new(1, 3, 122, 3); +/// BLK_VERSION_MAJOR of BLOCK2 +pub const BLK_VERSION_MAJOR: EfuseField = EfuseField::new(1, 3, 125, 2); +/// Flash capacity +pub const FLASH_CAP: EfuseField = EfuseField::new(1, 3, 127, 3); +/// Flash vendor +pub const FLASH_VENDOR: EfuseField = EfuseField::new(1, 4, 130, 3); +/// Psram capacity +pub const PSRAM_CAP: EfuseField = EfuseField::new(1, 4, 133, 3); +/// Psram vendor +pub const PSRAM_VENDOR: EfuseField = EfuseField::new(1, 4, 136, 2); +/// Temp (die embedded inside) +pub const TEMP: EfuseField = EfuseField::new(1, 4, 138, 2); +/// Package version +pub const PKG_VERSION: EfuseField = EfuseField::new(1, 4, 140, 3); +/// PVT DBIAS +pub const PVT_DBIAS: EfuseField = EfuseField::new(1, 4, 143, 5); +/// SPI LDO adjust of 1.2v +pub const ADJUST_1V2: EfuseField = EfuseField::new(1, 4, 148, 4); +/// SPI LDO adjust of 1.8v +pub const ADJUST_1V8: EfuseField = EfuseField::new(1, 4, 152, 4); +/// DCDC-DCDC DBIAS of 1.25v +pub const ACTIVE_DCDC_1V25: EfuseField = EfuseField::new(1, 4, 156, 4); +/// DCDC-DCDC DBIAS of 1.35v +pub const ACTIVE_DCDC_1V35: EfuseField = EfuseField::new(1, 5, 160, 4); +/// DCDC DBIAS in sleep +pub const SLP_DCDC: EfuseField = EfuseField::new(1, 5, 164, 5); +/// HP DRVB in light sleep +pub const LSLP_HP_DRVB: EfuseField = EfuseField::new(1, 5, 169, 5); +/// LP DBIAS in deep sleep +pub const DSLP_LP_DBIAS: EfuseField = EfuseField::new(1, 5, 174, 2); +/// Temperature calibration data +pub const TEMP_CALIB: EfuseField = EfuseField::new(1, 5, 176, 10); +/// reserved +pub const RESERVED_1_186: EfuseField = EfuseField::new(1, 5, 186, 6); +/// Optional unique 128-bit ID +pub const OPTIONAL_UNIQUE_ID: EfuseField = EfuseField::new(2, 0, 0, 128); +/// ADC OCode +pub const OCODE: EfuseField = EfuseField::new(2, 4, 128, 8); +/// DCDC OCode +pub const DCDC_OCODE: EfuseField = EfuseField::new(2, 4, 136, 8); +/// ADC dout of vdd 3.4v +pub const VDD_3V4_DOUT: EfuseField = EfuseField::new(2, 4, 144, 10); +/// Average initcode of ADC1 atten0 +pub const ADC1_AVE_INITCODE_ATTEN0: EfuseField = EfuseField::new(2, 4, 154, 9); +/// Average initcode of ADC1 atten1 +pub const ADC1_AVE_INITCODE_ATTEN1: EfuseField = EfuseField::new(2, 5, 163, 9); +/// Average initcode of ADC1 atten2 +pub const ADC1_AVE_INITCODE_ATTEN2: EfuseField = EfuseField::new(2, 5, 172, 9); +/// Average initcode of ADC1 atten3 +pub const ADC1_AVE_INITCODE_ATTEN3: EfuseField = EfuseField::new(2, 5, 181, 9); +/// HI dout of ADC1 atten0 +pub const ADC1_HI_DOUT_ATTEN0: EfuseField = EfuseField::new(2, 5, 190, 9); +/// HI dout of ADC1 atten1 +pub const ADC1_HI_DOUT_ATTEN1: EfuseField = EfuseField::new(2, 6, 199, 9); +/// HI dout of ADC1 atten2 +pub const ADC1_HI_DOUT_ATTEN2: EfuseField = EfuseField::new(2, 6, 208, 9); +/// HI dout of ADC1 atten3 +pub const ADC1_HI_DOUT_ATTEN3: EfuseField = EfuseField::new(2, 6, 217, 9); +/// Gap between ADC1 CH0 and average initcode +pub const ADC1_CH0_ATTEN0_INITCODE_DIFF: EfuseField = EfuseField::new(2, 7, 226, 3); +/// Gap between ADC1 CH1 and average initcode +pub const ADC1_CH1_ATTEN0_INITCODE_DIFF: EfuseField = EfuseField::new(2, 7, 229, 3); +/// Gap between ADC1 CH2 and average initcode +pub const ADC1_CH2_ATTEN0_INITCODE_DIFF: EfuseField = EfuseField::new(2, 7, 232, 3); +/// Gap between ADC1 CH3 and average initcode +pub const ADC1_CH3_ATTEN0_INITCODE_DIFF: EfuseField = EfuseField::new(2, 7, 235, 3); +/// Gap between ADC1 CH4 and average initcode +pub const ADC1_CH4_ATTEN0_INITCODE_DIFF: EfuseField = EfuseField::new(2, 7, 238, 3); +/// Initcode diff between IO LDO 1.8v and 3.3v +pub const INITCODE_DIFF_1P8_3P3: EfuseField = EfuseField::new(2, 7, 241, 5); +/// HI dout diff between IO LDO 1.8v and 3.3v +pub const HI_DOUT_DIFF_1P8_3P3: EfuseField = EfuseField::new(2, 7, 246, 5); +/// reserved +pub const RESERVED_2_251: EfuseField = EfuseField::new(2, 7, 251, 5); +/// User data +pub const BLOCK_USR_DATA: EfuseField = EfuseField::new(3, 0, 0, 192); +/// reserved +pub const RESERVED_3_192: EfuseField = EfuseField::new(3, 6, 192, 8); +/// Custom MAC +pub const CUSTOM_MAC: EfuseField = EfuseField::new(3, 6, 200, 48); +/// reserved +pub const RESERVED_3_248: EfuseField = EfuseField::new(3, 7, 248, 8); +/// Key0 or user data +pub const BLOCK_KEY0: EfuseField = EfuseField::new(4, 0, 0, 256); +/// Key1 or user data +pub const BLOCK_KEY1: EfuseField = EfuseField::new(5, 0, 0, 256); +/// Key2 or user data +pub const BLOCK_KEY2: EfuseField = EfuseField::new(6, 0, 0, 256); +/// Key3 or user data +pub const BLOCK_KEY3: EfuseField = EfuseField::new(7, 0, 0, 256); +/// Key4 or user data +pub const BLOCK_KEY4: EfuseField = EfuseField::new(8, 0, 0, 256); +/// Key5 or user data +pub const BLOCK_KEY5: EfuseField = EfuseField::new(9, 0, 0, 256); +/// System data part 2 (reserved) +pub const BLOCK_SYS_DATA2: EfuseField = EfuseField::new(10, 0, 0, 256); diff --git a/esp-hal/src/efuse/esp32h4/mod.rs b/esp-hal/src/efuse/esp32h4/mod.rs new file mode 100644 index 00000000000..d9f365811d5 --- /dev/null +++ b/esp-hal/src/efuse/esp32h4/mod.rs @@ -0,0 +1,80 @@ +//! # Reading of eFuses (ESP32-H4) + +use crate::peripherals::EFUSE; + +#[cfg_attr(not(feature = "unstable"), allow(dead_code))] +mod fields; +#[instability::unstable] +pub use fields::*; + +/// Returns whether SPI boot encryption is enabled. +#[instability::unstable] +pub fn flash_encryption() -> bool { + !super::read_field_le::(SPI_BOOT_CRYPT_CNT) + .count_ones() + .is_multiple_of(2) +} + +/// Returns the multiplier for the timeout value of the RWDT STAGE 0 register. +#[instability::unstable] +pub fn rwdt_multiplier() -> u8 { + super::read_field_le::(WDT_DELAY_SEL) +} + +/// Returns the eFuse block version. +/// +/// Returns (major, minor). +#[instability::unstable] +pub fn block_version() -> (u8, u8) { + ( + super::read_field_le::(BLK_VERSION_MAJOR), + super::read_field_le::(BLK_VERSION_MINOR), + ) +} + +/// Returns the major hardware revision. +#[instability::unstable] +pub fn major_chip_version() -> u8 { + super::read_field_le(WAFER_VERSION_MAJOR) +} + +/// Returns the minor hardware revision. +#[instability::unstable] +pub fn minor_chip_version() -> u8 { + super::read_field_le(WAFER_VERSION_MINOR) +} + +#[derive(Debug, Clone, Copy, strum::FromRepr)] +#[repr(u32)] +pub(crate) enum EfuseBlock { + Block0, + Block1, + Block2, + Block3, + Block4, + Block5, + Block6, + Block7, + Block8, + Block9, + Block10, +} + +impl EfuseBlock { + pub(crate) fn address(self) -> *const u32 { + let efuse = EFUSE::regs(); + match self { + Self::Block0 => efuse.rd_wr_dis0().as_ptr(), + Self::Block1 => efuse.rd_mac_sys0().as_ptr(), + Self::Block2 => efuse.rd_sys_part1_data(0).as_ptr(), + Self::Block3 => efuse.rd_usr_data(0).as_ptr(), + Self::Block4 => efuse.rd_key0_data(0).as_ptr(), + Self::Block5 => efuse.rd_key1_data(0).as_ptr(), + Self::Block6 => efuse.rd_key2_data(0).as_ptr(), + Self::Block7 => efuse.rd_key3_data(0).as_ptr(), + Self::Block8 => efuse.rd_key4_data(0).as_ptr(), + Self::Block9 => efuse.rd_key5_data(0).as_ptr(), + Self::Block10 => efuse.rd_sys_part2_data(0).as_ptr(), + } + } +} diff --git a/esp-hal/src/efuse/esp32p4/mod.rs b/esp-hal/src/efuse/esp32p4/mod.rs index c4f9394c782..e85df59cb94 100644 --- a/esp-hal/src/efuse/esp32p4/mod.rs +++ b/esp-hal/src/efuse/esp32p4/mod.rs @@ -7,7 +7,7 @@ mod fields; #[instability::unstable] pub use fields::*; -/// Get status of SPI boot encryption. +/// Returns whether SPI boot encryption is enabled. #[instability::unstable] pub fn flash_encryption() -> bool { !super::read_field_le::(SPI_BOOT_CRYPT_CNT) @@ -15,13 +15,13 @@ pub fn flash_encryption() -> bool { .is_multiple_of(2) } -/// Get the multiplier for the timeout value of the RWDT STAGE 0 register. +/// Returns the multiplier for the timeout value of the RWDT STAGE 0 register. #[instability::unstable] pub fn rwdt_multiplier() -> u8 { super::read_field_le::(WDT_DELAY_SEL) } -/// Get efuse block version +/// Returns the eFuse block version. /// /// see #[instability::unstable] @@ -32,23 +32,22 @@ pub fn block_version() -> (u8, u8) { ) } -/// Get version of RTC calibration block +/// Returns the version of RTC calibration block. /// /// see #[instability::unstable] pub fn rtc_calib_version() -> u8 { - // ESP-IDF compares `major * 100 + minor` against 1, so any non-zero block version - // selects calibration version 1. + // Any non-zero block version selects calibration version 1. let (major, minor) = block_version(); if major > 0 || minor > 0 { 1 } else { 0 } } -/// Returns the major hardware revision +/// Returns the major hardware revision. pub(crate) fn major_chip_version() -> u8 { super::read_field_le(WAFER_VERSION_MAJOR) } -/// Returns the minor hardware revision +/// Returns the minor hardware revision. pub(crate) fn minor_chip_version() -> u8 { super::read_field_le(WAFER_VERSION_MINOR) } @@ -89,27 +88,16 @@ impl EfuseBlock { } } -/// Selects which ADC we are interested in the efuse calibration data for +/// Selects which ADC the eFuse calibration data applies to. #[instability::unstable] pub enum AdcCalibUnit { - /// Select efuse calibration data for ADC1 + /// Selects efuse calibration data for ADC1. ADC1, - /// Select efuse calibration data for ADC2 + /// Selects efuse calibration data for ADC2. ADC2, } -/// Get a signed value from the raw data from eFuse. Sign bit is the index of the sign bit, starting -/// from 0. see -fn get_signed_val(data: u32, sign_bit: u32) -> i32 { - let sign_mask = 1u32 << sign_bit; - if data & sign_mask != 0 { - -((data & !sign_mask) as i32) - } else { - data as i32 - } -} - -/// Get ADC initial code for specified attenuation from efuse +/// Returns the ADC initial code for specified attenuation from efuse. /// /// see #[instability::unstable] @@ -132,7 +120,7 @@ pub fn rtc_calib_init_code(unit: AdcCalibUnit, atten: Attenuation) -> Option #[instability::unstable] @@ -141,6 +129,10 @@ pub fn rtc_calib_get_chan_compens( channel: u16, atten: Attenuation, ) -> Option { + if rtc_calib_version() != 1 { + return None; + } + let chan_diff: u32 = super::read_field_le(match (unit, channel) { (AdcCalibUnit::ADC1, 0) => ADC1_CH0_ATTEN0_INITCODE_DIFF, (AdcCalibUnit::ADC1, 1) => ADC1_CH1_ATTEN0_INITCODE_DIFF, @@ -159,23 +151,23 @@ pub fn rtc_calib_get_chan_compens( _ => return None, }); - Some(get_signed_val(chan_diff, 3) * (4 - atten as i32)) + Some(super::sign_magnitude(chan_diff, 3) * (4 - atten as i32)) } -/// Get ADC calibration reference point voltage +/// Returns the ADC calibration reference point voltage. /// /// see #[instability::unstable] -pub fn rtc_calib_cal_mv(_unit: AdcCalibUnit, atten: Attenuation) -> u16 { - match atten { +pub fn rtc_calib_cal_mv(_unit: AdcCalibUnit, atten: Attenuation) -> Option { + Some(match atten { Attenuation::_0dB => 600, Attenuation::_2p5dB => 800, Attenuation::_6dB => 1200, Attenuation::_11dB => 2300, - } + }) } -/// Get ADC calibration code +/// Returns the ADC calibration code. /// /// see #[instability::unstable] @@ -200,5 +192,5 @@ pub fn rtc_calib_cal_code(unit: AdcCalibUnit, atten: Attenuation) -> Option Attenuation::_6dB | Attenuation::_11dB => 2350, }; - Some((chk_offset + get_signed_val(cal_vol as u32, 9)) as u16) + Some((chk_offset + super::sign_magnitude(cal_vol as u32, 9)) as u16) } diff --git a/esp-hal/src/efuse/esp32s2/mod.rs b/esp-hal/src/efuse/esp32s2/mod.rs index 55678f65bf8..f89a4157c59 100644 --- a/esp-hal/src/efuse/esp32s2/mod.rs +++ b/esp-hal/src/efuse/esp32s2/mod.rs @@ -5,12 +5,12 @@ mod fields; #[instability::unstable] pub use fields::*; -/// Selects which ADC we are interested in the efuse calibration data for +/// Selects which ADC the eFuse calibration data applies to. #[instability::unstable] pub enum AdcCalibUnit { - /// Select efuse calibration data for ADC1 + /// Selects efuse calibration data for ADC1. ADC1, - /// Select efuse calibration data for ADC2 + /// Selects efuse calibration data for ADC2. ADC2, } @@ -282,14 +282,6 @@ const RTC_CALIB_MAP: [RtcCalibEntry; 33] = [ }, ]; -fn signed_bit_to_int(number: u32, len: u32) -> i32 { - if number >> (len - 1) != 0 { - -((number ^ (1 << (len - 1))) as i32) - } else { - number as i32 - } -} - fn rtc_calib_tag(version: u8, unit: u8, atten: Attenuation, param: RtcCalibParam) -> Option { let atten = atten as u8; let offset = match (version, param) { @@ -302,6 +294,17 @@ fn rtc_calib_tag(version: u8, unit: u8, atten: Attenuation, param: RtcCalibParam Some(offset + unit * 4 + atten) } +// Reads the RTC bandgap trim from eFuse block 2. +// +// See `efuse_ll_get_ocode` in +// +pub(crate) fn ocode() -> u8 { + const OCODE1: crate::efuse::EfuseField = crate::efuse::EfuseField::new(2, 4, 128, 4); + const OCODE2: crate::efuse::EfuseField = crate::efuse::EfuseField::new(2, 4, 144, 3); + + (super::read_field_le::(OCODE2) << 4) + super::read_field_le::(OCODE1) +} + fn rtc_calib_parsed(tag: u8, skip_efuse: bool) -> i32 { if tag == 0 { return 0; @@ -317,7 +320,7 @@ fn rtc_calib_parsed(tag: u8, skip_efuse: bool) -> i32 { entry.length as u32, ); let bits = super::read_field_le::(field); - signed_bit_to_int(bits, entry.length as u32) * i32::from(entry.multiplier) + super::sign_magnitude(bits, entry.length as u32 - 1) * i32::from(entry.multiplier) }; raw + i32::from(entry.base) + rtc_calib_parsed(entry.depends, skip_efuse) } @@ -342,7 +345,7 @@ pub(crate) fn rtc_calib_reading_inner( .unwrap_or(0) } -/// Get version of RTC calibration block +/// Returns the version of RTC calibration block. /// /// See #[instability::unstable] @@ -350,7 +353,7 @@ pub fn rtc_calib_version() -> u8 { super::read_field_le::(BLK_VERSION_MINOR) } -/// Get ADC initial code for specified attenuation from efuse +/// Returns the ADC initial code for specified attenuation from efuse. #[instability::unstable] pub fn rtc_calib_init_code(unit: AdcCalibUnit, atten: Attenuation) -> Option { if rtc_calib_version() != 2 { @@ -359,18 +362,18 @@ pub fn rtc_calib_init_code(unit: AdcCalibUnit, atten: Attenuation) -> Option u16 { - match atten { +pub fn rtc_calib_cal_mv(_unit: AdcCalibUnit, atten: Attenuation) -> Option { + Some(match atten { Attenuation::_0dB => 600, Attenuation::_2p5dB => 800, Attenuation::_6dB => 1000, Attenuation::_11dB => 2000, - } + }) } -/// Get ADC reference point digital code for specified attenuation +/// Returns the ADC reference point digital code for specified attenuation. #[instability::unstable] pub fn rtc_calib_cal_code(unit: AdcCalibUnit, atten: Attenuation) -> Option { if rtc_calib_version() != 2 { @@ -379,7 +382,7 @@ pub fn rtc_calib_cal_code(unit: AdcCalibUnit, atten: Attenuation) -> Option Some(rtc_calib_reading(2, unit.index(), atten, RtcCalibParam::Vhigh) as u16) } -/// Get status of SPI boot encryption. +/// Returns whether SPI boot encryption is enabled. #[instability::unstable] pub fn flash_encryption() -> bool { !super::read_field_le::(SPI_BOOT_CRYPT_CNT) @@ -387,19 +390,19 @@ pub fn flash_encryption() -> bool { .is_multiple_of(2) } -/// Get the multiplier for the timeout value of the RWDT STAGE 0 register. +/// Returns the multiplier for the timeout value of the RWDT STAGE 0 register. #[instability::unstable] pub fn rwdt_multiplier() -> u8 { super::read_field_le::(WDT_DELAY_SEL) } -/// Returns the major hardware revision +/// Returns the major hardware revision. #[instability::unstable] pub fn major_chip_version() -> u8 { super::read_field_le(WAFER_VERSION_MAJOR) } -/// Returns the minor hardware revision +/// Returns the minor hardware revision. #[instability::unstable] pub fn minor_chip_version() -> u8 { super::read_field_le::(WAFER_VERSION_MINOR_HI) << 3 diff --git a/esp-hal/src/efuse/esp32s3/mod.rs b/esp-hal/src/efuse/esp32s3/mod.rs index 6529de1d1ba..cacb1cf07df 100644 --- a/esp-hal/src/efuse/esp32s3/mod.rs +++ b/esp-hal/src/efuse/esp32s3/mod.rs @@ -5,16 +5,16 @@ mod fields; #[instability::unstable] pub use fields::*; -/// Selects which ADC we are interested in the efuse calibration data for +/// Selects which ADC the eFuse calibration data applies to. #[instability::unstable] pub enum AdcCalibUnit { - /// Select efuse calibration data for ADC1 + /// Selects efuse calibration data for ADC1. ADC1, - /// Select efuse calibration data for ADC2 + /// Selects efuse calibration data for ADC2. ADC2, } -/// Get status of SPI boot encryption. +/// Returns whether SPI boot encryption is enabled. #[instability::unstable] pub fn flash_encryption() -> bool { !super::read_field_le::(SPI_BOOT_CRYPT_CNT) @@ -22,13 +22,13 @@ pub fn flash_encryption() -> bool { .is_multiple_of(2) } -/// Get the multiplier for the timeout value of the RWDT STAGE 0 register. +/// Returns the multiplier for the timeout value of the RWDT STAGE 0 register. #[instability::unstable] pub fn rwdt_multiplier() -> u8 { super::read_field_le::(WDT_DELAY_SEL) } -/// Get efuse block version +/// Returns the eFuse block version. /// /// see #[instability::unstable] @@ -41,7 +41,7 @@ pub fn block_version() -> (u8, u8) { ) } -/// Get version of RTC calibration block +/// Returns the version of RTC calibration block. /// /// see #[instability::unstable] @@ -51,7 +51,7 @@ pub fn rtc_calib_version() -> u8 { if major == 1 { 1 } else { 0 } } -/// Get ADC initial code for specified attenuation from efuse +/// Returns the ADC initial code for specified attenuation from efuse. /// /// see #[instability::unstable] @@ -105,15 +105,15 @@ pub fn rtc_calib_init_code(unit: AdcCalibUnit, atten: Attenuation) -> Option #[instability::unstable] -pub fn rtc_calib_cal_mv(_unit: AdcCalibUnit, _atten: Attenuation) -> u16 { - 850 +pub fn rtc_calib_cal_mv(_unit: AdcCalibUnit, _atten: Attenuation) -> Option { + Some(850) } -/// Get ADC reference point digital code for specified attenuation +/// Returns the ADC reference point digital code for specified attenuation. /// /// see #[instability::unstable] @@ -159,13 +159,13 @@ pub fn rtc_calib_cal_code(unit: AdcCalibUnit, atten: Attenuation) -> Option }) } -/// Returns the major hardware revision +/// Returns the major hardware revision. #[instability::unstable] pub fn major_chip_version() -> u8 { super::read_field_le(WAFER_VERSION_MAJOR) } -/// Returns the minor hardware revision +/// Returns the minor hardware revision. #[instability::unstable] pub fn minor_chip_version() -> u8 { super::read_field_le::(WAFER_VERSION_MINOR_HI) << 3 diff --git a/esp-hal/src/efuse/esp32s31/mod.rs b/esp-hal/src/efuse/esp32s31/mod.rs index fe680ba3841..fe86dfc7668 100644 --- a/esp-hal/src/efuse/esp32s31/mod.rs +++ b/esp-hal/src/efuse/esp32s31/mod.rs @@ -7,7 +7,7 @@ mod fields; #[instability::unstable] pub use fields::*; -/// Get status of SPI boot encryption. +/// Returns whether SPI boot encryption is enabled. #[instability::unstable] pub fn flash_encryption() -> bool { !super::read_field_le::(SPI_BOOT_CRYPT_CNT) @@ -15,13 +15,13 @@ pub fn flash_encryption() -> bool { .is_multiple_of(2) } -/// Get the multiplier for the timeout value of the RWDT STAGE 0 register. +/// Returns the multiplier for the timeout value of the RWDT STAGE 0 register. #[instability::unstable] pub fn rwdt_multiplier() -> u8 { super::read_field_le::(WDT_DELAY_SEL) } -/// Get efuse block version. +/// Returns the eFuse block version. /// /// Returns (major, minor). #[instability::unstable] @@ -32,7 +32,7 @@ pub fn block_version() -> (u8, u8) { ) } -/// Get version of RTC calibration block. +/// Returns the version of RTC calibration block. #[instability::unstable] pub fn rtc_calib_version() -> u8 { let (_major, minor) = block_version(); diff --git a/esp-hal/src/efuse/mod.rs b/esp-hal/src/efuse/mod.rs index 70eab69e973..b638019428f 100644 --- a/esp-hal/src/efuse/mod.rs +++ b/esp-hal/src/efuse/mod.rs @@ -48,6 +48,7 @@ use portable_atomic::AtomicU8; #[cfg_attr(esp32c6, path = "esp32c6/mod.rs")] #[cfg_attr(esp32c61, path = "esp32c61/mod.rs")] #[cfg_attr(esp32h2, path = "esp32h2/mod.rs")] +#[cfg_attr(esp32h4, path = "esp32h4/mod.rs")] #[cfg_attr(esp32p4, path = "esp32p4/mod.rs")] #[cfg_attr(esp32s2, path = "esp32s2/mod.rs")] #[cfg_attr(esp32s3, path = "esp32s3/mod.rs")] @@ -58,13 +59,13 @@ pub(crate) mod implem; pub use implem::*; use procmacros::doc_replace; -/// The bit field for get access to efuse data +/// The bit field for get access to efuse data. #[derive(Debug, Clone, Copy)] #[instability::unstable] pub struct EfuseField { - /// The block + /// The block. pub(crate) block: EfuseBlock, - /// Word number - this is just informational + /// Word number - this is just informational. pub(crate) _word: u32, /// Starting bit in the efuse block pub(crate) bit_start: u32, @@ -83,7 +84,7 @@ impl EfuseField { } } -/// Read field value in a little-endian order +/// Reads field value in a little-endian order. #[inline(always)] #[instability::unstable] pub fn read_field_le(field: EfuseField) -> T { @@ -151,9 +152,9 @@ pub fn read_field_le(field: EfuseField) -> T { unsafe { output.assume_init() } } -/// Read bit value. +/// Reads bit value. /// -/// This function panics if the field's bit length is not equal to 1. +/// Panics if the field's bit length is not equal to 1. #[inline(always)] #[instability::unstable] pub fn read_bit(field: EfuseField) -> bool { @@ -161,6 +162,24 @@ pub fn read_bit(field: EfuseField) -> bool { read_field_le::(field) != 0 } +/// Decodes a sign-magnitude number, where bit `sign_bit` carries the sign and the bits below it +/// carry the magnitude. +/// +/// The RTC calibration fields store their differences this way rather than in two's complement, +/// so a raw read has to be converted before it can be added to a reference point. +#[allow( + dead_code, + reason = "not every chip has sign-magnitude calibration fields" +)] +pub(crate) fn sign_magnitude(value: u32, sign_bit: u32) -> i32 { + let sign_mask = 1 << sign_bit; + if value & sign_mask != 0 { + -((value & !sign_mask) as i32) + } else { + value as i32 + } +} + /// Overrides the base MAC address used by [`interface_mac_address`]. /// /// After a successful call, [`interface_mac_address`] will derive @@ -196,7 +215,7 @@ pub fn override_mac_address(mac: MacAddress) -> Result<(), SetMacError> { /// effective MAC for a specific radio interface (which may be overridden via /// [`override_mac_address`]), use [`interface_mac_address`] instead. /// -/// ## Example +/// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -245,7 +264,7 @@ pub fn base_mac_address() -> MacAddress { /// interfaces (such as Bluetooth) additionally adjust the last octet to /// obtain a distinct address. /// -/// ## Example +/// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -285,7 +304,7 @@ pub fn interface_mac_address(kind: InterfaceMacAddress) -> MacAddress { #[doc_replace] /// Returns the hardware revision. /// -/// ## Examples +/// # Examples /// /// ```rust,no_run /// # {before_snippet} @@ -307,12 +326,12 @@ pub fn chip_revision() -> ChipRevision { /// The type supports converting between two separate u16-based representations: /// /// - Combined: a `u16` calculated as `major * 100 + minor`. The combined representation is more -/// often used by ESP-IDF, and working with it involves integer division. Note that the combined +/// often used by ESP-IDF, and working with it involves integer division. The combined /// representation assumes minor is less than 100. /// - Packed: a `u16` with the major revision in the high byte and the minor revision in the low /// byte. /// -/// ## Examples +/// # Examples /// /// ```rust,no_run /// # {before_snippet} diff --git a/esp-hal/src/ethernet/clock/esp32.rs b/esp-hal/src/ethernet/clock/esp32.rs index 94b109c2956..97e3548cc0a 100644 --- a/esp-hal/src/ethernet/clock/esp32.rs +++ b/esp-hal/src/ethernet/clock/esp32.rs @@ -73,14 +73,18 @@ impl RmiiClockConfig for ExternalRefClock

{ } } +#[cfg_attr(docsrs, procmacros::doc_replace( + "clk_out_gpio" => gpio_for_signal!(EMAC_CLK_OUT), + "clk_180_gpio" => gpio_for_signal!(EMAC_CLK_180), +))] /// RMII reference clock generated internally by the ESP32 APLL at 50 MHz. /// /// Should not be used together with Wi-Fi. No other APLL consumer must be active. /// -/// The APLL output is routed to GPIO16 (`EMAC_CLK_OUT`) or GPIO17 +/// The APLL output is routed to __clk_out_gpio__ (`EMAC_CLK_OUT`) or __clk_180_gpio__ /// (`EMAC_CLK_180`). Wrap the chosen GPIO: /// ```rust,ignore -/// ApllClock::new(peripherals.GPIO16) +/// ApllClock::new(peripherals.__clk_out_gpio__) /// ``` pub struct ApllClock

(P); @@ -181,9 +185,13 @@ impl RmiiClockConfig for ApllClock

{ // ── MiiClock ────────────────────────────────────────────────────────────── +#[cfg_attr(docsrs, procmacros::doc_replace( + "tx_clk_gpio" => gpio_for_signal!(EMAC_TX_CLK), + "rx_clk_gpio" => gpio_for_signal!(EMAC_RX_CLK), +))] /// MII clock configuration. /// -/// In MII mode the PHY drives both `TX_CLK` (GPIO0) and `RX_CLK` (GPIO5). +/// In MII mode the PHY drives both `TX_CLK` (__tx_clk_gpio__) and `RX_CLK` (__rx_clk_gpio__). /// The EMAC_EXT block only needs the MII clock buffers enabled; /// no internal clock source is required. pub(crate) struct MiiClock; diff --git a/esp-hal/src/ethernet/clock/esp32p4.rs b/esp-hal/src/ethernet/clock/esp32p4.rs index bfde141c6bd..afc6139a260 100644 --- a/esp-hal/src/ethernet/clock/esp32p4.rs +++ b/esp-hal/src/ethernet/clock/esp32p4.rs @@ -1,3 +1,7 @@ +#![cfg_attr(docsrs, procmacros::doc_replace( + "rmii_clk_gpio" => gpio_for_signal!(EMAC_RMII_CLK), + "ref_50m_gpio" => gpio_for_signal!(REF_50M_CLK), +))] //! EMAC clock configuration for ESP32-P4. //! //! # RMII reference clock sources @@ -5,12 +9,12 @@ //! The ESP32-P4 EMAC needs a 50 MHz reference clock for RMII. //! //! - **[`ExternalRefClock`]** — the PHY drives the reference clock into one of the `EMAC_RMII_CLK` -//! input pads (GPIO32, GPIO44, or GPIO50). This is the recommended configuration when the PHY has -//! an integrated oscillator. +//! input pads (for example __rmii_clk_gpio__). This is the recommended configuration when the PHY +//! has an integrated oscillator. //! //! - **[`InternalRefClock`]** — the ESP32-P4 MPLL generates a 50 MHz clock and drives it out on a -//! `REF_50M_CLK` pad (GPIO23 or GPIO39). This signal must be looped back externally into one of -//! the `EMAC_RMII_CLK` input pads. +//! `REF_50M_CLK` pad (for example __ref_50m_gpio__). This signal must be looped back externally +//! into one of the `EMAC_RMII_CLK` input pads. //! //! # MII clock source //! @@ -30,10 +34,13 @@ const CLOCK_STABILIZE_US: u32 = 300; // ── ExternalRefClock ───────────────────────────────────────────────────────── +#[cfg_attr(docsrs, procmacros::doc_replace( + "rmii_clk_gpio" => gpio_for_signal!(EMAC_RMII_CLK), +))] /// RMII reference clock provided externally by the PHY. /// /// The PHY must drive a 50 MHz clock into one of the `EMAC_RMII_CLK` input -/// pads: GPIO32, GPIO44, or GPIO50. +/// pads (for example __rmii_clk_gpio__). pub struct ExternalRefClock

(P); impl

ExternalRefClock

{ @@ -54,22 +61,31 @@ impl RmiiClockConfig for ExternalRefClock

{ // ── InternalRefClock ───────────────────────────────────────────────────────── +#[cfg_attr(docsrs, procmacros::doc_replace( + "rmii_clk_gpio" => gpio_for_signal!(EMAC_RMII_CLK), + "ref_50m_gpio" => gpio_for_signal!(REF_50M_CLK), +))] /// RMII reference clock derived from the ESP32-P4 MPLL at 50 MHz. /// -/// The MPLL output is driven out on a `REF_50M_CLK` output pad (GPIO23 or -/// GPIO39) and must be looped back externally into one of the `EMAC_RMII_CLK` -/// input pads (GPIO32, GPIO44, or GPIO50). +/// The MPLL output is driven out on a `REF_50M_CLK` output pad (for example +/// __ref_50m_gpio__) and must be looped back externally into one of the `EMAC_RMII_CLK` +/// input pads (for example __rmii_clk_gpio__). pub struct InternalRefClock { ref_clk_out: POut, ref_clk_in: PIn, } impl InternalRefClock { + #[cfg_attr(docsrs, procmacros::doc_replace( + "rmii_clk_gpio" => gpio_for_signal!(EMAC_RMII_CLK), + "ref_50m_gpio" => gpio_for_signal!(REF_50M_CLK), + ))] /// Creates an internal MPLL clock configuration. /// - /// - `ref_clk_out` — the pad that will output the 50 MHz `REF_50M_CLK` signal (GPIO23 or - /// GPIO39). - /// - `ref_clk_in` — the pad that receives the looped-back signal (GPIO32, GPIO44, or GPIO50). + /// - `ref_clk_out` — the pad that will output the 50 MHz `REF_50M_CLK` signal (for example + /// __ref_50m_gpio__). + /// - `ref_clk_in` — the pad that receives the looped-back signal (for example + /// __rmii_clk_gpio__). pub fn new(ref_clk_out: POut, ref_clk_in: PIn) -> Self { Self { ref_clk_out, @@ -112,8 +128,6 @@ impl MiiClock { // ── Private helpers ─────────────────────────────────────────────────────────── /// Configures the EMAC clock tree for RMII with an external clock input. -/// -/// Matches `emac_ll_clock_enable_rmii_input()` in esp-idf. fn configure_rmii_input() { HP_SYS::regs() .gmac_ctrl0() @@ -177,8 +191,7 @@ fn enable_mpll_50m_output() { /// Configures the EMAC clock tree for MII mode. /// -/// Matches `emac_ll_clock_enable_mii()` in esp-idf. In MII mode the RX and TX -/// clocks come from separate pads (not the combined RMII pad), so +/// In MII mode the RX and TX clocks come from separate pads (not the combined RMII pad), so /// `emac_rx_clk_src_sel = 1` and `emac_tx_clk_src_sel = 1`. fn configure_mii() { HP_SYS::regs() @@ -217,9 +230,8 @@ fn configure_mii() { /// Pulses the EMAC peripheral reset via `LP_AON_CLKRST` (assert then deassert). /// -/// Matches `emac_ll_reset_register()` in esp-idf. The `GenericPeripheralGuard` -/// for EMAC on P4 does not perform a hardware reset (the reset handler is a -/// no-op), so this must be called explicitly during clock configuration. +/// The `GenericPeripheralGuard` for EMAC on P4 does not perform a hardware reset (the reset handler +/// is a no-op), so this must be called explicitly during clock configuration. fn deassert_reset() { LP_AON_CLKRST::regs() .lp_aonclkrst_hp_sdmmc_emac_rst_ctrl() diff --git a/esp-hal/src/ethernet/clock/esp32s31.rs b/esp-hal/src/ethernet/clock/esp32s31.rs new file mode 100644 index 00000000000..477c91dfbd3 --- /dev/null +++ b/esp-hal/src/ethernet/clock/esp32s31.rs @@ -0,0 +1,277 @@ +#![cfg_attr(docsrs, procmacros::doc_replace( + "rmii_clk_gpio" => gpio_for_signal!(EMAC_RMII_CLK), +))] +//! EMAC clock configuration for ESP32-S31. +//! +//! # RMII reference clock sources +//! +//! The ESP32-S31 EMAC needs a 50 MHz reference clock for RMII. +//! +//! - **[`ExternalRefClock`]** — the PHY drives the reference clock into one of the `EMAC_RMII_CLK` +//! input pads (for example __rmii_clk_gpio__). This is the recommended configuration when the PHY +//! has an integrated oscillator. +//! +//! # MII clock source +//! +//! The PHY drives `TX_CLK` and `RX_CLK` separately at 25 MHz (100 Mbps) or +//! 2.5 MHz (10 Mbps). No internal clock generation is required. +//! +//! # RGMII clock sources +//! +//! RGMII uses PHY-driven `RX_CLK`. The MAC drives `TX_CLK` from the MPLL +//! (125 MHz at 1000 Mbps, 25 MHz at 100 Mbps, 2.5 MHz at 10 Mbps). +//! +//! The `TX_CLK` divider is an integer, so 1000 Mbps needs the MPLL at 500 MHz. +//! At 400 MHz, the rate that 200 MHz PSRAM needs, RGMII runs at up to 100 Mbps. + +use esp_rom_sys::rom::ets_delay_us; + +use crate::{ + clock::ll::{ClockTree, mpll_clk_frequency, request_mpll_clk}, + ethernet::{RmiiClkIn, RmiiClockConfig, mac::Speed}, + peripherals::{CNNT_IO_MUX, CNNT_SYS}, + private::Sealed, +}; + +/// Number of spin-loop iterations to wait after enabling the EMAC clock tree. +const CLOCK_STABILIZE_US: u32 = 300; + +/// RMII PHY interface select (`CNNT_SYS.sys_gmac_ctrl0.sys_phy_intf_sel`). +const PHY_INTF_RMII: u8 = 4; +/// RGMII PHY interface select. +const PHY_INTF_RGMII: u8 = 1; +/// MII PHY interface select. +const PHY_INTF_MII: u8 = 0; + +/// MPLL source for `SYS_HP_EMAC_REF_CTRL.sys_emac_ref_clk_sel`. +const REF_CLK_SEL_MPLL: u8 = 0; + +/// RGMII TX clock: 125 MHz (1000 Mbps), 25 MHz (100 Mbps), 2.5 MHz (10 Mbps). +const RGMII_TX_CLK_1000M_HZ: u32 = 125_000_000; +const RGMII_TX_CLK_100M_HZ: u32 = 25_000_000; +const RGMII_TX_CLK_10M_HZ: u32 = 2_500_000; + +// ── ExternalRefClock ───────────────────────────────────────────────────────── + +#[cfg_attr(docsrs, procmacros::doc_replace( + "rmii_clk_gpio" => gpio_for_signal!(EMAC_RMII_CLK), +))] +/// RMII reference clock provided externally by the PHY. +/// +/// The PHY must drive a 50 MHz clock into one of the `EMAC_RMII_CLK` input +/// pads (for example __rmii_clk_gpio__). +pub struct ExternalRefClock

(P); + +impl

ExternalRefClock

{ + /// Wraps the GPIO pin that receives the PHY reference clock. + pub fn new(pin: P) -> Self { + Self(pin) + } +} + +impl

Sealed for ExternalRefClock

{} + +impl RmiiClockConfig for ExternalRefClock

{ + fn configure(self) { + self.0.configure_iomux(); + configure_rmii_input(); + } +} + +// ── RgmiiClock ─────────────────────────────────────────────────────────────── + +/// RGMII clock configuration. +/// +/// The PHY drives `RX_CLK`. The MAC generates `TX_CLK` from the MPLL. +pub(crate) struct RgmiiClock; + +impl RgmiiClock { + pub(super) fn configure(&self) { + configure_rgmii(); + } +} + +// ── MiiClock ───────────────────────────────────────────────────────────────── + +/// MII clock configuration. +/// +/// In MII mode the PHY drives `TX_CLK` and `RX_CLK` separately +/// (25 MHz at 100 Mbps, 2.5 MHz at 10 Mbps). No internal clock generation is +/// required. +pub(crate) struct MiiClock; + +impl MiiClock { + pub(super) fn configure(&self) { + configure_mii(); + } +} + +// ── Private helpers ─────────────────────────────────────────────────────────── + +/// Configures the EMAC clock tree for RMII with an external clock input. +fn configure_rmii_input() { + let cnnt = CNNT_SYS::regs(); + + cnnt.sys_gmac_ctrl0() + .modify(|_, w| unsafe { w.sys_phy_intf_sel().bits(PHY_INTF_RMII) }); + + cnnt.sys_hp_emac_rmii_ctrl().modify(|_, w| unsafe { + w.sys_emac_rmii_clk_en().set_bit(); + // 1 = external clock + w.sys_emac_rmii_clk_sel().set_bit(); + // 50 / 2 = 25 MHz for 100 Mbps + w.sys_emac_rxtx_clk_div_num().bits(1); + w.sys_emac_rmii_pad_out_clk_en().clear_bit() + }); + + cnnt.sys_hp_emac_rx_ctrl().modify(|_, w| { + w.sys_emac_rx_pad_clk_en().clear_bit(); + w.sys_emac_rx_clk_sel().clear_bit() + }); + + cnnt.sys_hp_emac_tx_ctrl().modify(|_, w| { + w.sys_emac_tx_pad_clk_en().clear_bit(); + w.sys_emac_tx_clk_sel().clear_bit() + }); + + cnnt.sys_hp_emac_rmii_pad_ctrl().modify(|_, w| { + w.sys_emac_rmii_pad_clk_en().set_bit(); + w.sys_emac_rmii_pad_clk_inv_en().clear_bit() + }); + + enable_common(); +} + +/// Configures the EMAC clock tree for RGMII. +fn configure_rgmii() { + ClockTree::with(request_mpll_clk); + + let cnnt = CNNT_SYS::regs(); + + cnnt.sys_gmac_ctrl0() + .modify(|_, w| unsafe { w.sys_phy_intf_sel().bits(PHY_INTF_RGMII) }); + + cnnt.sys_hp_emac_rmii_pad_ctrl().modify(|_, w| { + w.sys_emac_rmii_pad_clk_en().clear_bit(); + w.sys_emac_rmii_pad_clk_inv_en().clear_bit() + }); + + cnnt.sys_hp_emac_rmii_ctrl().modify(|_, w| { + w.sys_emac_rmii_clk_sel().clear_bit(); + w.sys_emac_rmii_clk_en().clear_bit(); + w.sys_emac_rmii_pad_out_clk_en().set_bit() + }); + + cnnt.sys_hp_emac_rx_ctrl().modify(|_, w| { + w.sys_emac_rx_pad_clk_en().set_bit(); + w.sys_emac_rx_clk_sel().set_bit(); + w.sys_emac_rx_pad_clk_inv_en().clear_bit(); + w.sys_emac_rx_180_clk_en().set_bit() + }); + + cnnt.sys_hp_emac_tx_ctrl().modify(|_, w| { + w.sys_emac_tx_pad_clk_en().clear_bit(); + w.sys_emac_tx_clk_sel().clear_bit(); + w.sys_emac_tx_180_clk_en().set_bit() + }); + + let max_speed = rgmii_max_speed(); + if max_speed != Speed::_1000M { + warn!( + "MPLL at {} MHz cannot make the 125 MHz RGMII clock, limiting Ethernet to 100 Mbps", + mpll_clk_frequency() / 1_000_000 + ); + } + apply_rgmii_tx_speed(max_speed); + enable_common(); +} + +/// Fastest RGMII speed the MPLL's rate can drive. +pub(super) fn rgmii_max_speed() -> Speed { + if mpll_clk_frequency().is_multiple_of(RGMII_TX_CLK_1000M_HZ) { + Speed::_1000M + } else { + Speed::_100M + } +} + +/// Updates the RGMII TX clock divider for the negotiated link speed. +/// +/// Only meaningful for RGMII, where the MAC drives `TX_CLK`; the RGMII pin +/// bundle is the only caller. +pub(super) fn apply_rgmii_tx_speed(speed: Speed) { + let out_hz = match speed { + Speed::_10M => RGMII_TX_CLK_10M_HZ, + Speed::_100M => RGMII_TX_CLK_100M_HZ, + Speed::_1000M => RGMII_TX_CLK_1000M_HZ, + }; + set_rgmii_tx_divider(out_hz); +} + +fn set_rgmii_tx_divider(out_hz: u32) { + let src_hz = mpll_clk_frequency(); + let div = (src_hz / out_hz).saturating_sub(1) as u8; + + CNNT_SYS::regs() + .sys_hp_emac_ref_ctrl() + .modify(|_, w| unsafe { + w.sys_emac_ref_clk_sel().bits(REF_CLK_SEL_MPLL); + w.sys_emac_ref_clk_div_num().bits(div); + w.sys_emac_ref_clk_en().set_bit() + }); +} + +/// Configures the EMAC clock tree for MII mode. +fn configure_mii() { + let cnnt = CNNT_SYS::regs(); + + cnnt.sys_gmac_ctrl0() + .modify(|_, w| unsafe { w.sys_phy_intf_sel().bits(PHY_INTF_MII) }); + + cnnt.sys_hp_emac_rmii_ctrl() + .modify(|_, w| w.sys_emac_rmii_clk_en().set_bit()); + + cnnt.sys_hp_emac_rx_ctrl().modify(|_, w| { + w.sys_emac_rx_pad_clk_en().set_bit(); + w.sys_emac_rx_clk_sel().set_bit() + }); + + cnnt.sys_hp_emac_tx_ctrl().modify(|_, w| { + w.sys_emac_tx_pad_clk_en().set_bit(); + w.sys_emac_tx_clk_sel().set_bit() + }); + + enable_common(); +} + +fn enable_common() { + CNNT_SYS::regs() + .sys_gmac_ctrl0() + .modify(|_, w| w.sys_gmac_mem_clk_force_on().set_bit()); + + // GPIO13-19 live in the CNNT domain. Dedicated pad control is required when + // those pads are used as GMAC I/O. + CNNT_IO_MUX::regs() + .ctrl() + .modify(|_, w| w.gmac_pad_pin_ctrl_ded_sel().set_bit()); + + deassert_reset(); + clock_stabilize(); +} + +/// Pulses the EMAC peripheral reset via `CNNT_SYS` (assert then deassert). +/// +/// The `GenericPeripheralGuard` for EMAC on S31 does not perform a hardware reset, so this must be +/// called during clock configuration. +fn deassert_reset() { + CNNT_SYS::regs() + .sys_hp_emac_ctrl() + .modify(|_, w| w.sys_emac_rst_en().set_bit()); + CNNT_SYS::regs() + .sys_hp_emac_ctrl() + .modify(|_, w| w.sys_emac_rst_en().clear_bit()); +} + +fn clock_stabilize() { + ets_delay_us(CLOCK_STABILIZE_US); +} diff --git a/esp-hal/src/ethernet/dma.rs b/esp-hal/src/ethernet/dma.rs index 39d5ffa22ee..32cc0ae55fe 100644 --- a/esp-hal/src/ethernet/dma.rs +++ b/esp-hal/src/ethernet/dma.rs @@ -1,7 +1,7 @@ //! EMAC DMA descriptor rings. //! //! Implements the chained-ring descriptor layout for the Synopsys DesignWare -//! GMAC as found on ESP32 and ESP32-P4. The driver always uses the **enhanced +//! GMAC as found on ESP32, ESP32-P4, and ESP32-S31. The driver always uses the **enhanced //! 32-byte descriptor format** (`ALT_DESC_SIZE = 1` in `EMAC_DMA.dmabusmode`). use core::sync::atomic::{Ordering, fence}; @@ -13,6 +13,8 @@ pub const MAX_FRAME_SIZE: usize = 1524; /// Minimum accepted RX frame length. pub const MIN_RX_FRAME_SIZE: usize = 14; +const TX_CHECKSUM_OFFLOAD: bool = property!("ethernet.tx_checksum_offload"); + // ── TDES bits ────────────────────────────────────────────────────────────── /// TX descriptor ownership bit: 1 = owned by DMA. @@ -23,11 +25,13 @@ pub const TDES0_IC: u32 = 1 << 30; pub const TDES0_LS: u32 = 1 << 29; /// TX first-segment flag. pub const TDES0_FS: u32 = 1 << 28; -/// TX checksum insertion control: 3 = IP Header checksum and payload checksum calculation -/// and insertion are enabled, and pseudo-header checksum is calculated in hardware. -pub const TDES0_CIC_FULL: u32 = 3 << 22; /// TX second-address-chained mode (next descriptor pointer in TDES3). pub const TDES0_CHAINED: u32 = 1 << 20; +/// TX checksum insertion control (`CIC`) shift. `0b11` inserts IPv4 header and +/// TCP/UDP/ICMP payload checksums including the pseudo-header. +pub const TDES0_CIC_SHIFT: u32 = 22; +/// Full Type-2 TX checksum insertion (`CIC = 0b11`). +pub const TDES0_CIC_FULL: u32 = 0b11 << TDES0_CIC_SHIFT; // ── RDES bits ────────────────────────────────────────────────────────────── @@ -51,11 +55,10 @@ pub const RDES1_CHAINED: u32 = 1 << 14; // ── RDES4 extended-status bits (Type-2 checksum offload) ───────────────────── // -// Only consumed on chips whose RX FIFO runs in cut-through mode and therefore -// cannot rely on the DMA to auto-drop checksum-error frames (see `dma_start`). +// Only consumed when RX COE is enabled (`ethernet.rx_checksum_offload`). cfg_select! { - esp32p4 => { + ethernet_rx_checksum_offload => { /// RDES0 extended-status-available bit: RDES4 holds valid COE status. pub const RDES0_ESA: u32 = 1 << 0; /// RDES4: IP header checksum error. @@ -137,11 +140,20 @@ impl TDes { self.tdes0.set(self.tdes0.get() | TDES0_CHAINED); } + /// Marks the descriptor as a complete frame of `len` bytes. + /// + /// Checksum insertion (`CIC`) follows `ethernet.tx_checksum_offload`. The + /// MAC can only insert a payload checksum with transmit store-and-forward, + /// which is enabled together with that property. fn set_len_and_flags(&mut self, len: usize) { self.tdes1.set(len as u32 & RDES1_BUF1_SIZE_MASK); - self.tdes0.set( - (self.tdes0.get() & TDES0_CHAINED) | TDES0_FS | TDES0_LS | TDES0_IC | TDES0_CIC_FULL, - ); + let cic = if TX_CHECKSUM_OFFLOAD { + TDES0_CIC_FULL + } else { + 0 + }; + self.tdes0 + .set((self.tdes0.get() & TDES0_CHAINED) | TDES0_FS | TDES0_LS | TDES0_IC | cic); } fn set_buffer_addr(&mut self, addr: *const u8) { @@ -164,8 +176,8 @@ pub struct RDes { pub(super) next_desc: VolatileCell, // Extended status; the GMAC writes IP checksum-offload results here. #[cfg_attr( - not(esp32p4), - allow(dead_code, reason = "only read for P4 RX checksum offload") + not(ethernet_rx_checksum_offload), + allow(dead_code, reason = "only read when RX checksum offload is enabled") )] rdes4: VolatileCell, _rdes5: VolatileCell, @@ -218,14 +230,14 @@ impl RDes { ((self.rdes0.get() & RDES0_FL_MASK) >> RDES0_FL_SHIFT) as usize } - /// Returns `true` if the hardware IP checksum-offload engine flagged a + /// Returns whether the hardware IP checksum-offload engine flagged a /// header or payload checksum error for this frame. /// /// These results live in the extended-status word (RDES4) rather than in /// `RDES0_ES`, so they must be inspected explicitly. Only meaningful on the /// last descriptor of a frame. Non-IP frames (e.g. ARP) and frames whose /// checksum the engine bypassed never report an error. - #[cfg(esp32p4)] + #[cfg(ethernet_rx_checksum_offload)] fn checksum_error(&self) -> bool { // The extended status is only valid when RDES0[0] (ESA) is set. if self.rdes0.get() & RDES0_ESA == 0 { @@ -279,7 +291,7 @@ impl Default for EthernetDmaStorage { } impl EthernetDmaStorage { - /// Creates a zero-initialized storage block, suitable for `static` placement. + /// Creates a new zero-initialized storage block, suitable for `static` placement. pub const fn new() -> Self { Self { rx_descs: [const { InternalMemory::new(RDes::new_zeroed()) }; RX], @@ -356,7 +368,7 @@ impl<'a> TDesRing<'a> { /// Copies `frame` into the next available TX buffer and hands it to DMA. /// - /// Returns `Err(DescriptorError::RingFull)` if no CPU-owned slot is available + /// Returns `Err(DescriptorError::RingFull)` if no CPU-owned slot is available. /// and `Err(DescriptorError::FrameTooLarge)` if the frame exceeds [`MAX_FRAME_SIZE`]. pub fn transmit(&mut self, frame: &[u8]) -> Result<(), TxError> { if frame.len() > MAX_FRAME_SIZE { @@ -372,7 +384,7 @@ impl<'a> TDesRing<'a> { } } - /// Returns `true` if the current slot is CPU-owned (ready to accept a frame). + /// Returns whether the current slot is CPU-owned (ready to accept a frame). pub fn has_capacity(&self) -> bool { let desc = self.descriptors[self.index].get_ref(); #[cfg(soc_internal_memory_cached)] @@ -381,10 +393,11 @@ impl<'a> TDesRing<'a> { desc.owned_by() == OwnedBy::Cpu } - /// Returns a mutable reference to the current TX DMA buffer if the slot is - /// CPU-owned, enabling zero-copy frame construction. + /// Returns a mutable reference to the current TX DMA buffer when the slot is + /// CPU-owned, which enables zero-copy frame construction. /// /// After writing the frame, call [`TDesRing::commit`] to hand it to DMA. + /// Returns `None` when the slot is not CPU-owned. pub fn available_buf(&mut self) -> Option<&mut [u8; MAX_FRAME_SIZE]> { if self.has_capacity() { let idx = self.index; @@ -484,7 +497,7 @@ impl<'a> RDesRing<'a> { self.descriptors[0].as_ptr() } - /// Returns a mutable data slice if a frame is ready. + /// Returns a mutable data slice for a ready frame, or `None` when no frame is ready. /// /// Loops past error/incomplete/oversized frames, recycling them back to DMA /// automatically. Returns `None` only when no CPU-owned descriptor remains. @@ -510,11 +523,10 @@ impl<'a> RDesRing<'a> { let is_complete = desc.is_complete_frame(); let frame_len = desc.frame_len(); - // On chips with cut-through RX the DMA can't auto-drop - // checksum-error frames, so reject them here based on the - // extended-status COE bits. + // When RX COE is on, checksum errors are reported in RDES4 + // rather than `RDES0_ES`. let checksum_bad = cfg_select! { - esp32p4 => desc.checksum_error(), + ethernet_rx_checksum_offload => desc.checksum_error(), _ => false, }; diff --git a/esp-hal/src/ethernet/embassy_net.rs b/esp-hal/src/ethernet/embassy_net.rs index cce51b90d57..32f6e705292 100644 --- a/esp-hal/src/ethernet/embassy_net.rs +++ b/esp-hal/src/ethernet/embassy_net.rs @@ -5,7 +5,7 @@ //! Ethernet peripheral to be used as a network interface with //! [`embassy-net`](https://crates.io/crates/embassy-net). //! -//! # Usage +//! ## Usage //! //! After obtaining an `Ethernet<'_, Async, P>` instance, pass it directly to //! `embassy_net::new()` — the [`Driver`] impl is inherent on the type. @@ -113,10 +113,6 @@ impl<'d, P: Phy> Driver for Ethernet<'d, Async, P> { // Check availability as plain booleans so the borrows end before we // split &mut self into the two ring references for the tokens. let rx_ready = self.rx.receive().is_some(); - // Poke the RX DMA unconditionally: receive() may have recycled error - // frames back to DMA ownership without a poll-demand write, which - // would leave the GMAC RX channel suspended. - EmacRegs.demand_rx_poll(); let tx_ready = self.tx.available_buf().is_some(); if rx_ready && tx_ready { @@ -138,13 +134,20 @@ impl<'d, P: Phy> Driver for Ethernet<'d, Async, P> { } } + /// Polls the PHY and tracks the DMA interrupt state with the link. + /// + /// DMA interrupts are only enabled while the link is up: with no link there + /// is no RX clock, and error interrupts would otherwise fire continuously. fn link_state(&mut self, cx: &mut Context<'_>) -> LinkState { let state = self.poll_link(Some(cx)); if state.up { self.set_speed(state.speed); self.set_duplex(state.duplex); + super::bind_eth_isr(); + EmacRegs.dma_enable_interrupts(true); LinkState::Up } else { + EmacRegs.dma_disable_interrupts(); LinkState::Down } } @@ -153,13 +156,21 @@ impl<'d, P: Phy> Driver for Ethernet<'d, Async, P> { let mut caps = Capabilities::default(); caps.max_transmission_unit = MTU; caps.max_burst_size = Some(self.tx.len()); - // Checksums are offloaded to hardware in both directions (RX COE + TX - // insertion via the descriptor CIC bits), so smoltcp does neither. - caps.checksum.ipv4 = Checksum::None; - caps.checksum.tcp = Checksum::None; - caps.checksum.udp = Checksum::None; - caps.checksum.icmpv4 = Checksum::None; - caps.checksum.icmpv6 = Checksum::None; + // `Checksum` names the direction(s) computed in software. Hardware + // offload is advertised so the stack skips that side. + const RX_COE: bool = property!("ethernet.rx_checksum_offload"); + const TX_COE: bool = property!("ethernet.tx_checksum_offload"); + let checksum = match (RX_COE, TX_COE) { + (true, true) => Checksum::None, + (true, false) => Checksum::Tx, + (false, true) => Checksum::Rx, + (false, false) => Checksum::Both, + }; + caps.checksum.ipv4 = checksum; + caps.checksum.tcp = checksum; + caps.checksum.udp = checksum; + caps.checksum.icmpv4 = checksum; + caps.checksum.icmpv6 = checksum; caps } diff --git a/esp-hal/src/ethernet/mac.rs b/esp-hal/src/ethernet/mac.rs index 473ff00aa36..c9cf8d9b815 100644 --- a/esp-hal/src/ethernet/mac.rs +++ b/esp-hal/src/ethernet/mac.rs @@ -6,43 +6,41 @@ use crate::peripherals::{EMAC_DMA, EMAC_MAC}; +/// Programmable DMA burst length, matching the esp-idf per-target defaults. +const DMA_BURST_LEN: u8 = property!("ethernet.dma_burst_len"); +const TX_CHECKSUM_OFFLOAD: bool = property!("ethernet.tx_checksum_offload"); + /// Returns the `miicsrclk` value for the MDIO management clock divider. /// /// On ESP32 the MDC CSR clock source is the APB clock (fixed at 80 MHz), so /// value 3 (35–60 MHz range → /26) has always been used and works in practice. /// -/// On ESP32-P4 the CSR clock source is the SYS (CPU) clock, which varies with -/// the selected [`crate::clock::CpuClock`] preset (100–400 MHz). The divider -/// is computed at runtime to keep MDC within the 1–2.5 MHz range required by -/// IEEE 802.3 clause 22. The 4-bit `miicsrclk` field on P4 supports extended -/// divider values (up to 6 = 300–500 MHz → /204). +/// On ESP32-P4 and ESP32-S31 the CSR clock source is the SYS clock. Both vary with the selected +/// [`crate::clock::CpuClock`] preset. The divider is computed at runtime to keep MDC within the +/// 1–2.5 MHz range required by IEEE 802.3 clause 22. fn mdc_csr_clock_range() -> u8 { - #[cfg(esp32p4)] - { - // Matches emac_hal_set_csr_clock_range() in esp-idf (emac_hal.c). - // The P4 EMAC (DWC_gmac) only defines encoding values 0–5; value 6+ - // is reserved and must not be used. The CSR clock source is the SYS - // (CPU) clock. - // - // emac_crs_div_table = {42, 62, 16, 26, 102, 124} - // encoding 0 → /42 (60–100 MHz) - // encoding 1 → /62 (100–150 MHz) - // encoding 2 → /16 (20–35 MHz) - // encoding 3 → /26 (35–60 MHz) - // encoding 4 → /102 (150–250 MHz) - // encoding 5 → /124 (≥ 250 MHz, slightly over 2.5 MHz spec at high SYS clocks) - match crate::clock::ll::sys_clk_frequency() { - hz if hz >= 250_000_000 => 5, // /124 - hz if hz >= 150_000_000 => 4, // /102 - hz if hz >= 100_000_000 => 1, // /62 - hz if hz >= 60_000_000 => 0, // /42 - hz if hz >= 35_000_000 => 3, // /26 - _ => 2, // /16 - } - } - #[cfg(not(esp32p4))] - { - 3 // ESP32: 80 MHz APB → /26, works in practice + // Matches emac_hal_set_csr_clock_range() in esp-idf (emac_hal.c). + // The DWC_gmac only defines encoding values 0–5; value 6+ + // is reserved and must not be used. + // + // emac_crs_div_table = {42, 62, 16, 26, 102, 124} + // encoding 0 → /42 (60–100 MHz) + // encoding 1 → /62 (100–150 MHz) + // encoding 2 → /16 (20–35 MHz) + // encoding 3 → /26 (35–60 MHz) + // encoding 4 → /102 (150–250 MHz) + // encoding 5 → /124 (≥ 250 MHz, slightly over 2.5 MHz spec at high SYS clocks) + let hz = cfg_select! { + soc_has_clock_node_sys_clk => crate::clock::ll::sys_clk_frequency(), + _ => 40_000_000, + }; + match hz { + hz if hz >= 250_000_000 => 5, // /124 + hz if hz >= 150_000_000 => 4, // /102 + hz if hz >= 100_000_000 => 1, // /62 + hz if hz >= 60_000_000 => 0, // /42 + hz if hz >= 35_000_000 => 3, // /26 + _ => 2, // /16 } } @@ -55,6 +53,8 @@ pub enum Speed { _10M, /// 100 Mbit/s _100M, + /// 1000 Mbit/s (RGMII) + _1000M, } /// Link duplex mode. @@ -99,39 +99,84 @@ impl EmacRegs { while EMAC_DMA::regs().dmabusmode().read().sw_rst().bit_is_set() {} - // Enhanced 32-byte descriptors, fixed burst, address-aligned beats, PBL=8. + // Bus mode per esp-idf `emac_hal_init_dma_default`: enhanced 32-byte + // descriptors, mixed burst, address-aligned beats, one PBL for both + // directions, round-robin arbitration with a 1:1 RX/TX ratio. EMAC_DMA::regs().dmabusmode().modify(|_, w| unsafe { w.alt_desc_size().set_bit(); - w.fixed_burst().set_bit(); + w.dmamixedburst().set_bit(); w.dmaaddralibea().set_bit(); - w.use_sep_pbl().set_bit(); - w.prog_burst_len().bits(8); - w.rx_dma_pbl().bits(8); + w.fixed_burst().clear_bit(); + w.use_sep_pbl().clear_bit(); + w.prog_burst_len().bits(DMA_BURST_LEN); + w.desc_skip_len().bits(0); + w.dma_arb_sch().clear_bit(); + w.pri_ratio().bits(0); + w + }); + } + + /// Configures the DMA operation mode, matching esp-idf + /// `emac_hal_init_dma_default`. + /// + /// RX store-and-forward follows `ethernet.rx_store_and_forward`. TX + /// store-and-forward is enabled only with TX checksum offload, which + /// needs the whole frame in the FIFO. Thresholds stay at 64 bytes for + /// cut-through. + pub fn dma_init_op_mode(&self) { + // The TX FIFO flush must complete before any other write to this + // register, so it is issued on its own first. + EMAC_DMA::regs() + .dmaoperation_mode() + .modify(|_, w| w.flush_tx_fifo().set_bit()); + for _ in 0..1000 { + if !EMAC_DMA::regs() + .dmaoperation_mode() + .read() + .flush_tx_fifo() + .bit_is_set() + { + break; + } + } + + EMAC_DMA::regs().dmaoperation_mode().modify(|_, w| unsafe { + // With RSF, drop FCS/length (and TCP/IP, if RX COE is on) error frames. + w.dis_drop_tcpip_err_fram() + .bit(!cfg!(ethernet_rx_store_and_forward)); + // Flush received frames when descriptors or buffers run out. + w.dis_flush_recv_frames().clear_bit(); + w.rx_store_forward() + .bit(cfg!(ethernet_rx_store_and_forward)); + // Payload checksum insertion (TDES0.CIC) requires TX store-and-forward. + w.tx_str_fwd().bit(TX_CHECKSUM_OFFLOAD); + w.tx_thresh_ctrl().bits(0); // 64 bytes + w.rx_thresh_ctrl().bits(0); // 64 bytes + w.fwd_err_frame().clear_bit(); + w.fwd_under_gf().clear_bit(); + // Start on a second frame before the first one's status is read. + w.opt_second_frame().set_bit(); w }); } // ── DMA operation ───────────────────────────────────────────────────── - /// Starts both DMA engines. + /// Starts the MAC and DMA transmit and receive paths. /// - /// P4's RX FIFO is too small (~256 B) to store full frames, so RSF must - /// not be set — it silently drops frames larger than the FIFO. Use - /// cut-through receive instead. + /// The order follows esp-idf `emac_hal_start`. The EMAC Databook allows + /// starting the DMA before enabling the MAC transmitter, but doing so has + /// been observed to hang the transmitter. pub fn dma_start(&self) { - EMAC_DMA::regs().dmaoperation_mode().modify(|_, w| { - w.tx_str_fwd().set_bit(); - cfg_select! { - esp32p4 => { - w.fwd_under_gf().set_bit(); - } - _ => { - w.rx_store_forward().set_bit(); - } - } - w.start_stop_rx().set_bit(); - w.start_stop_transmission_command().set_bit() - }); + EMAC_MAC::regs().config().modify(|_, w| w.tx().set_bit()); + EMAC_DMA::regs() + .dmaoperation_mode() + .modify(|_, w| w.start_stop_transmission_command().set_bit()); + + EMAC_DMA::regs() + .dmaoperation_mode() + .modify(|_, w| w.start_stop_rx().set_bit()); + EMAC_MAC::regs().config().modify(|_, w| w.rx().set_bit()); } /// Stops both DMA engines. @@ -169,17 +214,31 @@ impl EmacRegs { // ── DMA interrupt control ───────────────────────────────────────────── - /// Enables Normal/Abnormal summary interrupts and the RX interrupt. - /// Optionally enables the TX interrupt (required in async mode). + /// Enables the normal summary and RX interrupts, optionally TX as well + /// (required in async mode). + /// + /// The abnormal summary stays masked: the ISR does not handle FBE/RBU, so + /// a sticky error would re-enter it forever. pub fn dma_enable_interrupts(&self, enable_tx: bool) { EMAC_DMA::regs().dmain_en().modify(|_, w| { w.dmain_rie().set_bit(); - w.dmain_aise().set_bit(); w.dmain_nise().set_bit(); w.dmain_tie().bit(enable_tx) }); } + /// Masks every MAC-level interrupt source (PMT, LPI, timestamp, and + /// RGMII/PCS on chips that have them). + /// + /// These share the peripheral interrupt line with the DMA but are not + /// gated by `dmain_en`, and the ISR only acknowledges `dmastatus`. Leaving + /// them unmasked lets a single PMT/LPI event re-enter the ISR forever. + pub fn mask_mac_interrupts(&self) { + unsafe { + EMAC_MAC::regs().intmask().write(|w| w.bits(u32::MAX)); + } + } + /// Disables all DMA interrupt sources. pub fn dma_disable_interrupts(&self) { unsafe { @@ -201,38 +260,67 @@ impl EmacRegs { // ── MAC configuration ───────────────────────────────────────────────── - /// Configures the MAC for the given speed/duplex and enables TX/RX. + /// Configures the MAC for the given speed/duplex. + /// + /// TX/RX are left disabled; [`Self::dma_start`] enables them in the order + /// the hardware requires. pub fn mac_init(&self, speed: Speed, duplex: Duplex) { - EMAC_MAC::regs().emacconfig().modify(|_, w| { - w.mii().set_bit(); - w.fespeed().bit(speed == Speed::_100M); + EMAC_MAC::regs().config().modify(|_, w| { + match speed { + Speed::_10M => { + w.mii().set_bit(); + w.fespeed().clear_bit(); + } + Speed::_100M => { + w.mii().set_bit(); + w.fespeed().set_bit(); + } + Speed::_1000M => { + w.mii().clear_bit(); + } + } w.duplex().bit(duplex == Duplex::Full); w.padcrcstrip().clear_bit(); - w.rxipcoffload().set_bit(); + w.rxipcoffload().bit(cfg!(ethernet_rx_checksum_offload)); w.retry().set_bit(); w.watchdog().set_bit(); w.rxown().set_bit(); w.loopback().clear_bit(); w.deferralcheck().clear_bit(); - w.rx().set_bit(); - w.tx().set_bit() + w.rx().clear_bit(); + w.tx().clear_bit() }); // Enable pass-all-multicast mode. - EMAC_MAC::regs().emacff().modify(|_, w| w.pam().set_bit()); + EMAC_MAC::regs().ff().modify(|_, w| w.pam().set_bit()); } /// Configures the MAC for the given speed. + /// + /// 10/100 Mbps sets `mii` (port select) and `fespeed`. 1000 Mbps clears `mii`. pub fn set_speed(&self, speed: Speed) { - EMAC_MAC::regs() - .emacconfig() - .modify(|_, w| w.fespeed().bit(speed == Speed::_100M)); + EMAC_MAC::regs().config().modify(|_, w| { + match speed { + Speed::_10M => { + w.mii().set_bit(); + w.fespeed().clear_bit(); + } + Speed::_100M => { + w.mii().set_bit(); + w.fespeed().set_bit(); + } + Speed::_1000M => { + w.mii().clear_bit(); + } + } + w + }); } /// Configures the MAC for the given duplex mode. pub fn set_duplex(&self, duplex: Duplex) { EMAC_MAC::regs() - .emacconfig() + .config() .modify(|_, w| w.duplex().bit(duplex == Duplex::Full)); } @@ -246,20 +334,18 @@ impl EmacRegs { | (addr[1] as u32) << 8 | (addr[0] as u32); - EMAC_MAC::regs().emacaddr0high().write(|w| unsafe { + EMAC_MAC::regs().addr0high().write(|w| unsafe { w.address0_hi().bits(hi as u16); w.address_enable0().set_bit() }); - EMAC_MAC::regs() - .emacaddr0low() - .write(|w| unsafe { w.bits(lo) }); + EMAC_MAC::regs().addr0low().write(|w| unsafe { w.bits(lo) }); } // ── MDIO ───────────────────────────────────────────────────────────── /// Reads one PHY register via the MDIO interface (Clause 22). pub fn mdio_read(&self, phy_addr: u8, reg: u8) -> u16 { - EMAC_MAC::regs().emacgmiiaddr().write(|w| unsafe { + EMAC_MAC::regs().gmiiaddr().write(|w| unsafe { w.miidev().bits(phy_addr); w.miireg().bits(reg); w.miicsrclk().bits(mdc_csr_clock_range()); @@ -268,15 +354,15 @@ impl EmacRegs { }); self.mdio_wait(); - EMAC_MAC::regs().emacmiidata().read().mii_data().bits() + EMAC_MAC::regs().miidata().read().mii_data().bits() } /// Writes one PHY register via the MDIO interface (Clause 22). pub fn mdio_write(&self, phy_addr: u8, reg: u8, data: u16) { EMAC_MAC::regs() - .emacmiidata() + .miidata() .write(|w| unsafe { w.mii_data().bits(data) }); - EMAC_MAC::regs().emacgmiiaddr().write(|w| unsafe { + EMAC_MAC::regs().gmiiaddr().write(|w| unsafe { w.miidev().bits(phy_addr); w.miireg().bits(reg); w.miicsrclk().bits(mdc_csr_clock_range()); @@ -288,11 +374,6 @@ impl EmacRegs { } fn mdio_wait(&self) { - while EMAC_MAC::regs() - .emacgmiiaddr() - .read() - .miibusy() - .bit_is_set() - {} + while EMAC_MAC::regs().gmiiaddr().read().miibusy().bit_is_set() {} } } diff --git a/esp-hal/src/ethernet/mod.rs b/esp-hal/src/ethernet/mod.rs index 56bc39feea1..00e04c6fb5e 100644 --- a/esp-hal/src/ethernet/mod.rs +++ b/esp-hal/src/ethernet/mod.rs @@ -1,39 +1,24 @@ #![cfg_attr(docsrs, procmacros::doc_replace( "clk_in_gpio" => { - cfg(esp32) => "GPIO0", - cfg(esp32p4) => "GPIO50", - }, - "rxd0_gpio" => { - cfg(esp32) => "GPIO25", - cfg(esp32p4) => "GPIO29", - }, - "rxd1_gpio" => { - cfg(esp32) => "GPIO26", - cfg(esp32p4) => "GPIO30", - }, - "rxdv_gpio" => { - cfg(esp32) => "GPIO27", - cfg(esp32p4) => "GPIO28", - }, - "txd0_gpio" => { - cfg(esp32) => "GPIO19", - cfg(esp32p4) => "GPIO34", - }, - "txd1_gpio" => { - cfg(esp32) => "GPIO22", - cfg(esp32p4) => "GPIO35", - }, - "txen_gpio" => { - cfg(esp32) => "GPIO21", - cfg(esp32p4) => "GPIO49", + cfg(esp32) => gpio_for_signal!(EMAC_TX_CLK), + _ => gpio_for_signal!(EMAC_RMII_CLK), }, + "rxd0_gpio" => gpio_for_signal!(EMAC_RXD0), + "rxd1_gpio" => gpio_for_signal!(EMAC_RXD1), + "rxdv_gpio" => gpio_for_signal!(EMAC_RXDV), + "txd0_gpio" => gpio_for_signal!(EMAC_TXD0), + "txd1_gpio" => gpio_for_signal!(EMAC_TXD1), + "txen_gpio" => gpio_for_signal!(EMAC_TXEN), + // MDC/MDIO are GPIO-matrix signals, so gpio_for_signal! has no pad and needs a fallback. "mdc_gpio" => { - cfg(esp32) => "GPIO23", - cfg(esp32p4) => "GPIO31", + cfg(esp32) => gpio_for_signal!(EMAC_MDC, "GPIO23"), + cfg(esp32p4) => gpio_for_signal!(EMAC_MDC, "GPIO31"), + cfg(esp32s31) => gpio_for_signal!(EMAC_MDC, "GPIO5"), }, "mdio_gpio" => { - cfg(esp32) => "GPIO18", - cfg(esp32p4) => "GPIO52", + cfg(esp32) => gpio_for_signal!(EMAC_MDI, "GPIO18"), + cfg(esp32p4) => gpio_for_signal!(EMAC_MDI, "GPIO52"), + cfg(esp32s31) => gpio_for_signal!(EMAC_MDI, "GPIO6"), } ))] //! EMAC Ethernet driver for ESP32. @@ -76,7 +61,11 @@ //! # {after_snippet} //! ``` -use core::{marker::PhantomData, task::Context}; +use core::{ + marker::PhantomData, + sync::atomic::{AtomicBool, Ordering}, + task::Context, +}; use crate::{ Async, @@ -92,19 +81,20 @@ use crate::{ Pin, interconnect::{self, PeripheralInput, PeripheralOutput}, }, - interrupt, - peripherals::{EMAC_DMA, ETH, Interrupt}, + peripherals::{EMAC_DMA, ETH}, private::Sealed, system::{GenericPeripheralGuard, Peripheral}, }; #[cfg_attr(esp32, path = "clock/esp32.rs")] #[cfg_attr(esp32p4, path = "clock/esp32p4.rs")] +#[cfg_attr(esp32s31, path = "clock/esp32s31.rs")] pub mod clock; pub(crate) mod dma; pub(crate) mod embassy_net; pub mod mac; pub mod phy; +pub(crate) mod xarxa; use core::task::Poll; @@ -155,6 +145,24 @@ macro_rules! emac_pin { }; } +/// Enable the GPIO output driver without touching GPIO-matrix routing. +/// +/// Matches IDF `gpio_iomux_output` for dedicated EMAC TX pads. `gpio::low_level` +/// is crate-private, so this writes the enable register directly. +fn enable_gpio_output(n: u8) { + let bit = 1u32 << (n % 32); + if n < 32 { + crate::peripherals::GPIO::regs() + .enable_w1ts() + .write(|w| unsafe { w.bits(bit) }); + } else { + #[cfg(gpio_has_bank_1)] + crate::peripherals::GPIO::regs() + .enable1_w1ts() + .write(|w| unsafe { w.bits(bit) }); + } +} + macro_rules! implement_trait { ($trait:ident, $gpio:ident, $af:ident) => { impl $trait for crate::peripherals::$gpio<'_> { @@ -164,8 +172,29 @@ macro_rules! implement_trait { // TX-direction pads where no peripheral reads the feedback path. crate::gpio::io_mux_reg(self.number()).modify(|_, w| { unsafe { w.mcu_sel().bits(AlternateFunction::$af as u8) }; + unsafe { w.fun_drv().bits(2) }; // 20 mA, IDF default for EMAC pads + w.fun_ie().set_bit() + }); + } + } + }; +} + +/// Like [`implement_trait`], but also enables the GPIO output driver. +/// +/// IDF `gpio_iomux_output` does this for RGMII TX_CLK/TXD/TX_CTL. S31 routes +/// RGMII TX_CLK through the RMII CLK pad (`EMAC_RMII_CLK`). +macro_rules! implement_output_trait { + ($trait:ident, $gpio:ident, $af:ident) => { + impl $trait for crate::peripherals::$gpio<'_> { + fn configure_iomux(self) { + let n = self.number(); + crate::gpio::io_mux_reg(n).modify(|_, w| { + unsafe { w.mcu_sel().bits(AlternateFunction::$af as u8) }; + unsafe { w.fun_drv().bits(2) }; w.fun_ie().set_bit() }); + enable_gpio_output(n); } } }; @@ -295,17 +324,22 @@ emac_pin!(RmiiTxd1, "RMII TXD1 pin"); emac_pin!(RmiiCrsDv, "RMII CRS/DV pin"); emac_pin!(RmiiRxd0, "RMII RXD0 pin"); emac_pin!(RmiiRxd1, "RMII RXD1 pin"); +emac_pin!(RgmiiRxClk, "RGMII RX clock pin"); +emac_pin!(RgmiiTxd2, "RGMII TXD2 pin"); +emac_pin!(RgmiiTxd3, "RGMII TXD3 pin"); +emac_pin!(RgmiiRxd2, "RGMII RXD2 pin"); +emac_pin!(RgmiiRxd3, "RGMII RXD3 pin"); // RMII traits for_each_iomux_function! { (EMAC_TXEN, $gpio:ident, $af:ident) => { - implement_trait!(RmiiTxEn, $gpio, $af); + implement_output_trait!(RmiiTxEn, $gpio, $af); }; (EMAC_TXD0, $gpio:ident, $af:ident) => { - implement_trait!(RmiiTxd0, $gpio, $af); + implement_output_trait!(RmiiTxd0, $gpio, $af); }; (EMAC_TXD1, $gpio:ident, $af:ident) => { - implement_trait!(RmiiTxd1, $gpio, $af); + implement_output_trait!(RmiiTxd1, $gpio, $af); }; (EMAC_RXDV, $gpio:ident, $af:ident) => { implement_trait!(RmiiCrsDv, $gpio, $af); @@ -316,32 +350,60 @@ for_each_iomux_function! { (EMAC_RXD1, $gpio:ident, $af:ident) => { implement_trait!(RmiiRxd1, $gpio, $af); }; + (EMAC_RX_CLK, $gpio:ident, $af:ident) => { + implement_trait!(RgmiiRxClk, $gpio, $af); + }; + (EMAC_TXD2, $gpio:ident, $af:ident) => { + implement_output_trait!(RgmiiTxd2, $gpio, $af); + }; + (EMAC_TXD3, $gpio:ident, $af:ident) => { + implement_output_trait!(RgmiiTxd3, $gpio, $af); + }; + (EMAC_RXD2, $gpio:ident, $af:ident) => { + implement_trait!(RgmiiRxd2, $gpio, $af); + }; + (EMAC_RXD3, $gpio:ident, $af:ident) => { + implement_trait!(RgmiiRxd3, $gpio, $af); + }; // ESP32-specific (EMAC_TX_CLK, $gpio:ident, $af:ident) => { implement_trait!(RmiiClkIn, $gpio, $af); }; (EMAC_CLK_OUT, $gpio:ident, $af:ident) => { - implement_trait!(RmiiClkOut, $gpio, $af); + implement_output_trait!(RmiiClkOut, $gpio, $af); }; (EMAC_CLK_180, $gpio:ident, $af:ident) => { - implement_trait!(RmiiClkOut, $gpio, $af); + implement_output_trait!(RmiiClkOut, $gpio, $af); }; - // ESP32-P4-specific: MPLL-derived 50 MHz reference clock output pad. + // ESP32-P4 / ESP32-S31: 50 MHz reference clock output pad. (REF_50M_CLK, $gpio:ident, $af:ident) => { - implement_trait!(RmiiClkOut, $gpio, $af); + implement_output_trait!(RmiiClkOut, $gpio, $af); }; (EMAC_RMII_CLK, $gpio:ident, $af:ident) => { implement_trait!(RmiiClkIn, $gpio, $af); + implement_output_trait!(RmiiClkOut, $gpio, $af); }; } /// RMII or MII pad wiring for [`Ethernet::new`]. pub trait EthernetPinBundle: crate::private::Sealed { + /// Fastest link speed this interface can carry. + /// + /// RMII and MII are limited to 100 Mbps; only RGMII reaches 1000 Mbps. The + /// PHY is told not to advertise anything faster. + const MAX_SPEED: Speed; + /// Applies the required configuration. Intended to be /// called by the Ethernet driver internally. fn apply(self); + + /// Retunes the interface clocking for a newly negotiated link speed. + /// + /// Called by the driver from [`Ethernet::set_speed`], after the pins have + /// been consumed by [`apply`][Self::apply], so it takes no `self`. + fn apply_speed(speed: Speed); } /// Wired RMII pads and RMII clock (pass to [`Ethernet::new`]). @@ -390,6 +452,13 @@ where configure_mdio(self.mdc, self.mdio); self.clock.configure(); } + + const MAX_SPEED: Speed = Speed::_100M; + + fn apply_speed(_speed: Speed) { + // No-op: the RMII reference clock is fixed at 50 MHz and the MAC derives + // the 10/100 Mbps timing from it internally. + } } /// Wired MII pads (pass to [`Ethernet::new`]). @@ -537,6 +606,138 @@ where clock::MiiClock.configure(); } + + const MAX_SPEED: Speed = Speed::_100M; + + fn apply_speed(_speed: Speed) { + // No-op: in MII mode the PHY drives `TX_CLK` and `RX_CLK` at the rate that + // matches the negotiated speed. + } +} + +/// Wired RGMII pads (pass to [`Ethernet::new`]). +/// +/// RGMII data and clock pads use IOMUX only. Do not route them through the GPIO +/// matrix (`MiiTxd*` / `MiiRxd*`). +#[cfg(ethernet_has_rgmii)] +#[allow( + missing_docs, + reason = "The field names are indicative of their function." +)] +pub struct RgmiiPinBundle< + RxClk, + TxClk, + RxCtl, + TxCtl, + Rxd0, + Rxd1, + Rxd2, + Rxd3, + Txd0, + Txd1, + Txd2, + Txd3, + Mdc, + Mdio, +> { + pub rx_clk: RxClk, + pub tx_clk: TxClk, + pub rx_ctl: RxCtl, + pub tx_ctl: TxCtl, + pub rxd0: Rxd0, + pub rxd1: Rxd1, + pub rxd2: Rxd2, + pub rxd3: Rxd3, + pub txd0: Txd0, + pub txd1: Txd1, + pub txd2: Txd2, + pub txd3: Txd3, + pub mdc: Mdc, + pub mdio: Mdio, +} + +#[cfg(ethernet_has_rgmii)] +impl + crate::private::Sealed + for RgmiiPinBundle< + RxClk, + TxClk, + RxCtl, + TxCtl, + Rxd0, + Rxd1, + Rxd2, + Rxd3, + Txd0, + Txd1, + Txd2, + Txd3, + Mdc, + Mdio, + > +{ +} + +#[cfg(ethernet_has_rgmii)] +impl<'d, RxClk, TxClk, RxCtl, TxCtl, Rxd0, Rxd1, Rxd2, Rxd3, Txd0, Txd1, Txd2, Txd3, Mdc, Mdio> + EthernetPinBundle + for RgmiiPinBundle< + RxClk, + TxClk, + RxCtl, + TxCtl, + Rxd0, + Rxd1, + Rxd2, + Rxd3, + Txd0, + Txd1, + Txd2, + Txd3, + Mdc, + Mdio, + > +where + RxClk: RgmiiRxClk + 'd, + TxClk: RmiiClkOut + 'd, + RxCtl: RmiiCrsDv + 'd, + TxCtl: RmiiTxEn + 'd, + Rxd0: RmiiRxd0 + 'd, + Rxd1: RmiiRxd1 + 'd, + Rxd2: RgmiiRxd2 + 'd, + Rxd3: RgmiiRxd3 + 'd, + Txd0: RmiiTxd0 + 'd, + Txd1: RmiiTxd1 + 'd, + Txd2: RgmiiTxd2 + 'd, + Txd3: RgmiiTxd3 + 'd, + Mdc: PeripheralOutput<'d>, + Mdio: PeripheralInput<'d> + PeripheralOutput<'d>, +{ + fn apply(self) { + self.rx_clk.configure_iomux(); + self.tx_clk.configure_iomux(); + self.rx_ctl.configure_iomux(); + self.tx_ctl.configure_iomux(); + self.rxd0.configure_iomux(); + self.rxd1.configure_iomux(); + self.rxd2.configure_iomux(); + self.rxd3.configure_iomux(); + self.txd0.configure_iomux(); + self.txd1.configure_iomux(); + self.txd2.configure_iomux(); + self.txd3.configure_iomux(); + + configure_mdio(self.mdc, self.mdio); + clock::RgmiiClock.configure(); + } + + const MAX_SPEED: Speed = Speed::_1000M; + + /// The MAC drives RGMII `TX_CLK`, so its divider has to follow the link: + /// 125 MHz at 1000 Mbps, 25 MHz at 100 Mbps, 2.5 MHz at 10 Mbps. + fn apply_speed(speed: Speed) { + clock::apply_rgmii_tx_speed(speed); + } } // ── Async wakers ────────────────────────────────────────────────────────────── @@ -548,6 +749,20 @@ const DMASTATUS_RI: u32 = 1 << 6; /// DMASTATUS bit mask for the TX-complete interrupt. const DMASTATUS_TI: u32 = 1 << 0; +static ISR_BOUND: AtomicBool = AtomicBool::new(false); + +/// Binds the DMA ISR on first use. +/// +/// `bind_peri_interrupt` also enables the interrupt, so this must not run before +/// the peripheral is ready to have its interrupt line unmasked. +pub(super) fn bind_eth_isr() { + if !ISR_BOUND.swap(true, Ordering::Relaxed) { + // Safety: the ISR only touches DMA status registers; ETH ownership is + // tracked by `Ethernet`. + unsafe { ETH::steal() }.bind_peri_interrupt(eth_mac_isr); + } +} + #[crate::handler] fn eth_mac_isr() { let status = EMAC_DMA::regs().dmastatus().read().bits(); @@ -573,24 +788,53 @@ pub struct Ethernet<'d, DM: DriverMode, P: Phy> { phy: P, mac_addr: [u8; 6], speed: Speed, + /// Fastest speed the wired interface can carry, from the pin bundle. + max_speed: Speed, + /// The pin bundle's [`EthernetPinBundle::apply_speed`]. The bundle itself is + /// consumed during setup, so the driver keeps only this hook. + apply_speed: fn(Speed), duplex: Duplex, _mode: PhantomData, } impl<'d, P: Phy> Ethernet<'d, Blocking, P> { /// Creates an Ethernet driver using RMII ([`RmiiPinBundle`]) or MII ([`MiiPinBundle`]). - pub fn new( + #[cfg_attr( + ethernet_has_rgmii, + doc = "On chips with RGMII, use [`RgmiiPinBundle`]. RGMII is limited to 100 Mbps when the + MPLL does not divide to its 125 MHz transmit clock." + )] + pub fn new( eth: ETH<'d>, storage: &'d mut EthernetDmaStorage, mac_addr: [u8; 6], phy: P, - pins: impl EthernetPinBundle + 'd, + pins: B, ) -> Result { let clock_guard = GenericPeripheralGuard::new(); pins.apply(); - init_common(clock_guard, storage, mac_addr, phy, eth) + let max_speed = cfg_select! { + ethernet_has_rgmii => { + if B::MAX_SPEED == Speed::_1000M { + clock::rgmii_max_speed() + } else { + B::MAX_SPEED + } + } + _ => B::MAX_SPEED, + }; + + init_common( + clock_guard, + storage, + mac_addr, + phy, + eth, + max_speed, + B::apply_speed, + ) } /// Returns the received frame data if one is ready. @@ -614,16 +858,20 @@ impl<'d, P: Phy> Ethernet<'d, Blocking, P> { EmacRegs.demand_rx_poll(); } - /// Converts to async mode, enabling DMA interrupts and binding the ISR. + /// Converts to async mode. + /// + /// The DMA ISR is bound and its interrupts enabled on the first link-up, + /// not here: without a link there is no RX clock and the DMA would only + /// report errors. pub fn into_async(self) -> Ethernet<'d, Async, P> { - EmacRegs.dma_enable_interrupts(true); - interrupt::bind_handler(Interrupt::ETH_MAC, eth_mac_isr); Ethernet { tx: self.tx, rx: self.rx, phy: self.phy, mac_addr: self.mac_addr, speed: self.speed, + max_speed: self.max_speed, + apply_speed: self.apply_speed, duplex: self.duplex, _clock_guard: self._clock_guard, _eth: self._eth, @@ -651,9 +899,18 @@ fn configure_mdio<'d>( impl<'d, Dm: DriverMode, P: Phy> Ethernet<'d, Dm, P> { /// Configures the MAC for the given speed. + /// + /// The speed must be one the wired interface can carry: MII and RMII top + /// out at 100 Mbps, only RGMII reaches 1000 Mbps. pub fn set_speed(&mut self, speed: Speed) { + debug_assert!( + !(speed == Speed::_1000M && self.max_speed != Speed::_1000M), + "1000 Mbps requires an RGMII interface" + ); + if speed != self.speed { EmacRegs.set_speed(speed); + (self.apply_speed)(speed); self.speed = speed; } } @@ -757,6 +1014,8 @@ impl<'d, P: Phy> Ethernet<'d, Async, P> { phy: self.phy, mac_addr: self.mac_addr, speed: self.speed, + max_speed: self.max_speed, + apply_speed: self.apply_speed, duplex: self.duplex, _clock_guard: self._clock_guard, _eth: self._eth, @@ -764,7 +1023,7 @@ impl<'d, P: Phy> Ethernet<'d, Async, P> { } } - /// Returns `true` if there is at least one free TX descriptor slot. + /// Returns whether there is at least one free TX descriptor slot. pub fn tx_has_capacity(&self) -> bool { self.tx.has_capacity() } @@ -792,13 +1051,16 @@ fn init_common<'d, P: Phy, const RX: usize, const TX: usize>( mac_addr: [u8; 6], mut phy: P, eth: ETH<'d>, + max_speed: Speed, + apply_speed: fn(Speed), ) -> Result, Error> { // DMA soft-reset (also enables enhanced 32B descriptor format). EmacRegs.dma_soft_reset(); + EmacRegs.dma_init_op_mode(); // Init PHY (MDIO requires DMA/MAC clocks to be running after reset). let mut mdio = MdioDriver::new(&EmacRegs); - phy.init(&mut mdio).map_err(Error::Phy)?; + phy.init(&mut mdio, max_speed).map_err(Error::Phy)?; // Build descriptor rings from the erased slice references. let tx = TDesRing::new(&mut storage.tx_descs, &mut storage.tx_bufs); @@ -813,6 +1075,8 @@ fn init_common<'d, P: Phy, const RX: usize, const TX: usize>( phy, mac_addr, speed: Speed::_100M, + max_speed, + apply_speed, duplex: Duplex::Full, _clock_guard: clock_guard, _eth: eth, @@ -823,9 +1087,16 @@ fn init_common<'d, P: Phy, const RX: usize, const TX: usize>( EmacRegs.mac_init(eth.speed, eth.duplex); EmacRegs.set_mac_address(ð.mac_addr); + // Bring the interface clocking in line with the recorded default speed. For + // RGMII the clock setup leaves TX_CLK at the 1000 Mbps rate, and + // `set_speed` skips speeds that already match, so without this a 100 Mbps + // link would keep transmitting at 125 MHz. + apply_speed(eth.speed); + // In blocking mode all DMA interrupts stay disabled; async mode enables - // them via into_async(). + // them once the link is up. EmacRegs.dma_disable_interrupts(); + EmacRegs.mask_mac_interrupts(); // Start both DMA engines. EmacRegs.dma_start(); diff --git a/esp-hal/src/ethernet/phy/generic.rs b/esp-hal/src/ethernet/phy/generic.rs index c32aca91a2e..317e2aaba47 100644 --- a/esp-hal/src/ethernet/phy/generic.rs +++ b/esp-hal/src/ethernet/phy/generic.rs @@ -6,14 +6,65 @@ use core::task::Context; use crate::ethernet::{ mac::{Duplex, LinkState, Speed}, - phy::{ANAR, ANLPAR, BMCR, BMSR, MdioBus, PHYIDR1, Phy, PhyError, an, bmcr, bmsr}, + phy::{ + ANAR, + ANLPAR, + BMCR, + BMSR, + EXSR, + GBCR, + GBSR, + MdioBus, + PHYIDR1, + PHYIDR2, + Phy, + PhyError, + an, + bmcr, + bmsr, + exsr, + gbcr, + gbsr, + }, }; /// Maximum iterations to wait for the PHY reset bit to self-clear. const RESET_POLL_LIMIT: u32 = 500_000; // us +/// Motorcomm YT8531 identifier (`PHYIDR1`/`PHYIDR2`). +const YT8531_ID: (u16, u16) = (0x4F51, 0xE91B); + +/// Extended-register address window (Motorcomm). +const REG_EXT_ADDR: u8 = 0x1E; +/// Extended-register data window (Motorcomm). +const REG_EXT_DATA: u8 = 0x1F; + +/// Chip config (extended). Bit 8 adds a coarse ~1.9 ns RXC delay. +const EXT_CHIP_CFG: u16 = 0xA001; +const RXC_DLY_EN: u16 = 1 << 8; + +/// RGMII delay config (extended). +/// `[13:10]` RX, `[7:4]` 100M TX, `[3:0]` 1000M TX. Unit 150 ps; 13 ≈ 1.95 ns. +const EXT_RGMII_CFG1: u16 = 0xA003; +const RGMII_TX_DLY_MASK: u16 = 0x00FF; +const RGMII_DLY_2NS: u16 = 13; + +fn ext_read(mdio: &mut M, addr: u8, ext: u16) -> u16 { + mdio.write(addr, REG_EXT_ADDR, ext); + mdio.read(addr, REG_EXT_DATA) +} + +fn ext_write(mdio: &mut M, addr: u8, ext: u16, val: u16) { + mdio.write(addr, REG_EXT_ADDR, ext); + mdio.write(addr, REG_EXT_DATA, val); +} + /// Generic PHY driver. /// +/// Initialization and link handling follow IEEE 802.3 Clause 22, matching +/// esp-idf `esp_eth_phy_802_3`. PHYs that need chip-specific setup get it +/// applied from [`Phy::init`] based on their identifier. +/// /// Can be constructed with a fixed address ([`GenericPhy::new`]) or with /// automatic address discovery ([`GenericPhy::new_auto`]). When using /// `new_auto`, the MDIO bus is scanned during [`Phy::init`] and the first @@ -25,12 +76,12 @@ pub struct GenericPhy { } impl GenericPhy { - /// Creates a driver instance for the given MDIO bus address. + /// Creates a new driver instance for the given MDIO bus address. pub const fn new(addr: u8) -> Self { Self { addr: Some(addr) } } - /// Creates a driver instance that discovers the PHY address automatically + /// Creates a new driver instance that discovers the PHY address automatically /// by scanning the MDIO bus during [`Phy::init`]. /// /// Returns [`PhyError::NotFound`] from `init` if no PHY responds. @@ -55,6 +106,56 @@ impl GenericPhy { } None } + + /// Removes advertisements faster than `max_speed`. + /// + /// A gigabit PHY wired to an RMII or MII MAC would otherwise negotiate 1000 + /// Mbps with the link partner and the MAC could not carry it. Returns + /// whether an advertisement was withdrawn, in which case auto-negotiation + /// has to be restarted to take effect. + fn limit_advertisement(mdio: &mut M, addr: u8, max_speed: Speed) -> bool { + let mut changed = false; + + if max_speed != Speed::_1000M { + let gbcr_val = mdio.read(addr, GBCR); + if gbcr_val != 0xFFFF { + let limited = gbcr_val & !(gbcr::ADV_1000_FULL | gbcr::ADV_1000_HALF); + if limited != gbcr_val { + mdio.write(addr, GBCR, limited); + changed = true; + } + } + } + + if max_speed == Speed::_10M { + let anar_val = mdio.read(addr, ANAR); + let limited = anar_val & !(an::BASE_100_FULL | an::BASE_100_HALF); + if limited != anar_val { + mdio.write(addr, ANAR, limited); + changed = true; + } + } + + changed + } + + /// Programs the Motorcomm YT8531 RGMII clock delays. + /// + /// RGMII needs roughly 2 ns of delay on both paths. Do not write the YT8521 `0xA000` UTP/fiber + /// page select: the YT8531 is UTP-only and that write maps the Clause 22 registers to dead + /// space. + fn init_yt8531(mdio: &mut M, addr: u8) { + let chip = ext_read(mdio, addr, EXT_CHIP_CFG); + ext_write(mdio, addr, EXT_CHIP_CFG, chip | RXC_DLY_EN); + + let mut rgmii = ext_read(mdio, addr, EXT_RGMII_CFG1); + rgmii = (rgmii & !RGMII_TX_DLY_MASK) | (RGMII_DLY_2NS << 4) | RGMII_DLY_2NS; + ext_write(mdio, addr, EXT_RGMII_CFG1, rgmii); + + // Restart auto-negotiation so the delays are in force before it resolves. + let ctrl = mdio.read(addr, BMCR); + mdio.write(addr, BMCR, ctrl | bmcr::RESTART_AN); + } } impl Phy for GenericPhy { @@ -63,26 +164,47 @@ impl Phy for GenericPhy { .expect("GenericPhy address not yet resolved — call init() first") } - fn init(&mut self, mdio: &mut M) -> Result<(), PhyError> { + fn init(&mut self, mdio: &mut M, max_speed: Speed) -> Result<(), PhyError> { // Resolve address if auto-discovery was requested. if self.addr.is_none() { self.addr = Some(Self::discover(mdio).ok_or(PhyError::NotFound)?); } let addr = self.addr.unwrap(); - mdio.write(addr, BMCR, bmcr::RESET); + // Match esp-idf `esp_eth_phy_802_3_basic_phy_init`: power up, then + // software reset. ANAR/GBCR keep their post-reset defaults except for + // abilities the MAC interface cannot carry. + let ctrl = mdio.read(addr, BMCR); + if ctrl & bmcr::POWER_DOWN != 0 { + mdio.write(addr, BMCR, ctrl & !bmcr::POWER_DOWN); + for _ in 0..RESET_POLL_LIMIT { + if mdio.read(addr, BMCR) & bmcr::POWER_DOWN == 0 { + break; + } + crate::rom::ets_delay_us(1); + } + } - // Wait for the RESET bit to self-clear (≤ ~0.5 ms per IEEE 802.3). + mdio.write(addr, BMCR, bmcr::RESET); for _ in 0..RESET_POLL_LIMIT { if mdio.read(addr, BMCR) & bmcr::RESET == 0 { - // Reset complete. Configure advertisement then restart AN. - let adv = - an::BASE_10_HALF | an::BASE_10_FULL | an::BASE_100_HALF | an::BASE_100_FULL; - mdio.write(addr, ANAR, adv | 0x0001); // selector = IEEE 802.3 - - // RMW so we don't disturb speed/duplex bits restored by reset. + // Some PHYs clear ANEN across a reset. Only restore the bit; + // advertisements stay at their post-reset defaults. let ctrl = mdio.read(addr, BMCR); - mdio.write(addr, BMCR, ctrl | bmcr::ANEN | bmcr::RESTART_AN); + if ctrl & bmcr::ANEN == 0 { + mdio.write(addr, BMCR, (ctrl & !bmcr::POWER_DOWN) | bmcr::ANEN); + } + + let restart_an = Self::limit_advertisement(mdio, addr, max_speed); + + let id = (mdio.read(addr, PHYIDR1), mdio.read(addr, PHYIDR2)); + if id == YT8531_ID { + // Also restarts auto-negotiation. + Self::init_yt8531(mdio, addr); + } else if restart_an { + let ctrl = mdio.read(addr, BMCR); + mdio.write(addr, BMCR, ctrl | bmcr::RESTART_AN); + } return Ok(()); } @@ -99,6 +221,9 @@ impl Phy for GenericPhy { duplex: Duplex::Full, }; + // No PHY interrupt is available, and esp-hal has no timer to defer to, + // so wake immediately to keep being polled. Wrap this driver to + // rate-limit the polling (see `Phy::poll_link`). if let Some(cx) = cx { cx.waker().wake_by_ref(); } @@ -115,27 +240,72 @@ impl Phy for GenericPhy { trace!("bmsr_val: {:x}", bmsr_val); + // Link is BMSR.LINK_STATUS alone, as in IDF + // `esp_eth_phy_802_3_updt_link_dup_spd`. AN_COMPLETE may still be clear + // while Clause 40 finishes even though copper is already up. if bmsr_val & bmsr::LINK_STATUS == 0 { return LINK_STATE_DOWN; } - if bmsr_val & bmsr::AN_COMPLETE == 0 { - return LINK_STATE_DOWN; + let bmcr_val = mdio.read(addr, BMCR); + if bmcr_val & bmcr::ANEN == 0 { + let speed = if bmcr_val & bmcr::SPEED_1000 != 0 { + Speed::_1000M + } else if bmcr_val & bmcr::SPEED_100 != 0 { + Speed::_100M + } else { + Speed::_10M + }; + let duplex = if bmcr_val & bmcr::FULL_DUPLEX != 0 { + Duplex::Full + } else { + Duplex::Half + }; + return LinkState { + up: true, + speed, + duplex, + }; } - // Link is up and auto-negotiation is complete. read ANLPAR to - // determine the negotiated speed/duplex. + if bmsr_val & bmsr::EXTENDED_STATUS != 0 { + let exsr_val = mdio.read(addr, EXSR); + if exsr_val != 0xFFFF && (exsr_val & (exsr::BASE1000_T_HD | exsr::BASE1000_T_FD) != 0) { + let gbcr_val = mdio.read(addr, GBCR); + let gbsr_val = mdio.read(addr, GBSR); + if gbcr_val != 0xFFFF && gbsr_val != 0xFFFF { + if gbcr_val & gbcr::ADV_1000_FULL != 0 && gbsr_val & gbsr::LP_1000_FULL != 0 { + return LinkState { + up: true, + speed: Speed::_1000M, + duplex: Duplex::Full, + }; + } + if gbcr_val & gbcr::ADV_1000_HALF != 0 && gbsr_val & gbsr::LP_1000_HALF != 0 { + return LinkState { + up: true, + speed: Speed::_1000M, + duplex: Duplex::Half, + }; + } + } + } + } + // IDF: resolved mode is ANAR ∩ ANLPAR, highest common ability first. + let anar_val = mdio.read(addr, ANAR); let anlpar_val = mdio.read(addr, ANLPAR); - let speed = if anlpar_val & an::BASE_100_FULL != 0 || anlpar_val & an::BASE_100_HALF != 0 { - Speed::_100M - } else { - Speed::_10M - }; - let duplex = if anlpar_val & an::BASE_10_FULL != 0 || anlpar_val & an::BASE_100_FULL != 0 { - Duplex::Full + let common = anar_val & anlpar_val; + let (speed, duplex) = if common & an::BASE_100_FULL != 0 { + (Speed::_100M, Duplex::Full) + } else if common & an::BASE_100_HALF != 0 { + (Speed::_100M, Duplex::Half) + } else if common & an::BASE_10_FULL != 0 { + (Speed::_10M, Duplex::Full) + } else if common & an::BASE_10_HALF != 0 { + (Speed::_10M, Duplex::Half) } else { - Duplex::Half + (Speed::_100M, Duplex::Full) }; LinkState { diff --git a/esp-hal/src/ethernet/phy/mod.rs b/esp-hal/src/ethernet/phy/mod.rs index 04e394ebfb6..18b72fb236f 100644 --- a/esp-hal/src/ethernet/phy/mod.rs +++ b/esp-hal/src/ethernet/phy/mod.rs @@ -6,7 +6,7 @@ use core::task::Context; -use crate::ethernet::mac::{EmacRegs, LinkState}; +use crate::ethernet::mac::{EmacRegs, LinkState, Speed}; pub mod generic; @@ -26,19 +26,29 @@ pub const ANAR: u8 = 0x04; pub const ANLPAR: u8 = 0x05; /// Auto-Negotiation Expansion Register. pub const ANER: u8 = 0x06; +/// 1000BASE-T Control Register. +pub const GBCR: u8 = 0x09; +/// 1000BASE-T Status Register. +pub const GBSR: u8 = 0x0A; +/// Extended Status Register. +pub const EXSR: u8 = 0x0F; /// Bit definitions for [`BMCR`]. pub mod bmcr { /// Software reset. pub const RESET: u16 = 1 << 15; - /// Select 100 Mbps (when auto-neg disabled). + /// Selects 100 Mbps (when auto-neg disabled). pub const SPEED_100: u16 = 1 << 13; - /// Enable auto-negotiation. + /// Enables auto-negotiation. pub const ANEN: u16 = 1 << 12; - /// Restart auto-negotiation. + /// IEEE power-down (all except MDIO). + pub const POWER_DOWN: u16 = 1 << 11; + /// Restarts auto-negotiation. pub const RESTART_AN: u16 = 1 << 9; /// Full-duplex (when auto-neg disabled). pub const FULL_DUPLEX: u16 = 1 << 8; + /// 1000 Mbps MSB (with [`SPEED_100`] clear) when auto-neg is disabled. + pub const SPEED_1000: u16 = 1 << 6; } /// Bit definitions for [`BMSR`]. @@ -49,6 +59,8 @@ pub mod bmsr { pub const AN_COMPLETE: u16 = 1 << 5; /// Auto-negotiation ability. pub const AN_ABILITY: u16 = 1 << 3; + /// Extended status register is present (register 15). + pub const EXTENDED_STATUS: u16 = 1 << 8; } /// Bit definitions for [`ANAR`] and [`ANLPAR`]. @@ -63,6 +75,32 @@ pub mod an { pub const BASE_100_FULL: u16 = 1 << 8; } +/// Bit definitions for [`GBCR`]. +pub mod gbcr { + /// Advertise 1000BASE-T half-duplex. + pub const ADV_1000_HALF: u16 = 1 << 8; + /// Advertise 1000BASE-T full-duplex. + pub const ADV_1000_FULL: u16 = 1 << 9; + /// Prefer 1000BASE-T master (AN, not forced). + pub const PREFER_MASTER: u16 = 1 << 11; +} + +/// Bit definitions for [`GBSR`]. +pub mod gbsr { + /// Link partner 1000BASE-T half-duplex. + pub const LP_1000_HALF: u16 = 1 << 10; + /// Link partner 1000BASE-T full-duplex. + pub const LP_1000_FULL: u16 = 1 << 11; +} + +/// Bit definitions for [`EXSR`]. +pub mod exsr { + /// 1000BASE-T half-duplex ability. + pub const BASE1000_T_HD: u16 = 1 << 12; + /// 1000BASE-T full-duplex ability. + pub const BASE1000_T_FD: u16 = 1 << 13; +} + // ── MdioBus trait ─────────────────────────────────────────────────────────── /// Generic MDIO bus interface for Clause 22 PHY register access. @@ -71,10 +109,10 @@ pub mod an { /// crates without depending on the concrete [`MdioDriver`]. PHY and /// register addresses are 5-bit Clause 22 fields (0-31). pub trait MdioBus { - /// Read a 16-bit PHY register. + /// Reads a 16-bit PHY register. fn read(&mut self, phy_addr: u8, reg_addr: u8) -> u16; - /// Write a 16-bit PHY register. + /// Writes a 16-bit PHY register. fn write(&mut self, phy_addr: u8, reg_addr: u8, value: u16); } @@ -138,16 +176,25 @@ pub enum PhyError { pub trait Phy { /// One-time hardware initialization. /// - /// Should reset the PHY, configure auto-negotiation, and wait until the + /// Must reset the PHY, configure auto-negotiation, and wait until the /// hardware is ready to respond to further MDIO transactions. - fn init(&mut self, mdio: &mut M) -> Result<(), PhyError>; + /// + /// `max_speed` is the fastest speed the wired MAC interface can carry (100 + /// Mbps for MII/RMII, 1000 Mbps for RGMII). Faster abilities must not be + /// advertised, or the link partner may settle on a speed the MAC cannot + /// drive. + fn init(&mut self, mdio: &mut M, max_speed: Speed) -> Result<(), PhyError>; /// Polls the current link state. /// - /// Returns [`LinkState`] with `up == true` once auto-negotiation is - /// complete and the link partner is detected. The context can be used - /// to wake the caller when the link state should be re-polled, if the PHY chip - /// supports interrupt-driven notifications. + /// Returns [`LinkState`] with `up == true` once the link partner is + /// detected. + /// + /// In async mode the context must be used to schedule the next poll: + /// register a waker for a PHY interrupt or a timer, or wake immediately. + /// An implementation that does neither will never be polled again, so + /// drivers without an interrupt source wake immediately, which busy-polls. + /// Wrap them to rate-limit the polling if a timer is available. fn poll_link(&mut self, mdio: &mut M, _cx: Option<&mut Context<'_>>) -> LinkState; /// Returns the Clause 22 PHY address on the MDIO bus. diff --git a/esp-hal/src/ethernet/xarxa.rs b/esp-hal/src/ethernet/xarxa.rs new file mode 100644 index 00000000000..507f94fcc62 --- /dev/null +++ b/esp-hal/src/ethernet/xarxa.rs @@ -0,0 +1,140 @@ +//! `xarxa` driver integration for the EMAC Ethernet peripheral. +//! +//! This module provides a [`xarxa_driver::Driver`] implementation for +//! [`Ethernet`] operating in async mode, enabling the Ethernet peripheral to be +//! used as a network interface with [`xarxa`](https://crates.io/crates/xarxa). +//! +//! ## Usage +//! +//! After obtaining an `Ethernet<'_, Async, P>` instance, pass it directly to the +//! stack — the [`Driver`] impl is inherent on the type. +//! +//! Unlike the `embassy-net` driver, this one copies each frame between the DMA +//! ring and a pool buffer, because `xarxa` passes ownership of packet buffers +//! instead of lending the driver's own memory. + +use core::{ + any::TypeId, + task::{Context, Waker}, +}; + +use xarxa_driver::{ + Capabilities, + ChecksumOffload, + Driver, + HardwareAddress, + LinkState, + NotSupported, + PacketBuf, + config::PACKET_BUF_SIZE, +}; + +use super::{Ethernet, RX_WAKER, TX_WAKER, mac::EmacRegs}; +use crate::{Async, DriverMode, ethernet::phy::Phy}; + +/// Maximum Ethernet frame size (header + payload, no FCS). +/// +/// The packet pool has a fixed buffer size, which caps the frames this driver +/// can pass on to the stack. +const MTU: usize = if 1514 < PACKET_BUF_SIZE { + 1514 +} else { + PACKET_BUF_SIZE +}; + +impl<'d, Dm: DriverMode + 'static, P: Phy> Driver for Ethernet<'d, Dm, P> { + fn capabilities(&self) -> Capabilities { + let mut caps = Capabilities::default(); + caps.max_transmission_unit = MTU; + // `Checksum` names the direction(s) computed in software. Hardware + // offload is advertised so the stack skips that side. + let checksum = ChecksumOffload { + tx: property!("ethernet.tx_checksum_offload"), + rx: property!("ethernet.rx_checksum_offload"), + }; + caps.checksum.ipv4 = checksum; + caps.checksum.tcp = checksum; + caps.checksum.udp = checksum; + caps.checksum.icmpv4 = checksum; + caps.checksum.icmpv6 = checksum; + caps + } + + fn hardware_address(&self) -> HardwareAddress { + HardwareAddress::Ethernet(self.mac_addr()) + } + + fn link_state(&mut self) -> LinkState { + let state = self.poll_link(None); + if state.up { + self.set_speed(state.speed); + self.set_duplex(state.duplex); + LinkState::Up + } else { + LinkState::Down + } + } + + fn register_waker(&mut self, waker: &Waker) -> Result<(), NotSupported> { + if TypeId::of::() == TypeId::of::() { + // The driver has one waker per event, the stack has one waker for all of them. + RX_WAKER.register(waker); + TX_WAKER.register(waker); + // The PHY keeps the waker to report a link change. A PHY that cannot do so wakes the + // stack at once, which makes it poll the link state instead. + self.poll_link(Some(&mut Context::from_waker(waker))); + Ok(()) + } else { + Err(NotSupported) + } + } + + fn receive(&mut self) -> Option { + let Some(frame) = self.rx.receive() else { + // receive() may have recycled error frames back to DMA ownership without a + // poll-demand write, which would leave the GMAC RX channel suspended. + EmacRegs.demand_rx_poll(); + return None; + }; + + let buffer = if frame.len() > PACKET_BUF_SIZE { + warn!( + "Dropping a {} byte frame, the packet buffer holds {} bytes", + frame.len(), + PACKET_BUF_SIZE + ); + None + } else if let Some(mut buffer) = PacketBuf::try_new() { + buffer.set_len(frame.len()); + buffer.copy_from_slice(frame); + Some(buffer) + } else { + // The pool is shared with the rest of the stack and can be empty. Dropping the + // frame is the only option, the descriptor must go back to the DMA. + None + }; + + self.rx.pop(); + EmacRegs.demand_rx_poll(); + + buffer + } + + fn can_transmit(&mut self) -> bool { + self.tx.available_buf().is_some() + } + + fn transmit(&mut self, buffer: PacketBuf) -> Result<(), PacketBuf> { + let Some(slot) = self.tx.available_buf() else { + return Err(buffer); + }; + + let len = buffer.len().min(MTU); + slot[..len].copy_from_slice(&buffer[..len]); + + self.tx.commit(len); + EmacRegs.demand_tx_poll(); + + Ok(()) + } +} diff --git a/esp-hal/src/etm.rs b/esp-hal/src/etm.rs index 9a9026f7ce1..912c8245185 100644 --- a/esp-hal/src/etm.rs +++ b/esp-hal/src/etm.rs @@ -110,9 +110,9 @@ use crate::{peripherals::ETM, system::GenericPeripheralGuard}; pub struct EtmChannel {} impl EtmChannel { - /// Setup the channel + /// Sets up the channel. /// - /// Enabled the channel and configures the assigned event and task. + /// Enables the channel and configures the assigned event and task. pub fn setup<'a, E, T>(self, event: &'a E, task: &'a T) -> EtmConfiguredChannel<'a, E, T, C> where E: EtmEvent, @@ -153,7 +153,7 @@ fn disable_channel(channel: u8) { } } -/// A readily configured channel +/// A readily configured channel. /// /// The channel is enabled and event and task are configured. #[non_exhaustive] @@ -183,7 +183,7 @@ macro_rules! create_etm { paste::paste! { /// ETM Instance /// - /// Provides access to all the [EtmChannel] + /// Provides access to all the [`EtmChannel`]. pub struct Etm<'d> { _peripheral: crate::peripherals::ETM<'d>, $( diff --git a/esp-hal/src/flash/cache.rs b/esp-hal/src/flash/cache.rs new file mode 100644 index 00000000000..8426b190140 --- /dev/null +++ b/esp-hal/src/flash/cache.rs @@ -0,0 +1,244 @@ +//! Cache suspend and resume around ROM flash operations. +//! +//! Dropping cache lines for a flash range needs the MMU table and lives in +//! [`super::mmu`] instead. + +use procmacros::ram; + +/// Suspends the flash-backed caches for the duration of a ROM flash operation. +pub(super) struct CacheGuard { + inner: Inner, + // Fields drop after `Drop::drop`, so the predictor turns on after the caches resume. + #[cfg(soc_cpu_has_branch_predictor)] + _predictor: crate::soc::branch_predictor::DisabledBranchPredictor, +} + +cfg_select! { + esp32 => { + struct Inner { + pro: bool, + app: bool, + } + } + any(esp32s2, esp32s3) => { + struct Inner { + icache: u32, + dcache: u32, + } + } + esp32p4 => { + // External flash/PSRAM is served by L2. L1 caches internal RAM; suspending + // it stalls instruction fetch from IRAM (`#[ram]`). + struct Inner { + l2: u32, + } + } + any(esp32h4, esp32s31) => { + struct Inner { + i0: u32, + i1: u32, + d: u32, + } + } + _ => { + struct Inner { + autoload: u32, + } + } +} + +impl CacheGuard { + /// Disable the branch predictor (it issues cache requests) and suspend the + /// external-memory caches. + #[ram] + pub(super) fn suspend() -> Self { + #[cfg(soc_cpu_has_branch_predictor)] + let _predictor = crate::soc::branch_predictor::DisabledBranchPredictor::new(); + + let inner = suspend_caches(); + Self { + inner, + #[cfg(soc_cpu_has_branch_predictor)] + _predictor, + } + } + + /// Flush every line. Must run while the caches are still off. + #[cfg(esp32)] + #[ram] + pub(super) fn flush_while_off(&self) { + unsafe { + if self.inner.pro { + Cache_Flush_rom(0); + } + if self.inner.app { + Cache_Flush_rom(1); + } + } + } +} + +impl Drop for CacheGuard { + #[ram] + fn drop(&mut self) { + resume_caches(&self.inner); + } +} + +unsafe extern "C" { + cfg_select! { + esp32 => { + fn Cache_Flush_rom(cpu: u32); + } + any(esp32s2, esp32s3) => { + fn Cache_Suspend_ICache() -> u32; + fn Cache_Suspend_DCache() -> u32; + fn Cache_Resume_ICache(autoload: u32); + fn Cache_Resume_DCache(autoload: u32); + } + esp32p4 => { + fn Cache_Suspend_L2_Cache() -> u32; + fn Cache_Resume_L2_Cache(autoload: u32); + } + esp32s31 => { + fn Cache_Suspend_L1_CORE0_ICache() -> u32; + fn Cache_Suspend_L1_CORE1_ICache() -> u32; + fn Cache_Suspend_L1_DCache() -> u32; + fn Cache_Resume_L1_CORE0_ICache(autoload: u32); + fn Cache_Resume_L1_CORE1_ICache(autoload: u32); + fn Cache_Resume_L1_DCache(autoload: u32); + } + // `map`: bit 0 is ICache0, bit 1 is ICache1, bit 4 is DCache, see + // https://github.com/espressif/esp-idf/blob/188e3e55bb20505b5fa9dc49ee390bf42c58b4ee/components/esp_rom/esp32h4/include/esp32h4/rom/cache.h#L162-L164 + esp32h4 => { + fn Cache_Suspend_Cache(map: u32) -> u32; + fn Cache_Resume_Cache(map: u32, autoload: u32); + } + any(esp32c5, esp32c61) => { + fn Cache_Suspend_Cache() -> u32; + fn Cache_Resume_Cache(autoload: u32); + } + any(esp32c2, esp32c3, esp32c6, esp32h2) => { + fn Cache_Suspend_ICache() -> u32; + fn Cache_Resume_ICache(autoload: u32); + } + _ => { + compile_error!("missing flash cache ROM bindings for this chip"); + } + } +} + +#[ram] +fn suspend_caches() -> Inner { + cfg_select! { + esp32 => { + use crate::peripherals::DPORT; + let dport = DPORT::regs(); + let pro = dport.pro_cache_ctrl().read().pro_cache_enable().bit(); + let app = dport.app_cache_ctrl().read().app_cache_enable().bit(); + // A cache must be idle before it is turned off, see `cache_ll_l1_disable_cache()`. + if pro { + while dport.pro_dcache_dbug0().read().pro_cache_state().bits() != 1 {} + dport + .pro_cache_ctrl() + .modify(|_, w| w.pro_cache_enable().clear_bit()); + } + if app { + while dport.app_dcache_dbug0().read().app_cache_state().bits() != 1 {} + dport + .app_cache_ctrl() + .modify(|_, w| w.app_cache_enable().clear_bit()); + } + // Complete the writes above before the flash MMU is written. + let _ = dport.pro_cache_ctrl().read(); + Inner { pro, app } + } + any(esp32s2, esp32s3) => { + #[cfg(esp32s3)] + use crate::peripherals::EXTMEM; + unsafe { + let icache = Cache_Suspend_ICache(); + // ROM `Cache_Suspend_I/DCache` on ESP32-S3 does not wait until + // the cache FSM is idle (`ESP_ROM_HAS_CACHE_SUSPEND_WAITI_BUG`). + #[cfg(esp32s3)] + while EXTMEM::regs().cache_state().read().icache_state().bits() != 1 {} + let dcache = Cache_Suspend_DCache(); + #[cfg(esp32s3)] + while EXTMEM::regs().cache_state().read().dcache_state().bits() != 1 {} + Inner { icache, dcache } + } + } + esp32p4 => unsafe { + Inner { + l2: Cache_Suspend_L2_Cache(), + } + }, + esp32s31 => unsafe { + Inner { + i0: Cache_Suspend_L1_CORE0_ICache(), + i1: Cache_Suspend_L1_CORE1_ICache(), + d: Cache_Suspend_L1_DCache(), + } + }, + // Same order as `cache_ll_suspend_cache()`, see + // https://github.com/espressif/esp-idf/blob/188e3e55bb20505b5fa9dc49ee390bf42c58b4ee/components/esp_hal_cache/esp32h4/include/hal/cache_ll.h#L295-L311 + esp32h4 => unsafe { + Inner { + i0: Cache_Suspend_Cache(1 << 0), + i1: Cache_Suspend_Cache(1 << 1), + d: Cache_Suspend_Cache(1 << 4), + } + }, + any(esp32c5, esp32c61) => unsafe { + Inner { + autoload: Cache_Suspend_Cache(), + } + }, + _ => unsafe { + Inner { + autoload: Cache_Suspend_ICache(), + } + }, + } +} + +#[ram] +fn resume_caches(inner: &Inner) { + cfg_select! { + esp32 => { + use crate::peripherals::DPORT; + let dport = DPORT::regs(); + if inner.pro { + dport + .pro_cache_ctrl() + .modify(|_, w| w.pro_cache_enable().set_bit()); + } + if inner.app { + dport + .app_cache_ctrl() + .modify(|_, w| w.app_cache_enable().set_bit()); + } + // The caller returns to flash right away, so make sure that the cache is on again + // before the next instruction is fetched: reading the register back completes the + // write. + let _ = dport.pro_cache_ctrl().read(); + } + any(esp32s2, esp32s3) => unsafe { + Cache_Resume_DCache(inner.dcache); + Cache_Resume_ICache(inner.icache); + }, + esp32p4 => unsafe { Cache_Resume_L2_Cache(inner.l2) }, + esp32s31 => unsafe { + Cache_Resume_L1_DCache(inner.d); + Cache_Resume_L1_CORE1_ICache(inner.i1); + Cache_Resume_L1_CORE0_ICache(inner.i0); + }, + esp32h4 => unsafe { + Cache_Resume_Cache(1 << 4, inner.d); + Cache_Resume_Cache(1 << 0, inner.i0); + Cache_Resume_Cache(1 << 1, inner.i1); + }, + any(esp32c5, esp32c61) => unsafe { Cache_Resume_Cache(inner.autoload) }, + _ => unsafe { Cache_Resume_ICache(inner.autoload) }, + } +} diff --git a/esp-hal/src/flash/mmu.rs b/esp-hal/src/flash/mmu.rs new file mode 100644 index 00000000000..90ba1b3552d --- /dev/null +++ b/esp-hal/src/flash/mmu.rs @@ -0,0 +1,669 @@ +//! Flash MMU access. +//! +//! Everything that has to know which flash is mapped where: dropping the cache +//! lines of a written flash range ([`invalidate_mapped`]), and the temporary +//! mappings that let [`read_flash_encrypted`] read decrypted flash through the +//! cache. Suspending the caches themselves is [`super::cache`]'s job. +//! +//! Nothing here runs with the cache suspended, so these helpers live in flash. +//! The two ESP32 exceptions "writing the MMU table and flushing the cache" +//! are confined to [`esp32_cache`]. + +use core::{ops::Range, ptr}; + +use super::Error; + +/// Guard for a temporarily mapped flash MMU page. +struct FlashMmapGuard { + entry_id: u32, + vaddr: *const u8, + #[cfg_attr( + esp32, + expect(dead_code, reason = "the ESP32 can only flush the whole cache") + )] + page_size: u32, + /// When `false` the entry was already mapped and must not be invalidated. + owned: bool, +} + +impl FlashMmapGuard { + /// A slot this driver mapped itself, and has to unmap again. + fn new_owned(entry_id: u32, vaddr: *const u8, page_size: u32) -> Self { + Self { + entry_id, + vaddr, + page_size, + owned: true, + } + } +} + +/// Map a flash physical address to a virtual address for encrypted reading. +/// +/// The returned mapping is ready to be read through: a temporary slot can +/// retain cache lines from its previous mapping, so the complete mapping is +/// invalidated before this function returns. +fn map_flash_page(paddr: u32) -> Result { + let page_size = mmu_page_size(); + let page_paddr = paddr & !(page_size - 1); + + if let Some(entry_id) = find_existing_entry(page_paddr) { + let vaddr = entry_id_to_vaddr(entry_id).ok_or(Error::NotSupported)?; + invalidate_cache(vaddr as u32, page_size); + return Ok(FlashMmapGuard { + entry_id, + vaddr, + page_size, + owned: false, + }); + } + + // The virtual address is resolved before the entry is written, so a slot + // without one is never left behind mapped. + cfg_select! { + esp32s2 => { + let entry_id = s2::alloc_entry().ok_or(Error::NotSupported)?; + let vaddr = s2::map_entry(entry_id, page_paddr)?; + Ok(FlashMmapGuard::new_owned(entry_id, vaddr, page_size)) + } + esp32 => { + let entry_id = find_free_entry().ok_or(Error::NotSupported)?; + let vaddr = entry_id_to_vaddr(entry_id).ok_or(Error::NotSupported)?; + // Writing the entry and making it visible to the cache must happen + // in one cache-off window. The register is looked up before that + // window: the bounds check of the lookup can call into flash. + esp32_cache::map_entry(table::entry(entry_id), page_paddr); + Ok(FlashMmapGuard::new_owned(entry_id, vaddr, page_size)) + } + _ => { + let entry_id = find_free_entry().ok_or(Error::NotSupported)?; + let vaddr = entry_id_to_vaddr(entry_id).ok_or(Error::NotSupported)?; + write_flash_entry(entry_id, page_paddr); + invalidate_cache(vaddr as u32, page_size); + Ok(FlashMmapGuard::new_owned(entry_id, vaddr, page_size)) + } + } +} + +/// Unmap a temporarily mapped flash page and invalidate the cache. +fn unmap_flash_page(guard: FlashMmapGuard) { + cfg_select! { + esp32 => { + esp32_cache::unmap_entry(guard.owned.then(|| table::entry(guard.entry_id))); + } + _ => { + invalidate_cache(guard.vaddr as u32, guard.page_size); + if guard.owned { + set_entry_invalid(guard.entry_id); + } + } + } +} + +/// Read decrypted flash bytes via temporary MMU mappings. +/// +/// The cache must stay on. Callers park the other core and disable interrupts. +pub(super) fn read_flash_encrypted(offset: u32, data: &mut [u32]) -> Result<(), Error> { + if data.is_empty() { + return Ok(()); + } + + let bytes = unsafe { + core::slice::from_raw_parts_mut( + data.as_mut_ptr().cast::(), + data.len() * super::WORD_SIZE as usize, + ) + }; + + let page_size = mmu_page_size(); + let mut remaining = bytes; + let mut current_offset = offset; + + while !remaining.is_empty() { + let page_base = current_offset & !(page_size - 1); + let in_page = (current_offset - page_base) as usize; + let chunk = remaining.len().min(page_size as usize - in_page); + + let guard = map_flash_page(page_base)?; + let src = unsafe { guard.vaddr.add(in_page) }; + unsafe { + ptr::copy_nonoverlapping(src, remaining.as_mut_ptr(), chunk); + } + unmap_flash_page(guard); + + current_offset += chunk as u32; + remaining = &mut remaining[chunk..]; + } + + Ok(()) +} + +/// Drop the cache lines covering `vaddr..vaddr + size`. +/// +/// Both users invalidate flash that may be mapped as code as well as data, so +/// every cache that can hold the line is included. +#[cfg(not(any(esp32, esp32h4, esp32p4, esp32s31)))] +fn invalidate_cache(vaddr: u32, size: u32) { + unsafe { crate::soc::cache_invalidate_addr(vaddr, size) } +} + +// Not `soc::cache_invalidate_addr`: it only covers the L1 D-cache (plus L2 on +// the P4) for DMA buffers, while flash is also cached by the L1 I-caches. On +// the P4, adding `soc::cache_invalidate_icache_addr` would invalidate L2 twice. +#[cfg(any(esp32h4, esp32p4, esp32s31))] +fn invalidate_cache(vaddr: u32, size: u32) { + const CACHE_MAP_L1_ICACHE_0: u32 = 1 << 0; + const CACHE_MAP_L1_ICACHE_1: u32 = 1 << 1; + const CACHE_MAP_L1_DCACHE: u32 = 1 << 4; + #[cfg(esp32p4)] + const CACHE_MAP_L2_CACHE: u32 = 1 << 5; + + // IROM and DROM share the same window on the P4, which also needs L2. + let map = CACHE_MAP_L1_ICACHE_0 | CACHE_MAP_L1_ICACHE_1 | CACHE_MAP_L1_DCACHE; + #[cfg(esp32p4)] + let map = map | CACHE_MAP_L2_CACHE; + + unsafe extern "C" { + fn Cache_Invalidate_Addr(map: u32, addr: u32, size: u32); + } + unsafe { + Cache_Invalidate_Addr(map, vaddr, size); + } +} + +#[cfg(esp32)] +fn invalidate_cache(_vaddr: u32, _size: u32) { + // The ESP32 cache cannot invalidate a single address range, so the whole cache is flushed. + esp32_cache::flush_caches(); +} + +/// Drop cache lines that map `start..start+len` after the caches are back on. +/// +/// IDF invalidates in this order (`spi_flash_check_and_flush_cache` after the +/// operation's cache-restore path). ESP32 cannot invalidate by address and +/// flushes while still off instead. +#[cfg(not(esp32))] +pub(super) fn invalidate_mapped(start: u32, len: u32) { + if len == 0 { + return; + } + + let page_size = mmu_page_size(); + let end = start.saturating_add(len); + let mut addr = start & !(page_size - 1); + + while addr < end { + invalidate_mapped_page(addr, page_size); + addr = addr.saturating_add(page_size); + } +} + +/// Drop cache lines for every MMU entry that maps `page_paddr`. +/// +/// One physical page can appear more than once. On C2, C3, and S3 the same +/// entry is also visible through a separate I-bus window, so both vaddrs are +/// invalidated. +#[cfg(not(esp32))] +fn invalidate_mapped_page(page_paddr: u32, page_size: u32) { + let page = flash_page_number(page_paddr); + + for entry_id in all_entries() { + if entry_is_valid(entry_id) + && entry_is_flash_mapping(entry_id) + && entry_flash_page(entry_id) == page + { + invalidate_entry_caches(entry_id, page_size); + } + } +} + +#[cfg(not(esp32))] +fn invalidate_entry_caches(entry_id: u32, page_size: u32) { + cfg_select! { + esp32s2 => { + if let Some(vaddr) = entry_id_to_vaddr(entry_id) { + invalidate_cache(vaddr as u32, page_size); + } + } + _ => { + let offset = entry_id * page_size; + let drom = memory_range!("DROM").start as u32 + offset; + let irom = memory_range!("IROM").start as u32 + offset; + invalidate_cache(drom, page_size); + if irom != drom { + invalidate_cache(irom, page_size); + } + } + } +} + +/// Virtual address an MMU entry maps to, if it is reachable through a data bus. +fn entry_id_to_vaddr(entry_id: u32) -> Option<*const u8> { + cfg_select! { + esp32s2 => s2::entry_id_to_vaddr(entry_id), + _ => { + let base = memory_range!("DROM").start as u32; + Some((base + entry_id * mmu_page_size()) as *const u8) + } + } +} + +fn find_existing_entry(page_paddr: u32) -> Option { + let page = flash_page_number(page_paddr); + + data_entries().find(|&entry_id| { + entry_is_valid(entry_id) + && entry_is_flash_mapping(entry_id) + && entry_flash_page(entry_id) == page + }) +} + +fn find_free_entry() -> Option { + let entries = data_entries(); + // Skip the last entry reserved for bootloader internal flash access. + (entries.start..entries.end.saturating_sub(1)) + .rev() + .find(|&entry_id| !entry_is_valid(entry_id)) +} + +/// The entries that map the data (DROM) window, in address order. +pub(super) fn drom_entries() -> Range { + cfg_select! { + // DROM0 is served by IBUS2. The data buses after it map other windows. + esp32s2 => s2::DATA_ENTRY_START..s2::IBUS_ENTRY_END, + _ => data_entries(), + } +} + +/// The flash offset that a DROM entry maps, or `None` when the entry is +/// outside the DROM window, invalid, or maps PSRAM. +pub(super) fn drom_entry_offset(entry_id: u32) -> Option { + (drom_entries().contains(&entry_id) + && entry_is_valid(entry_id) + && entry_is_flash_mapping(entry_id)) + .then(|| entry_flash_page(entry_id) * mmu_page_size()) +} + +/// Entries that can back a temporary mapping and be read through as data. +fn data_entries() -> Range { + cfg_select! { + not(soc_has_mmu_table) => 0..property!("mmu.entry_num"), + esp32s2 => s2::DATA_ENTRY_START..s2::DATA_ENTRY_END, + // The table peripheral bounds the usable entry ids: `mmu.entry_num` + // counts logical entries across every bus and indexes out of range on + // the ESP32, whose table exposes its 64 DROM0 slots only. + _ => 0..table::entry_count(), + } +} + +/// Every entry that can map flash, including windows that only serve code. +#[cfg(not(esp32))] +fn all_entries() -> Range { + cfg_select! { + // Include the S2 I-bus slots (0..0x80). Skip DBUS2/DPORT (0x140..). + esp32s2 => 0..s2::DATA_ENTRY_END, + _ => data_entries(), + } +} + +fn mmu_page_size() -> u32 { + cfg_select! { + not(soc_has_mmu_table) => indexed::mmu_page_size(), + // The C2 page size is configurable (IDF `mmu_ll_get_page_size`). + esp32c2 => c2::mmu_page_size(), + _ => property!("mmu.page_size"), + } +} + +/// Inlined so that the ESP32 can call it from its cache-off window. +#[inline(always)] +fn flash_page_number(page_paddr: u32) -> u32 { + cfg_select! { + not(soc_has_mmu_table) => indexed::flash_page_number(page_paddr), + esp32c2 => page_paddr >> c2::mmu_page_size().trailing_zeros(), + _ => page_paddr >> 16, + } +} + +fn entry_is_valid(entry_id: u32) -> bool { + cfg_select! { + not(soc_has_mmu_table) => indexed::entry_is_valid(entry_id), + _ => table::entry_is_valid(entry_id), + } +} + +fn entry_is_flash_mapping(entry_id: u32) -> bool { + cfg_select! { + not(soc_has_mmu_table) => indexed::entry_is_flash_mapping(entry_id), + _ => table::entry_is_flash_mapping(entry_id), + } +} + +fn entry_flash_page(entry_id: u32) -> u32 { + cfg_select! { + not(soc_has_mmu_table) => indexed::entry_flash_page(entry_id), + _ => table::entry_flash_page(entry_id), + } +} + +/// The ESP32 writes its entries inside a cache-off window instead. +#[cfg(not(any(esp32, esp32s2)))] +fn write_flash_entry(entry_id: u32, page_paddr: u32) { + cfg_select! { + not(soc_has_mmu_table) => indexed::write_flash_entry(entry_id, page_paddr), + _ => table::write_flash_entry(entry_id, page_paddr), + } +} + +/// The ESP32 invalidates its entries inside a cache-off window instead. +#[cfg(not(esp32))] +fn set_entry_invalid(entry_id: u32) { + cfg_select! { + not(soc_has_mmu_table) => indexed::set_entry_invalid(entry_id), + _ => table::set_entry_invalid(entry_id), + } +} + +#[cfg(not(soc_has_mmu_table))] +mod indexed { + use crate::peripherals::SPI0; + + pub(super) fn mmu_page_size() -> u32 { + let code = mmu_page_size_code(); + cfg_select! { + // The S31 flash MMU's maximum page size is 256 KiB. + esp32s31 => 0x40000 >> code, + _ => 0x10000 >> code, + } + } + + fn mmu_page_size_code() -> u32 { + let ctrl = SPI0::regs().mmu_power_ctrl().read(); + cfg_select! { + any(esp32c5, esp32c61, esp32s31) => ctrl.mmu_page_size().bits() as u32, + _ => ctrl.spi_mmu_page_size().bits() as u32, + } + } + + pub(super) fn flash_page_number(page_paddr: u32) -> u32 { + page_paddr >> mmu_page_size().trailing_zeros() + } + + fn with_entry(entry_id: u32, f: impl FnOnce() -> R) -> R { + SPI0::regs() + .mmu_item_index() + .write(|w| unsafe { w.mmu_item_index().bits(entry_id) }); + f() + } + + pub(super) fn entry_is_valid(entry_id: u32) -> bool { + with_entry(entry_id, || { + SPI0::regs().mmu_item_content().read().valid().bit() + }) + } + + pub(super) fn entry_is_flash_mapping(entry_id: u32) -> bool { + cfg_select! { + any(esp32c5, esp32c61, esp32h4) => with_entry(entry_id, || { + !SPI0::regs().mmu_item_content().read().access_spiram().bit() + }), + _ => { + let _ = entry_id; + true + } + } + } + + pub(super) fn entry_flash_page(entry_id: u32) -> u32 { + with_entry(entry_id, || { + SPI0::regs().mmu_item_content().read().paddr().bits() as u32 + }) + } + + pub(super) fn write_flash_entry(entry_id: u32, page_paddr: u32) { + let page = super::flash_page_number(page_paddr) as u16; + let encrypted = crate::efuse::flash_encryption(); + with_entry(entry_id, || { + SPI0::regs().mmu_item_content().write(|w| { + unsafe { w.paddr().bits(page) }; + #[cfg(any(esp32c5, esp32c61, esp32h4))] + w.access_spiram().clear_bit(); + w.valid().set_bit(); + if encrypted { + w.sensitive().set_bit(); + } + w + }); + }); + } + + pub(super) fn set_entry_invalid(entry_id: u32) { + with_entry(entry_id, || SPI0::regs().mmu_item_content().reset()); + } +} + +#[cfg(soc_has_mmu_table)] +mod table { + use crate::{pac::mmu_table::ENTRY, peripherals::MMU_TABLE}; + + /// Look up one MMU entry. + /// + /// The ESP32 looks the entry up before it turns the cache off: the bounds + /// check of the lookup can call into flash, which is unreachable then. + #[inline(always)] + pub(super) fn entry(entry_id: u32) -> &'static ENTRY { + MMU_TABLE::regs().entry(entry_id as usize) + } + + pub(super) fn entry_is_valid(entry_id: u32) -> bool { + !entry(entry_id).read().invalid().bit() + } + + pub(super) fn entry_is_flash_mapping(entry_id: u32) -> bool { + let e = entry(entry_id).read(); + cfg_select! { + esp32s2 => e.access_flash().bit(), + esp32s3 => !e.access_spiram().bit(), + _ => { + let _ = e; + true + } + } + } + + pub(super) fn entry_flash_page(entry_id: u32) -> u32 { + entry(entry_id).read().paddr().bits() as u32 + } + + // The ESP32 calls the two functions below with the cache off, where a call into flash would + // hang. Inlining them into the caller in RAM keeps them reachable. + #[cfg(not(esp32s2))] + #[inline(always)] + pub(super) fn write_entry(entry: &ENTRY, page_paddr: u32) { + let page = super::flash_page_number(page_paddr) as u16; + entry.write(|w| { + cfg_select! { + any(esp32, esp32c2, esp32c3) => unsafe { w.paddr().bits(page as u8) }, + _ => unsafe { w.paddr().bits(page) }, + }; + w.invalid().clear_bit(); + #[cfg(all(soc_has_psram, not(any(esp32, esp32s2))))] + w.access_spiram().clear_bit(); + w + }); + } + + #[inline(always)] + pub(super) fn invalidate_entry(entry: &ENTRY) { + entry.write(|w| w.invalid().set_bit()); + } + + #[cfg(not(any(esp32, esp32s2)))] + pub(super) fn write_flash_entry(entry_id: u32, page_paddr: u32) { + write_entry(entry(entry_id), page_paddr); + } + + #[cfg(not(esp32))] + pub(super) fn set_entry_invalid(entry_id: u32) { + invalidate_entry(entry(entry_id)); + } + + /// The S2 derives its range from the bus layout instead. + #[cfg(not(esp32s2))] + pub(super) fn entry_count() -> u32 { + MMU_TABLE::regs().entry_iter().count() as u32 + } +} + +/// Flash MMU and cache maintenance for the ESP32. +/// +/// The ESP32 cache must be off while the flash MMU is written or the cache is +/// flushed. Both operations disturb a cache fill that runs at the same time, +/// and the core that waits for the fill then hangs. ESP-IDF turns the cache +/// off around both operations, see `s_do_mapping()` in +/// `components/esp_mm/esp_mmu_map.c`. +/// +/// Everything that runs inside the cache-off window must be reachable without +/// flash: the `#[ram]` entry points below only call `#[ram]` guard methods and +/// helpers that are inlined into them. +#[cfg(esp32)] +mod esp32_cache { + use procmacros::ram; + + use super::table; + use crate::{flash::cache::CacheGuard, pac::mmu_table::ENTRY}; + + /// Map `page_paddr` into `entry` and make the new mapping visible. + #[ram] + pub(super) fn map_entry(entry: &ENTRY, page_paddr: u32) { + let cache = CacheGuard::suspend(); + table::write_entry(entry, page_paddr); + cache.flush_while_off(); + } + + /// Drop the lines of a temporary mapping and invalidate its entry, if we own it. + #[ram] + pub(super) fn unmap_entry(owned_entry: Option<&ENTRY>) { + let cache = CacheGuard::suspend(); + if let Some(entry) = owned_entry { + table::invalidate_entry(entry); + } + cache.flush_while_off(); + } + + /// Drop every cached line. + #[ram] + pub(super) fn flush_caches() { + let cache = CacheGuard::suspend(); + cache.flush_while_off(); + } +} + +#[cfg(esp32c2)] +mod c2 { + use crate::peripherals::EXTMEM; + + /// 0 = 16 KiB, 1 = 32 KiB, 2 = 64 KiB (`EXTMEM_CACHE_MMU_PAGE_SIZE`). + pub(super) fn mmu_page_size() -> u32 { + match EXTMEM::regs() + .cache_conf_misc() + .read() + .cache_mmu_page_size() + .bits() + { + 0 => 0x4000, + 1 => 0x8000, + _ => 0x10000, + } + } +} + +#[cfg(esp32s2)] +mod s2 { + use procmacros::ram; + + use super::*; + + pub(super) const DATA_ENTRY_START: u32 = 0x200 / 4; + pub(super) const DATA_ENTRY_END: u32 = 0x500 / 4; + pub(super) const IBUS_ENTRY_END: u32 = 0x300 / 4; + + /// Virtual address for an S2 MMU entry. + /// + /// Matches `mmu_ll_entry_id_to_vaddr_base()`: IBUS0/1 at 0x4000_0000, + /// DROM/DBUS at 0x3F00_0000. DBUS2/DPORT (0x140..) is 32-bit access only + /// and has no usable base here. + pub(super) fn entry_id_to_vaddr(entry_id: u32) -> Option<*const u8> { + let page_size = mmu_page_size(); + let (base, relative) = match entry_id { + 0x00..0x40 => (0x4000_0000u32, entry_id), + 0x40..0x80 => (0x4000_0000u32, entry_id - 0x40), + 0x80..0xC0 => (0x3F00_0000u32, entry_id - 0x80), + 0xC0..0x100 => (0x3F00_0000u32, entry_id - 0xC0), + 0x100..0x140 => (0x3F00_0000u32, entry_id - 0x100), + _ => return None, + }; + Some((base + relative * page_size) as *const u8) + } + + /// Pick a free MMU slot, preferring IBUS2/DROM entries first. + /// + /// Only data-bus entries are considered: on ESP32-S2, DROM (entries + /// 128..192) is backed by the I-cache bus (`drom0_in_icache = 1` in + /// ESP-IDF) but is addressed through 0x3F00_0000, while IBUS0/1 is not + /// reachable with 8-bit loads. + pub(super) fn alloc_entry() -> Option { + (DATA_ENTRY_START..IBUS_ENTRY_END - 1) + .rev() + .find(|&entry_id| !entry_is_valid(entry_id)) + .or_else(find_free_entry) + } + + fn entry_uses_ibus(entry_id: u32) -> bool { + (DATA_ENTRY_START..IBUS_ENTRY_END).contains(&entry_id) + } + + #[ram] + fn mmu_rom_set(entry_id: u32, access: u32, vaddr: u32, paddr: u32) -> i32 { + unsafe extern "C" { + fn Cache_Ibus_MMU_Set( + ext_ram: u32, + vaddr: u32, + paddr: u32, + psize: u32, + num: u32, + fixed: u32, + ) -> i32; + fn Cache_Dbus_MMU_Set( + ext_ram: u32, + vaddr: u32, + paddr: u32, + psize: u32, + num: u32, + fixed: u32, + ) -> i32; + } + + unsafe { + if entry_uses_ibus(entry_id) { + Cache_Ibus_MMU_Set(access, vaddr, paddr, 64, 1, 0) + } else { + Cache_Dbus_MMU_Set(access, vaddr, paddr, 64, 1, 0) + } + } + } + + /// Map an MMU entry to a flash page via ROM (must run from IRAM on ESP32-S2). + #[ram] + pub(super) fn map_entry(entry_id: u32, page_paddr: u32) -> Result<*const u8, Error> { + let vaddr = entry_id_to_vaddr(entry_id).ok_or(Error::NotSupported)?; + let page_size = mmu_page_size(); + let vaddr_u32 = vaddr as u32; + invalidate_cache(vaddr_u32, page_size); + if mmu_rom_set(entry_id, 1 << 15, vaddr_u32, page_paddr) != 0 { + return Err(Error::NotSupported); + } + invalidate_cache(vaddr_u32, page_size); + Ok(vaddr) + } +} diff --git a/esp-hal/src/flash/mod.rs b/esp-hal/src/flash/mod.rs new file mode 100644 index 00000000000..4db007c6c5c --- /dev/null +++ b/esp-hal/src/flash/mod.rs @@ -0,0 +1,973 @@ +#![cfg_attr(docsrs, procmacros::doc_replace)] +//! # Internal SPI Flash (FLASH) +//! +//! ## Overview +//! +//! Provides blocking access to the attached SPI flash memory. The driver owns +//! the virtual [`FLASH`] peripheral. +//! +//! Write and erase are NOR flash operations: bits change only from 1 to 0 +//! without an erase. The driver does not perform read-modify-write. +//! [`Flash::read`] and [`Flash::write`] take word slices (`&[u32]`) and a +//! 4-byte-aligned byte offset. The buffer must reside in DRAM. +//! [`Flash::erase`] operates on 4096-byte sectors. +//! +//! [`Flash::read_encrypted`] and [`Flash::write_encrypted`] provide transparent +//! flash encryption. Encrypted writes require a 16-byte-aligned address and a +//! length that is a multiple of 16 bytes (4 words). The destination must already +//! be erased, and bytes outside the requested range are not programmed. +//! Encrypted reads return plaintext if flash encryption is disabled. +//! +//! For more information, see the +#![doc = concat!("[ESP-IDF documentation](https://docs.espressif.com/projects/esp-idf/en/latest/", chip!(), "/api-reference/peripherals/spi_flash/index.html)")] +//! ## Configuration +//! +//! On a dual-core chip, [`Config`] selects the strategy for the other core. +//! +//! ## Usage +//! +//! Construct [`Flash`] from the virtual [`FLASH`] peripheral. `offset` is a +//! flash byte address, not a word index. The driver does not implement traits +//! from `embedded-storage`; higher layers provide partition management and +//! storage trait implementations. +//! +//! ## Examples +//! +//! ### Read a word-aligned range +//! +//! ```rust, no_run +//! # {before_snippet} +//! use esp_hal::flash::{Config, Flash}; +//! +//! let mut flash = Flash::new(peripherals.FLASH, Config::default())?; +//! let mut buf = [0u32; 8]; +//! flash.read(0x10_020, &mut buf)?; +//! # {after_snippet} +//! ``` +//! +//! ## Implementation State +#![cfg_attr( + esp32, + doc = "- On ESP32, a second-stage bootloader must identify the flash chip; the ROM does not. + [`Flash::new`] fails with [`ConfigError::UnknownFlashChip`] if identification is missing + (including the ROM placeholder ID `0x001540EF`, a valid W25Q16 ID on other chips)." +)] +//! - Driver bounds checks use the JEDEC density from the ROM-cached device ID. ROM operations also +//! check the ROM-cached chip size, which a bootloader can set from the application image header. +//! An operation within [`Flash`] capacity can still fail in the ROM if the ROM-cached size is +//! smaller. +//! - Operations do not check whether the target flash range is mapped. Writing or erasing a mapped +//! section (such as `.text` or `.rodata`) can corrupt running code or immutable data. +//! - Each [`Flash::read`] or [`Flash::write`] call executes one ROM operation. The flash cache +//! stays off for the whole transfer. Split a large transfer when latency matters. +//! - On a dual-core chip, the multi-core strategy controls the other core for every operation, +//! including a read. + +use core::marker::PhantomData; + +use procmacros::{BuilderLite, ram}; +#[cfg(xtensa)] +use xtensa_lx::interrupt::free; + +#[cfg(not(xtensa))] +use crate::interrupt::free; +use crate::{Blocking, DriverMode, peripherals::FLASH, soc::is_slice_in_dram}; + +mod cache; +mod mmu; +mod rom; + +/// Word size required by the read and write paths, in bytes. +const WORD_SIZE: u32 = 4; +/// Program page size in bytes. +const PAGE_SIZE: u32 = 256; +/// Erase sector size in bytes. +const SECTOR_SIZE: u32 = 4096; +/// Erase block size in bytes. +const BLOCK_SIZE: u32 = 65536; +/// Flash-encryption AES block size, and the public encrypted-write alignment. +const ENCRYPT_BLOCK_SIZE: u32 = 16; +/// ESP32 ROM encrypted-write row (two AES blocks that share a tweak). +#[cfg(esp32)] +const ESP32_ENCRYPT_ROW: u32 = 32; + +/// Flash driver configuration. +#[instability::unstable] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, BuilderLite)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[non_exhaustive] +pub struct Config { + /// Strategy for the other core during flash operations. + /// + /// [`MultiCoreStrategy::ignore`] is safe only when the other core cannot + /// fetch from flash during the operation. + #[doc = cfg_select! { + feature = "rt" => "\n\nDefault: [`MultiCoreStrategy::AutoPark`].", + _ => "\n\nDefault: [`MultiCoreStrategy::Error`].", + }] + #[cfg(multi_core)] + #[builder_lite(unstable)] + multi_core_strategy: MultiCoreStrategy, +} + +/// Strategy for the other core during flash operations. +#[cfg(multi_core)] +#[instability::unstable] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[non_exhaustive] +pub enum MultiCoreStrategy { + /// Returns [`Error::OtherCoreRunning`] if the other core is running. + #[cfg_attr(not(feature = "rt"), default)] + Error, + /// Posts an IPC function on the other core for the operation. + /// + /// The function runs from RAM. The function masks interrupts on that core and waits until + /// the operation finishes. The operation waits until that core enters the function. A core + /// that does not take the IPC interrupt delays the operation. + /// + /// If [`crate::system::CpuControl`] did not start the APP core, the CPU-control registers + /// stall that core instead. + #[cfg(feature = "rt")] + #[cfg_attr(docsrs, doc(cfg(feature = "rt")))] + #[default] + AutoPark, + /// Does not check or stop the other core. + /// + /// Construct with [`Self::ignore`]. + Ignore(IgnoreMarker), +} + +/// Marker so [`MultiCoreStrategy::Ignore`] can only be built via +/// [`MultiCoreStrategy::ignore`]. +#[cfg(multi_core)] +#[doc(hidden)] +#[instability::unstable] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub struct IgnoreMarker { + _private: (), +} + +#[cfg(multi_core)] +impl MultiCoreStrategy { + /// Creates a strategy that does not check or stop the other core. + /// + /// # Safety + /// + /// The other core must not fetch instructions or data from flash during any + /// operation, including reads. Flash-backed caches are unavailable while + /// an operation runs. + #[instability::unstable] + pub const unsafe fn ignore() -> Self { + Self::Ignore(IgnoreMarker { _private: () }) + } +} + +/// Error constructing or configuring the flash driver. +#[instability::unstable] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[non_exhaustive] +pub enum ConfigError { + /// The attached flash chip cannot be identified, or its size is not + /// recognized. + /// + /// This includes no-response JEDEC sentinels, an unrecognized density + /// byte, and the ESP32 ROM placeholder ID `0x001540EF` (the ROM does not + /// execute `RDID`; this value is a valid W25Q16 ID on other chips). + UnknownFlashChip, +} + +impl core::error::Error for ConfigError {} + +impl core::fmt::Display for ConfigError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::UnknownFlashChip => { + write!( + f, + "Flash chip could not be identified, or its size is not recognized" + ) + } + } + } +} + +/// Flash operation error. +#[instability::unstable] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[allow(clippy::enum_variant_names, reason = "matches ROM result / issue 6203")] +#[non_exhaustive] +pub enum Error { + /// I/O error reported by the ROM. + /// + /// Includes a ROM-side size check against its cached chip size when that + /// is smaller than [`Flash::capacity`]. + IoError, + /// Operation timed out. + IoTimeout, + /// Address or length is not aligned for this operation. + /// + /// [`Flash::read`], [`Flash::read_encrypted`], and [`Flash::write`] require a + /// 4-byte-aligned flash offset. [`Flash::write_encrypted`] requires a + /// 16-byte address and a word count that is a multiple of 4 (16 bytes). + /// [`Flash::erase`] requires a 4096-byte range. + NotAligned, + /// Address range exceeds [`Flash::capacity`], or `from > to`. + /// + /// Capacity is the JEDEC density, not the ROM cached chip size. An address + /// range within this limit can still fail in the ROM if the cached size is + /// smaller (often the image-header size on ESP32). + OutOfBounds, + /// Not supported in the current environment. + /// + /// Returned when the buffer is not in DRAM, when + /// [`Flash::write_encrypted`] is called while flash encryption is disabled, + /// or when [`Flash::read_encrypted`] cannot allocate an MMU entry. + NotSupported, + /// The other core is running and the configured strategy is + /// [`MultiCoreStrategy::Error`]. + #[cfg(multi_core)] + OtherCoreRunning, + /// Unexpected ROM status code (logged). + Unknown, +} + +impl core::error::Error for Error {} + +impl core::fmt::Display for Error { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::IoError => write!(f, "Flash I/O error"), + Self::IoTimeout => write!(f, "Flash I/O timed out"), + Self::NotAligned => write!(f, "Flash address or length is not aligned"), + Self::OutOfBounds => write!(f, "Flash range is out of bounds"), + Self::NotSupported => write!(f, "Flash operation is not supported"), + #[cfg(multi_core)] + Self::OtherCoreRunning => write!(f, "The other core is running"), + Self::Unknown => write!(f, "Unknown flash error"), + } + } +} + +/// Flash chip identification and geometry. +/// +/// `chip_id` contains the manufacturer ID in bits 23:16. Geometry is fixed at +/// 256-byte pages, 4096-byte sectors, and 64 KiB blocks; it is not probed from +/// the chip. +#[instability::unstable] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[non_exhaustive] +pub struct ChipInfo { + /// JEDEC ID with manufacturer ID in bits 23:16. + pub chip_id: u32, + /// JEDEC-decoded physical capacity in bytes. + /// + /// See [`Flash::capacity`]. + pub capacity: usize, + /// Erase sector size in bytes. + pub sector_size: u32, + /// Erase block size in bytes. + pub block_size: u32, + /// Program page size in bytes. + pub page_size: u32, +} + +/// Returns the flash MMU entries that map the data (DROM) window, in address +/// order. +/// +/// Entry `start` maps the window's first page and entry `end - 1` its last. +#[instability::unstable] +pub fn flash_mmu_drom_entries() -> core::ops::Range { + mmu::drom_entries() +} + +/// Returns the flash offset that the DROM entry `index` maps. +/// +/// Returns `None` when `index` is outside [`flash_mmu_drom_entries`], or when +/// the entry is invalid or maps PSRAM. +#[instability::unstable] +pub fn flash_mmu_entry_offset(index: u32) -> Option { + mmu::drom_entry_offset(index) +} + +/// Internal SPI flash driver. +/// +/// Constructible only in [`Blocking`] mode. +#[instability::unstable] +#[derive(Debug)] +pub struct Flash<'d, Dm: DriverMode> { + _flash: FLASH<'d>, + capacity: usize, + chip_id: u32, + #[cfg(multi_core)] + multi_core_strategy: MultiCoreStrategy, + _mode: PhantomData, +} + +impl<'d> Flash<'d, Blocking> { + /// Program page size in bytes. + #[instability::unstable] + pub const PAGE_SIZE: u32 = 256; + /// Erase sector size in bytes. + #[instability::unstable] + pub const SECTOR_SIZE: u32 = 4096; + /// Erase block size in bytes. + #[instability::unstable] + pub const BLOCK_SIZE: u32 = 65536; + + /// Creates a new flash driver from the [`FLASH`] peripheral. + /// + /// Capacity is determined from the JEDEC density in the ROM-cached device + /// ID, not the image-header size or the ROM cached chip size used by + /// read, write, and erase operations. + /// + /// # Errors + /// + /// - [`ConfigError::UnknownFlashChip`] if the attached flash chip cannot be identified or its + /// size is not recognized. On ESP32, this error also occurs when a second-stage bootloader + /// has not identified the chip (including the ROM placeholder ID `0x001540EF`). + #[instability::unstable] + pub fn new(flash: FLASH<'d>, config: Config) -> Result { + let raw_id = rom::cached_device_id(); + let capacity = rom::capacity_from_cached_id(raw_id)?; + let chip_id = raw_id & 0x00FF_FFFF; + #[cfg(not(multi_core))] + let _ = config; + + Ok(Self { + _flash: flash, + capacity, + chip_id, + #[cfg(multi_core)] + multi_core_strategy: config.multi_core_strategy, + _mode: PhantomData, + }) + } + + /// Applies a new configuration. + /// + /// Updates the multi-core strategy on dual-core chips. On single-core + /// chips, this is a no-op. The return type is reserved for future + /// configuration options. + #[instability::unstable] + pub fn apply_config(&mut self, config: &Config) -> Result<(), ConfigError> { + #[cfg(multi_core)] + { + self.multi_core_strategy = config.multi_core_strategy; + } + let _ = config; + Ok(()) + } + + /// Returns the JEDEC-decoded flash capacity in bytes. + /// + /// Driver bounds checks use this value. ROM read, write, and erase operations + /// also check the ROM-cached chip size, which a bootloader can set from the + /// application image header. + #[instability::unstable] + pub fn capacity(&self) -> usize { + self.capacity + } + + /// Returns chip identification and geometry. + /// + /// `chip_id` contains the manufacturer ID in bits 23:16. `capacity` is the + /// JEDEC density; see [`Self::capacity`]. Geometry is fixed, not probed + /// from the chip. + #[instability::unstable] + pub fn chip_info(&self) -> ChipInfo { + ChipInfo { + chip_id: self.chip_id, + capacity: self.capacity, + sector_size: SECTOR_SIZE, + block_size: BLOCK_SIZE, + page_size: PAGE_SIZE, + } + } + + /// Reads words into `data` starting at byte address `offset`. + /// + /// `offset` is a flash byte address and must be a multiple of 4. `data` + /// must reside in DRAM, not in flash, IRAM, RTC memory, or PSRAM. An empty + /// `data` slice only checks that `offset` is within [`Self::capacity`]. + /// + /// # Errors + /// + /// - [`Error::NotAligned`] if `data` is non-empty and `offset` is not a multiple of 4. + /// - [`Error::OutOfBounds`] if the range exceeds [`Self::capacity`]. + /// - [`Error::NotSupported`] if `data` is not in DRAM. + #[cfg_attr( + multi_core, + doc = "- [`Error::OtherCoreRunning`] on dual-core chips with [`MultiCoreStrategy::Error`]." + )] + /// - [`Error::IoError`], [`Error::IoTimeout`], or [`Error::Unknown`] if the ROM reports an I/O + /// error. + #[instability::unstable] + #[ram] + pub fn read(&mut self, offset: u32, data: &mut [u32]) -> Result<(), Error> { + let Some(len) = byte_len(data) else { + return Err(Error::OutOfBounds); + }; + if data.is_empty() { + return self.check_bounds(offset, 0); + } + + self.check_word_offset(offset)?; + self.check_bounds(offset, len)?; + check_buffer(data)?; + self.with_guard(None, |_| rom::read(offset, data)) + } + + /// Writes `data` starting at byte address `offset`. + /// + /// The target flash range must already be erased. `offset` is a flash byte + /// address and must be a multiple of 4. `data` must reside in DRAM, not in + /// flash, IRAM, RTC memory, or PSRAM. An empty `data` slice only checks + /// that `offset` is within [`Self::capacity`]. + /// + /// # Errors + /// + /// - [`Error::NotAligned`] if `data` is non-empty and `offset` is not a multiple of 4. + /// - [`Error::OutOfBounds`] if the range exceeds [`Self::capacity`]. + /// - [`Error::NotSupported`] if `data` is not in DRAM. + #[cfg_attr( + multi_core, + doc = "- [`Error::OtherCoreRunning`] on dual-core chips with [`MultiCoreStrategy::Error`]." + )] + /// - [`Error::IoError`], [`Error::IoTimeout`], or [`Error::Unknown`] if the ROM reports an I/O + /// error. + /// + /// # Safety + /// + /// The programmed range must not be mapped for instruction fetch or as + /// immutable data. Writing a mapped `.text` or `.rodata` page overwrites + /// the running image or mutates data the compiler treats as immutable. + #[instability::unstable] + #[ram] + pub unsafe fn write(&mut self, offset: u32, data: &[u32]) -> Result<(), Error> { + let Some(len) = byte_len(data) else { + return Err(Error::OutOfBounds); + }; + if data.is_empty() { + return self.check_bounds(offset, 0); + } + + self.check_word_offset(offset)?; + self.check_bounds(offset, len)?; + check_buffer(data)?; + self.with_guard(Some((offset, len as u32)), |_| rom::write(offset, data)) + } + + /// Erases flash sectors in the range `[from, to)`. + /// + /// `from` and `to` must be multiples of [`Self::SECTOR_SIZE`] (4096 bytes); + /// there is no byte-granular erase. `to == capacity` is allowed. When + /// `from == to`, this function only checks that `from` is within + /// [`Self::capacity`]. + /// + /// # Errors + /// + /// - [`Error::NotAligned`] if `from != to` and `from` or `to` is not a multiple of 4096. + /// - [`Error::OutOfBounds`] if `from > to` or the range exceeds [`Self::capacity`]. + #[cfg_attr( + multi_core, + doc = "- [`Error::OtherCoreRunning`] on dual-core chips with [`MultiCoreStrategy::Error`]." + )] + /// - [`Error::IoError`], [`Error::IoTimeout`], or [`Error::Unknown`] if the ROM reports an I/O + /// error. + /// + /// # Safety + /// + /// The erased range must not be mapped for instruction fetch or as + /// immutable data. Erasing a mapped `.text` or `.rodata` page destroys the + /// running image or mutates data the compiler treats as immutable. + #[instability::unstable] + #[ram] + pub unsafe fn erase(&mut self, from: u32, to: u32) -> Result<(), Error> { + let Some(len) = to.checked_sub(from) else { + return Err(Error::OutOfBounds); + }; + let len = len as usize; + if len == 0 { + return self.check_bounds(from, 0); + } + + self.check_alignment(SECTOR_SIZE, from, len)?; + self.check_bounds(from, len)?; + self.erase_range(from, to) + } + + /// Reads decrypted words into `data` starting at byte address `offset`. + /// + /// Uses a temporary MMU mapping to read decrypted data through the cache. + /// If flash encryption is not enabled, this returns plaintext. + /// + /// `offset` is a flash byte address and must be a multiple of 4. `data` + /// must reside in DRAM, not in flash, IRAM, RTC memory, or PSRAM. An empty + /// `data` slice only checks that `offset` is within [`Self::capacity`]. + /// + /// # Errors + /// + /// - [`Error::NotAligned`] if `data` is non-empty and `offset` is not a multiple of 4. + /// - [`Error::OutOfBounds`] if the range exceeds [`Self::capacity`]. + /// - [`Error::NotSupported`] if `data` is not in DRAM or no MMU entry is available. + #[cfg_attr( + multi_core, + doc = "- [`Error::OtherCoreRunning`] on dual-core chips with [`MultiCoreStrategy::Error`]." + )] + #[instability::unstable] + pub fn read_encrypted(&mut self, offset: u32, data: &mut [u32]) -> Result<(), Error> { + let Some(len) = byte_len(data) else { + return Err(Error::OutOfBounds); + }; + if data.is_empty() { + return self.check_bounds(offset, 0); + } + + self.check_word_offset(offset)?; + self.check_bounds(offset, len)?; + check_buffer(data)?; + self.with_mmu_guard(|_| mmu::read_flash_encrypted(offset, data)) + } + + /// Writes `data` with transparent flash encryption. + /// + /// `offset` must be a multiple of 16, and `data.len()` must be a multiple + /// of 4 words (16 bytes). The destination must already be erased, and bytes + /// outside the requested range are not programmed. `data` must reside in + /// DRAM, not in flash, IRAM, RTC memory, or PSRAM. + /// + /// On ESP32, encrypted writes operate in 32-byte rows. If a boundary is not + /// 32-byte aligned, the driver preserves the adjacent 16-byte block by + /// re-encrypting its existing plaintext to the same ciphertext. The neighbor + /// block therefore does not require prior erasing. + #[cfg_attr( + esp32c5, + doc = " Encrypted writes may fail at higher CPU frequencies (240 MHz)." + )] + /// An empty `data` slice only checks that `offset` is within [`Self::capacity`]. + /// + /// # Errors + /// + /// - [`Error::NotSupported`] if flash encryption is disabled. The eFuse gate is checked before + /// the arguments are. + /// - [`Error::NotAligned`] if `data` is non-empty and `offset` is not a multiple of 16, or + /// `data.len()` is not a multiple of 4 words (16 bytes). + /// - [`Error::OutOfBounds`] if the range exceeds [`Self::capacity`]. + /// - [`Error::NotSupported`] if `data` is not in DRAM, or on ESP32 if reading a row neighbor + /// fails because no MMU entry is available. + #[cfg_attr( + multi_core, + doc = "- [`Error::OtherCoreRunning`] on dual-core chips with [`MultiCoreStrategy::Error`]." + )] + /// - [`Error::IoError`], [`Error::IoTimeout`], or [`Error::Unknown`] if the ROM reports an I/O + /// error. + /// + /// # Safety + /// + /// The programmed range must not be mapped for instruction fetch or as + /// immutable data. Writing a mapped `.text` or `.rodata` page overwrites + /// the running image, or mutates `static` or `.rodata` data the compiler + /// treats as immutable. + #[instability::unstable] + #[ram] + pub unsafe fn write_encrypted(&mut self, offset: u32, data: &[u32]) -> Result<(), Error> { + #[cfg(not(__test_flash))] + if !crate::efuse::flash_encryption() { + return Err(Error::NotSupported); + } + + let Some(len) = byte_len(data) else { + return Err(Error::OutOfBounds); + }; + if data.is_empty() { + return self.check_bounds(offset, 0); + } + + self.check_alignment(ENCRYPT_BLOCK_SIZE, offset, len)?; + self.check_bounds(offset, len)?; + check_buffer(data)?; + + #[cfg(esp32)] + let neighbors = self.esp32_row_neighbors(offset, len)?; + // On ESP32 the programmed range can extend one 16-byte block past each + // end; `with_guard` flushes the whole cache there, so the range only + // needs to cover the request. + self.with_guard(Some((offset, len as u32)), |_| { + write_encrypted_rows( + offset, + words_as_bytes(data), + #[cfg(esp32)] + &neighbors, + ) + }) + } +} + +#[inline(always)] +fn byte_len(data: &[u32]) -> Option { + data.len().checked_mul(WORD_SIZE as usize) +} + +#[inline(always)] +fn words_as_bytes(data: &[u32]) -> &[u8] { + // SAFETY: inspecting the in-memory bytes of `u32` words. + unsafe { core::slice::from_raw_parts(data.as_ptr().cast(), size_of_val(data)) } +} + +#[inline(always)] +fn check_buffer(buf: &[u32]) -> Result<(), Error> { + if !is_slice_in_dram(buf) { + return Err(Error::NotSupported); + } + Ok(()) +} + +/// Word-aligned staging buffer. The ROM encrypts in place. +#[repr(C, align(4))] +struct EncryptRow([u8; XTS_AES_BLOCK_MAX]); + +#[ram] +fn write_encrypted_rows( + offset: u32, + data: &[u8], + #[cfg(esp32)] neighbors: &Esp32Neighbors, +) -> Result<(), Error> { + let mut row = EncryptRow([0; XTS_AES_BLOCK_MAX]); + let mut i = 0; + while i < data.len() { + let row_addr = offset + i as u32; + let (program_addr, program_len, consumed) = cfg_select! { + esp32 => prepare_esp32_row(&mut row.0, row_addr, &data[i..], neighbors), + _ => prepare_xts_row(&mut row.0, row_addr, &data[i..]), + }; + rom::write_encrypted(program_addr, row.0.as_mut_ptr().cast(), program_len)?; + i += consumed; + } + Ok(()) +} + +#[cfg(esp32)] +struct Esp32Neighbors { + pre: [u32; 4], + post: [u32; 4], +} + +/// Fill a 32-byte ESP32 ROM row. Returns `(program_addr, program_len, consumed)`. +/// +/// Mirrors the ESP32 arm of ESP-IDF `esp_flash_write_encrypted`: a row is two +/// AES blocks sharing an address-derived tweak, so a 16-byte write must carry +/// the decrypted neighbor block along and re-encrypt it to the same ciphertext. +#[cfg(esp32)] +#[ram] +fn prepare_esp32_row( + buf: &mut [u8; XTS_AES_BLOCK_MAX], + row_addr: u32, + remaining: &[u8], + neighbors: &Esp32Neighbors, +) -> (u32, u32, usize) { + const BLOCK: usize = ENCRYPT_BLOCK_SIZE as usize; + const ROW: usize = ESP32_ENCRYPT_ROW as usize; + + if !row_addr.is_multiple_of(ESP32_ENCRYPT_ROW) { + buf[..BLOCK].copy_from_slice(words_as_bytes(&neighbors.pre)); + buf[BLOCK..ROW].copy_from_slice(&remaining[..BLOCK]); + (row_addr - ENCRYPT_BLOCK_SIZE, ESP32_ENCRYPT_ROW, BLOCK) + } else if remaining.len() == BLOCK { + buf[..BLOCK].copy_from_slice(&remaining[..BLOCK]); + buf[BLOCK..ROW].copy_from_slice(words_as_bytes(&neighbors.post)); + (row_addr, ESP32_ENCRYPT_ROW, BLOCK) + } else { + buf[..ROW].copy_from_slice(&remaining[..ROW]); + (row_addr, ESP32_ENCRYPT_ROW, ROW) + } +} + +/// Largest row the flash-encryption hardware accepts, matching IDF's +/// `SOC_FLASH_ENCRYPTED_XTS_AES_BLOCK_MAX`. +#[cfg(any(esp32, esp32c2, esp32c3))] +const XTS_AES_BLOCK_MAX: usize = 32; +#[cfg(not(any(esp32, esp32c2, esp32c3)))] +const XTS_AES_BLOCK_MAX: usize = 64; + +/// Pick the largest aligned row, as ESP-IDF does for ESP32-S2 and later. +#[cfg(not(esp32))] +#[ram] +fn prepare_xts_row( + buf: &mut [u8; XTS_AES_BLOCK_MAX], + row_addr: u32, + remaining: &[u8], +) -> (u32, u32, usize) { + let row_size = + if XTS_AES_BLOCK_MAX >= 64 && row_addr.is_multiple_of(64) && remaining.len() >= 64 { + 64 + } else if row_addr.is_multiple_of(32) && remaining.len() >= 32 { + 32 + } else { + 16 + }; + buf[..row_size].copy_from_slice(&remaining[..row_size]); + (row_addr, row_size as u32, row_size) +} + +impl Flash<'_, Blocking> { + #[inline(always)] + fn check_word_offset(&self, offset: u32) -> Result<(), Error> { + if !offset.is_multiple_of(WORD_SIZE) { + return Err(Error::NotAligned); + } + Ok(()) + } + + #[inline(always)] + fn check_alignment(&self, align: u32, offset: u32, length: usize) -> Result<(), Error> { + if !offset.is_multiple_of(align) || !length.is_multiple_of(align as usize) { + return Err(Error::NotAligned); + } + Ok(()) + } + + #[inline(always)] + fn check_bounds(&self, offset: u32, length: usize) -> Result<(), Error> { + let offset = offset as usize; + if length > self.capacity || offset > self.capacity - length { + return Err(Error::OutOfBounds); + } + Ok(()) + } + + /// Park and disable interrupts without suspending the cache. + /// + /// Encrypted reads map flash through the MMU and copy with the cache on, so + /// neither this guard nor anything it calls has to live in RAM. + fn with_mmu_guard( + &mut self, + f: impl FnOnce(&mut Self) -> Result, + ) -> Result { + free(|| { + let _park = ParkGuard::enter(self)?; + f(self) + }) + } + + /// Plaintext of row halves the write will touch but not replace. + /// + /// Read before the cache-off write path: [`Self::read_encrypted`] needs the + /// cache on. Re-encrypting this plaintext in [`prepare_esp32_row`] reproduces + /// the ciphertext already in flash, so those neighbors need no separate erase. + #[cfg(esp32)] + fn esp32_row_neighbors(&mut self, offset: u32, len: usize) -> Result { + let mut neighbors = Esp32Neighbors { + pre: [0; 4], + post: [0; 4], + }; + if !offset.is_multiple_of(ESP32_ENCRYPT_ROW) { + self.read_encrypted(offset - ENCRYPT_BLOCK_SIZE, &mut neighbors.pre)?; + } + let end = offset + len as u32; + if !end.is_multiple_of(ESP32_ENCRYPT_ROW) { + self.read_encrypted(end, &mut neighbors.post)?; + } + Ok(neighbors) + } + + #[ram] + fn with_guard( + &mut self, + invalidate: Option<(u32, u32)>, + f: impl FnOnce(&mut Self) -> Result, + ) -> Result { + free(|| { + let _park = ParkGuard::enter(self)?; + let cache = cache::CacheGuard::suspend(); + let result = f(self); + cfg_select! { + esp32 => { + // Address-based invalidate is unavailable; flush while still off. + if invalidate.is_some() { + cache.flush_while_off(); + } + drop(cache); + } + _ => { + drop(cache); + if let Some((start, len)) = invalidate { + mmu::invalidate_mapped(start, len); + } + } + } + result + }) + } + + #[ram] + fn erase_range(&mut self, from: u32, to: u32) -> Result<(), Error> { + let mut address = from; + while address < to && !address.is_multiple_of(BLOCK_SIZE) { + self.with_guard(Some((address, SECTOR_SIZE)), |_| { + rom::erase_sector(address / SECTOR_SIZE) + })?; + address += SECTOR_SIZE; + } + + while (to - address) >= BLOCK_SIZE { + self.with_guard(Some((address, BLOCK_SIZE)), |_| { + rom::erase_block(address / BLOCK_SIZE) + })?; + address += BLOCK_SIZE; + } + + while address < to { + self.with_guard(Some((address, SECTOR_SIZE)), |_| { + rom::erase_sector(address / SECTOR_SIZE) + })?; + address += SECTOR_SIZE; + } + + Ok(()) + } +} + +/// Stops the other core according to [`MultiCoreStrategy`]. [`Drop`] releases that core. +struct ParkGuard { + #[cfg(all(multi_core, feature = "rt"))] + release: Release, +} + +#[cfg(multi_core)] +#[cfg_attr(not(feature = "rt"), expect(dead_code))] +#[derive(Clone, Copy)] +enum Release { + None, + Ipc, + Unpark(crate::system::Cpu), +} + +impl ParkGuard { + #[ram] + fn enter(_flash: &Flash<'_, Blocking>) -> Result { + cfg_select! { + multi_core => { + #[cfg_attr(not(feature = "rt"), expect(unused_variables))] + let release = match _flash.multi_core_strategy { + MultiCoreStrategy::Error => { + for other in crate::system::Cpu::other() { + if crate::system::is_running(other) { + return Err(Error::OtherCoreRunning); + } + } + Release::None + } + #[cfg(feature = "rt")] + MultiCoreStrategy::AutoPark => { + let mut release = Release::None; + for other in crate::system::Cpu::other() { + if !crate::system::is_running(other) { + continue; + } + // A core that `CpuControl` did not start has no IPC handler. It can + // run ROM code, which a CPU-control stall does not break. + if other == crate::system::Cpu::ProCpu + || crate::system::multi_core::app_core_takes_ipc() + { + ipc_stall::enter(other); + release = Release::Ipc; + } else { + let mut cpu_ctrl = crate::system::CpuControl::new(unsafe { + crate::peripherals::CPU_CTRL::steal() + }); + unsafe { cpu_ctrl.park_core(other) }; + release = Release::Unpark(other); + } + } + release + } + MultiCoreStrategy::Ignore(_) => Release::None, + }; + Ok(Self { + #[cfg(feature = "rt")] + release, + }) + } + _ => Ok(Self {}), + } + } +} + +impl Drop for ParkGuard { + #[ram] + fn drop(&mut self) { + #[cfg(all(multi_core, feature = "rt"))] + match self.release { + Release::None => {} + Release::Ipc => ipc_stall::leave(), + Release::Unpark(core) => { + let mut cpu_ctrl = crate::system::CpuControl::new(unsafe { + crate::peripherals::CPU_CTRL::steal() + }); + cpu_ctrl.unpark_core(core); + } + } + } +} + +/// RAM loop posted to the other core for [`MultiCoreStrategy::AutoPark`]. +#[cfg(all(multi_core, feature = "rt"))] +mod ipc_stall { + use esp_sync::raw::{RawLock, SingleCoreInterruptLock}; + use portable_atomic::Ordering; + use portable_atomic_enum::atomic_enum; + use procmacros::ram; + + use crate::private::DropGuard; + + #[atomic_enum] + #[derive(PartialEq, Debug, Clone, Copy)] + enum Phase { + /// The other core is outside the loop. + Idle, + /// The other core is inside the loop. Interrupts on that core are masked. + Ack, + /// The operation has finished. The caches are on. The other core leaves the loop. + Release, + } + + static PHASE: AtomicPhase = AtomicPhase::new(Phase::Idle); + + pub(super) fn enter(core: crate::system::Cpu) { + crate::interrupt::ipc::Ipc.call_function(core, stall); + while PHASE.load(Ordering::Acquire) != Phase::Ack { + core::hint::spin_loop(); + } + } + + pub(super) fn leave() { + PHASE.store(Phase::Release, Ordering::Release); + while PHASE.load(Ordering::Acquire) != Phase::Idle { + core::hint::spin_loop(); + } + } + + #[ram] + fn stall() { + { + // The mask is taken before `Phase::Ack`. The guards drop after the cache is on again. + let token = unsafe { SingleCoreInterruptLock.enter() }; + let _mask = DropGuard::new(token, |token| unsafe { + SingleCoreInterruptLock.exit(token) + }); + #[cfg(soc_cpu_has_branch_predictor)] + let _predictor = crate::soc::branch_predictor::DisabledBranchPredictor::new(); + + PHASE.store(Phase::Ack, Ordering::Release); + while PHASE.load(Ordering::Acquire) == Phase::Ack { + core::hint::spin_loop(); + } + } + PHASE.store(Phase::Idle, Ordering::Release); + } +} diff --git a/esp-hal/src/flash/rom.rs b/esp-hal/src/flash/rom.rs new file mode 100644 index 00000000000..8b4422f7bd3 --- /dev/null +++ b/esp-hal/src/flash/rom.rs @@ -0,0 +1,187 @@ +//! ROM SPI flash wrappers and JEDEC capacity decode. + +use procmacros::ram; + +use super::{ConfigError, Error}; + +#[repr(C)] +struct RomSpiflashChip { + device_id: u32, +} + +/// ROM-cached JEDEC id (manufacturer in bits 23:16). +/// +/// ESP32 and ESP32-S2 export `g_rom_flashchip` as a BSS symbol. Later chips +/// store the same fields behind `rom_spiflash_legacy_data` (IDF exposes the +/// old name as a macro). +pub(super) fn cached_device_id() -> u32 { + cfg_select! { + any(esp32, esp32s2) => { + unsafe extern "C" { + static g_rom_flashchip: RomSpiflashChip; + } + unsafe { g_rom_flashchip.device_id } + } + _ => { + #[repr(C)] + struct RomSpiflashLegacyData { + chip: RomSpiflashChip, + } + unsafe extern "C" { + static rom_spiflash_legacy_data: *const RomSpiflashLegacyData; + } + let data = unsafe { rom_spiflash_legacy_data }; + if data.is_null() { + 0 + } else { + unsafe { (*data).chip.device_id } + } + } + } +} + +/// No-response sentinels. +/// +/// `0xFFFF3F` is esptool's raw `RDID` no-response value; `0x3FFFFF` is that +/// word after the ROM's manufacturer-first swap. +/// +/// `0x001540EF` is a valid Winbond W25Q16 JEDEC id. It is only rejected on +/// ESP32, where the ROM does not run `RDID` and leaves that word as a +/// static placeholder until a second-stage bootloader identifies the chip. +fn is_unusable_id(id: u32) -> bool { + let no_response = matches!(id, 0x0000_0000 | 0x00FF_FFFF | 0x00FF_FF3F | 0x003F_FFFF); + cfg_select! { + esp32 => no_response || id == 0x0015_40EF, + _ => no_response, + } +} + +#[inline(never)] +fn unknown_flash_chip(raw: u32) -> ConfigError { + warn!("unknown cached flash id {:#010x}", raw); + ConfigError::UnknownFlashChip +} + +/// Decode flash density from a ROM-cached JEDEC id. +/// +/// The ROM stores the id manufacturer-first, which is the reverse of a raw +/// `RDID` word. Adesto (`0x1F`) density nibble sits in bits 12:8 in both +/// layouts. +pub(super) fn capacity_from_cached_id(raw: u32) -> Result { + let id = raw & 0x00FF_FFFF; + if is_unusable_id(id) { + return Err(unknown_flash_chip(raw)); + } + + const KB: u32 = 1024; + const MB: u32 = 1024 * KB; + + let manufacturer = (id >> 16) as u8; + let size = if manufacturer == 0x1F { + // https://github.com/espressif/esptool/blob/8363cae8eca42ec70e26edfe4d1727549d6ce578/esptool/cmds.py#L55-L98 + match ((id >> 8) as u8) & 0x1F { + 0x04 => 512 * KB, + 0x05 => MB, + 0x06 => 2 * MB, + 0x07 => 4 * MB, + 0x08 => 8 * MB, + 0x09 => 16 * MB, + _ => return Err(unknown_flash_chip(raw)), + } + } else { + match id as u8 { + 0x12 => 256 * KB, + 0x13 => 512 * KB, + 0x14 => MB, + 0x15 => 2 * MB, + 0x16 => 4 * MB, + 0x17 => 8 * MB, + 0x18 => 16 * MB, + 0x19 => 32 * MB, + 0x1A => 64 * MB, + 0x1B => 128 * MB, + 0x1C => 256 * MB, + 0x20 => 64 * MB, + 0x21 => 128 * MB, + 0x22 => 256 * MB, + 0x32 => 256 * KB, + 0x33 => 512 * KB, + 0x34 => MB, + 0x35 => 2 * MB, + 0x36 => 4 * MB, + 0x37 => 8 * MB, + 0x38 => 16 * MB, + 0x39 => 32 * MB, + 0x3A => 64 * MB, + _ => return Err(unknown_flash_chip(raw)), + } + }; + + Ok(size as usize) +} + +#[inline(always)] +fn check_rc(rc: i32) -> Result<(), Error> { + if rc == 0 { + Ok(()) + } else { + decode_rom_error(rc) + } +} + +/// Must live in RAM: callers run with the flash cache suspended. +#[ram] +fn decode_rom_error(rc: i32) -> Result<(), Error> { + match rc { + 1 => Err(Error::IoError), + 2 => Err(Error::IoTimeout), + other => { + warn!("unexpected flash ROM status {}", other); + Err(Error::Unknown) + } + } +} + +#[inline(always)] +pub(super) fn read(src_addr: u32, data: &mut [u32]) -> Result<(), Error> { + check_rc(unsafe { + esp_rom_sys::rom::spiflash::esp_rom_spiflash_read( + src_addr, + data.as_mut_ptr(), + data.len() as u32 * super::WORD_SIZE, + ) + }) +} + +#[inline(always)] +pub(super) fn write(dest_addr: u32, data: &[u32]) -> Result<(), Error> { + check_rc(unsafe { + esp_rom_sys::rom::spiflash::esp_rom_spiflash_write( + dest_addr, + data.as_ptr(), + data.len() as u32 * super::WORD_SIZE, + ) + }) +} + +/// Write `len` bytes at `dest_addr` with transparent encryption. +/// +/// `data` must be word-aligned. On ESP32, `dest_addr` and `len` must be +/// 32-byte aligned. On later chips, 16/32/64-byte rows are accepted. The +/// ROM may encrypt in place. +#[inline(always)] +pub(super) fn write_encrypted(dest_addr: u32, data: *mut u32, len: u32) -> Result<(), Error> { + check_rc(unsafe { + esp_rom_sys::rom::spiflash::esp_rom_spiflash_write_encrypted(dest_addr, data, len) + }) +} + +#[inline(always)] +pub(super) fn erase_sector(sector_number: u32) -> Result<(), Error> { + check_rc(unsafe { esp_rom_sys::rom::spiflash::esp_rom_spiflash_erase_sector(sector_number) }) +} + +#[inline(always)] +pub(super) fn erase_block(block_number: u32) -> Result<(), Error> { + check_rc(unsafe { esp_rom_sys::rom::spiflash::esp_rom_spiflash_erase_block(block_number) }) +} diff --git a/esp-hal/src/gpio/asynch.rs b/esp-hal/src/gpio/asynch.rs index efc818a49f9..2b724adf427 100644 --- a/esp-hal/src/gpio/asynch.rs +++ b/esp-hal/src/gpio/asynch.rs @@ -6,14 +6,14 @@ use core::{ use crate::gpio::{Event, Flex, GpioBank, Input, InputPin}; impl Flex<'_> { - /// Wait until the pin experiences a particular [`Event`]. + /// Waits until the pin experiences a particular [`Event`]. /// /// The GPIO driver will disable listening for the event once it occurs, /// or if the `Future` is dropped - which also means this method is **not** /// cancellation-safe, it will always wait for a future event. /// - /// Note that calling this function will overwrite previous - /// [`listen`][Self::listen] operations for this pin. + /// Calling this method overwrites previous [`listen`][Self::listen] operations + /// for this pin. /// /// A wait continues through a light sleep, and a pin that waits also ends the sleep, like a /// listening pin. There is one exception: a wait for an edge on a pin that is already at the @@ -49,7 +49,7 @@ impl Flex<'_> { PinFuture { pin: self }.await; } - /// Wait until the pin is high. + /// Waits until the pin is high. /// /// See [Self::wait_for] for more information. #[inline] @@ -58,7 +58,7 @@ impl Flex<'_> { self.wait_for(Event::HighLevel).await } - /// Wait until the pin is low. + /// Waits until the pin is low. /// /// See [Self::wait_for] for more information. #[inline] @@ -67,7 +67,7 @@ impl Flex<'_> { self.wait_for(Event::LowLevel).await } - /// Wait for the pin to undergo a transition from low to high. + /// Waits for the pin to undergo a transition from low to high. /// /// See [Self::wait_for] for more information. #[inline] @@ -76,7 +76,7 @@ impl Flex<'_> { self.wait_for(Event::RisingEdge).await } - /// Wait for the pin to undergo a transition from high to low. + /// Waits for the pin to undergo a transition from high to low. /// /// See [Self::wait_for] for more information. #[inline] @@ -85,7 +85,7 @@ impl Flex<'_> { self.wait_for(Event::FallingEdge).await } - /// Wait for the pin to undergo any transition, i.e low to high OR high + /// Waits for the pin to undergo any transition, i.e. low to high or high /// to low. /// /// See [Self::wait_for] for more information. @@ -98,9 +98,9 @@ impl Flex<'_> { impl Input<'_> { #[procmacros::doc_replace] - /// Wait until the pin experiences a particular [`Event`]. + /// Waits until the pin experiences a particular [`Event`]. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -111,15 +111,14 @@ impl Input<'_> { /// # {after_snippet} /// ``` /// - /// ## Cancellation + /// # Cancellation Safety /// - /// This function is not cancellation-safe. + /// Not cancellation-safe. /// - /// - Calling this function will overwrite previous [`listen`][Self::listen] operations for this - /// pin, making it side-effectful. - /// - Dropping the [`Future`] returned by this function will cancel the wait operation. If the - /// event occurs after the future is dropped, a consequent wait operation will ignore the - /// event. + /// - Calling this method overwrites previous [`listen`][Self::listen] operations for this pin, + /// making it side-effectful. + /// - Dropping the [`Future`] returned by this method cancels the wait operation. If the event + /// occurs after the future is dropped, a subsequent wait operation ignores the event. /// /// A wait continues through a light sleep, and a pin that waits also ends the sleep, like a /// listening pin. There is one exception: a wait for an edge on a pin that is already at the @@ -131,11 +130,11 @@ impl Input<'_> { } #[procmacros::doc_replace] - /// Wait until the pin is high. + /// Waits until the pin is high. /// /// See [Self::wait_for] for more information. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -151,11 +150,11 @@ impl Input<'_> { } #[procmacros::doc_replace] - /// Wait until the pin is low. + /// Waits until the pin is low. /// /// See [Self::wait_for] for more information. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -171,11 +170,11 @@ impl Input<'_> { } #[procmacros::doc_replace] - /// Wait for the pin to undergo a transition from low to high. + /// Waits for the pin to undergo a transition from low to high. /// /// See [Self::wait_for] for more information. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -191,11 +190,11 @@ impl Input<'_> { } #[procmacros::doc_replace] - /// Wait for the pin to undergo a transition from high to low. + /// Waits for the pin to undergo a transition from high to low. /// /// See [Self::wait_for] for more information. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -211,12 +210,12 @@ impl Input<'_> { } #[procmacros::doc_replace] - /// Wait for the pin to undergo any transition, i.e low to high OR high + /// Waits for the pin to undergo any transition, i.e. low to high or high /// to low. /// /// See [Self::wait_for] for more information. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} diff --git a/esp-hal/src/gpio/dedicated/mod.rs b/esp-hal/src/gpio/dedicated/mod.rs index 1263e79c5d3..f51fadfe4bd 100644 --- a/esp-hal/src/gpio/dedicated/mod.rs +++ b/esp-hal/src/gpio/dedicated/mod.rs @@ -25,7 +25,8 @@ //! The drivers can take channels and pins by value or by reference. Pass these objects by reference //! if you plan on reusing them again, after dropping the dedicated driver. //! -//! Due to how the hardware works, [`DedicatedGpioOutput`] can drive any number of GPIO pins. +//! [`DedicatedGpioOutput`] can drive any number of GPIO pins. Each connected pin follows the +//! current dedicated GPIO channel level immediately. //! //! ## Bundles //! @@ -43,6 +44,7 @@ //! - [`write_ll`]: write output levels for a selected set of channels in one operation //! - [`read_all_ll`]: read the current input levels of all channels //! - [`output_levels_ll`]: read the current output levels of all channels +//! //! These functions operate purely on channel bitmasks (bit 0 -> channel 0, bit 1 -> channel 1, ...) //! and do not track pin configuration. Prefer the higher-level drivers and bundles unless you //! specifically need the lowest overhead. @@ -367,7 +369,7 @@ impl OutputDriver for &mut super::Flex<'_> { /// A single dedicated GPIO channel, both input and output. /// -/// You can split the channel by moving its fields out into separate input/output channel variables. +/// The channel can be split by moving its fields into separate input/output channel variables. pub struct DedicatedGpioChannel<'lt, const CH: u8> { /// Channel input pub input: DedicatedGpioInputChannel<'lt, CH>, @@ -479,13 +481,13 @@ impl OutputChannel for &mut DedicatedGpioOutputChannel<'_, CH> { doc = r#"

-Note that the driver must only be used on the core that has created it. Do not send the driver to +The driver must only be used on the core that has created it. Do not send the driver to another core, either directly, or indirectly via a thread that is not pinned to a core.
"# )] #[doc = ""] -/// ## Examples +/// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -532,7 +534,7 @@ impl<'lt> DedicatedGpioInput<'lt> { } } - /// Read the current state of the GPIO pins. + /// Reads the current state of the GPIO pins. #[inline(always)] pub fn level(&self) -> Level { #[cfg(all(debug_assertions, multi_core))] @@ -566,21 +568,21 @@ impl embedded_hal::digital::InputPin for DedicatedGpioInput<'_> { #[doc_replace] /// A dedicated GPIO output driver. /// -/// Due to how the hardware works, [`DedicatedGpioOutput`] can drive any number of GPIO pins. To -/// create a driver, you can use the [`DedicatedGpioOutput::new`] method, then -/// [`DedicatedGpioOutput::with_pin`] to add output drivers. +/// Due to how the hardware works, [`DedicatedGpioOutput`] can drive any number of GPIO pins. Use +/// [`DedicatedGpioOutput::new`] to create a driver, then [`DedicatedGpioOutput::with_pin`] to add +/// output drivers. #[cfg_attr( multi_core, doc = r#"
-Note that the driver must only be used on the core that has created it. Do not send the driver to +The driver must only be used on the core that has created it. Do not send the driver to another core, either directly, or indirectly via a thread that is not pinned to a core.
"# )] #[doc = ""] -/// ## Examples +/// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -617,8 +619,7 @@ pub struct DedicatedGpioOutput<'lt> { impl<'lt> DedicatedGpioOutput<'lt> { /// Creates a new dedicated GPIO output driver. /// - /// This function returns an empty driver. You will need to add output drivers to it using the - /// [`Self::with_pin`] method. + /// Returns an empty driver. Output drivers must be added with the [`Self::with_pin`] method. pub fn new(channel: CH) -> Self where CH: OutputChannel + 'lt, @@ -634,11 +635,13 @@ impl<'lt> DedicatedGpioOutput<'lt> { } } - /// Adds a new output driver to the GPIO pins. + /// Adds a GPIO output pin to this dedicated GPIO output. + /// + /// A dedicated GPIO output can drive any number of GPIO pins. The driver releases the pins when + /// it is dropped. /// - /// A dedicated GPIO output driver can control any number of GPIO pins. The pins will be - /// released when the driver is dropped. This function does not change the state of the newly - /// added GPIO pin. + /// The GPIO matrix routes the current output of the dedicated GPIO channel to the pin. The pin + /// follows the channel level immediately. The GPIO output register of the pin does not change. pub fn with_pin(mut self, pin: impl OutputDriver + 'lt) -> Self { pin.set_output_connection(self.signal); @@ -738,13 +741,13 @@ On ESP32-S2 and ESP32-S3, the GPIO's output is always enabled. doc = r#"
-Note that the driver must only be used on the core that has created it. Do not send the driver to +The driver must only be used on the core that has created it. Do not send the driver to another core, either directly, or indirectly via a thread that is not pinned to a core.
"# )] #[doc = ""] -/// ## Examples +/// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -807,7 +810,7 @@ impl<'lt> DedicatedGpioFlex<'lt> { low_level::set_output_enabled(self.mask, enabled); } - /// Change the current state of the GPIO pin. + /// Changes the current state of the GPIO pin. #[inline(always)] pub fn set_level(&mut self, level: Level) { #[cfg(all(debug_assertions, multi_core))] @@ -837,7 +840,7 @@ impl<'lt> DedicatedGpioFlex<'lt> { Level::from(low_level::read_out() & self.mask != 0) } - /// Read the current state of the GPIO pins. + /// Reads the current state of the GPIO pins. #[inline(always)] pub fn level(&self) -> Level { #[cfg(all(debug_assertions, multi_core))] @@ -876,7 +879,7 @@ impl Drop for DedicatedGpioFlex<'_> { /// `value` is the value to write to the selected channels. A 0 bit sets the /// channel's output to low, a 1 bit sets it to high. /// -/// # Example +/// # Examples /// /// ```rust,no_run /// # {before_snippet} @@ -948,8 +951,8 @@ pub fn output_levels_ll() -> u32 { /// A bundle of dedicated GPIO output drivers. /// /// An output bundle precomputes a channel mask from one or more -/// [`DedicatedGpioOutput`] drivers. This lets you update multiple dedicated output -/// channels with a single low-level write. +/// [`DedicatedGpioOutput`] drivers. Enables updating multiple dedicated output channels with a +/// single low-level write. /// /// Attaching a driver does **not** change any output state. Dropping the output /// drivers still controls when the underlying GPIO pins are released back to @@ -972,7 +975,7 @@ configured on the same core, and the bundle must only be used on the core that c "# )] #[doc = ""] -/// ## Examples +/// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1036,9 +1039,7 @@ impl<'lt> DedicatedGpioOutputBundle<'lt> { /// The returned bundle initially contains no channels. Add outputs using /// [`Self::enable_output`]. /// - /// ## Notes - /// - /// - Creating a bundle does **not** configure any hardware by itself. + /// Creating a bundle does **not** configure any hardware by itself. pub fn new() -> Self { Self { _marker: PhantomData, @@ -1058,7 +1059,7 @@ impl<'lt> DedicatedGpioOutputBundle<'lt> { /// /// A bit is set to 1 if that channel is currently included in the bundle. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1094,16 +1095,14 @@ impl<'lt> DedicatedGpioOutputBundle<'lt> { self.mask } - /// Attaches (enables) a dedicated output driver in this bundle. After enabling, you will - /// be able to control the output channels of `out` via this bundle. + /// Attaches (enables) a dedicated output driver in this bundle. After enabling, the output + /// channels of `out` can be controlled via this bundle. /// - /// This method logically borrows the provided [`DedicatedGpioOutput`] for the lifetime `'lt`. + /// Logically borrows the provided [`DedicatedGpioOutput`] for the lifetime `'lt`. /// Multiple bundles may borrow the same output driver at the same time. Check examples in the /// module-level documentation for more. /// - /// ## Notes - /// - /// - This function does not change any GPIO output state. + /// Does not change any GPIO output state. #[cfg_attr( multi_core, doc = r#" @@ -1127,18 +1126,16 @@ All dedicated GPIO drivers in a bundle must be configured on the same core as th /// This updates the internal mask by clearing the channel bit(s) of `out`. After disabling, /// future *bundle* operations will no longer touch those channels. /// - /// ## Notes - /// /// - This does **not** affect `out` itself. It only changes which channels future *bundle* /// operations will touch. /// - This does **not** end the lifetime-based borrow of `out`. Even after disabling, `out` /// still cannot be moved or dropped while this bundle exists. - /// - You can re-enable it later via [`Self::enable_output`]. + /// - Can be re-enabled later via [`Self::enable_output`] #[cfg_attr( multi_core, doc = r#"
-You should only disable dedicated GPIO drivers that were configured on the same core as the bundle itself. +Dedicated GPIO drivers must only be disabled if configured on the same core as the bundle itself.
"# )] @@ -1157,7 +1154,7 @@ You should only disable dedicated GPIO drivers that were configured on the same /// For every bit set to 1 in `bits`, the corresponding dedicated output channel is driven /// high. Bits set to 0 are left unchanged. /// - /// ## Example + /// # Examples /// /// `bundle.set_high(0b1011_0001)` sets channels 0, 4, 5, and 7 high. /// @@ -1167,7 +1164,7 @@ You should only disable dedicated GPIO drivers that were configured on the same /// i.e. `bits & !self.mask() == 0`. /// /// For example, if the bundle mask is `0b0000_1011` (channels 0, 1, and 3), then `bits` - /// must not set bit 2 (e.g. `0b0000_0100`), or you would modify channel 2 outside the bundle. + /// must not set bit 2 (e.g. `0b0000_0100`), or channel 2 outside the bundle would be modified /// /// When compiled with `debug-assertions`, this condition is checked at runtime. ///
@@ -1192,7 +1189,7 @@ You should only disable dedicated GPIO drivers that were configured on the same /// For every bit set to 1 in `bits`, the corresponding dedicated output channel is driven /// low. Bits set to 0 are left unchanged. /// - /// ## Example + /// # Examples /// /// `bundle.set_low(0b1011_0001)` sets channels 0, 4, 5, and 7 low. /// @@ -1202,7 +1199,7 @@ You should only disable dedicated GPIO drivers that were configured on the same /// i.e. `bits & !self.mask() == 0`. /// /// For example, if the bundle mask is `0b0000_1011` (channels 0, 1, and 3), then `bits` - /// must not set bit 7 (e.g. `0b1000_0000`), or you would clear channel 7 outside the bundle. + /// must not set bit 7 (e.g. `0b1000_0000`), or channel 7 outside the bundle would be cleared /// /// When compiled with `debug-assertions`, this condition is checked at runtime. ///
@@ -1226,14 +1223,14 @@ You should only disable dedicated GPIO drivers that were configured on the same /// Writes output levels for **all channels included by this bundle**. /// - /// This method updates the output state of every channel whose bit is set in + /// Updates the output state of every channel whose bit is set in /// [`Self::mask`]. Channels not included in the bundle are not modified. /// /// `bits` provides the level for each channel in the bundle: /// - bit = 0 -> low /// - bit = 1 -> high /// - /// ## Example + /// # Examples /// /// If `self.mask()` is `0b1111_0000` (bundle contains channels 4..=7), then /// `bundle.write_bits(0b0001_0000)` sets channel 4 high and channels 5..=7 low, @@ -1241,10 +1238,10 @@ You should only disable dedicated GPIO drivers that were configured on the same /// ///
/// - /// This function only writes channels selected by [`Self::mask`]. It will **not** - /// change channels outside the mask, even if `bits` contains 1s there. + /// Only writes channels selected by [`Self::mask`]. Does **not** change channels outside the + /// mask, even if `bits` contains 1s there /// - /// Make sure this "masked write" behavior matches what you intend. + /// The masked write only updates channels selected by the mask. /// ///
#[inline(always)] @@ -1263,7 +1260,7 @@ You should only disable dedicated GPIO drivers that were configured on the same /// /// For channels outside the bundle mask, the corresponding bits are always 0. /// - /// ## Example + /// # Examples /// /// If the bundle mask is `0b0000_1011` (channels 0, 1, and 3), then /// `output_levels()` will only contain bits 0, 1, and 3, regardless of the output @@ -1290,8 +1287,8 @@ impl<'lt> Default for DedicatedGpioOutputBundle<'lt> { /// A bundle of dedicated GPIO input drivers. /// /// An input bundle precomputes a channel mask from one or more [`DedicatedGpioInput`] -/// drivers. This lets you read multiple dedicated input channels with a single -/// low-level read (see [`DedicatedGpioInputBundle::levels`]). +/// drivers. Enables reading multiple dedicated input channels with a single low-level read (see +/// [`DedicatedGpioInputBundle::levels`]) /// /// Attaching a driver does **not** change any pin state. The bundle only stores a /// channel mask; it does not own pins or remember which GPIOs were connected. @@ -1302,9 +1299,8 @@ impl<'lt> Default for DedicatedGpioOutputBundle<'lt> { /// [`DedicatedGpioInput`]. The bundle operates on *channels*, not individual pins: /// each bit in the returned mask corresponds to a dedicated input channel. /// -/// If you later reconfigure a GPIO pin (e.g. connect it to a different peripheral -/// input), that changes what the channel reads. The bundle does not prevent such -/// reconfiguration. +/// If a GPIO pin is later reconfigured (e.g. connected to a different peripheral input), that +/// changes what the channel reads. The bundle does not prevent such reconfiguration. #[cfg_attr( multi_core, doc = r#" @@ -1316,7 +1312,7 @@ configured on the same core, and the bundle must only be used on the core that c "# )] #[doc = ""] -/// ## Examples +/// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1363,9 +1359,7 @@ impl<'lt> DedicatedGpioInputBundle<'lt> { /// The returned bundle initially contains no channels. Add inputs using /// [`Self::enable_input`]. /// - /// ## Notes - /// - /// - Creating a bundle does **not** configure any hardware by itself. + /// Creating a bundle does **not** configure any hardware by itself. pub fn new() -> Self { Self { _marker: PhantomData, @@ -1385,7 +1379,7 @@ impl<'lt> DedicatedGpioInputBundle<'lt> { /// /// A bit is set to 1 if that channel is currently included in the bundle. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1420,15 +1414,13 @@ impl<'lt> DedicatedGpioInputBundle<'lt> { } /// Attaches (enables) an already-configured dedicated input driver to this bundle. After - /// enabling, you will be able to read the input channels of `inp` via this bundle. + /// enabling, the input channels of `inp` can be read via this bundle. /// - /// This method logically borrows the provided [`DedicatedGpioInput`] for the lifetime `'lt`. + /// Logically borrows the provided [`DedicatedGpioInput`] for the lifetime `'lt`. /// Multiple bundles may borrow the same input driver at the same time. Check examples in the /// module-level documentation for more. /// - /// ## Notes - /// - /// - This function does not change any input state. + /// Does not change any input state. #[cfg_attr( multi_core, doc = r#" @@ -1452,18 +1444,16 @@ All dedicated GPIO drivers in a bundle must be configured on the same core as th /// This updates the internal mask by clearing the channel bit(s) of `inp`. After disabling, /// future *bundle* operations will no longer touch those channels. /// - /// ## Notes - /// /// - This does **not** affect `inp` itself. It only changes which channels future *bundle* /// operations will touch. /// - This does **not** end the lifetime-based borrow of `inp`. Even after disabling, `inp` /// still cannot be moved or dropped while this bundle exists. - /// - You can re-enable it later via [`Self::enable_input`]. + /// - Can be re-enabled later via [`Self::enable_input`] #[cfg_attr( multi_core, doc = r#"
-You should only disable dedicated GPIO drivers that were configured on the same core as the bundle itself. +Dedicated GPIO drivers must only be disabled if configured on the same core as the bundle itself.
"# )] @@ -1481,7 +1471,7 @@ You should only disable dedicated GPIO drivers that were configured on the same /// /// For channels outside the bundle mask, the corresponding bits are always 0. /// - /// ## Example + /// # Examples /// /// If the bundle mask is `0b0000_1011` (channels 0, 1, and 3), then /// `levels()` will only contain bits 0, 1, and 3, regardless of the state @@ -1498,7 +1488,7 @@ You should only disable dedicated GPIO drivers that were configured on the same low_level::read_in() & self.mask } - /// Returns `true` if all channels in this bundle are currently high. + /// Returns whether all channels in this bundle are currently high. #[inline(always)] pub fn all_high(&self) -> bool { #[cfg(all(debug_assertions, multi_core))] @@ -1511,7 +1501,7 @@ You should only disable dedicated GPIO drivers that were configured on the same (low_level::read_in() & self.mask) == self.mask } - /// Returns `true` if all channels in this bundle are currently low. + /// Returns whether all channels in this bundle are currently low. #[inline(always)] pub fn all_low(&self) -> bool { #[cfg(all(debug_assertions, multi_core))] @@ -1535,9 +1525,9 @@ impl<'lt> Default for DedicatedGpioInputBundle<'lt> { /// A bundle of dedicated GPIO flex drivers (input + output). /// /// A flex bundle precomputes a channel mask from one or more [`DedicatedGpioFlex`] -/// drivers. This lets you: -/// - update multiple dedicated output channels with a single low-level write, and -/// - read multiple dedicated input channels with a single low-level read. +/// drivers. Enables: +/// - updating multiple dedicated output channels with a single low-level write, and +/// - reading multiple dedicated input channels with a single low-level read. /// /// Attaching a driver does **not** change any pin state. The bundle only stores a /// channel mask; it does not own pins or remember which GPIOs were connected. @@ -1561,7 +1551,7 @@ running on core 1. "# )] #[doc = ""] -/// ## Examples +/// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1614,9 +1604,7 @@ impl<'lt> DedicatedGpioFlexBundle<'lt> { /// The returned bundle initially contains no channels. Add flex drivers using /// [`Self::enable_flex`]. /// - /// ## Notes - /// - /// - Creating a bundle does **not** configure any hardware by itself. + /// Creating a bundle does **not** configure any hardware by itself. pub fn new() -> Self { Self { _marker: PhantomData, @@ -1636,7 +1624,7 @@ impl<'lt> DedicatedGpioFlexBundle<'lt> { /// /// A bit is set to 1 if that channel is currently included in the bundle. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1664,16 +1652,13 @@ impl<'lt> DedicatedGpioFlexBundle<'lt> { } /// Attaches (enables) an already-configured dedicated flex driver to this bundle. After - /// enabling, you will be able to control the input/output channels of `flex` via this - /// bundle. + /// enabling, the input/output channels of `flex` can be controlled via this bundle. /// - /// This method logically borrows the provided [`DedicatedGpioFlex`] for the lifetime `'lt`. + /// Logically borrows the provided [`DedicatedGpioFlex`] for the lifetime `'lt`. /// Multiple bundles may borrow the same flex driver at the same time. Check examples in the /// module-level documentation for more. /// - /// ## Notes - /// - /// - This function does not change any input/output state. + /// Does not change any input/output state. #[cfg_attr( multi_core, doc = r#" @@ -1697,18 +1682,16 @@ All dedicated GPIO drivers in a bundle must be configured on the same core as th /// This updates the internal mask by clearing the channel bit(s) of `flex`. After disabling, /// future *bundle* operations will no longer touch those channels. /// - /// ## Notes - /// /// - This does **not** affect `flex` itself. It only changes which channels future *bundle* /// operations will touch. /// - This does **not** end the lifetime-based borrow of `flex`. Even after disabling, `flex` /// still cannot be moved or dropped while this bundle exists. - /// - You can re-enable it later via [`Self::enable_flex`]. + /// - Can be re-enabled later via [`Self::enable_flex`] #[cfg_attr( multi_core, doc = r#"
-You should only disable dedicated GPIO drivers that were configured on the same core as the bundle itself. +Dedicated GPIO drivers must only be disabled if configured on the same core as the bundle itself.
"# )] @@ -1727,7 +1710,7 @@ You should only disable dedicated GPIO drivers that were configured on the same /// For every bit set to 1 in `bits`, the corresponding channel is driven high. /// Bits set to 0 are left unchanged. /// - /// ## Example + /// # Examples /// /// If the bundle contains channels 0 and 2, then `bundle.set_high(0b0000_0101)` sets /// channel 0 and 2 high. @@ -1738,7 +1721,7 @@ You should only disable dedicated GPIO drivers that were configured on the same /// i.e. `bits & !self.mask() == 0`. /// /// For example, if the bundle mask is `0b0000_0011` (channels 0 and 1), then `bits` must not - /// set bit 2 (e.g. `0b0000_0100`), or you would modify channel 2 outside the bundle. + /// set bit 2 (e.g. `0b0000_0100`), or channel 2 outside the bundle would be modified /// /// When compiled with `debug-assertions`, this condition is checked at runtime. /// @@ -1763,7 +1746,7 @@ You should only disable dedicated GPIO drivers that were configured on the same /// For every bit set to 1 in `bits`, the corresponding channel is driven low. /// Bits set to 0 are left unchanged. /// - /// ## Example + /// # Examples /// /// If the bundle contains channels 0 and 2, then `bundle.set_low(0b0000_0101)` sets /// channel 0 and 2 low. @@ -1774,7 +1757,7 @@ You should only disable dedicated GPIO drivers that were configured on the same /// i.e. `bits & !self.mask() == 0`. /// /// For example, if the bundle mask is `0b0000_0011` (channels 0 and 1), then `bits` must not - /// set bit 7 (e.g. `0b1000_0000`), or you would modify channel 7 outside the bundle. + /// set bit 7 (e.g. `0b1000_0000`), or channel 7 outside the bundle would be modified /// /// When compiled with `debug-assertions`, this condition is checked at runtime. /// @@ -1796,14 +1779,14 @@ You should only disable dedicated GPIO drivers that were configured on the same /// Writes output levels for **all channels included by this bundle**. /// - /// This method updates the output state of every channel whose bit is set in + /// Updates the output state of every channel whose bit is set in /// [`Self::mask`]. Channels not included in the bundle are not modified. /// /// `bits` provides the level for each channel in the bundle: /// - bit = 0 -> low /// - bit = 1 -> high /// - /// ## Example + /// # Examples /// /// If `self.mask()` is `0b1111_0000` (bundle contains channels 4..=7), then /// `bundle.write_bits(0b0001_0000)` sets channel 4 high and channels 5..=7 low, @@ -1811,10 +1794,10 @@ You should only disable dedicated GPIO drivers that were configured on the same /// ///
/// - /// This function only writes channels selected by [`Self::mask`]. It will **not** - /// change channels outside the mask, even if `bits` contains 1s there. + /// Only writes channels selected by [`Self::mask`]. Does **not** change channels outside the + /// mask, even if `bits` contains 1s there /// - /// Make sure this "masked write" behavior matches what you intend. + /// The masked write only updates channels selected by the mask. /// ///
#[inline(always)] @@ -1832,7 +1815,7 @@ You should only disable dedicated GPIO drivers that were configured on the same /// /// For channels outside the bundle mask, the corresponding bits are always 0. /// - /// ## Example + /// # Examples /// /// If the bundle mask is `0b0000_1011` (channels 0, 1, and 3), then /// `output_levels()` will only contain bits 0, 1, and 3, regardless of the output @@ -1852,7 +1835,7 @@ You should only disable dedicated GPIO drivers that were configured on the same /// /// For channels outside the bundle mask, the corresponding bits are always 0. /// - /// ## Example + /// # Examples /// /// If the bundle mask is `0b0000_1011` (channels 0, 1, and 3), then /// `levels()` will only contain bits 0, 1, and 3, regardless of the state @@ -1869,7 +1852,7 @@ You should only disable dedicated GPIO drivers that were configured on the same low_level::read_in() & self.mask } - /// Returns `true` if all channels in this bundle are currently high. + /// Returns whether all channels in this bundle are currently high. #[inline(always)] pub fn all_high(&self) -> bool { #[cfg(all(debug_assertions, multi_core))] @@ -1882,7 +1865,7 @@ You should only disable dedicated GPIO drivers that were configured on the same (low_level::read_in() & self.mask) == self.mask } - /// Returns `true` if all channels in this bundle are currently low. + /// Returns whether all channels in this bundle are currently low. #[inline(always)] pub fn all_low(&self) -> bool { #[cfg(all(debug_assertions, multi_core))] diff --git a/esp-hal/src/gpio/etm.rs b/esp-hal/src/gpio/etm.rs index 262346e42b5..c028bf4d477 100644 --- a/esp-hal/src/gpio/etm.rs +++ b/esp-hal/src/gpio/etm.rs @@ -99,7 +99,7 @@ pub struct Channels<'d> { } impl<'d> Channels<'d> { - /// Create a new instance + /// Creates a new instance. pub fn new(peripheral: GPIO_SD<'d>) -> Self { Self { _gpio_sd: peripheral, @@ -138,11 +138,11 @@ impl Default for InputConfig { } } -/// An ETM controlled GPIO event +/// An ETM controlled GPIO event. pub struct EventChannel {} impl EventChannel { - /// Trigger at rising edge + /// Triggers at rising edge. pub fn rising_edge<'d>( self, pin: impl Into>, @@ -151,7 +151,7 @@ impl EventChannel { self.into_event(pin, pin_config, EventKind::Rising) } - /// Trigger at falling edge + /// Triggers at falling edge. pub fn falling_edge<'d>( self, pin: impl Into>, @@ -160,7 +160,7 @@ impl EventChannel { self.into_event(pin, pin_config, EventKind::Falling) } - /// Trigger at any edge + /// Triggers at any edge. pub fn any_edge<'d>( self, pin: impl Into>, @@ -225,7 +225,7 @@ impl crate::etm::EtmEvent for Event<'_> { #[derive(Clone, Copy, Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub struct OutputConfig { - /// Set to open-drain output + /// Sets to open-drain output. pub open_drain: bool, /// Only used when open-drain pub pull: Pull, @@ -243,7 +243,7 @@ impl Default for OutputConfig { } } -/// An ETM controlled GPIO task +/// An ETM controlled GPIO task. pub struct TaskChannel {} impl TaskChannel { diff --git a/esp-hal/src/gpio/interconnect.rs b/esp-hal/src/gpio/interconnect.rs index bfa2e0ce353..22c8bfed5c6 100644 --- a/esp-hal/src/gpio/interconnect.rs +++ b/esp-hal/src/gpio/interconnect.rs @@ -5,7 +5,7 @@ //! and drivers, like routing fixed logic levels to peripheral inputs, or //! inverting input and output signals. //! -//! > Note that routing a signal through the GPIO matrix adds some latency to +//! > Routing a signal through the GPIO matrix adds some latency to //! > the signal. This is not a problem for most peripherals, but it can be an //! > issue for high-speed peripherals like SPI or I2S. `esp-hal` tries to //! > bypass the GPIO matrix when possible (e.g. when the pin can be configured @@ -29,7 +29,7 @@ //! - A fixed logic [`Level`] //! - [`NoPin`] //! -//! Note that some of these exist for convenience only. `Level` is meaningful as +//! Some of these exist for convenience only. `Level` is meaningful as //! a peripheral input, but not as a peripheral output. `NoPin` is a placeholder //! for when a peripheral driver does not require a pin, but the API requires //! one. It is equivalent to [`Level::Low`]. @@ -42,7 +42,7 @@ //! then be individually connected to a peripheral input or output signal. This //! allows for flexible routing of signals between peripherals and GPIO pins. //! -//! Note that only configured GPIO drivers can be safely turned into signals. +//! Only configured GPIO drivers can be safely turned into signals. //! This conversion freezes the pin configuration, otherwise it would be //! possible for multiple peripheral drivers to configure the same GPIO pin at //! the same time, which is undefined behavior. @@ -50,7 +50,7 @@ //! ### Splitting pins into signals //! //! GPIO pin types such as [`GPIO0`] or [`AnyPin`] can be **unsafely** -//! [split](AnyPin::split) into signals. In this case you need to carefully +//! [split](AnyPin::split) into signals. In that case, carefully //! ensure that only a single driver configures the split pin, by selectively //! [freezing](`InputSignal::freeze`) the signals. #![cfg_attr( @@ -59,7 +59,7 @@ input and a [UART](crate::uart::Uart) RX line, you will need to make sure one of the signals is frozen, otherwise the driver that is configured later will overwrite the other driver's configuration. Configuring the signals on - multiple cores is undefined behaviour unless you ensure the configuration + multiple cores is undefined behavior unless you ensure the configuration does not happen at the same time." )] //! ### Using pins and signals @@ -113,7 +113,7 @@ use crate::{ /// The base of all peripheral signals. /// -/// This trait represents a signal in the GPIO matrix. Signals are converted or +/// Represents a signal in the GPIO matrix. Signals are converted or /// split from GPIO pins and can be connected to peripheral inputs and outputs. /// /// All signals can be peripheral inputs, but not all output-like types should @@ -129,16 +129,22 @@ pub trait PeripheralSignal<'d>: Sealed { /// /// Peripheral drivers are encouraged to accept types that implement this and /// [`PeripheralOutput`] as arguments instead of pin types. +/// +/// To allow writing functions that are generic over GPIOs, this trait is +/// blanket-implemented for [`InputPin`][gpio::InputPin] types. #[allow( private_bounds, reason = "InputSignal is unstable, but the trait needs to be public" )] pub trait PeripheralInput<'d>: Into> + PeripheralSignal<'d> {} -/// A signal that can be connected to a peripheral input and/or output. +/// A signal that can be connected to a peripheral input or output. /// /// Peripheral drivers are encouraged to accept types that implement this and /// [`PeripheralInput`] as arguments instead of pin types. +/// +/// To allow writing functions that are generic over GPIOs, this trait is +/// blanket-implemented for [`OutputPin`] types. #[allow( private_bounds, reason = "OutputSignal is unstable, but the trait needs to be public" @@ -150,10 +156,9 @@ pub trait PeripheralOutput<'d>: Into> + PeripheralSignal<'d> { /// Disconnects the peripheral output from an output signal target. /// - /// This function clears the entry in the IO MUX that - /// associates this output pin with a previously connected - /// [signal](`gpio::OutputSignal`). Any other outputs connected to the - /// peripheral remain intact. + /// Clears the entry in the IO MUX that associates this output pin with a + /// previously connected [signal](`gpio::OutputSignal`). Any other outputs + /// connected to the peripheral remain intact. #[doc(hidden)] // Considered unstable fn disconnect_from_peripheral_output(&self); } @@ -289,15 +294,14 @@ impl gpio::InputSignal { /// Connects a peripheral input signal to a GPIO or a constant level. /// - /// Note that connecting multiple GPIOs to a single peripheral input is not - /// possible and the previous connection will be replaced. + /// Connecting multiple GPIOs to a single peripheral input is not possible, + /// and the previous connection is replaced. /// - /// Also note that a peripheral input must always be connected to something, - /// so if you want to disconnect it from GPIOs, you should connect it to a - /// constant level. + /// A peripheral input must always be connected to something. To disconnect it + /// from GPIOs, connect it to a constant level. /// - /// This function allows connecting a peripheral input to either a - /// [`PeripheralInput`] or [`PeripheralOutput`] implementation. + /// Connects a peripheral input to either a [`PeripheralInput`] or + /// [`PeripheralOutput`] implementation #[inline] #[instability::unstable] pub fn connect_to<'a>(self, pin: &impl PeripheralSignal<'a>) { @@ -312,11 +316,11 @@ impl gpio::OutputSignal { /// Connects a peripheral output signal to a GPIO. /// - /// Note that connecting multiple output signals to a single GPIO is not - /// possible and the previous connection will be replaced. + /// Connecting multiple output signals to a single GPIO is not possible, and + /// the previous connection is replaced. /// - /// Also note that it is possible to connect a peripheral output signal to - /// multiple GPIOs, and old connections will not be cleared automatically. + /// A peripheral output signal can be connected to multiple GPIOs. Old + /// connections are not cleared automatically. #[inline] #[instability::unstable] pub fn connect_to<'d>(self, pin: &impl PeripheralOutput<'d>) { @@ -579,11 +583,10 @@ impl<'d> InputSignal<'d> { /// /// # Safety /// - /// This function is unsafe because it allows peripherals to modify the pin - /// configuration again. This can lead to undefined behavior if the pin - /// is being configured by multiple peripherals at the same time. It can - /// also lead to surprising behavior if the pin is passed to multiple - /// peripherals that expect conflicting settings. + /// Lets peripherals modify the pin configuration again. This can lead to + /// undefined behavior if the pin is being configured by multiple peripherals + /// at the same time. It can also lead to surprising behavior if the pin is + /// passed to multiple peripherals that expect conflicting settings. pub unsafe fn unfreeze(&mut self) { self.flags.remove(InputFlags::Frozen); } @@ -595,24 +598,24 @@ impl<'d> InputSignal<'d> { self.pin.gpio_number() } - /// Returns `true` if the input signal is high. + /// Returns whether the input signal is high. /// - /// Note that this does not take [`Self::with_input_inverter`] into account. + /// Does not take [`Self::with_input_inverter`] into account. pub fn is_input_high(&self) -> bool { self.pin.is_input_high() } /// Returns the current signal level. /// - /// Note that this does not take [`Self::with_input_inverter`] into account. + /// Does not take [`Self::with_input_inverter`] into account. pub fn level(&self) -> Level { self.is_input_high().into() } - /// Returns `true` if the input signal is configured to be inverted. + /// Returns whether the input signal is configured to be inverted. /// - /// Note that the hardware is not configured until the signal is actually - /// connected to a peripheral. + /// The hardware is not configured until the signal is actually connected to + /// a peripheral. pub fn is_input_inverted(&self) -> bool { self.flags.contains(InputFlags::InvertInput) } @@ -631,7 +634,7 @@ impl<'d> InputSignal<'d> { self } - /// Returns `true` if the input signal must be routed through the GPIO + /// Returns whether the input signal must be routed through the GPIO /// matrix. pub fn is_gpio_matrix_forced(&self) -> bool { self.flags.contains(InputFlags::ForceGpioMatrix) @@ -677,8 +680,8 @@ enum OutputFlags { /// for configuring the pin with the correct settings, peripheral drivers will /// not be able to modify the pin settings. /// -/// Note that connecting this to a peripheral input will enable the input stage -/// of the GPIO pin. +/// Connecting this to a peripheral input enables the input stage of the GPIO +/// pin. /// /// Multiple pins can be connected to one output signal. #[instability::unstable] @@ -755,11 +758,10 @@ impl<'d> OutputSignal<'d> { /// /// # Safety /// - /// This function is unsafe because it allows peripherals to modify the pin - /// configuration again. This can lead to undefined behavior if the pin - /// is being configured by multiple peripherals at the same time. - /// It can also lead to surprising behavior if the pin is passed to multiple - /// peripherals that expect conflicting settings. + /// Lets peripherals modify the pin configuration again. This can lead to + /// undefined behavior if the pin is being configured by multiple peripherals + /// at the same time. It can also lead to surprising behavior if the pin is + /// passed to multiple peripherals that expect conflicting settings. pub unsafe fn unfreeze(&mut self) { self.flags.remove(OutputFlags::Frozen); } @@ -771,18 +773,18 @@ impl<'d> OutputSignal<'d> { self.pin.gpio_number() } - /// Returns `true` if the input signal is configured to be inverted. + /// Returns whether the input signal is configured to be inverted. /// - /// Note that the hardware is not configured until the signal is actually - /// connected to a peripheral. + /// The hardware is not configured until the signal is actually connected to + /// a peripheral. pub fn is_input_inverted(&self) -> bool { self.flags.contains(OutputFlags::InvertInput) } - /// Returns `true` if the output signal is configured to be inverted. + /// Returns whether the output signal is configured to be inverted. /// - /// Note that the hardware is not configured until the signal is actually - /// connected to a peripheral. + /// The hardware is not configured until the signal is actually connected to + /// a peripheral. pub fn is_output_inverted(&self) -> bool { self.flags.contains(OutputFlags::InvertOutput) } @@ -808,23 +810,22 @@ impl<'d> OutputSignal<'d> { self } - /// Returns `true` if the output signal must be routed through the GPIO + /// Returns whether the output signal must be routed through the GPIO /// matrix. pub fn is_gpio_matrix_forced(&self) -> bool { self.flags.contains(OutputFlags::ForceGpioMatrix) } - /// Returns `true` if the input signal is high. + /// Returns whether the input signal is high. /// - /// Note that this does not take [`Self::with_input_inverter`] into account. + /// Does not take [`Self::with_input_inverter`] into account. pub fn is_input_high(&self) -> bool { self.pin.is_input_high() } - /// Returns `true` if the output signal is set high. + /// Returns whether the output signal is set high. /// - /// Note that this does not take [`Self::with_output_inverter`] into - /// account. + /// Does not take [`Self::with_output_inverter`] into account. pub fn is_set_high(&self) -> bool { self.pin.is_set_high() } diff --git a/esp-hal/src/gpio/interrupt.rs b/esp-hal/src/gpio/interrupt.rs index 3fc95867796..228234dea1f 100644 --- a/esp-hal/src/gpio/interrupt.rs +++ b/esp-hal/src/gpio/interrupt.rs @@ -41,7 +41,7 @@ //! //! ## Signaling async completion //! -//! The completion is signalled by clearing a flag in an AtomicU32. This flag is +//! The completion is signaled by clearing a flag in an AtomicU32. This flag is //! set at the start of the async operation, and cleared when the interrupt //! handler is called. The flag is not accessible by the user, so they can't //! force-complete an async operation accidentally from the interrupt handler. @@ -51,42 +51,25 @@ //! (If the user were to clear the interrupt status, we would need to re-enable //! it, for PinFuture to detect the completion). -use portable_atomic::{AtomicPtr, Ordering}; +use portable_atomic::Ordering; use strum::EnumCount; -use crate::{ - gpio::{AnyPin, GPIO_LOCK, GpioBank, InputPin, low_level::set_int_enable}, - ram, -}; #[cfg(feature = "rt")] use crate::{ + gpio::low_level::disable_cpu_interrupt, handler, interrupt::{self, DEFAULT_INTERRUPT_HANDLER}, peripherals::Interrupt, system::Cpu, }; +use crate::{ + gpio::{AnyPin, GPIO_LOCK, GpioBank, InputPin, low_level::set_int_enable}, + private::CFnPtr, + ram, +}; -/// Convenience constant for `Option::None` pin pub(super) static USER_INTERRUPT_HANDLER: CFnPtr = CFnPtr::new(); -pub(super) struct CFnPtr(AtomicPtr<()>); -impl CFnPtr { - pub const fn new() -> Self { - Self(AtomicPtr::new(core::ptr::null_mut())) - } - - pub fn store(&self, f: extern "C" fn()) { - self.0.store(f as *mut (), Ordering::Relaxed); - } - - pub fn call(&self) { - let ptr = self.0.load(Ordering::Relaxed); - if !ptr.is_null() { - unsafe { (core::mem::transmute::<*mut (), extern "C" fn()>(ptr))() }; - } - } -} - #[cfg(feature = "rt")] pub(crate) fn bind_default_interrupt_handler() { // We first check if a handler is set in the vector table. @@ -117,9 +100,9 @@ pub(crate) fn bind_default_interrupt_handler() { super::low_level::enable_interrupt(default_gpio_interrupt_handler); } -/// The default GPIO interrupt handler, when the user has not set one. +/// The default GPIO interrupt handler, used when no custom handler is set. /// -/// This handler will disable all pending interrupts and leave the interrupt +/// This handler disables all pending interrupts and leaves the interrupt /// status bits unchanged. This enables functions like `is_interrupt_set` to /// work correctly. #[ram] @@ -148,15 +131,15 @@ fn default_gpio_interrupt_handler() { let pin_nr = pin_pos as u8 + bank.offset(); // The remaining interrupts are not async, we treat them as single-shot. - set_int_enable(pin_nr, Some(0), 0, false); + disable_cpu_interrupt(pin_nr); } } }); } -/// The user GPIO interrupt handler, when the user has set one. +/// The custom GPIO interrupt handler, used when one is set. /// -/// This handler only disables interrupts associated with async pins. The user +/// This handler only disables interrupts associated with async pins. The custom /// handler is responsible for clearing the interrupt status bits or disabling /// the interrupts. #[ram] diff --git a/esp-hal/src/gpio/low_level/mod.rs b/esp-hal/src/gpio/low_level/mod.rs index 58f14eab03e..b1dc680c530 100644 --- a/esp-hal/src/gpio/low_level/mod.rs +++ b/esp-hal/src/gpio/low_level/mod.rs @@ -81,7 +81,7 @@ impl GpioBank { /// /// The same bits also give the pins that can end a light sleep, because one write sets the /// interrupt enable and the wakeup enable of a pad. Sleep entry reads these bits, and thus - /// needs no register read for each pin. + /// needs no register read for each pin. The default interrupt handler clears only `int_ena`. pub(crate) fn listening(self) -> &'static AtomicU32 { static FLAGS: PadMask = PadMask::new(); @@ -198,7 +198,7 @@ pub(crate) fn bank(_gpio_num: u8) -> GpioBank { GpioBank::_0 } -/// Set GPIO event listening. +/// Sets GPIO event listening. /// /// - `gpio_num`: the pin to configure /// - `int_ena`: maskable and non-maskable CPU interrupt bits. None to leave unchanged. @@ -229,6 +229,14 @@ pub(crate) fn set_int_enable( } } +/// Clears the CPU interrupt enable of a pad, and keeps its wake condition. +#[cfg(feature = "rt")] +pub(crate) fn disable_cpu_interrupt(gpio_num: u8) { + GPIO::regs() + .pin(gpio_num as usize) + .modify(|_, w| unsafe { w.int_ena().bits(0) }); +} + pub(crate) fn is_int_enabled(gpio_num: u8) -> bool { GPIO::regs().pin(gpio_num as usize).read().int_ena().bits() != 0 } diff --git a/esp-hal/src/gpio/lp_io/low_level/esp32s31.rs b/esp-hal/src/gpio/lp_io/low_level/esp32s31.rs new file mode 100644 index 00000000000..9903c061b55 --- /dev/null +++ b/esp-hal/src/gpio/lp_io/low_level/esp32s31.rs @@ -0,0 +1,194 @@ +#[cfg(all(lp_io_has_gpio_matrix, lp_uart_driver_supported))] +use crate::gpio::lp_io::{LpInputSignal, LpOutputSignal}; +use crate::{ + gpio::{LpPin, lp_io::LpFunction}, + peripherals::{LP_GPIO, LP_IO_MUX, LP_PERI, LP_SYS}, +}; + +/// Number of pads that the low-power registers reach. Digital hold bits start after this count. +const LP_PAD_COUNT: u8 = 8; + +for_each_lp_function! { + (($_lp_pin_name:ident, LP_GPIOn, $lp_pin:literal), $gpio:ident, $_af:ident, $_lp_in:tt $_lp_out:tt) => { + impl LpPin for crate::peripherals::$gpio<'_> { + fn lp_number(&self) -> u8 { + $lp_pin + } + } + }; + + // Each pad has its own signal table, so this code selects the table by the low-power number. + (LP_GPIOn $(( + ($_lp_pin_name:ident, LP_GPIOn, $lp_pin:literal), + $gpio:ident, + $_af:ident, + ($( $lp_in_af:ident => $lp_in_signal:ident )*) + ($( $lp_out_af:ident => $lp_out_signal:ident )*) + )),*) => { + #[cfg(all(lp_io_has_gpio_matrix, lp_uart_driver_supported))] + pub(crate) fn input_signals(lp: u8) -> &'static [(LpFunction, LpInputSignal)] { + match lp { + $( $lp_pin => &[$( (LpFunction::$lp_in_af, LpInputSignal::$lp_in_signal) ),*], )* + _ => unreachable!(), + } + } + + #[cfg(all(lp_io_has_gpio_matrix, lp_uart_driver_supported))] + pub(crate) fn output_signals(lp: u8) -> &'static [(LpFunction, LpOutputSignal)] { + match lp { + $( $lp_pin => &[$( (LpFunction::$lp_out_af, LpOutputSignal::$lp_out_signal) ),*], )* + _ => unreachable!(), + } + } + }; +} + +fn enable_io_clock() { + LP_PERI::regs() + .iomux_ctrl() + .modify(|_, w| w.lp_iomux_clk_en().set_bit()); + LP_GPIO::regs() + .clock_gate() + .modify(|_, w| w.clk_en().set_bit()); + while LP_PERI::regs() + .iomux_ctrl() + .read() + .lp_iomux_clk_en() + .bit_is_clear() + || LP_GPIO::regs().clock_gate().read().clk_en().bit_is_clear() + {} +} + +pub(crate) fn set_config(lp: u8, input_enable: bool, mux: bool, func: LpFunction) { + if mux { + enable_io_clock(); + } + + LP_SYS::regs().padctrl().modify(|r, w| unsafe { + let mut sel = r.pad_mux_sel().bits(); + if mux { + sel |= 1u8 << lp; + } else { + sel &= !(1u8 << lp); + } + w.pad_mux_sel().bits(sel) + }); + + LP_IO_MUX::regs().gpio(lp as usize).modify(|_, w| unsafe { + w.slp_sel().bit(false); + w.fun_ie().bit(input_enable); + w.mcu_sel().bits(func as u8) + }); +} + +#[cfg(lp_io_has_gpio_matrix)] +pub(crate) fn init_pin(lp: u8, input_enable: bool) -> u8 { + set_config(lp, input_enable, true, LpFunction::LP_GPIO); + lp +} + +#[cfg(lp_io_has_gpio_matrix)] +pub(crate) fn output_enable(lp: u8, enable: bool) { + if enable { + LP_GPIO::regs() + .enable_w1ts() + .write(|w| unsafe { w.enable_w1ts().bits(1u8 << lp) }); + } else { + LP_GPIO::regs() + .enable_w1tc() + .write(|w| unsafe { w.enable_w1tc().bits(1u8 << lp) }); + } +} + +#[cfg(lp_io_has_gpio_matrix)] +pub(crate) fn input_enable(lp: u8, enable: bool) { + LP_IO_MUX::regs() + .gpio(lp as usize) + .modify(|_, w| w.fun_ie().bit(enable)); +} + +pub(crate) fn pullup_enable(lp: u8, enable: bool) { + LP_IO_MUX::regs() + .gpio(lp as usize) + .modify(|_, w| w.fun_wpu().bit(enable)); +} + +pub(crate) fn pulldown_enable(lp: u8, enable: bool) { + LP_IO_MUX::regs() + .gpio(lp as usize) + .modify(|_, w| w.fun_wpd().bit(enable)); +} + +pub(crate) fn pad_hold(lp: u8, enable: bool) { + LP_SYS::regs().padctrl().modify(|r, w| unsafe { + let mut hold = r.pad_hold().bits(); + if enable { + hold |= 1u8 << lp; + } else { + hold &= !(1u8 << lp); + } + w.pad_hold().bits(hold) + }); +} + +/// Returns whether something holds the pad. +pub(crate) fn is_pad_held(lp: u8) -> bool { + LP_SYS::regs().padctrl().read().pad_hold().bits() & (1u8 << lp) != 0 +} + +/// Takes or releases the hold of the pad of `gpio`. +/// +/// The digital hold registers start at GPIO8, which is the first pad of the digital supply. +pub(crate) fn digital_pad_hold(gpio: u8, enable: bool) { + let Some(bit) = gpio.checked_sub(LP_PAD_COUNT) else { + return; + }; + + if bit < 32 { + let mask = 1 << bit; + LP_SYS::regs().hp_gpio_o_hold_ctrl0().modify(|r, w| unsafe { + let bits = r.hp_gpio_0_hold_ctrl0().bits(); + w.hp_gpio_0_hold_ctrl0() + .bits(if enable { bits | mask } else { bits & !mask }) + }); + } else { + let mask = 1 << (bit - 32); + LP_SYS::regs().hp_gpio_o_hold_ctrl1().modify(|r, w| unsafe { + let bits = r.hp_gpio_0_hold_ctrl1().bits(); + w.hp_gpio_0_hold_ctrl1() + .bits(if enable { bits | mask } else { bits & !mask }) + }); + } +} + +/// Returns whether something holds the pad of `gpio`. +pub(crate) fn is_digital_pad_held(gpio: u8) -> bool { + let Some(bit) = gpio.checked_sub(LP_PAD_COUNT) else { + return false; + }; + + if bit < 32 { + LP_SYS::regs() + .hp_gpio_o_hold_ctrl0() + .read() + .hp_gpio_0_hold_ctrl0() + .bits() + & (1 << bit) + != 0 + } else { + LP_SYS::regs() + .hp_gpio_o_hold_ctrl1() + .read() + .hp_gpio_0_hold_ctrl1() + .bits() + & (1 << (bit - 32)) + != 0 + } +} + +#[cfg(lp_io_has_gpio_matrix)] +pub(crate) fn set_open_drain_output(lp: u8, enable: bool) { + LP_GPIO::regs() + .pin(lp as usize) + .modify(|_, w| w.pad_driver().bit(enable)); +} diff --git a/esp-hal/src/gpio/lp_io/low_level/v4.rs b/esp-hal/src/gpio/lp_io/low_level/v4.rs index ca8eded59e1..f7ee88ddd9b 100644 --- a/esp-hal/src/gpio/lp_io/low_level/v4.rs +++ b/esp-hal/src/gpio/lp_io/low_level/v4.rs @@ -7,7 +7,7 @@ cfg_select! { esp32c6 => { use crate::peripherals::{LP_IO as LP_GPIO, LP_IO as LP_IO_MUX}; } - any(esp32c5, esp32c61) => { + any(esp32c5, esp32c61, esp32h4) => { // Only a low-power peripheral or a low-power core reads and drives the pads. #[cfg(any( ulp_riscv_driver_supported, @@ -43,17 +43,25 @@ pub(crate) fn is_pad_held(lp: u8) -> bool { /// Takes or releases the hold of the pad of `gpio`. pub(crate) fn digital_pad_hold(gpio: u8, enable: bool) { - let mask = 1 << gpio; - LP_AON::regs().gpio_hold0().modify(|r, w| unsafe { - let bits = r.gpio_hold0().bits(); - w.gpio_hold0() - .bits(if enable { bits | mask } else { bits & !mask }) - }); + let update = |bits: u32, mask: u32| if enable { bits | mask } else { bits & !mask }; + if gpio < 32 { + LP_AON::regs() + .gpio_hold0() + .modify(|r, w| unsafe { w.bits(update(r.bits(), 1 << gpio)) }); + } else { + LP_AON::regs() + .gpio_hold1() + .modify(|r, w| unsafe { w.bits(update(r.bits(), 1 << (gpio - 32))) }); + } } /// Returns whether something holds the pad of `gpio`. pub(crate) fn is_digital_pad_held(gpio: u8) -> bool { - LP_AON::regs().gpio_hold0().read().gpio_hold0().bits() & (1 << gpio) != 0 + if gpio < 32 { + LP_AON::regs().gpio_hold0().read().bits() & (1 << gpio) != 0 + } else { + LP_AON::regs().gpio_hold1().read().bits() & (1 << (gpio - 32)) != 0 + } } pub(crate) fn set_config(lp: u8, input_enable: bool, mux: bool, func: LpFunction) { @@ -66,6 +74,7 @@ pub(crate) fn set_config(lp: u8, input_enable: bool, mux: bool, func: LpFunction LP_IO_MUX::regs().gpio(lp as usize).modify(|_, w| unsafe { w.slp_sel().bit(false); w.fun_ie().bit(input_enable); + w.mcu_ie().bit(input_enable); w.mcu_sel().bits(func as u8) }); } @@ -95,9 +104,10 @@ pub(crate) fn output_enable(lp: u8, enable: bool) { #[cfg(any(ulp_riscv_driver_supported, lp_io_has_gpio_matrix))] pub(crate) fn input_enable(lp: u8, enable: bool) { - LP_IO_MUX::regs() - .gpio(lp as usize) - .modify(|_, w| w.fun_ie().bit(enable)); + LP_IO_MUX::regs().gpio(lp as usize).modify(|_, w| { + w.fun_ie().bit(enable); + w.mcu_ie().bit(enable) + }); } pub(crate) fn pullup_enable(lp: u8, enable: bool) { diff --git a/esp-hal/src/gpio/lp_io/mod.rs b/esp-hal/src/gpio/lp_io/mod.rs index 468fb579c1d..0a9c122a440 100644 --- a/esp-hal/src/gpio/lp_io/mod.rs +++ b/esp-hal/src/gpio/lp_io/mod.rs @@ -64,6 +64,7 @@ define_lp_functions!(); #[cfg_attr(lp_io_version = "v3", path = "low_level/v3.rs")] #[cfg_attr(lp_io_version = "esp32h2", path = "low_level/esp32h2.rs")] #[cfg_attr(lp_io_version = "esp32p4", path = "low_level/esp32p4.rs")] +#[cfg_attr(lp_io_version = "esp32s31", path = "low_level/esp32s31.rs")] #[cfg_attr(lp_io_version = "v4", path = "low_level/v4.rs")] pub(crate) mod low_level; @@ -171,8 +172,16 @@ fn route_input(lp_pin: u8, input: LpInputSignal, use_gpio_matrix: bool) { .func_in_sel_cfg(input as usize) .write(|w| unsafe { w.sig_in_sel().bit(use_gpio_matrix); - w.in_inv_sel().clear_bit(); - w.in_sel().bits(lp_pin) + cfg_select! { + esp32s31 => { + w.func_in_inv_sel().clear_bit(); + w.func_in_sel().bits(lp_pin) + } + _ => { + w.in_inv_sel().clear_bit(); + w.in_sel().bits(lp_pin) + } + } }); } @@ -181,11 +190,21 @@ fn route_output(lp_pin: u8, output: LpOutputSignal) { crate::peripherals::LP_GPIO::regs() .func_out_sel_cfg(lp_pin as usize) .write(|w| unsafe { - w.out_sel().bits(output as _); - w.out_inv_sel().clear_bit(); - // Let the peripheral drive the output enable signal. - w.oe_sel().clear_bit(); - w.oe_inv_sel().clear_bit() + cfg_select! { + esp32s31 => { + w.func_out_sel().bits(output as _); + w.func_out_inv_sel().clear_bit(); + w.func_oe_sel().clear_bit(); + w.func_oe_inv_sel().clear_bit() + } + _ => { + w.out_sel().bits(output as _); + w.out_inv_sel().clear_bit(); + // Let the peripheral drive the output enable signal. + w.oe_sel().clear_bit(); + w.oe_inv_sel().clear_bit() + } + } }); } @@ -218,7 +237,7 @@ mod ulp_tokens { /// /// # Errors /// - /// Returns the driver unchanged if the pad is not the low-power pin numbered `PIN`. + /// The original driver when the pad is not the low-power pin numbered `PIN`. #[instability::unstable] pub fn into_lp(self) -> Result, Self> { if lp_number(self.pin.pin.number()) != Some(PIN) { @@ -237,7 +256,7 @@ mod ulp_tokens { /// /// # Errors /// - /// Returns the driver unchanged if the pad is not the low-power pin numbered `PIN`. + /// The original driver when the pad is not the low-power pin numbered `PIN`. #[instability::unstable] pub fn into_lp(self) -> Result, Self> { if lp_number(self.pin.pin.number()) != Some(PIN) { @@ -254,7 +273,7 @@ mod ulp_tokens { /// /// # Errors /// - /// Returns the driver unchanged if the pad is not the low-power pin numbered `PIN`. + /// The original driver when the pad is not the low-power pin numbered `PIN`. #[instability::unstable] pub fn into_open_drain_lp( self, diff --git a/esp-hal/src/gpio/mod.rs b/esp-hal/src/gpio/mod.rs index 32e4ead0ba0..2bc59d0623b 100644 --- a/esp-hal/src/gpio/mod.rs +++ b/esp-hal/src/gpio/mod.rs @@ -100,8 +100,8 @@ pub(crate) static GPIO_LOCK: RawMutex = RawMutex::new(); /// Represents a pin-peripheral connection that, when dropped, disconnects the /// peripheral from the pin. /// -/// This only needs to be applied to output signals, as it's not possible to -/// connect multiple inputs to the same peripheral signal. +/// This only needs to be applied to output signals, as it is not possible to connect multiple +/// inputs to the same peripheral signal. #[derive(Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub(crate) struct PinGuard { @@ -189,7 +189,7 @@ impl core::ops::Not for Level { } impl Level { - /// Create a [`Level`] from [`bool`]. + /// Creates a new [`Level`] from [`bool`]. /// /// Like `>::from(val)`, but `const`. pub(crate) const fn const_from(val: bool) -> Self { @@ -199,7 +199,7 @@ impl Level { } } - /// Convert a [`Level`] to [`bool`]. + /// Converts a [`Level`] to [`bool`]. /// /// Like `>::from(self)`, but `const`. pub(crate) const fn const_into(self) -> bool { @@ -280,7 +280,7 @@ pub enum DriveStrength { /// output. /// /// The different variants correspond to different functionality depending on -/// the chip and the specific pin. For more information, refer to your chip's +/// the chip and the specific pin. For more information, refer to the chip's #[doc(hidden)] #[doc = crate::trm_markdown_link!("iomuxgpio")] #[derive(Debug, Eq, PartialEq, Copy, Clone, Hash)] @@ -346,13 +346,13 @@ pub trait Pin: Sealed { fn number(&self) -> u8; #[procmacros::doc_replace] - /// Type-erase this pin into an [`AnyPin`]. + /// Type-erases this pin into an [`AnyPin`]. /// - /// This function converts pin singletons (`GPIO0<'_>`, …), which are all - /// different types, into the same type. It is useful for creating - /// arrays of pins, or avoiding generics. + /// Converts pin singletons (`GPIO0<'_>`, …), which are all different types, + /// into the same type. Useful for creating arrays of pins, or avoiding + /// generics. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -402,31 +402,31 @@ pub trait InputPin: Pin { /// Trait implemented by pins which can be used as outputs. pub trait OutputPin: Pin {} -/// Trait implemented by pins which can be used as analog pins +/// Trait implemented by pins which can be used as analog pins. #[instability::unstable] pub trait AnalogPin: Pin { - /// Configure the pin for analog operation + /// Configures the pin for analog operation. #[doc(hidden)] fn set_analog(&self, _: private::Internal); } -/// Trait implemented by pins which can be used as Touchpad pins +/// Trait implemented by pins which can be used as Touchpad pins. #[cfg(touch_driver_supported)] #[instability::unstable] pub trait TouchPin: Pin { - /// Configure the pin for analog operation + /// Configures the pin for analog operation. #[doc(hidden)] fn set_touch(&self, _: private::Internal); - /// Reads the pin's touch measurement register + /// Reads the pin's touch measurement register. #[doc(hidden)] fn touch_measurement(&self, _: private::Internal) -> u16; - /// Maps the pin nr to the touch pad nr + /// Maps the pin nr to the touch pad nr. #[doc(hidden)] fn touch_nr(&self, _: private::Internal) -> u8; - /// Set a pins touch threshold for interrupts. + /// Sets a pins touch threshold for interrupts. #[doc(hidden)] fn set_threshold(&self, threshold: u16, _: private::Internal); } @@ -439,7 +439,7 @@ pub struct AnyPin<'lt> { pub(crate) _lifetime: core::marker::PhantomData<&'lt mut ()>, } -/// General Purpose Input/Output driver +/// General Purpose Input/Output driver. #[derive(Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[instability::unstable] @@ -448,14 +448,14 @@ pub struct Io<'d> { } impl<'d> Io<'d> { - /// Initialize the I/O driver. + /// Initializes the I/O driver. #[instability::unstable] pub fn new(_io_mux: IO_MUX<'d>) -> Self { Io { _io_mux } } #[doc = cfg_select!{ - any(single_core, esp32s3) => "Sets the the interrupt priority and enables GPIO interrupts.", + any(single_core, esp32s3) => "Sets the interrupt priority and enables GPIO interrupts.", _ => "Sets the interrupt priority and enables GPIO interrupts on all cores.", }] #[instability::unstable] @@ -468,18 +468,17 @@ impl<'d> Io<'d> { _ => "Registers an interrupt handler for all GPIO pins. Enables interrupts on all cores.", }] #[doc = ""] - /// Note that when using interrupt handlers registered by this function, or - /// by defining a `#[no_mangle] unsafe extern "C" fn GPIO()` function, we do - /// **not** clear the interrupt status register or the interrupt enable - /// setting for you. Based on your use case, you need to do one of this - /// yourself: - /// - /// - Disabling the interrupt enable setting for the GPIO pin allows you to handle an event once - /// per call to [`listen()`]. Using this method, the [`is_interrupt_set()`] method will return - /// `true` if the interrupt is set even after your handler has finished running. - /// - Clearing the interrupt status register allows you to handle an event repeatedly after - /// [`listen()`] is called. Using this method, [`is_interrupt_set()`] will return `false` - /// after your handler has finished running. + /// When using interrupt handlers registered by this method, or by defining a + /// `#[no_mangle] unsafe extern "C" fn GPIO()` function, the interrupt status + /// register and the interrupt enable setting for the GPIO pin are **not** + /// cleared automatically. Based on the use case, do one of the following: + /// + /// - Disabling the interrupt enable setting for the GPIO pin lets an event be handled once per + /// call to [`listen()`]. Using this method, the [`is_interrupt_set()`] method returns `true` + /// if the interrupt is set even after the handler has finished running. + /// - Clearing the interrupt status register lets an event be handled repeatedly after + /// [`listen()`] is called. Using this method, [`is_interrupt_set()`] returns `false` after + /// the handler has finished running. /// /// [`listen()`]: Input::listen /// [`is_interrupt_set()`]: Input::is_interrupt_set @@ -502,12 +501,12 @@ impl crate::interrupt::InterruptConfigurable for Io<'_> { } } -/// Drive the GPIO async API from a user-installed raw GPIO interrupt handler. +/// Drives the GPIO async API from a user-installed raw GPIO interrupt handler. /// -/// This is the entry point that lets users who bypass esp-hal's GPIO ISR -/// dispatch (typically by defining their own `#[unsafe(no_mangle)] -/// unsafe extern "C" fn GPIO()`, or by registering their own handler via -/// [`crate::interrupt::bind_handler`]) keep the GPIO async API working. +/// Entry point for code that bypasses esp-hal's GPIO ISR dispatch (typically +/// by defining a custom `#[unsafe(no_mangle)] unsafe extern "C" fn GPIO()`, or +/// by registering a handler via [`crate::interrupt::bind_handler`]) and needs +/// the GPIO async API to keep working. /// /// # Safety /// @@ -517,7 +516,7 @@ pub unsafe fn handle_gpio_interrupt() { unsafe { interrupt::handle_gpio_interrupt_impl() } } -/// Complete any in-flight async wait on a single GPIO pin. +/// Completes any in-flight async wait on a single GPIO pin. /// /// Per-pin counterpart of [`handle_gpio_interrupt`]. /// @@ -538,16 +537,11 @@ for_each_analog_function! { xtensa => { self.set_analog_impl(); } riscv => { // Just configure as a floating GPIO. - io_mux_reg(self.number()).modify(|_, w| unsafe { - w.mcu_sel().bits(AlternateFunction::GPIO as u8); - w.fun_ie().clear_bit(); + unsafe { AnyPin::steal(self.number()) }.init_gpio(); + io_mux_reg(self.number()).modify(|_, w| { w.fun_wpu().clear_bit(); w.fun_wpd().clear_bit() }); - - GPIO::regs() - .enable_w1tc() - .write(|w| unsafe { w.bits(1 << self.number()) }); } } } @@ -580,8 +574,8 @@ pub enum DriveMode { /// Output pin configuration. /// -/// This struct is used to configure the drive mode, drive strength, and pull -/// direction of an output pin. By default, the configuration is set to: +/// Configures the drive mode, drive strength, and pull direction of an output +/// pin. By default, the configuration is set to: /// - Drive mode: [`DriveMode::PushPull`] /// - Drive strength: [`DriveStrength::_20mA`] /// - Pull direction: [`Pull::None`] (no pull resistors connected) @@ -629,7 +623,7 @@ impl<'d> Output<'d> { /// The `config` parameter sets the drive mode, drive strength, and pull /// direction of the pin. /// - /// ## Example + /// # Examples /// /// The following example configures `GPIO5` to pulse a LED once. The /// example assumes that the LED is connected such that it is on when @@ -675,10 +669,9 @@ impl<'d> Output<'d> { /// The output signal can be passed to peripherals in place of an output /// pin. /// - /// Note that the signal returned by this function is - /// [frozen](interconnect::OutputSignal::freeze). + /// The returned signal is [frozen](interconnect::OutputSignal::freeze). /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -695,9 +688,9 @@ impl<'d> Output<'d> { } #[procmacros::doc_replace] - /// Change the configuration. + /// Changes the configuration. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -713,9 +706,9 @@ impl<'d> Output<'d> { self.pin.apply_output_config(config) } #[procmacros::doc_replace] - /// Set the output as high. + /// Sets the output as high. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -731,9 +724,9 @@ impl<'d> Output<'d> { } #[procmacros::doc_replace] - /// Set the output as low. + /// Sets the output as low. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -749,9 +742,9 @@ impl<'d> Output<'d> { } #[procmacros::doc_replace] - /// Set the output level.ç + /// Sets the output level. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -769,10 +762,10 @@ impl<'d> Output<'d> { #[procmacros::doc_replace] /// Returns whether the pin is set to high level. /// - /// This function reads back the value set using `set_level`, `set_high` or - /// `set_low`. It does not need the input stage to be enabled. + /// Reads back the value set using `set_level`, `set_high` or `set_low`. Does + /// not need the input stage to be enabled. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -790,10 +783,10 @@ impl<'d> Output<'d> { #[procmacros::doc_replace] /// Returns whether the pin is set to low level. /// - /// This function reads back the value set using `set_level`, `set_high` or - /// `set_low`. It does not need the input stage to be enabled. + /// Reads back the value set using `set_level`, `set_high` or `set_low`. Does + /// not need the input stage to be enabled. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -811,10 +804,10 @@ impl<'d> Output<'d> { #[procmacros::doc_replace] /// Returns which level the pin is set to. /// - /// This function reads back the value set using `set_level`, `set_high` or - /// `set_low`. It does not need the input stage to be enabled. + /// Reads back the value set using `set_level`, `set_high` or `set_low`. Does + /// not need the input stage to be enabled. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -835,7 +828,7 @@ impl<'d> Output<'d> { /// If the pin was previously set to high, it will be set to low, and vice /// versa. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -951,7 +944,7 @@ impl<'d> Input<'d> { /// The `pull` parameter configures internal pull-up or pull-down /// resistors. /// - /// ## Example + /// # Examples /// /// The following example configures `GPIO5` to read a button press. The /// example assumes that the button is connected such that the pin is low @@ -1000,10 +993,9 @@ impl<'d> Input<'d> { /// /// The input signal can be passed to peripherals in place of an input pin. /// - /// Note that the signal returned by this function is - /// [frozen](interconnect::InputSignal::freeze). + /// The returned signal is [frozen](interconnect::InputSignal::freeze). /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1022,9 +1014,9 @@ impl<'d> Input<'d> { } #[procmacros::doc_replace] - /// Get whether the pin input level is high. + /// Returns whether the pin input level is high. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1040,9 +1032,9 @@ impl<'d> Input<'d> { } #[procmacros::doc_replace] - /// Get whether the pin input level is low. + /// Returns whether the pin input level is low. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1058,9 +1050,9 @@ impl<'d> Input<'d> { } #[procmacros::doc_replace] - /// Get the current pin input level. + /// Returns the current pin input level. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1076,9 +1068,9 @@ impl<'d> Input<'d> { } #[procmacros::doc_replace] - /// Change the configuration. + /// Changes the configuration. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1093,17 +1085,16 @@ impl<'d> Input<'d> { } #[procmacros::doc_replace] - /// Listen for interrupts. + /// Listens for interrupts. /// /// The interrupts will be handled by the handler set using /// [`Io::set_interrupt_handler`]. All GPIO pins share the same /// interrupt handler. /// - /// Note that [`Event::LowLevel`] and [`Event::HighLevel`] are fired - /// continuously when the pin is low or high, respectively. You must use - /// a custom interrupt handler to stop listening for these events, - /// otherwise your program will be stuck in a loop as long as the pin is - /// reading the corresponding level. + /// [`Event::LowLevel`] and [`Event::HighLevel`] are fired continuously when + /// the pin is low or high, respectively. A custom interrupt handler is + /// required to stop listening for these events; otherwise the program can + /// remain in a loop as long as the pin reads the corresponding level. /// /// A listening pin also ends a light sleep. On most chips, sleep entry must give the trigger as /// a level, so an edge trigger becomes the level at the end of the edge. A rising edge becomes @@ -1112,7 +1103,7 @@ impl<'d> Input<'d> { /// that is already high therefore ends each light sleep immediately, and without an /// interrupt, because no edge occurred. Automatic light sleep then makes no sleep at all. /// - /// ## Examples + /// # Examples /// /// ### Print something when a button is pressed. /// ```rust, no_run @@ -1176,21 +1167,21 @@ impl<'d> Input<'d> { self.pin.listen(event); } - /// Stop listening for interrupts + /// Stops listening for interrupts. #[inline] #[instability::unstable] pub fn unlisten(&mut self) { self.pin.unlisten(); } - /// Clear the interrupt status bit for this Pin + /// Clears the interrupt status bit for this Pin. #[inline] #[instability::unstable] pub fn clear_interrupt(&mut self) { self.pin.clear_interrupt(); } - /// Checks if the interrupt status bit for this Pin is set + /// Returns whether the interrupt status bit for this Pin is set. #[inline] #[instability::unstable] pub fn is_interrupt_set(&self) -> bool { @@ -1204,7 +1195,7 @@ impl<'d> Input<'d> { /// /// # Errors /// - /// Returns [`WakeConfigError::NoLowPowerPath`] if the configuration requests the low-power path + /// [`WakeConfigError::NoLowPowerPath`] when the configuration requests the low-power path /// for a pad that has no such path. #[cfg(sleep_driver_supported)] #[instability::unstable] @@ -1256,7 +1247,7 @@ impl<'d> Input<'d> { /// separately configurable, and they have independent enable states. /// /// Enabling the input stage does not change the output stage, and vice versa. -/// Disabling the input or output stages don't forget their configuration. +/// Disabling the input or output stages do not forget their configuration. /// Disabling the output stage will not change the output level, but it will /// disable the driver. #[derive(Debug)] @@ -1270,7 +1261,7 @@ impl private::Sealed for Flex<'_> {} impl private::Sealed for &mut Flex<'_> {} impl<'d> Flex<'d> { - /// Create flexible pin driver for a [Pin]. + /// Creates flexible pin driver for a [Pin]. /// No mode change happens. #[inline] #[instability::unstable] @@ -1287,16 +1278,15 @@ impl<'d> Flex<'d> { /// Applies the given input configuration to the pin. /// - /// This function does not set the pin as input (i.e. it does not enable the - /// input buffer). Note that the pull direction is common between the - /// input and output configuration. + /// Does not set the pin as input (does not enable the input buffer). The pull + /// direction is common between the input and output configuration. #[inline] #[instability::unstable] pub fn apply_input_config(&mut self, config: &InputConfig) { self.pin.apply_input_config(config); } - /// Enable or disable the GPIO pin input buffer. + /// Enables or disables the GPIO pin input buffer. #[inline] #[instability::unstable] pub fn set_input_enable(&mut self, enable_input: bool) { @@ -1321,28 +1311,28 @@ impl<'d> Flex<'d> { self.pin.is_pad_held() } - /// Get whether the pin input level is high. + /// Returns whether the pin input level is high. #[inline] #[instability::unstable] pub fn is_high(&self) -> bool { self.level() == Level::High } - /// Get whether the pin input level is low. + /// Returns whether the pin input level is low. #[inline] #[instability::unstable] pub fn is_low(&self) -> bool { self.level() == Level::Low } - /// Get the current pin input level. + /// Returns the current pin input level. #[inline] #[instability::unstable] pub fn level(&self) -> Level { self.pin.is_input_high().into() } - /// Listen for interrupts. + /// Listens for interrupts. /// /// See [`Input::listen`] for more information and an example. #[inline] @@ -1351,7 +1341,7 @@ impl<'d> Flex<'d> { self.pin.listen(event); } - /// Stop listening for interrupts. + /// Stops listening for interrupts. #[inline] #[instability::unstable] pub fn unlisten(&mut self) { @@ -1367,14 +1357,14 @@ impl<'d> Flex<'d> { }); } - /// Check if the pin is listening for interrupts. + /// Returns whether the pin is listening for interrupts. #[inline] #[instability::unstable] pub fn is_listening(&self) -> bool { is_int_enabled(self.pin.number()) } - /// Clear the interrupt status bit for this Pin + /// Clears the interrupt status bit for this Pin. #[inline] #[instability::unstable] pub fn clear_interrupt(&mut self) { @@ -1383,7 +1373,7 @@ impl<'d> Flex<'d> { .write_interrupt_status_clear(self.pin.mask()); } - /// Checks if the interrupt status bit for this Pin is set + /// Returns whether the interrupt status bit for this Pin is set. #[inline] #[instability::unstable] pub fn is_interrupt_set(&self) -> bool { @@ -1403,7 +1393,7 @@ impl<'d> Flex<'d> { /// /// # Errors /// - /// Returns [`WakeConfigError::NoLowPowerPath`] if the configuration requests the low-power path + /// [`WakeConfigError::NoLowPowerPath`] when the configuration requests the low-power path /// for a pad that has no such path. #[cfg(sleep_driver_supported)] #[inline] @@ -1434,43 +1424,42 @@ impl<'d> Flex<'d> { /// Applies the given output configuration to the pin. /// - /// This function does not set the pin to output (i.e. it does not enable - /// the output driver). Note that the pull direction is common between - /// the input and output configuration. + /// Does not set the pin to output (does not enable the output driver). The + /// pull direction is common between the input and output configuration. #[inline] #[instability::unstable] pub fn apply_output_config(&mut self, config: &OutputConfig) { self.pin.apply_output_config(config); } - /// Enable or disable the GPIO pin output driver. + /// Enables or disables the GPIO pin output driver. /// /// The output level will be set to the last value. Use [`Self::set_high`], /// [`Self::set_low`] or [`Self::set_level`] to set the output level before /// enabling the output. /// - /// This function does not disable the input buffer. + /// Does not disable the input buffer. #[inline] #[instability::unstable] pub fn set_output_enable(&mut self, enable_output: bool) { self.pin.set_output_enable(enable_output); } - /// Set the output as high. + /// Sets the output as high. #[inline] #[instability::unstable] pub fn set_high(&mut self) { self.set_level(Level::High) } - /// Set the output as low. + /// Sets the output as low. #[inline] #[instability::unstable] pub fn set_low(&mut self) { self.set_level(Level::Low) } - /// Set the output level. + /// Sets the output level. #[inline] #[instability::unstable] pub fn set_level(&mut self, level: Level) { @@ -1491,14 +1480,14 @@ impl<'d> Flex<'d> { self.output_level() == Level::Low } - /// What level output is set to + /// What level output is set to. #[inline] #[instability::unstable] pub fn output_level(&self) -> Level { self.pin.is_set_high().into() } - /// Toggle pin output + /// Toggles pin output. #[inline] #[instability::unstable] pub fn toggle(&mut self) { @@ -1514,8 +1503,7 @@ impl<'d> Flex<'d> { /// /// The input signal can be passed to peripherals in place of an input pin. /// - /// Note that the signal returned by this function is - /// [frozen](interconnect::InputSignal::freeze). + /// The returned signal is [frozen](interconnect::InputSignal::freeze). /// /// ```rust, no_run /// # {before_snippet} @@ -1538,13 +1526,12 @@ impl<'d> Flex<'d> { } #[procmacros::doc_replace] - /// Split the pin into an input and output signal pair. + /// Splits the pin into an input and output signal pair. /// /// Peripheral signals allow connecting peripherals together without using /// external hardware. /// - /// Note that the signals returned by this function is - /// [frozen](interconnect::InputSignal::freeze). + /// The returned signals are [frozen](interconnect::InputSignal::freeze). /// /// ```rust, no_run /// # {before_snippet} @@ -1567,16 +1554,14 @@ impl<'d> Flex<'d> { (input, output) } - /// Split the pin into an [Input] and an [Output] driver pair. + /// Splits the pin into an [Input] and an [Output] driver pair. /// - /// Note that the signal returned by this function is - /// [frozen](interconnect::InputSignal::freeze). On the other hand, - /// the pin driver is free to change settings. + /// The returned input signal is [frozen](interconnect::InputSignal::freeze). The + /// pin driver is free to change settings. /// - /// This function allows you to configure an input-output pin, then keep - /// working with the output half. This is mainly intended for testing, - /// allowing you to drive a peripheral from a signal generated by - /// software. + /// Lets an input-output pin be configured, then keeps working with the output + /// half. Mainly intended for testing, to drive a peripheral from a signal + /// generated by software. /// /// # Safety /// @@ -1608,8 +1593,7 @@ impl<'d> Flex<'d> { /// The output signal can be passed to peripherals in place of an output /// pin. /// - /// Note that the signal returned by this function is - /// [frozen](interconnect::OutputSignal::freeze). + /// The returned signal is [frozen](interconnect::OutputSignal::freeze). /// /// ```rust, no_run /// # {before_snippet} @@ -1653,7 +1637,7 @@ impl<'lt> AnyPin<'lt> { }); } - #[cfg(esp32p4)] + #[cfg(any(esp32h4, esp32p4))] fn disable_usb_fs_pads(_gpionum: u8) { crate::peripherals::USB_WRAP::regs() .otg_conf() @@ -1671,7 +1655,7 @@ impl<'lt> AnyPin<'lt> { ($gpio:ident) => { if self.number() == crate::peripherals::$gpio::NUMBER { cfg_select! { - esp32p4 => { + any(esp32h4, esp32p4) => { disable_usb_fs_pads(crate::peripherals::$gpio::NUMBER); } _ => { @@ -1733,7 +1717,7 @@ impl<'lt> AnyPin<'lt> { #[inline] /// Resets the GPIO to a known state. /// - /// This function needs to be called before using the GPIO pin: + /// Must be called before using the GPIO pin: /// - Before converting it into signals /// - Before using it as an input or output pub(crate) fn init_gpio(&self) { @@ -1768,24 +1752,14 @@ impl<'lt> AnyPin<'lt> { } #[procmacros::doc_replace] - /// Split the pin into an input and output signal. + /// Splits the pin into an input and output signal. /// /// Peripheral signals allow connecting peripherals together without /// using external hardware. /// /// Creating an input signal enables the pin's input buffer. /// - /// # Safety - /// - /// The caller must ensure that peripheral drivers don't configure the same - /// GPIO at the same time in multiple places. This includes clones of the - /// `InputSignal` struct, as well as the `OutputSignal` struct. - /// - /// # Panics - /// - /// This function panics if the pin is not an output pin. - /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1794,6 +1768,16 @@ impl<'lt> AnyPin<'lt> { /// let (input, output) = unsafe { pin1.split() }; /// # {after_snippet} /// ``` + /// + /// # Panics + /// + /// Panics if the pin is not an output pin. + /// + /// # Safety + /// + /// The caller must ensure that peripheral drivers do not configure the same + /// GPIO at the same time in multiple places. This includes clones of the + /// `InputSignal` struct, as well as the `OutputSignal` struct #[inline] #[instability::unstable] pub unsafe fn split( @@ -1818,7 +1802,7 @@ impl<'lt> AnyPin<'lt> { (input, output) } - /// Convert the pin into an input signal. + /// Converts the pin into an input signal. /// /// Peripheral signals allow connecting peripherals together without /// using external hardware. @@ -1827,7 +1811,7 @@ impl<'lt> AnyPin<'lt> { /// /// # Safety /// - /// The caller must ensure that peripheral drivers don't configure the same + /// The caller must ensure that peripheral drivers do not configure the same /// GPIO at the same time in multiple places. This includes clones of the /// `InputSignal` struct. #[inline] @@ -1842,14 +1826,14 @@ impl<'lt> AnyPin<'lt> { input } - /// Convert the pin into an output signal. + /// Converts the pin into an output signal. /// /// Peripheral signals allow connecting peripherals together without /// using external hardware. /// /// # Panics /// - /// This function panics if the pin is not an output pin. + /// Panics if the pin is not an output pin. #[inline] #[instability::unstable] pub fn into_output_signal(self) -> interconnect::OutputSignal<'lt> { @@ -1894,14 +1878,14 @@ impl<'lt> AnyPin<'lt> { // io_mux_reg(self.number()).modify(|_, w| w.slp_sel().bit(on)); // } - /// Enable or disable the GPIO pin output buffer. + /// Enables or disables the GPIO pin output buffer. #[inline] pub(crate) fn set_output_enable(&self, enable: bool) { assert!(self.is_output() || !enable); self.bank().write_out_en(self.mask(), enable); } - /// Enable input for the pin + /// Enables input for the pin. #[inline] pub(crate) fn set_input_enable(&self, on: bool) { io_mux_reg(self.number()).modify(|_, w| w.fun_ie().bit(on)); @@ -1999,19 +1983,19 @@ impl<'lt> AnyPin<'lt> { 1 << (self.number() % 32) } - /// The current state of the input + /// The current state of the input. #[inline] pub(crate) fn is_input_high(&self) -> bool { self.bank().read_input() & self.mask() != 0 } - /// Set the pin's level to high or low + /// Sets the pin's level to high or low. #[inline] pub(crate) fn set_output_high(&self, high: bool) { self.bank().write_output(self.mask(), high); } - /// Is the output set to high + /// Is the output set to high. #[inline] pub(crate) fn is_set_high(&self) -> bool { self.bank().read_output() & self.mask() != 0 @@ -2105,7 +2089,7 @@ impl AnyPin<'_> { #[procmacros::doc_replace] /// Attempts to downcast the pin into the underlying GPIO instance. /// - /// ## Example + /// # Examples /// /// ```rust,no_run /// # {before_snippet} @@ -2138,15 +2122,7 @@ impl AnyPin<'_> { #[procmacros::doc_replace] /// Conjure a new GPIO pin out of thin air. /// - /// # Safety - /// - /// The caller must ensure that only one instance of a pin is in use at one time. - /// - /// # Panics - /// - /// Panics if the pin with the given number does not exist. - /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -2156,6 +2132,14 @@ impl AnyPin<'_> { /// # /// # {after_snippet} /// ``` + /// + /// # Panics + /// + /// Panics if the pin with the given number does not exist. + /// + /// # Safety + /// + /// The caller must ensure that only one instance of a pin is in use at one time. pub unsafe fn steal(pin: u8) -> Self { for_each_gpio! { (all $( ($n:literal $($any:tt)*) ),*) => { const PINS: &[u8] = &[ $($n),* ]; }; @@ -2170,11 +2154,7 @@ impl AnyPin<'_> { #[procmacros::doc_replace] /// Unsafely clone the pin. /// - /// # Safety - /// - /// Ensure that only one instance of a pin is in use at one time. - /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -2185,6 +2165,10 @@ impl AnyPin<'_> { /// # /// # {after_snippet} /// ``` + /// + /// # Safety + /// + /// The caller must ensure that only one instance of a pin is in use at one time. pub unsafe fn clone_unchecked(&self) -> Self { Self { pin: self.pin, @@ -2193,10 +2177,10 @@ impl AnyPin<'_> { } #[procmacros::doc_replace] - /// Create a new AnyPin object that is limited to the lifetime of the + /// Creates a new AnyPin object that is limited to the lifetime of the /// passed reference. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -2253,14 +2237,14 @@ for_each_gpio! { pub(crate) const NUMBER: u8 = $n; #[procmacros::doc_replace] - /// Split the pin into an input and output signal. + /// Splits the pin into an input and output signal. /// /// Peripheral signals allow connecting peripherals together without using /// external hardware. /// /// # Safety /// - /// The caller must ensure that peripheral drivers don't configure the same + /// The caller must ensure that peripheral drivers do not configure the same /// GPIO at the same time in multiple places. This includes clones of the /// `InputSignal` struct, as well as the `OutputSignal` struct. /// @@ -2312,8 +2296,9 @@ for_each_gpio! { define_io_mux_reg!(); -// Implement the signal traits outside of interconnect, so that the impls -// don't inherit the module-level instability. +// documentation only - renders nicer than the blanket implementation, but +// doesn't prevent generic code from working. +#[cfg(docsrs)] mod io_matrix_impls { use crate::gpio::{ self, @@ -2333,6 +2318,7 @@ mod io_matrix_impls { InputSignal::new(pin).connect_input_to_peripheral(signal); } } + impl<'d> PeripheralInput<'d> for AnyPin<'d> {} impl<'d> PeripheralOutput<'d> for AnyPin<'d> { @@ -2354,6 +2340,7 @@ mod io_matrix_impls { pin.connect_input_to_peripheral(signal); } } + impl<'d> PeripheralInput<'d> for crate::peripherals::$gpio<'d> {} }; } @@ -2374,3 +2361,47 @@ mod io_matrix_impls { }; } } + +#[cfg(not(docsrs))] +mod io_matrix_impls { + use crate::gpio::{ + self, + AnyPin, + InputPin, + OutputPin, + Pin, + interconnect::{ + InputSignal, + OutputSignal, + PeripheralInput, + PeripheralOutput, + PeripheralSignal, + }, + }; + + // Pins + impl<'d, P> PeripheralSignal<'d> for P + where + P: Pin + 'd, + { + fn connect_input_to_peripheral(&self, signal: gpio::InputSignal) { + let pin = unsafe { AnyPin::steal(self.number()) }; + InputSignal::new(pin).connect_input_to_peripheral(signal); + } + } + impl<'d, P> PeripheralInput<'d> for P where P: InputPin + 'd {} + + impl<'d, P> PeripheralOutput<'d> for P + where + P: OutputPin + 'd, + { + fn connect_peripheral_to_output(&self, signal: gpio::OutputSignal) { + let pin = unsafe { AnyPin::steal(self.number()) }; + OutputSignal::new(pin).connect_peripheral_to_output(signal); + } + fn disconnect_from_peripheral_output(&self) { + let pin = unsafe { AnyPin::steal(self.number()) }; + OutputSignal::new(pin).disconnect_from_peripheral_output(); + } + } +} diff --git a/esp-hal/src/gpio/placeholder.rs b/esp-hal/src/gpio/placeholder.rs index 3161ffb4226..30e9b0eac73 100644 --- a/esp-hal/src/gpio/placeholder.rs +++ b/esp-hal/src/gpio/placeholder.rs @@ -1,7 +1,7 @@ //! Placeholder pins/signals. //! -//! These are useful to pass them into peripheral drivers where you don't want -//! an actual pin but one is required. +//! These are useful to pass into peripheral drivers when a pin is required but +//! no actual pin should be used. // This module also contains peripheral signal impls for `Level` to avoid // polluting the main module. diff --git a/esp-hal/src/gpio/wakeup/ext1_v2.rs b/esp-hal/src/gpio/wakeup/ext1_v2.rs index 5ac1305d198..1e29f48622d 100644 --- a/esp-hal/src/gpio/wakeup/ext1_v2.rs +++ b/esp-hal/src/gpio/wakeup/ext1_v2.rs @@ -1,4 +1,4 @@ -//! The low-power path of esp32c5, esp32c6, esp32c61 and esp32h2. +//! The low-power path of esp32c5, esp32c6, esp32c61, esp32h2 and esp32h4. //! //! On these chips, `ext1` has one level per pad, covers every low-power pad, and does not increase //! the sleep current. There is thus nothing to compare, and every pin goes to `ext1`. These chips @@ -49,14 +49,7 @@ pub(super) fn caused_wakeup(gpio: u8, cause: WakeupReason) -> bool { return false; }; - cause.contains(WakeupSource::Ext1) - && LP_AON::regs() - .ext_wakeup_cntl() - .read() - .ext_wakeup_status() - .bits() - & (1 << lp) - != 0 + cause.contains(WakeupSource::Ext1) && ext1_status() & (1 << lp) != 0 } /// Releases the pads that the previous run armed for a deep sleep. @@ -76,13 +69,44 @@ pub(super) fn wake_io_reset() { } } -fn write_ext1(pads: u8, levels: u8) { - LP_AON::regs() - .ext_wakeup_cntl() - .modify(|_, w| w.ext_wakeup_status_clr().set_bit()); - LP_AON::regs().ext_wakeup_cntl().modify(|_, w| unsafe { - w.ext_wakeup_status_clr().clear_bit(); - w.ext_wakeup_sel().bits(pads); - w.ext_wakeup_lv().bits(levels) - }); +fn ext1_status() -> u16 { + cfg_select! { + esp32h4 => LP_AON::regs() + .ext_wakeup_cntl1() + .read() + .ext_wakeup_status() + .bits(), + _ => LP_AON::regs() + .ext_wakeup_cntl() + .read() + .ext_wakeup_status() + .bits() as u16, + } +} + +fn write_ext1(pads: u16, levels: u16) { + cfg_select! { + esp32h4 => { + LP_AON::regs() + .ext_wakeup_cntl1() + .modify(|_, w| w.ext_wakeup_status_clr().set_bit()); + LP_AON::regs() + .ext_wakeup_cntl1() + .modify(|_, w| w.ext_wakeup_status_clr().clear_bit()); + LP_AON::regs().ext_wakeup_cntl().modify(|_, w| unsafe { + w.ext_wakeup_sel().bits(pads); + w.ext_wakeup_lv().bits(levels) + }); + } + _ => { + LP_AON::regs() + .ext_wakeup_cntl() + .modify(|_, w| w.ext_wakeup_status_clr().set_bit()); + LP_AON::regs().ext_wakeup_cntl().modify(|_, w| unsafe { + w.ext_wakeup_status_clr().clear_bit(); + w.ext_wakeup_sel().bits(pads as u8); + w.ext_wakeup_lv().bits(levels as u8) + }); + } + } } diff --git a/esp-hal/src/gpio/wakeup/mod.rs b/esp-hal/src/gpio/wakeup/mod.rs index 009222ed475..b70125c2bcc 100644 --- a/esp-hal/src/gpio/wakeup/mod.rs +++ b/esp-hal/src/gpio/wakeup/mod.rs @@ -68,7 +68,7 @@ use crate::{ /// [`Pull::None`][crate::gpio::Pull::None] and no external resistor therefore floats during the /// sleep, and a floating pad wakes the chip immediately and every time. /// -/// Give a level-triggered wake pin a pull against the level that wakes the chip, or an external +/// A level-triggered wake pin needs a pull against the level that wakes the chip, or an external /// resistor. For a pin that wakes the chip on a low level, use an external pull-up. #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, procmacros::BuilderLite)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] @@ -393,7 +393,7 @@ fn collect(buffer: &mut [Armed; MAX_ARMED]) -> (&[Armed], bool) { /// Returns the level that wakes the chip through this pad, or `None` if the trigger sets no level. /// /// The wake paths accept a level only, so an edge trigger becomes the level at the end of the edge. -/// This keeps the request of the user. `AnyEdge` ends at the level that the pin is not at now, +/// This keeps the configured request. `AnyEdge` ends at the level that the pin is not at now, /// which is the meaning of "wake when the pin changes". This read of the pin can race with the pin, /// but the result is safe. If the pin changes before the sleep starts, the path arms a level that /// is already present, and the sleep is rejected or ends immediately. @@ -445,7 +445,7 @@ fn prepare_pad(pin: &Armed, deep: bool) { /// peripheral function that drove it. It therefore runs at sleep entry, on the chips that cannot /// hold a single pad through a deep sleep, and after the wakeup sources take the holds that they /// need. -#[cfg(sleep_deep_sleep_needs_gpio_isolation)] +#[cfg(all(sleep_deep_sleep_needs_gpio_isolation, feature = "rt"))] pub(crate) fn isolate_pads_for_deep_sleep() { use crate::{ gpio::{AlternateFunction, OutputSignal, io_mux_reg}, @@ -486,3 +486,37 @@ pub(crate) fn isolate_pads_for_deep_sleep() { }); } } + +/// Isolates digital pads when a power domain that feeds them is powered down. +/// +/// ESP-IDF does this when `SOC_GPIO_NEED_SOFT_ISOLATE_DURING_PD` is set. The chip can still hold a +/// single pad, so a held pad is left alone. The pad list comes from `for_each_gpio_soft_isolate`, +/// which already omits low-power pads and the flash or PSRAM interface. +#[cfg(gpio_need_soft_isolate_during_pd)] +pub(crate) fn isolate_pads_for_deep_sleep() { + for_each_gpio_soft_isolate! { + ($n:literal) => { + isolate_soft_isolate_pad($n); + }; + } +} + +/// Disconnects one digital pad so that a powered-down driver does not increase the sleep current. +#[cfg(gpio_need_soft_isolate_during_pd)] +fn isolate_soft_isolate_pad(gpio: u8) { + use crate::gpio::{AlternateFunction, io_mux_reg, low_level}; + + if crate::gpio::lp_io::low_level::is_digital_pad_held(gpio) { + return; + } + + io_mux_reg(gpio).modify(|_, w| unsafe { + w.fun_wpu().clear_bit(); + w.fun_wpd().clear_bit(); + w.fun_ie().clear_bit(); + w.mcu_sel().bits(AlternateFunction::GPIO as u8) + }); + + let bank = low_level::bank(gpio); + bank.write_out_en_clear(1 << (gpio - bank.offset())); +} diff --git a/esp-hal/src/hmac.rs b/esp-hal/src/hmac.rs index 8b499479920..dd4ed2a30c7 100644 --- a/esp-hal/src/hmac.rs +++ b/esp-hal/src/hmac.rs @@ -38,31 +38,30 @@ use crate::{ pac, peripherals::HMAC, reg_access::{AlignmentHelper, SocDependentEndianess}, - system::{GenericPeripheralGuard, Peripheral as PeripheralEnable}, + system::{CryptoClockGuard, GenericPeripheralGuard, Peripheral as PeripheralEnable}, }; /// Provides an interface for interacting with the HMAC hardware peripheral. -/// It allows users to compute HMACs for cryptographic purposes, ensuring data -/// integrity and authenticity. +/// Computes HMACs for cryptographic purposes and ensures data integrity and authenticity. pub struct Hmac<'d> { hmac: HMAC<'d>, alignment_helper: AlignmentHelper, byte_written: usize, next_command: NextCommand, _guard: GenericPeripheralGuard<{ PeripheralEnable::Hmac as u8 }>, + _clock_guard: CryptoClockGuard, } /// HMAC interface error #[derive(Debug, Clone, Copy, PartialEq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum Error { - /// It means the purpose of the selected block does not match the - /// configured key purpose and the calculation will not proceed. + /// Purpose of the selected block does not match the configured key purpose. KeyPurposeMismatch, } -/// The peripheral can be configured to deliver its output directly to the -/// user. It can also deliver to other peripherals. +/// The peripheral can be configured to deliver its output directly to +/// software. It can also deliver to other peripherals. #[derive(Debug, Clone, Copy, PartialEq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[allow(clippy::enum_variant_names, reason = "peripheral is unstable")] @@ -72,9 +71,9 @@ pub enum HmacPurpose { /// HMAC is provided to the digital signature peripheral to decrypt the /// private key. ToDs = 7, - /// Let the user provide a message and read the result. + /// Provides a message and reads the result. ToUser = 8, - /// HMAC is used for both the digital signature or JTAG. + /// HMAC is used for both the digital signature and JTAG. ToDsOrJtag = 5, } @@ -105,6 +104,7 @@ enum NextCommand { impl<'d> Hmac<'d> { /// Creates a new instance of the HMAC peripheral. pub fn new(hmac: HMAC<'d>) -> Self { + let clock_guard = CryptoClockGuard::new(); let guard = GenericPeripheralGuard::new(); Self { @@ -113,6 +113,7 @@ impl<'d> Hmac<'d> { byte_written: 64, next_command: NextCommand::None, _guard: guard, + _clock_guard: clock_guard, } } @@ -120,11 +121,11 @@ impl<'d> Hmac<'d> { self.hmac.register_block() } - /// Step 1. Enable HMAC module. + /// Enables the HMAC module. /// - /// Before these steps, the user shall set the peripheral clocks bits for - /// HMAC and SHA peripherals and clear the corresponding peripheral - /// reset bits. + /// Before these steps, the peripheral clock bits for + /// HMAC and SHA must be set and the corresponding peripheral + /// reset bits must be cleared. pub fn init(&mut self) { self.regs().set_start().write(|w| w.set_start().set_bit()); self.alignment_helper.reset(); @@ -132,7 +133,7 @@ impl<'d> Hmac<'d> { self.next_command = NextCommand::None; } - /// Step 2. Configure HMAC keys and key purposes. + /// Configures HMAC keys and key purposes. pub fn configure(&mut self, m: HmacPurpose, key_id: KeyId) -> nb::Result<(), Error> { self.regs() .set_para_purpose() @@ -151,9 +152,9 @@ impl<'d> Hmac<'d> { Ok(()) } - /// Process the msg block after block + /// Processes the message block by block. /// - /// Call this function as many times as necessary (msg.len() > 0) + /// Must be called as many times as necessary while `msg.len() > 0`. pub fn update<'a>(&mut self, msg: &'a [u8]) -> nb::Result<&'a [u8], Infallible> { if self.is_busy() { return Err(nb::Error::WouldBlock); diff --git a/esp-hal/src/i2c/lp_i2c/lp_i2c.rs b/esp-hal/src/i2c/lp_i2c/lp_i2c.rs index 9ba19e8daf5..fcb0bb55605 100644 --- a/esp-hal/src/i2c/lp_i2c/lp_i2c.rs +++ b/esp-hal/src/i2c/lp_i2c/lp_i2c.rs @@ -238,7 +238,7 @@ impl<'d> LpI2c<'d> { self.select_lp_fast_clock(); - // Configure LP I2C timing paramters. source_clk is ignored for LP_I2C in this + // Configure LP I2C timing parameters. source_clk is ignored for LP_I2C in this // call let source_clk = 16_000_000; @@ -600,7 +600,7 @@ impl<'d> LpI2c<'d> { self.regs().data().read().fifo_rdata().bits() } - /// Update I2C configuration + /// Updates I2C configuration. fn lp_i2c_update(&self) { self.i2c .register_block() diff --git a/esp-hal/src/i2c/lp_i2c/mod.rs b/esp-hal/src/i2c/lp_i2c/mod.rs index 18bf44a9525..00dc16d16b3 100644 --- a/esp-hal/src/i2c/lp_i2c/mod.rs +++ b/esp-hal/src/i2c/lp_i2c/mod.rs @@ -156,7 +156,7 @@ pub enum Error { )] /// Low-power I2C driver /// -/// ## Example +/// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -193,12 +193,7 @@ impl<'d> LpI2c<'d> { )] /// Creates a new instance of the `LpI2c` peripheral. /// - /// ## Errors - /// - /// A [`crate::i2c::lp_i2c::ConfigError`] variant will be returned if the provided config is - /// invalid. - /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -211,6 +206,10 @@ impl<'d> LpI2c<'d> { /// )?; /// # {after_snippet} /// ``` + /// + /// # Errors + /// + /// [`crate::i2c::lp_i2c::ConfigError`] when the provided config is invalid. pub fn new( i2c: LP_I2C0<'d>, config: Config, @@ -248,12 +247,7 @@ impl<'d> LpI2c<'d> { )] /// Applies a new configuration. /// - /// ## Errors - /// - /// A [`crate::i2c::lp_i2c::ConfigError`] variant will be returned if the provided config is - /// invalid. - /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -268,6 +262,10 @@ impl<'d> LpI2c<'d> { /// i2c.apply_config(&Config::default())?; /// # {after_snippet} /// ``` + /// + /// # Errors + /// + /// [`crate::i2c::lp_i2c::ConfigError`] when the provided config is invalid. pub fn apply_config(&mut self, config: &Config) -> Result<(), ConfigError> { self.configure(config) } @@ -287,12 +285,7 @@ impl<'d> LpI2c<'d> { /// The transfer consists of a single write transaction that sends the device address, the /// register address, then `data`. /// - /// ## Errors - /// - /// [`Error::TransactionSizeLimitExceeded`] is returned if `data` is longer than the driver - /// can transfer in a single transaction. - /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -308,6 +301,11 @@ impl<'d> LpI2c<'d> { /// i2c.write(DEVICE_ADDR, 2, &[0xaa])?; /// # {after_snippet} /// ``` + /// + /// # Errors + /// + /// [`Error::TransactionSizeLimitExceeded`] when `data` is longer than the driver + /// can transfer in a single transaction. pub fn write(&mut self, address: u8, register: u8, data: &[u8]) -> Result<(), Error> { self.write_bytes(address, register, data) } @@ -328,12 +326,7 @@ impl<'d> LpI2c<'d> { /// The transfer writes the device address and the register address, then repeats the start /// condition to read `data` back. /// - /// ## Errors - /// - /// [`Error::TransactionSizeLimitExceeded`] is returned if `data` is longer than the driver - /// can transfer in a single transaction. - /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -350,6 +343,11 @@ impl<'d> LpI2c<'d> { /// i2c.read(DEVICE_ADDR, 7, &mut data)?; /// # {after_snippet} /// ``` + /// + /// # Errors + /// + /// [`Error::TransactionSizeLimitExceeded`] when `data` is longer than the driver + /// can transfer in a single transaction. pub fn read(&mut self, address: u8, register: u8, data: &mut [u8]) -> Result<(), Error> { self.read_bytes(address, register, data) } diff --git a/esp-hal/src/i2c/lp_i2c/rtc_i2c.rs b/esp-hal/src/i2c/lp_i2c/rtc_i2c.rs index e1bdbb6e61e..f3371753a1c 100644 --- a/esp-hal/src/i2c/lp_i2c/rtc_i2c.rs +++ b/esp-hal/src/i2c/lp_i2c/rtc_i2c.rs @@ -183,23 +183,20 @@ impl<'d> LpI2c<'d> { for &byte in data.iter().skip(1) { match self.wait_for_tx_interrupt() { - Ok(is_tx) => { - if is_tx { - sens.sar_i2c_ctrl().modify(|r, w| { - let mut value = r.sar_i2c_ctrl().bits(); - value &= !(0xFF << 19); - value |= (byte as u32) << 19; - value |= 1 << 27; - unsafe { w.sar_i2c_ctrl().bits(value) } - }); - self.i2c - .register_block() - .int_clr() - .write(|w| w.tx_data().clear_bit_by_one()); - } else { - core::panic!("Peripheral didn't wait for data"); - } + Ok(true) => { + sens.sar_i2c_ctrl().modify(|r, w| { + let mut value = r.sar_i2c_ctrl().bits(); + value &= !(0xFF << 19); + value |= (byte as u32) << 19; + value |= 1 << 27; + unsafe { w.sar_i2c_ctrl().bits(value) } + }); + self.i2c + .register_block() + .int_clr() + .write(|w| w.tx_data().clear_bit_by_one()); } + Ok(false) => panic!("Peripheral didn't wait for data"), Err(err) => { // Stop transmission. sens.sar_i2c_ctrl().modify(|_, w| { @@ -300,17 +297,14 @@ impl<'d> LpI2c<'d> { for byte in data { match self.wait_for_rx_interrupt() { - Ok(is_rx) => { - if is_rx { - *byte = self.i2c.register_block().data().read().i2c_rdata().bits(); - self.i2c - .register_block() - .int_clr() - .write(|w| w.rx_data().clear_bit_by_one()); - } else { - core::panic!("Peripheral didn't wait for data to be read"); - } + Ok(true) => { + *byte = self.i2c.register_block().data().read().i2c_rdata().bits(); + self.i2c + .register_block() + .int_clr() + .write(|w| w.rx_data().clear_bit_by_one()); } + Ok(false) => panic!("Peripheral didn't wait for data to be read"), Err(err) => { // Stop transmission. sens.sar_i2c_ctrl().modify(|_, w| { @@ -485,7 +479,7 @@ fn nanos_to_clock(nanos: u64) -> u32 { ((nanos as u128 * crate::soc::clocks::rc_fast_clk_frequency() as u128) / 1_000_000_000) as u32 } -/// A generic I2C Command +/// A generic I2C Command. enum Command { Start, Stop, diff --git a/esp-hal/src/i2c/master/low_level/mod.rs b/esp-hal/src/i2c/master/low_level/mod.rs index 83b0b0ac393..f160f87544e 100644 --- a/esp-hal/src/i2c/master/low_level/mod.rs +++ b/esp-hal/src/i2c/master/low_level/mod.rs @@ -141,7 +141,7 @@ pub(super) fn async_handler(info: &Info, state: &State) { } /// Sets the filter with a supplied threshold in clock cycles for which a -/// pulse must be present to pass the filter +/// pulse must be present to pass the filter. fn set_filter( register_block: &RegisterBlock, sda_threshold: Option, @@ -265,7 +265,7 @@ pub struct Info { /// Pointer to the register block for this I2C instance. /// - /// Use [Self::register_block] to access the register block. + /// Used with [`Self::register_block`] to access the register block. pub register_block: *const RegisterBlock, /// System peripheral marker. @@ -296,7 +296,7 @@ impl Info { unsafe { &*self.register_block } } - /// Listen for the given interrupts + /// Listens for the given interrupts. pub(super) fn enable_listen(&self, interrupts: EnumSet, enable: bool) { let reg_block = self.regs(); @@ -499,7 +499,7 @@ impl Driver<'_> { } } - /// Resets the I2C controller (FIFO + FSM + command list) + /// Resets the I2C controller (FIFO + FSM + command list). // This function implements esp-idf's `s_i2c_hw_fsm_reset` // https://github.com/espressif/esp-idf/blob/27d68f57e6bdd3842cd263585c2c352698a9eda2/components/esp_driver_i2c/i2c_master.c#L115 // @@ -543,11 +543,10 @@ impl Driver<'_> { self.reset_command_list(); } - /// Implements s_i2c_master_clear_bus + /// Implements s_i2c_master_clear_bus. /// - /// If a transaction ended incorrectly for some reason, the slave may drive - /// SDA indefinitely. This function forces the slave to release the - /// bus by sending 9 clock pulses. + /// If a transaction ended incorrectly for some reason, the slave may drive SDA + /// indefinitely. Forces the slave to release the bus by sending 9 clock pulses. fn clear_bus_blocking(&self, reset_fsm: bool) { let mut future = ClearBusFuture::new(*self, reset_fsm); let start = Instant::now(); @@ -667,7 +666,7 @@ impl Driver<'_> { /// Configures the I2C peripheral for a write operation. /// - `addr` is the address of the slave device. - /// - `bytes` is the data two be sent. + /// - `bytes` is the data to be sent /// - `start` indicates whether the operation should start by a START condition and sending the /// address. /// - `stop` indicates whether the operation will end with a STOP condition. @@ -761,7 +760,7 @@ impl Driver<'_> { /// address. /// - `stop` indicates whether the operation will end with a STOP condition. /// - `will_continue` indicates whether there is another read operation following this one and - /// we should not nack the last byte. + /// the last byte must not be nacked. /// - `cmd_iterator` is an iterator over the command registers. fn setup_read<'a, I>( &self, @@ -945,7 +944,7 @@ impl Driver<'_> { Ok(true) } - /// Checks whether all I2C commands have completed execution. + /// Returns whether all I2C commands have completed execution. fn check_all_commands_done_blocking(&self, deadline: Option) -> Result<(), Error> { // loop until commands are actually done while !self.all_commands_done(deadline)? {} @@ -954,7 +953,7 @@ impl Driver<'_> { Ok(()) } - /// Checks whether all I2C commands have completed execution. + /// Returns whether all I2C commands have completed execution. async fn check_all_commands_done(&self, deadline: Option) -> Result<(), Error> { // loop until commands are actually done while !self.all_commands_done(deadline)? { @@ -967,11 +966,10 @@ impl Driver<'_> { /// Checks for I2C transmission errors and handles them. /// - /// This function inspects specific I2C-related interrupts to detect errors - /// during communication, such as timeouts, failed acknowledgments, or - /// arbitration loss. If an error is detected, the function handles it - /// by resetting the I2C peripheral to clear the error condition and then - /// returns an appropriate error. + /// Inspects specific I2C-related interrupts to detect errors during + /// communication, such as timeouts, failed acknowledgments, or arbitration loss. + /// If an error is detected, resets the I2C peripheral to clear the error condition + /// and returns an appropriate error. fn check_errors(&self) -> Result<(), Error> { let r = self.regs().int_raw().read(); @@ -1010,13 +1008,10 @@ impl Driver<'_> { /// Updates the configuration of the I2C peripheral. /// - /// This function ensures that the configuration values, such as clock - /// settings, SDA/SCL filtering, timeouts, and other operational - /// parameters, which are configured in other functions, are properly - /// propagated to the I2C hardware. This step is necessary to synchronize - /// the software-configured settings with the peripheral's internal - /// registers, ensuring that the hardware behaves according to the - /// current configuration. + /// Ensures that configuration values, such as clock settings, SDA/SCL filtering, + /// timeouts, and other operational parameters configured in other methods, are + /// propagated to the I2C hardware. This step synchronizes the software-configured + /// settings with the peripheral's internal registers. fn update_registers(&self) { // Ensure that the configuration of the peripheral is correctly propagated // (only necessary for C2, C3, C6, H2 and S3 variant) @@ -1080,7 +1075,7 @@ impl Driver<'_> { /// address. /// - `stop` indicates whether the operation should end with a STOP condition. /// - `will_continue` indicates whether there is another read operation following this one and - /// we should not nack the last byte. + /// the last byte must not be nacked. /// - `cmd_iterator` is an iterator over the command registers. fn start_read_operation( &self, @@ -1115,7 +1110,7 @@ impl Driver<'_> { /// Executes an I2C write operation. /// - `addr` is the address of the slave device. - /// - `bytes` is the data two be sent. + /// - `bytes` is the data to be sent /// - `start` indicates whether the operation should start by a START condition and sending the /// address. /// - `stop` indicates whether the operation should end with a STOP condition. @@ -1151,7 +1146,7 @@ impl Driver<'_> { /// address. /// - `stop` indicates whether the operation should end with a STOP condition. /// - `will_continue` indicates whether there is another read operation following this one and - /// we should not nack the last byte. + /// the last byte must not be nacked. /// - `cmd_iterator` is an iterator over the command registers. fn read_operation_blocking( &self, @@ -1181,7 +1176,7 @@ impl Driver<'_> { /// Executes an async I2C write operation. /// - `addr` is the address of the slave device. - /// - `bytes` is the data two be sent. + /// - `bytes` is the data to be sent /// - `start` indicates whether the operation should start by a START condition and sending the /// address. /// - `stop` indicates whether the operation should end with a STOP condition. @@ -1216,7 +1211,7 @@ impl Driver<'_> { /// address. /// - `stop` indicates whether the operation should end with a STOP condition. /// - `will_continue` indicates whether there is another read operation following this one and - /// we should not nack the last byte. + /// the last byte must not be nacked. /// - `cmd_iterator` is an iterator over the command registers. async fn read_operation( &self, @@ -1724,7 +1719,7 @@ mod bus_clear { driver.info.scl_output.disconnect_from(&scl); driver.info.sda_output.disconnect_from(&sda); - // Starting from (9, false), becase: + // Starting from (9, false), because: // - we start with SCL low // - a complete SCL cycle consists of a high period and a low period // - we decrement the remaining counter at the beginning of a cycle, which gives us 9 @@ -1870,7 +1865,7 @@ pub trait Instance: crate::private::Sealed + any::Degrade { /// Adds a command to the I2C command sequence. /// -/// Make sure the first command after a FSM reset is a START, otherwise +/// The first command after a FSM reset must be a START, otherwise /// the hardware will hang with no timeouts. fn add_cmd<'a, I>(cmd_iterator: &mut I, command: Command) -> Result<(), Error> where diff --git a/esp-hal/src/i2c/master/low_level/v1.rs b/esp-hal/src/i2c/master/low_level/v1.rs index 9314bd0adb4..5c672cc13a4 100644 --- a/esp-hal/src/i2c/master/low_level/v1.rs +++ b/esp-hal/src/i2c/master/low_level/v1.rs @@ -2,7 +2,7 @@ use super::{Config, ConfigError, Driver, RegisterBlock, configure_clock}; /// Sets the frequency of the I2C interface by calculating and applying the /// associated timings - corresponds to i2c_ll_cal_bus_clk and -/// i2c_ll_set_bus_timing in ESP-IDF +/// i2c_ll_set_bus_timing in ESP-IDF. pub(super) fn set_frequency(driver: &Driver<'_>, clock_config: &Config) -> Result<(), ConfigError> { let timeout = clock_config.timeout; let bus_freq = clock_config.frequency.as_hz(); @@ -21,7 +21,7 @@ pub(super) fn set_frequency(driver: &Driver<'_>, clock_config: &Config) -> Resul // SCL period. According to the TRM, we should always subtract 1 to SCL low // period let scl_low = scl_low - 1; - // Still according to the TRM, if filter is not enbled, we have to subtract 7, + // Still according to the TRM, if filter is not enabled, we have to subtract 7, // if SCL filter is enabled, we have to subtract: // 8 if SCL filter is between 0 and 2 (included) // 6 + SCL threshold if SCL filter is between 3 and 7 (included) diff --git a/esp-hal/src/i2c/master/low_level/v2.rs b/esp-hal/src/i2c/master/low_level/v2.rs index 219af5a015d..368f66e4a60 100644 --- a/esp-hal/src/i2c/master/low_level/v2.rs +++ b/esp-hal/src/i2c/master/low_level/v2.rs @@ -3,7 +3,7 @@ use crate::soc::clocks::{ClockTree, I2cFunctionClockConfig}; /// Sets the frequency of the I2C interface by calculating and applying the /// associated timings - corresponds to i2c_ll_cal_bus_clk and -/// i2c_ll_set_bus_timing in ESP-IDF +/// i2c_ll_set_bus_timing in ESP-IDF. pub(super) fn set_frequency(driver: &Driver<'_>, clock_config: &Config) -> Result<(), ConfigError> { let timeout = clock_config.timeout; let bus_freq = clock_config.frequency.as_hz(); diff --git a/esp-hal/src/i2c/master/low_level/v3.rs b/esp-hal/src/i2c/master/low_level/v3.rs index 5cda1298faa..f974732c8b2 100644 --- a/esp-hal/src/i2c/master/low_level/v3.rs +++ b/esp-hal/src/i2c/master/low_level/v3.rs @@ -3,7 +3,7 @@ use crate::soc::clocks::{ClockTree, I2cFunctionClockConfig, I2cInstance}; /// Sets the frequency of the I2C interface by calculating and applying the /// associated timings - corresponds to i2c_ll_cal_bus_clk and -/// i2c_ll_set_bus_timing in ESP-IDF +/// i2c_ll_set_bus_timing in ESP-IDF. pub(super) fn set_frequency(driver: &Driver<'_>, clock_config: &Config) -> Result<(), ConfigError> { let timeout = clock_config.timeout; let bus_freq = clock_config.frequency.as_hz(); diff --git a/esp-hal/src/i2c/master/mod.rs b/esp-hal/src/i2c/master/mod.rs index 4c373a6fed4..6601cded4b5 100644 --- a/esp-hal/src/i2c/master/mod.rs +++ b/esp-hal/src/i2c/master/mod.rs @@ -165,8 +165,8 @@ const CLEAR_BUS_TIMEOUT_MS: Duration = Duration::from_millis(50); pub enum I2cAddress { /// 7-bit address mode type. /// - /// Note that 7-bit addresses are specified in **right-aligned** form, e.g. - /// in the range `0x00..=0x7F`. + /// 7-bit addresses are specified in **right-aligned** form, e.g. in the range + /// `0x00..=0x7F` /// /// For example, a device that has the seven bit address of `0b011_0010`, /// and therefore is addressed on the wire using: @@ -213,7 +213,7 @@ impl From for I2cAddress { #[doc = ""] #[cfg_attr( i2c_master_bus_timeout_is_exponential, - doc = "Note that the effective timeout may be longer than the value configured here." + doc = "The effective timeout may be longer than the value configured here." )] #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, strum::Display)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] @@ -223,7 +223,7 @@ pub enum BusTimeout { /// Use the maximum timeout value. Maximum, - /// Disable timeout control. + /// Disables timeout control. #[cfg(i2c_master_has_bus_timeout_enable)] Disabled, @@ -234,11 +234,10 @@ pub enum BusTimeout { impl BusTimeout { /// Returns the timeout in APB cycles, or `None` if the timeout is disabled. /// - /// Newer devices only support power-of-two timeouts, so we'll have to take - /// the logarithm of the timeout value. This may cause considerably - /// longer (at most ~double) timeouts than configured. We may provide an - /// `ApbCycles` variant in the future to allow specifying the timeout in - /// APB cycles directly. + /// Newer devices only support power-of-two timeouts, so the value must be rounded to a + /// power of two using the logarithm of the timeout value. This may cause considerably longer + /// (at most approximately double) timeouts than configured. An `ApbCycles` variant may be + /// provided in the future to allow specifying the timeout in APB cycles directly. fn apb_cycles(self, half_bus_cycle: u32) -> Result, ConfigError> { match self { BusTimeout::Maximum => Ok(Some(property!("i2c_master.max_bus_timeout"))), @@ -269,11 +268,10 @@ impl BusTimeout { /// Software timeout for I2C operations. /// /// This timeout is used to limit the duration of I2C operations in software. -/// Note that using this in conjunction with `async` operations will cause the -/// task to be woken up continuously until the operation completes or the -/// timeout is reached. You should prefer using an asynchronous -/// timeout mechanism (like [`embassy_time::with_timeout`]) for better -/// efficiency. +/// Using this in conjunction with `async` operations causes the task to be woken +/// up continuously until the operation completes or the timeout is reached. Prefer +/// an asynchronous timeout mechanism (like [`embassy_time::with_timeout`]) for +/// better efficiency. /// /// [`embassy_time::with_timeout`]: https://docs.rs/embassy-time/0.4.0/embassy_time/fn.with_timeout.html #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] @@ -282,10 +280,10 @@ pub enum SoftwareTimeout { /// No software timeout is set. None, - /// Define a fixed timeout for I2C operations. + /// Defines a fixed timeout for I2C operations. Transaction(Duration), - /// Define a data length dependent timeout for I2C operations. + /// Defines a data length dependent timeout for I2C operations. /// /// The applied timeout is calculated as `data_length * duration_per_byte`. /// In [`I2c::transaction`] and [`I2c::transaction_async`], the timeout is @@ -482,10 +480,10 @@ enum OpKind { #[derive(Debug, PartialEq, Eq, Hash, strum::Display)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum Operation<'a> { - /// Write data from the provided buffer. + /// Writes data from the provided buffer. Write(&'a [u8]), - /// Read data into the provided buffer. + /// Reads data into the provided buffer. Read(&'a mut [u8]), } @@ -527,7 +525,7 @@ impl Operation<'_> { } } -/// A generic I2C Command +/// A generic I2C Command. #[derive(Debug)] enum Command { Start, @@ -538,7 +536,7 @@ enum Command { ack_exp: Ack, /// Enables checking the ACK value received against the ack_exp value. ack_check_en: bool, - /// Length of data (in bytes) to be written. The maximum length is + /// Length of data (in bytes) to be written. The maximum length is. #[doc = property!("i2c_master.fifo_size", str)] /// , while the minimum is 1. length: u8, @@ -547,7 +545,7 @@ enum Command { /// Indicates whether the receiver will send an ACK after this byte has /// been received. ack_value: Ack, - /// Length of data (in bytes) to be read. The maximum length is + /// Length of data (in bytes) to be read. The maximum length is. #[doc = property!("i2c_master.fifo_size", str)] /// , while the minimum is 1. length: u8, @@ -659,7 +657,7 @@ impl Default for Config { #[procmacros::doc_replace] /// I2C driver /// -/// ## Example +/// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -692,14 +690,9 @@ struct DriverConfig { impl<'d> I2c<'d, Blocking> { #[procmacros::doc_replace] - /// Create a new I2C instance. + /// Creates a new I2C instance. /// - /// ## Errors - /// - /// A [`ConfigError`] variant will be returned if bus frequency or timeout - /// passed in config is invalid. - /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -709,6 +702,10 @@ impl<'d> I2c<'d, Blocking> { /// .with_scl(peripherals.GPIO2); /// # {after_snippet} /// ``` + /// + /// # Errors + /// + /// [`ConfigError`] when bus frequency or timeout passed in config is invalid. pub fn new(i2c: impl Instance + 'd, config: Config) -> Result { let guard = PeripheralGuard::new(i2c.info().peripheral); @@ -771,10 +768,9 @@ impl<'d> I2c<'d, Blocking> { doc = "Registers an interrupt handler for the peripheral on the current core." )] #[doc = ""] - /// Note that this will replace any previously registered interrupt - /// handlers. + /// Replaces any previously registered interrupt handlers. /// - /// You can restore the default/unhandled interrupt handler by passing + /// The default/unhandled interrupt handler can be restored by passing /// [DEFAULT_INTERRUPT_HANDLER][crate::interrupt::DEFAULT_INTERRUPT_HANDLER]. /// /// # Panics @@ -786,25 +782,25 @@ impl<'d> I2c<'d, Blocking> { self.i2c.set_interrupt_handler(handler); } - /// Listen for the given interrupts + /// Listens for the given interrupts. #[instability::unstable] pub fn listen(&mut self, interrupts: impl Into>) { self.i2c.info().enable_listen(interrupts.into(), true) } - /// Unlisten the given interrupts + /// Unlistens from the given interrupts. #[instability::unstable] pub fn unlisten(&mut self, interrupts: impl Into>) { self.i2c.info().enable_listen(interrupts.into(), false) } - /// Gets asserted interrupts + /// Returns the asserted interrupts. #[instability::unstable] pub fn interrupts(&mut self) -> EnumSet { self.i2c.info().interrupts() } - /// Resets asserted interrupts + /// Resets asserted interrupts. #[instability::unstable] pub fn clear_interrupts(&mut self, interrupts: EnumSet) { self.i2c.info().clear_interrupts(interrupts) @@ -857,10 +853,10 @@ impl<'d> I2c<'d, Async> { #[procmacros::doc_replace] /// Writes bytes to slave with given `address`. /// - /// Note that dropping the returned Future will abort the transfer, but doing so will - /// block while the driver is finishing clearing and releasing the bus. + /// Dropping the returned Future aborts the transfer, but blocks while the + /// driver finishes clearing and releasing the bus. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -886,15 +882,10 @@ impl<'d> I2c<'d, Async> { #[procmacros::doc_replace] /// Reads enough bytes from slave with `address` to fill `buffer`. /// - /// Note that dropping the returned Future will abort the transfer, but doing so will - /// block while the driver is finishing clearing and releasing the bus. + /// Dropping the returned Future aborts the transfer, but blocks while the + /// driver finishes clearing and releasing the bus. /// - /// ## Errors - /// - /// The corresponding error variant from [`Error`] will be returned if the - /// passed buffer has zero length. - /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -909,6 +900,10 @@ impl<'d> I2c<'d, Async> { /// i2c.read_async(DEVICE_ADDR, &mut data).await?; /// # {after_snippet} /// ``` + /// + /// # Errors + /// + /// [`Error`] when the passed buffer has zero length. pub async fn read_async>( &mut self, address: A, @@ -922,15 +917,10 @@ impl<'d> I2c<'d, Async> { /// Writes bytes to slave with given `address` and then reads enough /// bytes to fill `buffer` *in a single transaction*. /// - /// Note that dropping the returned Future will abort the transfer, but doing so will - /// block while the driver is finishing clearing and releasing the bus. - /// - /// ## Errors - /// - /// The corresponding error variant from [`Error`] will be returned if the - /// passed buffer has zero length. + /// Dropping the returned Future aborts the transfer, but blocks while the + /// driver finishes clearing and releasing the bus. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -946,6 +936,10 @@ impl<'d> I2c<'d, Async> { /// .await?; /// # {after_snippet} /// ``` + /// + /// # Errors + /// + /// [`Error`] when the passed buffer has zero length. pub async fn write_read_async>( &mut self, address: A, @@ -960,10 +954,10 @@ impl<'d> I2c<'d, Async> { } #[procmacros::doc_replace] - /// Execute the provided operations on the I2C bus as a single transaction. + /// Executes the provided operations on the I2C bus as a single transaction. /// - /// Note that dropping the returned Future will abort the transfer, but doing so will - /// block while the driver is finishing clearing and releasing the bus. + /// Dropping the returned Future aborts the transfer, but blocks while the + /// driver finishes clearing and releasing the bus. /// /// Transaction contract: /// - Before executing the first operation an ST is sent automatically. This is followed by @@ -983,12 +977,7 @@ impl<'d> I2c<'d, Async> { any(esp32, esp32s2), doc = "\n\nOn ESP32 and ESP32-S2 there might be issues combining large read/write operations with small (<3 bytes) read/write operations.\n\n" )] - /// ## Errors - /// - /// The corresponding error variant from [`Error`] will be returned if the - /// buffer passed to an [`Operation`] has zero length. - /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1007,6 +996,10 @@ impl<'d> I2c<'d, Async> { /// .await?; /// # {after_snippet} /// ``` + /// + /// # Errors + /// + /// [`Error`] when the buffer passed to an [`Operation`] has zero length. pub async fn transaction_async<'a, A: Into>( &mut self, address: A, @@ -1039,16 +1032,16 @@ where } #[procmacros::doc_replace] - /// Connect a pin to the I2C SDA signal. + /// Connects a pin to the I2C SDA signal. /// - /// If this function is called with a pin singleton (e.g. `GPIO2`), the pin will be configured - /// to use the internal pull-up resistor. If this is undesired, call this function with a fully - /// configured [`Flex`][crate::gpio::Flex] pin driver. Note that if you use `Flex`, the I2C - /// driver will not change the pin's configuration in any way. + /// If called with a pin singleton (e.g. `GPIO2`), the pin is configured to use + /// the internal pull-up resistor. If that is undesired, call this method with a + /// fully configured [`Flex`][crate::gpio::Flex] pin driver. With `Flex`, the I2C + /// driver does not change the pin configuration. /// /// This will replace previous pin assignments for this signal. /// - /// ## Examples + /// # Examples /// /// Basic usage /// @@ -1091,16 +1084,16 @@ where } #[procmacros::doc_replace] - /// Connect a pin to the I2C SCL signal. + /// Connects a pin to the I2C SCL signal. /// - /// If this function is called with a pin singleton (e.g. `GPIO2`), the pin will be configured - /// to use the internal pull-up resistor. If this is undesired, call this function with a fully - /// configured [`Flex`][crate::gpio::Flex] pin driver. Note that if you use `Flex`, the I2C - /// driver will not change the pin's configuration in any way. + /// If called with a pin singleton (e.g. `GPIO2`), the pin is configured to use + /// the internal pull-up resistor. If that is undesired, call this method with a + /// fully configured [`Flex`][crate::gpio::Flex] pin driver. With `Flex`, the I2C + /// driver does not change the pin configuration. /// /// This will replace previous pin assignments for this signal. /// - /// ## Examples + /// # Examples /// /// Basic usage /// @@ -1143,9 +1136,9 @@ where } #[procmacros::doc_replace] - /// Writes bytes to slave with given `address` + /// Writes bytes to slave with given `address`. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1163,9 +1156,9 @@ where } #[procmacros::doc_replace] - /// Reads enough bytes from slave with `address` to fill `buffer` + /// Reads enough bytes from slave with `address` to fill `buffer`. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1180,10 +1173,9 @@ where /// # {after_snippet} /// ``` /// - /// ## Errors + /// # Errors /// - /// The corresponding error variant from [`Error`] will be returned if the passed buffer has - /// zero length. + /// [`Error`] when the passed buffer has zero length. pub fn read>( &mut self, address: A, @@ -1194,14 +1186,9 @@ where #[procmacros::doc_replace] /// Writes bytes to slave with given `address` and then reads enough bytes - /// to fill `buffer` *in a single transaction* - /// - /// ## Errors - /// - /// The corresponding error variant from [`Error`] will be returned if the passed buffer has - /// zero length. + /// to fill `buffer` *in a single transaction*. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1215,6 +1202,10 @@ where /// i2c.write_read(DEVICE_ADDR, &[0xaa], &mut data)?; /// # {after_snippet} /// ``` + /// + /// # Errors + /// + /// [`Error`] when the passed buffer has zero length. pub fn write_read>( &mut self, address: A, @@ -1228,7 +1219,7 @@ where } #[procmacros::doc_replace] - /// Execute the provided operations on the I2C bus. + /// Executes the provided operations on the I2C bus. /// /// Transaction contract: /// - Before executing the first operation an ST is sent automatically. This is followed by @@ -1245,7 +1236,7 @@ where /// - `SR` = repeated start condition /// - `SP` = stop condition /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1266,10 +1257,9 @@ where any(esp32, esp32s2), doc = "\n\nOn ESP32 and ESP32-S2 it is advisable to not combine large read/write operations with small (<3 bytes) read/write operations.\n\n" )] - /// ## Errors + /// # Errors /// - /// The corresponding error variant from [`Error`] will be returned if the - /// buffer passed to an [`Operation`] has zero length. + /// [`Error`] when the buffer passed to an [`Operation`] has zero length. pub fn transaction<'a, A: Into>( &mut self, address: A, @@ -1284,12 +1274,7 @@ where #[procmacros::doc_replace] /// Applies a new configuration. /// - /// ## Errors - /// - /// A [`ConfigError`] variant will be returned if bus frequency or timeout - /// passed in config is invalid. - /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1299,6 +1284,10 @@ where /// i2c.apply_config(&Config::default().with_frequency(Rate::from_khz(400)))?; /// # {after_snippet} /// ``` + /// + /// # Errors + /// + /// [`ConfigError`] when bus frequency or timeout passed in config is invalid. pub fn apply_config(&mut self, config: &Config) -> Result<(), ConfigError> { self.config.config = *config; self.driver().setup(config)?; diff --git a/esp-hal/src/i2c/slave/mod.rs b/esp-hal/src/i2c/slave/mod.rs index 906ef5c82cd..83ee96709e2 100644 --- a/esp-hal/src/i2c/slave/mod.rs +++ b/esp-hal/src/i2c/slave/mod.rs @@ -150,7 +150,7 @@ impl embedded_hal::i2c::ErrorType for I2cSlave<'_, Dm> { } impl<'d> I2cSlave<'d, Blocking> { - /// Create a new I2C slave instance. + /// Creates a new I2C slave instance. pub fn new(i2c: impl Instance + 'd, config: Config) -> Result { let guard = PeripheralGuard::new(i2c.info().peripheral); @@ -209,7 +209,7 @@ impl<'d, Dm: DriverMode> I2cSlave<'d, Dm> { } } - /// Connect a pin to the I2C SDA signal. + /// Connects a pin to the I2C SDA signal. pub fn with_sda(mut self, sda: impl PeripheralInput<'d> + PeripheralOutput<'d>) -> Self { let info = self.driver().info; let input = info.sda_input; @@ -218,7 +218,7 @@ impl<'d, Dm: DriverMode> I2cSlave<'d, Dm> { self } - /// Connect a pin to the I2C SCL signal. + /// Connects a pin to the I2C SCL signal. pub fn with_scl(mut self, scl: impl PeripheralInput<'d> + PeripheralOutput<'d>) -> Self { let info = self.driver().info; let input = info.scl_input; diff --git a/esp-hal/src/i2s/clocks/esp32p4.rs b/esp-hal/src/i2s/clocks/esp32p4.rs new file mode 100644 index 00000000000..f955426afc1 --- /dev/null +++ b/esp-hal/src/i2s/clocks/esp32p4.rs @@ -0,0 +1,223 @@ +use super::MclkFraction; +use crate::{ + clock::ll::{ClockTree, I2sClkConfig, I2sClkSclk, I2sInstance, I2sMclkOutConfig}, + peripherals::HP_SYS_CLKRST, +}; + +fn clk_sel(sclk: I2sClkSclk) -> u8 { + match sclk { + I2sClkSclk::Xtal => 0, + I2sClkSclk::PllF160m => 3, + } +} + +/// Applies a module clock configuration to one instance and direction. +/// +/// The fields of one divider are spread over two `PERI_CLK_CTRLn` registers, and the split +/// differs per instance, so every field is named with the register that holds it. +/// +/// The divider applies twice, unless the coefficients are set in this sequence, with a small +/// division before the target one. +macro_rules! configure_clk { + ( + $config:ident, $fraction:ident, + div_n = $n_reg:ident :: $n:ident, + div_x = $x_reg:ident :: $x:ident, + div_y = $y_reg:ident :: $y:ident, + div_z = $z_reg:ident :: $z:ident, + div_yn1 = $yn1_reg:ident :: $yn1:ident, + clk_src_sel = $sel_reg:ident :: $sel:ident, + ) => {{ + let clkrst = HP_SYS_CLKRST::regs(); + + clkrst + .$sel_reg() + .modify(|_, w| unsafe { w.$sel().bits(clk_sel($config.sclk())) }); + + clkrst.$n_reg().modify(|_, w| unsafe { w.$n().bits(2) }); + clkrst.$yn1_reg().modify(|_, w| w.$yn1().clear_bit()); + clkrst.$y_reg().modify(|_, w| unsafe { w.$y().bits(1) }); + clkrst.$z_reg().modify(|_, w| unsafe { w.$z().bits(0) }); + clkrst.$x_reg().modify(|_, w| unsafe { w.$x().bits(0) }); + + clkrst.$yn1_reg().modify(|_, w| w.$yn1().bit($fraction.yn1)); + clkrst + .$z_reg() + .modify(|_, w| unsafe { w.$z().bits($fraction.z) }); + clkrst + .$y_reg() + .modify(|_, w| unsafe { w.$y().bits($fraction.y) }); + clkrst + .$x_reg() + .modify(|_, w| unsafe { w.$x().bits($fraction.x) }); + + clkrst + .$n_reg() + .modify(|_, w| unsafe { w.$n().bits($config.div_num() as u8) }); + }}; +} + +impl I2sInstance { + // I2S_TX_CLK + + pub(crate) fn enable_tx_clk_impl(self, _clocks: &mut ClockTree, en: bool) { + let clkrst = HP_SYS_CLKRST::regs(); + match self { + Self::I2s0 => { + clkrst + .peri_clk_ctrl13() + .modify(|_, w| w.i2s0_tx_clk_en().bit(en)); + } + Self::I2s1 => { + clkrst + .peri_clk_ctrl15() + .modify(|_, w| w.i2s1_tx_clk_en().bit(en)); + } + Self::I2s2 => { + clkrst + .peri_clk_ctrl18() + .modify(|_, w| w.i2s2_tx_clk_en().bit(en)); + } + } + } + + pub(crate) fn configure_tx_clk_impl( + self, + _clocks: &mut ClockTree, + _old_config: Option, + new_config: I2sClkConfig, + ) { + let fraction = MclkFraction::new(new_config.div_a(), new_config.div_b()); + + match self { + Self::I2s0 => configure_clk!( + new_config, + fraction, + div_n = peri_clk_ctrl13::i2s0_tx_div_n, + div_x = peri_clk_ctrl13::i2s0_tx_div_x, + div_y = peri_clk_ctrl14::i2s0_tx_div_y, + div_z = peri_clk_ctrl14::i2s0_tx_div_z, + div_yn1 = peri_clk_ctrl14::i2s0_tx_div_yn1, + clk_src_sel = peri_clk_ctrl13::i2s0_tx_clk_src_sel, + ), + Self::I2s1 => configure_clk!( + new_config, + fraction, + div_n = peri_clk_ctrl16::i2s1_tx_div_n, + div_x = peri_clk_ctrl16::i2s1_tx_div_x, + div_y = peri_clk_ctrl16::i2s1_tx_div_y, + div_z = peri_clk_ctrl17::i2s1_tx_div_z, + div_yn1 = peri_clk_ctrl17::i2s1_tx_div_yn1, + clk_src_sel = peri_clk_ctrl15::i2s1_tx_clk_src_sel, + ), + Self::I2s2 => configure_clk!( + new_config, + fraction, + div_n = peri_clk_ctrl18::i2s2_tx_div_n, + div_x = peri_clk_ctrl19::i2s2_tx_div_x, + div_y = peri_clk_ctrl19::i2s2_tx_div_y, + div_z = peri_clk_ctrl19::i2s2_tx_div_z, + div_yn1 = peri_clk_ctrl19::i2s2_tx_div_yn1, + clk_src_sel = peri_clk_ctrl18::i2s2_tx_clk_src_sel, + ), + } + } + + // I2S_RX_CLK + + pub(crate) fn enable_rx_clk_impl(self, _clocks: &mut ClockTree, en: bool) { + let clkrst = HP_SYS_CLKRST::regs(); + match self { + Self::I2s0 => { + clkrst + .peri_clk_ctrl11() + .modify(|_, w| w.i2s0_rx_clk_en().bit(en)); + } + Self::I2s1 => { + clkrst + .peri_clk_ctrl14() + .modify(|_, w| w.i2s1_rx_clk_en().bit(en)); + } + Self::I2s2 => { + clkrst + .peri_clk_ctrl17() + .modify(|_, w| w.i2s2_rx_clk_en().bit(en)); + } + } + } + + pub(crate) fn configure_rx_clk_impl( + self, + _clocks: &mut ClockTree, + _old_config: Option, + new_config: I2sClkConfig, + ) { + let fraction = MclkFraction::new(new_config.div_a(), new_config.div_b()); + + match self { + Self::I2s0 => configure_clk!( + new_config, + fraction, + div_n = peri_clk_ctrl12::i2s0_rx_div_n, + div_x = peri_clk_ctrl12::i2s0_rx_div_x, + div_y = peri_clk_ctrl12::i2s0_rx_div_y, + div_z = peri_clk_ctrl13::i2s0_rx_div_z, + div_yn1 = peri_clk_ctrl13::i2s0_rx_div_yn1, + clk_src_sel = peri_clk_ctrl11::i2s0_rx_clk_src_sel, + ), + Self::I2s1 => configure_clk!( + new_config, + fraction, + div_n = peri_clk_ctrl14::i2s1_rx_div_n, + div_x = peri_clk_ctrl15::i2s1_rx_div_x, + div_y = peri_clk_ctrl15::i2s1_rx_div_y, + div_z = peri_clk_ctrl15::i2s1_rx_div_z, + div_yn1 = peri_clk_ctrl15::i2s1_rx_div_yn1, + clk_src_sel = peri_clk_ctrl14::i2s1_rx_clk_src_sel, + ), + Self::I2s2 => configure_clk!( + new_config, + fraction, + div_n = peri_clk_ctrl17::i2s2_rx_div_n, + div_x = peri_clk_ctrl17::i2s2_rx_div_x, + div_y = peri_clk_ctrl18::i2s2_rx_div_y, + div_z = peri_clk_ctrl18::i2s2_rx_div_z, + div_yn1 = peri_clk_ctrl18::i2s2_rx_div_yn1, + clk_src_sel = peri_clk_ctrl17::i2s2_rx_clk_src_sel, + ), + } + } + + // I2S_MCLK_OUT + + pub(crate) fn enable_mclk_out_impl(self, _clocks: &mut ClockTree, _en: bool) { + // The pad is driven as long as the selected module clock runs. + } + + pub(crate) fn configure_mclk_out_impl( + self, + _clocks: &mut ClockTree, + _old_config: Option, + new_config: I2sMclkOutConfig, + ) { + let tx = matches!(new_config, I2sMclkOutConfig::Tx); + let clkrst = HP_SYS_CLKRST::regs(); + match self { + Self::I2s0 => { + clkrst + .peri_clk_ctrl14() + .modify(|_, w| w.i2s0_mst_clk_sel().bit(tx)); + } + Self::I2s1 => { + clkrst + .peri_clk_ctrl17() + .modify(|_, w| w.i2s1_mst_clk_sel().bit(tx)); + } + Self::I2s2 => { + clkrst + .peri_clk_ctrl19() + .modify(|_, w| w.i2s2_mst_clk_sel().bit(tx)); + } + } + } +} diff --git a/esp-hal/src/i2s/clocks/esp32s31.rs b/esp-hal/src/i2s/clocks/esp32s31.rs new file mode 100644 index 00000000000..a8f9484f050 --- /dev/null +++ b/esp-hal/src/i2s/clocks/esp32s31.rs @@ -0,0 +1,189 @@ +use super::MclkFraction; +use crate::{ + clock::ll::{ClockTree, I2sClkConfig, I2sClkSclk, I2sInstance, I2sMclkOutConfig}, + peripherals::HP_SYS_CLKRST, +}; + +fn clk_sel(sclk: I2sClkSclk) -> u8 { + match sclk { + I2sClkSclk::Xtal => 0, + } +} + +/// Applies a module clock configuration to one instance and direction. +/// +/// Each instance and direction has a `ctrl0` register with the source selector and the integer +/// part of the divider, and a `div_ctrl0` register with the fraction. +/// +/// The divider applies twice, unless the coefficients are set in this sequence, with a small +/// division before the target one. +macro_rules! configure_clk { + ( + $config:ident, $fraction:ident, + ctrl = $ctrl_reg:ident, + div_ctrl = $div_ctrl_reg:ident, + div_n = $n:ident, + div_x = $x:ident, + div_y = $y:ident, + div_z = $z:ident, + div_yn1 = $yn1:ident, + clk_src_sel = $sel:ident, + ) => {{ + let clkrst = HP_SYS_CLKRST::regs(); + + clkrst.$ctrl_reg().modify(|_, w| unsafe { w.$n().bits(2) }); + clkrst.$div_ctrl_reg().modify(|_, w| { + w.$yn1().clear_bit(); + unsafe { + w.$y().bits(1); + w.$z().bits(0); + w.$x().bits(0) + } + }); + + clkrst.$div_ctrl_reg().modify(|_, w| { + w.$yn1().bit($fraction.yn1); + unsafe { + w.$z().bits($fraction.z); + w.$y().bits($fraction.y); + w.$x().bits($fraction.x) + } + }); + + clkrst.$ctrl_reg().modify(|_, w| unsafe { + w.$n().bits($config.div_num() as u8); + w.$sel().bits(clk_sel($config.sclk())) + }); + }}; +} + +impl I2sInstance { + // I2S_TX_CLK + + pub(crate) fn enable_tx_clk_impl(self, _clocks: &mut ClockTree, en: bool) { + let clkrst = HP_SYS_CLKRST::regs(); + match self { + Self::I2s0 => { + clkrst.i2s0_tx_ctrl0().modify(|_, w| w.tx_clk_en().bit(en)); + } + Self::I2s1 => { + clkrst.i2s1_tx_ctrl0().modify(|_, w| w.tx_clk_en().bit(en)); + } + } + } + + pub(crate) fn configure_tx_clk_impl( + self, + _clocks: &mut ClockTree, + _old_config: Option, + new_config: I2sClkConfig, + ) { + let fraction = MclkFraction::new(new_config.div_a(), new_config.div_b()); + + match self { + Self::I2s0 => configure_clk!( + new_config, + fraction, + ctrl = i2s0_tx_ctrl0, + div_ctrl = i2s0_tx_div_ctrl0, + div_n = tx_div_n, + div_x = tx_div_x, + div_y = tx_div_y, + div_z = tx_div_z, + div_yn1 = tx_div_yn1, + clk_src_sel = tx_clk_src_sel, + ), + Self::I2s1 => configure_clk!( + new_config, + fraction, + ctrl = i2s1_tx_ctrl0, + div_ctrl = i2s1_tx_div_ctrl0, + div_n = tx_div_n, + div_x = tx_div_x, + div_y = tx_div_y, + div_z = tx_div_z, + div_yn1 = tx_div_yn1, + clk_src_sel = tx_clk_src_sel, + ), + } + } + + // I2S_RX_CLK + + pub(crate) fn enable_rx_clk_impl(self, _clocks: &mut ClockTree, en: bool) { + let clkrst = HP_SYS_CLKRST::regs(); + match self { + Self::I2s0 => { + clkrst.i2s0_rx_ctrl0().modify(|_, w| w.rx_clk_en().bit(en)); + } + Self::I2s1 => { + clkrst.i2s1_rx_ctrl0().modify(|_, w| w.rx_clk_en().bit(en)); + } + } + } + + pub(crate) fn configure_rx_clk_impl( + self, + _clocks: &mut ClockTree, + _old_config: Option, + new_config: I2sClkConfig, + ) { + let fraction = MclkFraction::new(new_config.div_a(), new_config.div_b()); + + match self { + Self::I2s0 => configure_clk!( + new_config, + fraction, + ctrl = i2s0_rx_ctrl0, + div_ctrl = i2s0_rx_div_ctrl0, + div_n = rx_div_n, + div_x = rx_div_x, + div_y = rx_div_y, + div_z = rx_div_z, + div_yn1 = rx_div_yn1, + clk_src_sel = rx_clk_src_sel, + ), + Self::I2s1 => configure_clk!( + new_config, + fraction, + ctrl = i2s1_rx_ctrl0, + div_ctrl = i2s1_rx_div_ctrl0, + div_n = rx_div_n, + div_x = rx_div_x, + div_y = rx_div_y, + div_z = rx_div_z, + div_yn1 = rx_div_yn1, + clk_src_sel = rx_clk_src_sel, + ), + } + } + + // I2S_MCLK_OUT + + pub(crate) fn enable_mclk_out_impl(self, _clocks: &mut ClockTree, _en: bool) { + // The pad is driven as long as the selected module clock runs. + } + + pub(crate) fn configure_mclk_out_impl( + self, + _clocks: &mut ClockTree, + _old_config: Option, + new_config: I2sMclkOutConfig, + ) { + // `mst_clk_sel` lives on the RX control register of the instance. + let tx = matches!(new_config, I2sMclkOutConfig::Tx); + let clkrst = HP_SYS_CLKRST::regs(); + match self { + Self::I2s0 => { + clkrst + .i2s0_rx_ctrl0() + .modify(|_, w| w.mst_clk_sel().bit(tx)); + } + Self::I2s1 => { + clkrst + .i2s1_rx_ctrl0() + .modify(|_, w| w.mst_clk_sel().bit(tx)); + } + } + } +} diff --git a/esp-hal/src/i2s/clocks/mod.rs b/esp-hal/src/i2s/clocks/mod.rs new file mode 100644 index 00000000000..aa28d08f84f --- /dev/null +++ b/esp-hal/src/i2s/clocks/mod.rs @@ -0,0 +1,70 @@ +//! Clock tree node implementations for the I2S peripherals. +//! +//! The I2S driver is available only with the `unstable` feature, but the clock tree contains the +//! I2S nodes in every build. `lib.rs` therefore includes this module directly, instead of through +//! `i2s/mod.rs`. +//! +//! Each version module implements the nodes of one register layout: +//! +//! - `v1`: a single `MCLK` node in the I2S register block, shared by both directions. +//! - `v2v3`: separate `TX_CLK` and `RX_CLK` nodes, and the `MCLK_OUT` selector, in the I2S register +//! block. +//! - `v2v3_pcr`: the same nodes, in the PCR register block. +//! - `esp32p4`: the same nodes, in the HP_SYS_CLKRST register block. +//! - `v2v3_esp32s31`: the same nodes, in the HP_SYS_CLKRST register block, but with a per-instance +//! register layout. + +#[cfg_attr(i2s_version = "1", path = "v1.rs")] +#[cfg_attr(i2s_clock_configured_by_pcr, path = "v2v3_pcr.rs")] +#[cfg_attr( + all(i2s_clock_configured_by_hp_sys_clkrst, esp32p4), + path = "esp32p4.rs" +)] +#[cfg_attr( + all(i2s_clock_configured_by_hp_sys_clkrst, esp32s31), + path = "esp32s31.rs" +)] +#[cfg_attr( + all( + not(i2s_version = "1"), + not(i2s_clock_configured_by_pcr), + not(i2s_clock_configured_by_hp_sys_clkrst) + ), + path = "v2v3.rs" +)] +mod version; + +/// The fractional part of an MCLK divider, in the X/Y/Z/YN1 encoding of the hardware. +/// +/// The clock tree describes the divider as `div_num + div_b / div_a`. This type converts the +/// `div_b / div_a` fraction, as `i2s_ll_tx_set_mclk` does in ESP-IDF. +#[cfg(not(i2s_version = "1"))] +struct MclkFraction { + x: u16, + y: u16, + z: u16, + yn1: bool, +} + +#[cfg(not(i2s_version = "1"))] +impl MclkFraction { + fn new(div_a: u32, div_b: u32) -> Self { + let (x, y, z, yn1) = if div_a == 0 || div_b == 0 { + // The divider is an integer one. All coefficients are zero, YN1 included. + (0, 0, 0, false) + } else if div_b > div_a / 2 { + // Fractions over one half are encoded as the complement. + let z = div_a - div_b; + (div_a / z - 1, div_a % z, z, true) + } else { + (div_a / div_b - 1, div_a % div_b, div_b, false) + }; + + Self { + x: x as u16, + y: y as u16, + z: z as u16, + yn1, + } + } +} diff --git a/esp-hal/src/i2s/clocks/v1.rs b/esp-hal/src/i2s/clocks/v1.rs new file mode 100644 index 00000000000..96881401aea --- /dev/null +++ b/esp-hal/src/i2s/clocks/v1.rs @@ -0,0 +1,49 @@ +use crate::clock::ll::{ClockTree, I2sInstance, I2sMclkConfig, I2sMclkSclk}; + +impl I2sInstance { + fn regs(self) -> &'static crate::pac::i2s0::RegisterBlock { + match self { + Self::I2s0 => crate::peripherals::I2S0::regs(), + #[cfg(soc_has_i2s1)] + Self::I2s1 => unsafe { + &*crate::peripherals::I2S1::PTR.cast::() + }, + } + } + + // I2S_MCLK + + pub(crate) fn enable_mclk_impl(self, _clocks: &mut ClockTree, en: bool) { + self.regs().clkm_conf().modify(|_, w| w.clk_en().bit(en)); + } + + pub(crate) fn configure_mclk_impl( + self, + _clocks: &mut ClockTree, + _old_config: Option, + new_config: I2sMclkConfig, + ) { + self.regs().clkm_conf().modify(|_, w| { + cfg_select! { + esp32 => { + // The ESP32 has no source selector. The peripheral uses PLL_F160M_CLK, + // unless the APLL is routed to it. + w.clka_ena() + .bit(matches!(new_config.sclk(), I2sMclkSclk::Apll)) + } + esp32s2 => unsafe { + w.clk_sel().bits(match new_config.sclk() { + I2sMclkSclk::Apll => 1, + I2sMclkSclk::PllF160m => 2, + }) + }, + } + }); + + self.regs().clkm_conf().modify(|_, w| unsafe { + w.clkm_div_num().bits(new_config.div_num() as u8); + w.clkm_div_a().bits(new_config.div_a() as u8); + w.clkm_div_b().bits(new_config.div_b() as u8) + }); + } +} diff --git a/esp-hal/src/i2s/clocks/v2v3.rs b/esp-hal/src/i2s/clocks/v2v3.rs new file mode 100644 index 00000000000..52392a301f1 --- /dev/null +++ b/esp-hal/src/i2s/clocks/v2v3.rs @@ -0,0 +1,125 @@ +use super::MclkFraction; +use crate::{ + clock::ll::{ClockTree, I2sClkConfig, I2sClkSclk, I2sInstance, I2sMclkOutConfig}, + pac::i2s0::RegisterBlock, +}; + +fn clk_sel(sclk: I2sClkSclk) -> u8 { + cfg_select! { + esp32c3 => match sclk { + I2sClkSclk::Xtal => 0, + I2sClkSclk::Pll160m => 2, + }, + esp32s3 => match sclk { + I2sClkSclk::Xtal => 0, + I2sClkSclk::PllD2 => 1, + I2sClkSclk::Pll160m => 2, + }, + } +} + +impl I2sInstance { + fn regs(self) -> &'static RegisterBlock { + match self { + Self::I2s0 => crate::peripherals::I2S0::regs(), + #[cfg(soc_has_i2s1)] + Self::I2s1 => unsafe { &*crate::peripherals::I2S1::PTR.cast::() }, + } + } + + // I2S_TX_CLK + + pub(crate) fn enable_tx_clk_impl(self, _clocks: &mut ClockTree, en: bool) { + self.regs().tx_clkm_conf().modify(|_, w| { + w.clk_en().bit(en); + w.tx_clk_active().bit(en) + }); + } + + pub(crate) fn configure_tx_clk_impl( + self, + _clocks: &mut ClockTree, + _old_config: Option, + new_config: I2sClkConfig, + ) { + let fraction = MclkFraction::new(new_config.div_a(), new_config.div_b()); + + // The divider applies twice, unless the coefficients are set in this sequence, with a + // small division before the target one. + self.regs() + .tx_clkm_conf() + .modify(|_, w| unsafe { w.tx_clkm_div_num().bits(2) }); + self.regs().tx_clkm_div_conf().modify(|_, w| unsafe { + w.tx_clkm_div_yn1().clear_bit(); + w.tx_clkm_div_y().bits(1); + w.tx_clkm_div_z().bits(0); + w.tx_clkm_div_x().bits(0) + }); + + self.regs().tx_clkm_div_conf().modify(|_, w| unsafe { + w.tx_clkm_div_yn1().bit(fraction.yn1); + w.tx_clkm_div_z().bits(fraction.z); + w.tx_clkm_div_y().bits(fraction.y); + w.tx_clkm_div_x().bits(fraction.x) + }); + self.regs().tx_clkm_conf().modify(|_, w| unsafe { + w.tx_clk_sel().bits(clk_sel(new_config.sclk())); + w.tx_clkm_div_num().bits(new_config.div_num() as u8) + }); + } + + // I2S_RX_CLK + + pub(crate) fn enable_rx_clk_impl(self, _clocks: &mut ClockTree, en: bool) { + self.regs() + .rx_clkm_conf() + .modify(|_, w| w.rx_clk_active().bit(en)); + } + + pub(crate) fn configure_rx_clk_impl( + self, + _clocks: &mut ClockTree, + _old_config: Option, + new_config: I2sClkConfig, + ) { + let fraction = MclkFraction::new(new_config.div_a(), new_config.div_b()); + + self.regs() + .rx_clkm_conf() + .modify(|_, w| unsafe { w.rx_clkm_div_num().bits(2) }); + self.regs().rx_clkm_div_conf().modify(|_, w| unsafe { + w.rx_clkm_div_yn1().clear_bit(); + w.rx_clkm_div_y().bits(1); + w.rx_clkm_div_z().bits(0); + w.rx_clkm_div_x().bits(0) + }); + + self.regs().rx_clkm_div_conf().modify(|_, w| unsafe { + w.rx_clkm_div_yn1().bit(fraction.yn1); + w.rx_clkm_div_z().bits(fraction.z); + w.rx_clkm_div_y().bits(fraction.y); + w.rx_clkm_div_x().bits(fraction.x) + }); + self.regs().rx_clkm_conf().modify(|_, w| unsafe { + w.rx_clk_sel().bits(clk_sel(new_config.sclk())); + w.rx_clkm_div_num().bits(new_config.div_num() as u8) + }); + } + + // I2S_MCLK_OUT + + pub(crate) fn enable_mclk_out_impl(self, _clocks: &mut ClockTree, _en: bool) { + // The pad is driven as long as the selected module clock runs. + } + + pub(crate) fn configure_mclk_out_impl( + self, + _clocks: &mut ClockTree, + _old_config: Option, + new_config: I2sMclkOutConfig, + ) { + self.regs() + .rx_clkm_conf() + .modify(|_, w| w.mclk_sel().bit(matches!(new_config, I2sMclkOutConfig::Rx))); + } +} diff --git a/esp-hal/src/i2s/clocks/v2v3_pcr.rs b/esp-hal/src/i2s/clocks/v2v3_pcr.rs new file mode 100644 index 00000000000..b678002b301 --- /dev/null +++ b/esp-hal/src/i2s/clocks/v2v3_pcr.rs @@ -0,0 +1,128 @@ +use super::MclkFraction; +use crate::{ + clock::ll::{ClockTree, I2sClkConfig, I2sClkSclk, I2sInstance, I2sMclkOutConfig}, + peripherals::PCR, +}; + +fn clk_sel(sclk: I2sClkSclk) -> u8 { + cfg_select! { + any(esp32c5, esp32c6) => match sclk { + I2sClkSclk::Xtal => 0, + I2sClkSclk::PllF240m => 1, + I2sClkSclk::PllF160m => 2, + }, + esp32c61 => match sclk { + I2sClkSclk::Xtal => 0, + I2sClkSclk::PllF120m => 1, + I2sClkSclk::PllF160m => 2, + }, + esp32h2 => match sclk { + I2sClkSclk::Xtal => 0, + I2sClkSclk::PllF96m => 1, + I2sClkSclk::PllF64m => 2, + }, + esp32h4 => match sclk { + I2sClkSclk::Xtal => 0, + I2sClkSclk::PllF96m => 1, + I2sClkSclk::XtalX2 => 2, + }, + } +} + +impl I2sInstance { + // I2S_TX_CLK + + pub(crate) fn enable_tx_clk_impl(self, _clocks: &mut ClockTree, en: bool) { + PCR::regs() + .i2s_tx_clkm_conf() + .modify(|_, w| w.i2s_tx_clkm_en().bit(en)); + } + + pub(crate) fn configure_tx_clk_impl( + self, + _clocks: &mut ClockTree, + _old_config: Option, + new_config: I2sClkConfig, + ) { + let fraction = MclkFraction::new(new_config.div_a(), new_config.div_b()); + let pcr = PCR::regs(); + + // The divider applies twice, unless the coefficients are set in this sequence, with a + // small division before the target one. + pcr.i2s_tx_clkm_conf() + .modify(|_, w| unsafe { w.i2s_tx_clkm_div_num().bits(2) }); + pcr.i2s_tx_clkm_div_conf().modify(|_, w| unsafe { + w.i2s_tx_clkm_div_yn1().clear_bit(); + w.i2s_tx_clkm_div_y().bits(1); + w.i2s_tx_clkm_div_z().bits(0); + w.i2s_tx_clkm_div_x().bits(0) + }); + + pcr.i2s_tx_clkm_div_conf().modify(|_, w| unsafe { + w.i2s_tx_clkm_div_yn1().bit(fraction.yn1); + w.i2s_tx_clkm_div_z().bits(fraction.z); + w.i2s_tx_clkm_div_y().bits(fraction.y); + w.i2s_tx_clkm_div_x().bits(fraction.x) + }); + pcr.i2s_tx_clkm_conf().modify(|_, w| unsafe { + w.i2s_tx_clkm_sel().bits(clk_sel(new_config.sclk())); + w.i2s_tx_clkm_div_num().bits(new_config.div_num() as u8) + }); + } + + // I2S_RX_CLK + + pub(crate) fn enable_rx_clk_impl(self, _clocks: &mut ClockTree, en: bool) { + PCR::regs() + .i2s_rx_clkm_conf() + .modify(|_, w| w.i2s_rx_clkm_en().bit(en)); + } + + pub(crate) fn configure_rx_clk_impl( + self, + _clocks: &mut ClockTree, + _old_config: Option, + new_config: I2sClkConfig, + ) { + let fraction = MclkFraction::new(new_config.div_a(), new_config.div_b()); + let pcr = PCR::regs(); + + pcr.i2s_rx_clkm_conf() + .modify(|_, w| unsafe { w.i2s_rx_clkm_div_num().bits(2) }); + pcr.i2s_rx_clkm_div_conf().modify(|_, w| unsafe { + w.i2s_rx_clkm_div_yn1().clear_bit(); + w.i2s_rx_clkm_div_y().bits(1); + w.i2s_rx_clkm_div_z().bits(0); + w.i2s_rx_clkm_div_x().bits(0) + }); + + pcr.i2s_rx_clkm_div_conf().modify(|_, w| unsafe { + w.i2s_rx_clkm_div_yn1().bit(fraction.yn1); + w.i2s_rx_clkm_div_z().bits(fraction.z); + w.i2s_rx_clkm_div_y().bits(fraction.y); + w.i2s_rx_clkm_div_x().bits(fraction.x) + }); + pcr.i2s_rx_clkm_conf().modify(|_, w| unsafe { + w.i2s_rx_clkm_sel().bits(clk_sel(new_config.sclk())); + w.i2s_rx_clkm_div_num().bits(new_config.div_num() as u8) + }); + } + + // I2S_MCLK_OUT + + pub(crate) fn enable_mclk_out_impl(self, _clocks: &mut ClockTree, _en: bool) { + // The pad is driven as long as the selected module clock runs. + } + + pub(crate) fn configure_mclk_out_impl( + self, + _clocks: &mut ClockTree, + _old_config: Option, + new_config: I2sMclkOutConfig, + ) { + PCR::regs().i2s_rx_clkm_conf().modify(|_, w| { + w.i2s_mclk_sel() + .bit(matches!(new_config, I2sMclkOutConfig::Rx)) + }); + } +} diff --git a/esp-hal/src/i2s/hp_sys_clkrst.rs b/esp-hal/src/i2s/hp_sys_clkrst.rs deleted file mode 100644 index 65c7ebf5d4a..00000000000 --- a/esp-hal/src/i2s/hp_sys_clkrst.rs +++ /dev/null @@ -1,222 +0,0 @@ -//! I2S clock programming via `HP_SYS_CLKRST`. - -use super::master::private::I2sClockDividers; -use crate::{peripherals::HP_SYS_CLKRST, system::Peripheral}; - -pub(crate) fn set_tx_clock(peripheral: Peripheral, clock_settings: &I2sClockDividers) { - let clkm_div = clock_settings.mclk_dividers(); - let clkrst = HP_SYS_CLKRST::regs(); - let clock_source = property!("i2s.default_clock_source"); - - match peripheral { - Peripheral::I2s0 => { - clkrst - .peri_clk_ctrl14() - .modify(|_, w| w.i2s0_mst_clk_sel().set_bit()); - - // Workaround for the double-division issue documented in esp-idf i2s_ll.h. - clkrst - .peri_clk_ctrl13() - .modify(|_, w| unsafe { w.i2s0_tx_div_n().bits(2) }); - clkrst.peri_clk_ctrl14().modify(|_, w| { - w.i2s0_tx_div_yn1().clear_bit(); - unsafe { - w.i2s0_tx_div_y().bits(1); - w.i2s0_tx_div_z().bits(0) - } - }); - clkrst - .peri_clk_ctrl13() - .modify(|_, w| unsafe { w.i2s0_tx_div_x().bits(0) }); - - clkrst.peri_clk_ctrl14().modify(|_, w| { - w.i2s0_tx_div_yn1().bit(clkm_div.yn1); - unsafe { - w.i2s0_tx_div_z().bits(clkm_div.z as u16); - w.i2s0_tx_div_y().bits(clkm_div.y as u16) - } - }); - clkrst.peri_clk_ctrl13().modify(|_, w| unsafe { - w.i2s0_tx_div_x().bits(clkm_div.x as u16); - w.i2s0_tx_div_n().bits(clock_settings.mclk_divider as u8); - w.i2s0_tx_clk_en().set_bit(); - w.i2s0_tx_clk_src_sel().bits(clock_source) - }); - } - Peripheral::I2s1 => { - clkrst - .peri_clk_ctrl17() - .modify(|_, w| w.i2s1_mst_clk_sel().set_bit()); - - clkrst - .peri_clk_ctrl16() - .modify(|_, w| unsafe { w.i2s1_tx_div_n().bits(2) }); - // See I2S0 RX: clear `z` before `y`/`x` when they are in different registers. - clkrst.peri_clk_ctrl17().modify(|_, w| { - w.i2s1_tx_div_yn1().clear_bit(); - unsafe { w.i2s1_tx_div_z().bits(0) } - }); - clkrst.peri_clk_ctrl16().modify(|_, w| unsafe { - w.i2s1_tx_div_y().bits(1); - w.i2s1_tx_div_x().bits(0) - }); - - clkrst.peri_clk_ctrl17().modify(|_, w| { - w.i2s1_tx_div_yn1().bit(clkm_div.yn1); - unsafe { w.i2s1_tx_div_z().bits(clkm_div.z as u16) } - }); - clkrst.peri_clk_ctrl16().modify(|_, w| unsafe { - w.i2s1_tx_div_y().bits(clkm_div.y as u16); - w.i2s1_tx_div_x().bits(clkm_div.x as u16); - w.i2s1_tx_div_n().bits(clock_settings.mclk_divider as u8) - }); - clkrst.peri_clk_ctrl15().modify(|_, w| unsafe { - w.i2s1_tx_clk_en().set_bit(); - w.i2s1_tx_clk_src_sel().bits(clock_source) - }); - } - Peripheral::I2s2 => { - clkrst - .peri_clk_ctrl19() - .modify(|_, w| w.i2s2_mst_clk_sel().set_bit()); - - clkrst - .peri_clk_ctrl18() - .modify(|_, w| unsafe { w.i2s2_tx_div_n().bits(2) }); - clkrst.peri_clk_ctrl19().modify(|_, w| { - w.i2s2_tx_div_yn1().clear_bit(); - unsafe { - w.i2s2_tx_div_y().bits(1); - w.i2s2_tx_div_z().bits(0); - w.i2s2_tx_div_x().bits(0) - } - }); - - clkrst.peri_clk_ctrl19().modify(|_, w| { - w.i2s2_tx_div_yn1().bit(clkm_div.yn1); - unsafe { - w.i2s2_tx_div_z().bits(clkm_div.z as u16); - w.i2s2_tx_div_y().bits(clkm_div.y as u16); - w.i2s2_tx_div_x().bits(clkm_div.x as u16) - } - }); - clkrst.peri_clk_ctrl18().modify(|_, w| unsafe { - w.i2s2_tx_div_n().bits(clock_settings.mclk_divider as u8); - w.i2s2_tx_clk_en().set_bit(); - w.i2s2_tx_clk_src_sel().bits(clock_source) - }); - } - _ => unreachable!(), - } -} - -pub(crate) fn set_rx_clock(peripheral: Peripheral, clock_settings: &I2sClockDividers) { - let clkm_div = clock_settings.mclk_dividers(); - let clkrst = HP_SYS_CLKRST::regs(); - let clock_source = property!("i2s.default_clock_source"); - - match peripheral { - Peripheral::I2s0 => { - clkrst - .peri_clk_ctrl14() - .modify(|_, w| w.i2s0_mst_clk_sel().clear_bit()); - - // Workaround for the double-division issue documented in esp-idf i2s_ll.h: - // bypass the divider (`div_n = 2`), reset the fractional terms, then apply - // the target values. Clear `z` before programming `y`/`x` when they sit in - // different registers, or the clock can glitch during reconfiguration. - clkrst - .peri_clk_ctrl12() - .modify(|_, w| unsafe { w.i2s0_rx_div_n().bits(2) }); - clkrst.peri_clk_ctrl13().modify(|_, w| { - w.i2s0_rx_div_yn1().clear_bit(); - unsafe { w.i2s0_rx_div_z().bits(0) } - }); - clkrst.peri_clk_ctrl12().modify(|_, w| unsafe { - w.i2s0_rx_div_y().bits(1); - w.i2s0_rx_div_x().bits(0) - }); - - clkrst.peri_clk_ctrl13().modify(|_, w| { - w.i2s0_rx_div_yn1().bit(clkm_div.yn1); - unsafe { w.i2s0_rx_div_z().bits(clkm_div.z as u16) } - }); - clkrst.peri_clk_ctrl12().modify(|_, w| unsafe { - w.i2s0_rx_div_y().bits(clkm_div.y as u16); - w.i2s0_rx_div_x().bits(clkm_div.x as u16); - w.i2s0_rx_div_n().bits(clock_settings.mclk_divider as u8) - }); - clkrst.peri_clk_ctrl11().modify(|_, w| unsafe { - w.i2s0_rx_clk_en().set_bit(); - w.i2s0_rx_clk_src_sel().bits(clock_source) - }); - } - Peripheral::I2s1 => { - clkrst - .peri_clk_ctrl17() - .modify(|_, w| w.i2s1_mst_clk_sel().clear_bit()); - - // See the I2S0 RX path for the double-division workaround. - clkrst - .peri_clk_ctrl14() - .modify(|_, w| unsafe { w.i2s1_rx_div_n().bits(2) }); - clkrst.peri_clk_ctrl15().modify(|_, w| { - w.i2s1_rx_div_yn1().clear_bit(); - unsafe { - w.i2s1_rx_div_y().bits(1); - w.i2s1_rx_div_x().bits(0); - w.i2s1_rx_div_z().bits(0) - } - }); - - clkrst.peri_clk_ctrl15().modify(|_, w| { - w.i2s1_rx_div_yn1().bit(clkm_div.yn1); - unsafe { - w.i2s1_rx_div_z().bits(clkm_div.z as u16); - w.i2s1_rx_div_y().bits(clkm_div.y as u16); - w.i2s1_rx_div_x().bits(clkm_div.x as u16) - } - }); - clkrst.peri_clk_ctrl14().modify(|_, w| unsafe { - w.i2s1_rx_div_n().bits(clock_settings.mclk_divider as u8); - w.i2s1_rx_clk_en().set_bit(); - w.i2s1_rx_clk_src_sel().bits(clock_source) - }); - } - Peripheral::I2s2 => { - clkrst - .peri_clk_ctrl19() - .modify(|_, w| w.i2s2_mst_clk_sel().clear_bit()); - - // See the I2S0 RX path for the double-division workaround. - clkrst - .peri_clk_ctrl17() - .modify(|_, w| unsafe { w.i2s2_rx_div_n().bits(2) }); - clkrst.peri_clk_ctrl18().modify(|_, w| { - w.i2s2_rx_div_yn1().clear_bit(); - unsafe { - w.i2s2_rx_div_y().bits(1); - w.i2s2_rx_div_z().bits(0) - } - }); - clkrst - .peri_clk_ctrl17() - .modify(|_, w| unsafe { w.i2s2_rx_div_x().bits(0) }); - - clkrst.peri_clk_ctrl18().modify(|_, w| { - w.i2s2_rx_div_yn1().bit(clkm_div.yn1); - unsafe { - w.i2s2_rx_div_z().bits(clkm_div.z as u16); - w.i2s2_rx_div_y().bits(clkm_div.y as u16) - } - }); - clkrst.peri_clk_ctrl17().modify(|_, w| unsafe { - w.i2s2_rx_div_x().bits(clkm_div.x as u16); - w.i2s2_rx_div_n().bits(clock_settings.mclk_divider as u8); - w.i2s2_rx_clk_en().set_bit(); - w.i2s2_rx_clk_src_sel().bits(clock_source) - }); - } - _ => unreachable!(), - } -} diff --git a/esp-hal/src/i2s/master/low_level/mod.rs b/esp-hal/src/i2s/master/low_level/mod.rs index c8c17928efe..018f3e1367d 100644 --- a/esp-hal/src/i2s/master/low_level/mod.rs +++ b/esp-hal/src/i2s/master/low_level/mod.rs @@ -1,9 +1,12 @@ use enumset::EnumSet; -use super::I2sInterrupt; +use super::{I2sClockSource, I2sInterrupt, private::I2sClockDividers}; #[cfg(not(i2s_version = "1"))] -use super::private::I2sClockDividers; +use crate::clock::ll::I2sClkConfig as ModuleClockConfig; +#[cfg(i2s_version = "1")] +use crate::clock::ll::I2sMclkConfig as ModuleClockConfig; use crate::{ + clock::ll::{ClockTree, I2sInstance}, gpio::{InputSignal, OutputSignal}, pac::i2s0::RegisterBlock, }; @@ -13,40 +16,6 @@ use crate::{ #[cfg_attr(i2s_version = "3", path = "v3.rs")] mod version; -#[cfg(not(i2s_version = "1"))] -pub(crate) struct I2sMclkDividers { - pub(crate) x: u32, - pub(crate) y: u32, - pub(crate) z: u32, - pub(crate) yn1: bool, -} - -#[cfg(not(i2s_version = "1"))] -impl I2sClockDividers { - pub(crate) fn mclk_dividers(&self) -> I2sMclkDividers { - let (x, y, z, yn1) = if self.denominator == 0 || self.numerator == 0 { - (0, 0, 0, true) - } else if self.numerator > self.denominator / 2 { - let x = self - .denominator - .overflowing_div(self.denominator.overflowing_sub(self.numerator).0) - .0 - .overflowing_sub(1) - .0; - let y = self.denominator % (self.denominator.overflowing_sub(self.numerator).0); - let z = self.denominator.overflowing_sub(self.numerator).0; - (x, y, z, true) - } else { - let x = self.denominator / self.numerator - 1; - let y = self.denominator % self.numerator; - let z = self.numerator; - (x, y, z, false) - }; - - I2sMclkDividers { x, y, z, yn1 } - } -} - /// Peripheral data describing a particular I2S instance. /// /// All the per-instance data (register block pointer, system peripheral marker and the @@ -94,6 +63,9 @@ pub struct Info { /// Hardware PDM-to-PCM format conversion filter supported on RX. pub pdm2pcm: bool, + + /// Clock tree instance for this I2S peripheral. + pub clock_instance: I2sInstance, } // SAFETY: The register block pointer refers to a static peripheral memory region. @@ -168,3 +140,50 @@ impl Info { }); } } + +/// Describes a module clock for the clock tree: the source to select, and the MCLK divider. +fn clock_config(source: I2sClockSource, dividers: &I2sClockDividers) -> ModuleClockConfig { + ModuleClockConfig::new( + source, + dividers.mclk_divider, + dividers.denominator, + dividers.numerator, + ) +} + +impl Info { + /// Configures the module clock that both directions share. + #[cfg(i2s_version = "1")] + pub(crate) fn configure_mclk(&self, source: I2sClockSource, dividers: &I2sClockDividers) { + ClockTree::with(|clocks| { + self.clock_instance + .configure_mclk(clocks, clock_config(source, dividers)); + }); + } + + /// Configures the module clock of the transmitter. + #[cfg(not(i2s_version = "1"))] + pub(crate) fn configure_tx_mclk(&self, source: I2sClockSource, dividers: &I2sClockDividers) { + ClockTree::with(|clocks| { + self.clock_instance + .configure_tx_clk(clocks, clock_config(source, dividers)); + }); + } + + /// Configures the module clock of the receiver. + #[cfg(not(i2s_version = "1"))] + pub(crate) fn configure_rx_mclk(&self, source: I2sClockSource, dividers: &I2sClockDividers) { + ClockTree::with(|clocks| { + self.clock_instance + .configure_rx_clk(clocks, clock_config(source, dividers)); + }); + } + + /// Selects the module clock that drives the MCLK pad. + #[cfg(not(i2s_version = "1"))] + pub(crate) fn configure_mclk_pad(&self, sel: super::MclkOut) { + ClockTree::with(|clocks| { + self.clock_instance.configure_mclk_out(clocks, sel); + }); + } +} diff --git a/esp-hal/src/i2s/master/low_level/v1.rs b/esp-hal/src/i2s/master/low_level/v1.rs index 9bc3cf0c7ba..80530685b72 100644 --- a/esp-hal/src/i2s/master/low_level/v1.rs +++ b/esp-hal/src/i2s/master/low_level/v1.rs @@ -3,39 +3,14 @@ use super::Info; use crate::i2s::master::Endianness; use crate::{ RegisterToggle, - i2s::master::{ - Channels, - Config, - ConfigError, - DataFormat, - UnitConfig, - WsWidth, - private::I2sClockDividers, - }, + i2s::master::{Channels, Config, ConfigError, DataFormat, UnitConfig, WsWidth}, }; impl Info { - pub(crate) fn set_clock(&self, clock_settings: I2sClockDividers) { - self.regs().clkm_conf().modify(|r, w| unsafe { - // select PLL_160M - w.bits(r.bits() | (property!("i2s.default_clock_source") << 21)) - }); - - #[cfg(esp32)] - self.regs() - .clkm_conf() - .modify(|_, w| w.clka_ena().clear_bit()); - - self.regs().clkm_conf().modify(|_, w| unsafe { - w.clk_en().set_bit(); - w.clkm_div_num().bits(clock_settings.mclk_divider as u8); - w.clkm_div_a().bits(clock_settings.denominator as u8); - w.clkm_div_b().bits(clock_settings.numerator as u8) - }); - + pub(crate) fn set_bclk(&self, bclk_divider: u32) { self.regs().sample_rate_conf().modify(|_, w| unsafe { - w.tx_bck_div_num().bits(clock_settings.bclk_divider as u8); - w.rx_bck_div_num().bits(clock_settings.bclk_divider as u8) + w.tx_bck_div_num().bits(bclk_divider as u8); + w.rx_bck_div_num().bits(bclk_divider as u8) }); } @@ -55,7 +30,9 @@ impl Info { self.configure_tx(&c.tx_config, c.data_format)?; self.configure_rx(&c.rx_config, c.data_format)?; - self.set_clock(config.calculate_clock()); + let clocks = c.calculate_clock(); + self.configure_mclk(c.clock_source, &clocks); + self.set_bclk(clocks.bclk_divider); self.regs().sample_rate_conf().modify(|_, w| unsafe { // Having different data formats for each direction would make clock diff --git a/esp-hal/src/i2s/master/low_level/v2.rs b/esp-hal/src/i2s/master/low_level/v2.rs index 894066c0ec0..c4aa1546332 100644 --- a/esp-hal/src/i2s/master/low_level/v2.rs +++ b/esp-hal/src/i2s/master/low_level/v2.rs @@ -2,147 +2,26 @@ use bitfield::Bit; use super::Info; use crate::i2s::master::{ + Alignment, BitOrder, Config, ConfigError, Endianness, Polarity, UnitConfig, - private::I2sClockDividers, }; impl Info { - #[cfg(not(any(i2s_clock_configured_by_pcr, i2s_clock_configured_by_hp_sys_clkrst)))] - pub(crate) fn set_tx_clock(&self, clock_settings: I2sClockDividers) { - let clkm_div = clock_settings.mclk_dividers(); - - self.regs().tx_clkm_div_conf().modify(|_, w| unsafe { - w.tx_clkm_div_x().bits(clkm_div.x as u16); - w.tx_clkm_div_y().bits(clkm_div.y as u16); - w.tx_clkm_div_yn1().bit(clkm_div.yn1); - w.tx_clkm_div_z().bits(clkm_div.z as u16) - }); - - self.regs().tx_clkm_conf().modify(|_, w| unsafe { - w.clk_en().set_bit(); - w.tx_clk_active().set_bit(); - // for now fixed at 160MHz - w.tx_clk_sel().bits(property!("i2s.default_clock_source")); - w.tx_clkm_div_num().bits(clock_settings.mclk_divider as u8) - }); - - self.regs().tx_conf1().modify(|_, w| unsafe { - w.tx_bck_div_num() - .bits((clock_settings.bclk_divider - 1) as u8) - }); - } - - #[cfg(not(any(i2s_clock_configured_by_pcr, i2s_clock_configured_by_hp_sys_clkrst)))] - pub(crate) fn set_rx_clock(&self, clock_settings: I2sClockDividers) { - let clkm_div = clock_settings.mclk_dividers(); - - self.regs().rx_clkm_div_conf().modify(|_, w| unsafe { - w.rx_clkm_div_x().bits(clkm_div.x as u16); - w.rx_clkm_div_y().bits(clkm_div.y as u16); - w.rx_clkm_div_yn1().bit(clkm_div.yn1); - w.rx_clkm_div_z().bits(clkm_div.z as u16) - }); - - self.regs().rx_clkm_conf().modify(|_, w| unsafe { - w.rx_clk_active().set_bit(); - // for now fixed at 160MHz - w.rx_clk_sel().bits(property!("i2s.default_clock_source")); - w.rx_clkm_div_num().bits(clock_settings.mclk_divider as u8); - w.mclk_sel().bit(true) - }); - - self.regs().rx_conf1().modify(|_, w| unsafe { - w.rx_bck_div_num() - .bits((clock_settings.bclk_divider - 1) as u8) - }); - } - - #[cfg(i2s_clock_configured_by_pcr)] - pub(crate) fn set_tx_clock(&self, clock_settings: I2sClockDividers) { - // I2S clocks are configured via PCR - use crate::peripherals::PCR; - - let clkm_div = clock_settings.mclk_dividers(); - let pcr = PCR::regs(); - - // Pulse a temporary divider before applying the target coefficients to avoid - // a hardware glitch where the clock divider applies twice on PCR chips. - pcr.i2s_tx_clkm_conf() - .modify(|_, w| unsafe { w.i2s_tx_clkm_div_num().bits(2) }); - pcr.i2s_tx_clkm_div_conf().modify(|_, w| unsafe { - w.i2s_tx_clkm_div_yn1().clear_bit(); - w.i2s_tx_clkm_div_y().bits(1); - w.i2s_tx_clkm_div_z().bits(0); - w.i2s_tx_clkm_div_x().bits(0) - }); - - pcr.i2s_tx_clkm_div_conf().modify(|_, w| unsafe { - w.i2s_tx_clkm_div_x().bits(clkm_div.x as u16); - w.i2s_tx_clkm_div_y().bits(clkm_div.y as u16); - w.i2s_tx_clkm_div_yn1().bit(clkm_div.yn1); - w.i2s_tx_clkm_div_z().bits(clkm_div.z as u16) - }); - - pcr.i2s_tx_clkm_conf().modify(|_, w| unsafe { - w.i2s_tx_clkm_en().set_bit(); - // for now fixed at 160MHz for C6 and 96MHz for H2 - w.i2s_tx_clkm_sel() - .bits(property!("i2s.default_clock_source")); - w.i2s_tx_clkm_div_num() - .bits(clock_settings.mclk_divider as u8) - }); - - self.regs().tx_conf1().modify(|_, w| unsafe { - w.tx_bck_div_num() - .bits((clock_settings.bclk_divider - 1) as u8) - }); + pub(crate) fn set_tx_bclk(&self, bclk_divider: u32) { + self.regs() + .tx_conf1() + .modify(|_, w| unsafe { w.tx_bck_div_num().bits((bclk_divider - 1) as u8) }); } - #[cfg(i2s_clock_configured_by_pcr)] - pub(crate) fn set_rx_clock(&self, clock_settings: I2sClockDividers) { - // I2S clocks are configured via PCR - use crate::peripherals::PCR; - - let clkm_div = clock_settings.mclk_dividers(); - let pcr = PCR::regs(); - - // Pulse a temporary divider before applying the target coefficients to avoid - // a hardware glitch where the clock divider applies twice on PCR chips. - pcr.i2s_rx_clkm_conf() - .modify(|_, w| unsafe { w.i2s_rx_clkm_div_num().bits(2) }); - pcr.i2s_rx_clkm_div_conf().modify(|_, w| unsafe { - w.i2s_rx_clkm_div_yn1().clear_bit(); - w.i2s_rx_clkm_div_y().bits(1); - w.i2s_rx_clkm_div_z().bits(0); - w.i2s_rx_clkm_div_x().bits(0) - }); - - pcr.i2s_rx_clkm_div_conf().modify(|_, w| unsafe { - w.i2s_rx_clkm_div_x().bits(clkm_div.x as u16); - w.i2s_rx_clkm_div_y().bits(clkm_div.y as u16); - w.i2s_rx_clkm_div_yn1().bit(clkm_div.yn1); - w.i2s_rx_clkm_div_z().bits(clkm_div.z as u16) - }); - - pcr.i2s_rx_clkm_conf().modify(|_, w| unsafe { - w.i2s_rx_clkm_en().set_bit(); - // for now fixed at 160MHz for C6 and 96MHz for H2 - w.i2s_rx_clkm_sel() - .bits(property!("i2s.default_clock_source")); - w.i2s_rx_clkm_div_num() - .bits(clock_settings.mclk_divider as u8); - w.i2s_mclk_sel().bit(true) - }); - - self.regs().rx_conf1().modify(|_, w| unsafe { - w.rx_bck_div_num() - .bits((clock_settings.bclk_divider - 1) as u8) - }); + pub(crate) fn set_rx_bclk(&self, bclk_divider: u32) { + self.regs() + .rx_conf1() + .modify(|_, w| unsafe { w.rx_bck_div_num().bits((bclk_divider - 1) as u8) }); } pub(crate) fn update_tx(&self) { @@ -166,6 +45,7 @@ impl Info { Config::Tdm(c) => { self.configure_tx(&c.tx_config)?; self.configure_rx(&c.rx_config)?; + self.configure_mclk_pad(c.mclk_out); self.regs() .tx_conf() @@ -185,15 +65,17 @@ impl Info { pub(crate) fn configure_tx(&self, config: &UnitConfig) -> Result<(), ConfigError> { let ws_width = config.calculate_ws_width()?; - self.set_tx_clock(config.calculate_clock()); + let clocks = config.calculate_clock(); + self.configure_tx_mclk(config.clock_source, &clocks); + self.set_tx_bclk(clocks.bclk_divider); self.regs().tx_conf1().modify(|_, w| unsafe { w.tx_msb_shift().bit(config.msb_shift); #[allow(clippy::useless_conversion)] w.tx_tdm_ws_width().bits((ws_width - 1).try_into().unwrap()); - w.tx_bits_mod().bits(config.data_format.data_bits() - 1); + w.tx_bits_mod().bits(config.data_format.channel_bits() - 1); w.tx_tdm_chan_bits() - .bits(config.data_format.channel_bits() - 1); + .bits(config.data_format.data_bits() - 1); w.tx_half_sample_bits() .bits((config.data_format.data_bits() * config.channels.count) / 2 - 1) }); @@ -211,7 +93,8 @@ impl Info { w.tx_bit_order().bit(config.bit_order == BitOrder::LsbFirst); w.tx_ws_idle_pol() .bit(config.ws_polarity == Polarity::ActiveHigh); - w.tx_chan_mod().bits(0) + w.tx_chan_mod().bits(0); + w.tx_left_align().bit(config.alignment() == Alignment::Left) }); self.regs().tx_tdm_ctrl().modify(|_, w| unsafe { @@ -244,15 +127,17 @@ impl Info { pub(crate) fn configure_rx(&self, config: &UnitConfig) -> Result<(), ConfigError> { let ws_width = config.calculate_ws_width()?; - self.set_rx_clock(config.calculate_clock()); + let clocks = config.calculate_clock(); + self.configure_rx_mclk(config.clock_source, &clocks); + self.set_rx_bclk(clocks.bclk_divider); self.regs().rx_conf1().modify(|_, w| unsafe { w.rx_msb_shift().bit(config.msb_shift); #[allow(clippy::useless_conversion)] w.rx_tdm_ws_width().bits((ws_width - 1).try_into().unwrap()); - w.rx_bits_mod().bits(config.data_format.data_bits() - 1); + w.rx_bits_mod().bits(config.data_format.channel_bits() - 1); w.rx_tdm_chan_bits() - .bits(config.data_format.channel_bits() - 1); + .bits(config.data_format.data_bits() - 1); w.rx_half_sample_bits() .bits((config.data_format.data_bits() * config.channels.count) / 2 - 1) }); @@ -268,7 +153,8 @@ impl Info { .bit(config.endianness == Endianness::BigEndian); w.rx_bit_order().bit(config.bit_order == BitOrder::LsbFirst); w.rx_ws_idle_pol() - .bit(config.ws_polarity == Polarity::ActiveHigh) + .bit(config.ws_polarity == Polarity::ActiveHigh); + w.rx_left_align().bit(config.alignment() == Alignment::Left) }); self.regs().rx_tdm_ctrl().modify(|_, w| unsafe { diff --git a/esp-hal/src/i2s/master/low_level/v3.rs b/esp-hal/src/i2s/master/low_level/v3.rs index ee67ee35564..6e5a377d32d 100644 --- a/esp-hal/src/i2s/master/low_level/v3.rs +++ b/esp-hal/src/i2s/master/low_level/v3.rs @@ -2,167 +2,26 @@ use bitfield::Bit; use super::Info; use crate::i2s::master::{ + Alignment, BitOrder, Config, ConfigError, Endianness, Polarity, UnitConfig, - private::I2sClockDividers, }; impl Info { - #[cfg(not(any(i2s_clock_configured_by_pcr, i2s_clock_configured_by_hp_sys_clkrst)))] - pub(crate) fn set_tx_clock(&self, clock_settings: I2sClockDividers) { - let clkm_div = clock_settings.mclk_dividers(); - - self.regs().tx_clkm_div_conf().modify(|_, w| unsafe { - w.tx_clkm_div_x().bits(clkm_div.x as u16); - w.tx_clkm_div_y().bits(clkm_div.y as u16); - w.tx_clkm_div_yn1().bit(clkm_div.yn1); - w.tx_clkm_div_z().bits(clkm_div.z as u16) - }); - - self.regs().tx_clkm_conf().modify(|_, w| unsafe { - w.clk_en().set_bit(); - w.tx_clk_active().set_bit(); - // for now fixed at 160MHz - w.tx_clk_sel().bits(property!("i2s.default_clock_source")); - w.tx_clkm_div_num().bits(clock_settings.mclk_divider as u8) - }); - - self.regs().tx_conf().modify(|_, w| unsafe { - w.tx_bck_div_num() - .bits((clock_settings.bclk_divider - 1) as u8) - }); - } - - #[cfg(not(any(i2s_clock_configured_by_pcr, i2s_clock_configured_by_hp_sys_clkrst)))] - pub(crate) fn set_rx_clock(&self, clock_settings: I2sClockDividers) { - let clkm_div = clock_settings.mclk_dividers(); - - self.regs().rx_clkm_div_conf().modify(|_, w| unsafe { - w.rx_clkm_div_x().bits(clkm_div.x as u16); - w.rx_clkm_div_y().bits(clkm_div.y as u16); - w.rx_clkm_div_yn1().bit(clkm_div.yn1); - w.rx_clkm_div_z().bits(clkm_div.z as u16) - }); - - self.regs().rx_clkm_conf().modify(|_, w| unsafe { - w.rx_clk_active().set_bit(); - // for now fixed at 160MHz - w.rx_clk_sel().bits(property!("i2s.default_clock_source")); - w.rx_clkm_div_num().bits(clock_settings.mclk_divider as u8); - w.mclk_sel().bit(true) - }); - - self.regs().rx_conf().modify(|_, w| unsafe { - w.rx_bck_div_num() - .bits((clock_settings.bclk_divider - 1) as u8) - }); - } - - #[cfg(i2s_clock_configured_by_pcr)] - pub(crate) fn set_tx_clock(&self, clock_settings: I2sClockDividers) { - // I2S clocks are configured via PCR - use crate::peripherals::PCR; - - let clkm_div = clock_settings.mclk_dividers(); - let pcr = PCR::regs(); - - // Pulse a temporary divider before applying the target coefficients to avoid - // a hardware glitch where the clock divider applies twice on PCR chips. - pcr.i2s_tx_clkm_conf() - .modify(|_, w| unsafe { w.i2s_tx_clkm_div_num().bits(2) }); - pcr.i2s_tx_clkm_div_conf().modify(|_, w| unsafe { - w.i2s_tx_clkm_div_yn1().clear_bit(); - w.i2s_tx_clkm_div_y().bits(1); - w.i2s_tx_clkm_div_z().bits(0); - w.i2s_tx_clkm_div_x().bits(0) - }); - - pcr.i2s_tx_clkm_div_conf().modify(|_, w| unsafe { - w.i2s_tx_clkm_div_x().bits(clkm_div.x as u16); - w.i2s_tx_clkm_div_y().bits(clkm_div.y as u16); - w.i2s_tx_clkm_div_yn1().bit(clkm_div.yn1); - w.i2s_tx_clkm_div_z().bits(clkm_div.z as u16) - }); - - pcr.i2s_tx_clkm_conf().modify(|_, w| unsafe { - w.i2s_tx_clkm_en().set_bit(); - // for now fixed at 160MHz for C6 and 96MHz for H2 - w.i2s_tx_clkm_sel() - .bits(property!("i2s.default_clock_source")); - w.i2s_tx_clkm_div_num() - .bits(clock_settings.mclk_divider as u8) - }); - - self.regs().tx_conf().modify(|_, w| unsafe { - w.tx_bck_div_num() - .bits((clock_settings.bclk_divider - 1) as u8) - }); - } - - #[cfg(i2s_clock_configured_by_pcr)] - pub(crate) fn set_rx_clock(&self, clock_settings: I2sClockDividers) { - // I2S clocks are configured via PCR - use crate::peripherals::PCR; - - let clkm_div = clock_settings.mclk_dividers(); - let pcr = PCR::regs(); - - // Pulse a temporary divider before applying the target coefficients to avoid - // a hardware glitch where the clock divider applies twice on PCR chips. - pcr.i2s_rx_clkm_conf() - .modify(|_, w| unsafe { w.i2s_rx_clkm_div_num().bits(2) }); - pcr.i2s_rx_clkm_div_conf().modify(|_, w| unsafe { - w.i2s_rx_clkm_div_yn1().clear_bit(); - w.i2s_rx_clkm_div_y().bits(1); - w.i2s_rx_clkm_div_z().bits(0); - w.i2s_rx_clkm_div_x().bits(0) - }); - - pcr.i2s_rx_clkm_div_conf().modify(|_, w| unsafe { - w.i2s_rx_clkm_div_x().bits(clkm_div.x as u16); - w.i2s_rx_clkm_div_y().bits(clkm_div.y as u16); - w.i2s_rx_clkm_div_yn1().bit(clkm_div.yn1); - w.i2s_rx_clkm_div_z().bits(clkm_div.z as u16) - }); - - pcr.i2s_rx_clkm_conf().modify(|_, w| unsafe { - w.i2s_rx_clkm_en().set_bit(); - // for now fixed at 160MHz for C6 and 96MHz for H2 - w.i2s_rx_clkm_sel() - .bits(property!("i2s.default_clock_source")); - w.i2s_rx_clkm_div_num() - .bits(clock_settings.mclk_divider as u8); - w.i2s_mclk_sel().bit(true) - }); - - self.regs().rx_conf().modify(|_, w| unsafe { - w.rx_bck_div_num() - .bits((clock_settings.bclk_divider - 1) as u8) - }); - } - - #[cfg(i2s_clock_configured_by_hp_sys_clkrst)] - pub(crate) fn set_tx_clock(&self, clock_settings: I2sClockDividers) { - crate::i2s::hp_sys_clkrst::set_tx_clock(self.peripheral, &clock_settings); - - self.regs().tx_conf().modify(|_, w| unsafe { - w.tx_bck_div_num() - .bits((clock_settings.bclk_divider - 1) as u8) - }); + pub(crate) fn set_tx_bclk(&self, bclk_divider: u32) { + self.regs() + .tx_conf() + .modify(|_, w| unsafe { w.tx_bck_div_num().bits((bclk_divider - 1) as u8) }); } - #[cfg(i2s_clock_configured_by_hp_sys_clkrst)] - pub(crate) fn set_rx_clock(&self, clock_settings: I2sClockDividers) { - crate::i2s::hp_sys_clkrst::set_rx_clock(self.peripheral, &clock_settings); - - self.regs().rx_conf().modify(|_, w| unsafe { - w.rx_bck_div_num() - .bits((clock_settings.bclk_divider - 1) as u8) - }); + pub(crate) fn set_rx_bclk(&self, bclk_divider: u32) { + self.regs() + .rx_conf() + .modify(|_, w| unsafe { w.rx_bck_div_num().bits((bclk_divider - 1) as u8) }); } pub(crate) fn update_tx(&self) { @@ -186,6 +45,7 @@ impl Info { Config::Tdm(c) => { self.configure_tx(&c.tx_config)?; self.configure_rx(&c.rx_config)?; + self.configure_mclk_pad(c.mclk_out); self.regs() .tx_conf() @@ -205,14 +65,16 @@ impl Info { pub(crate) fn configure_tx(&self, config: &UnitConfig) -> Result<(), ConfigError> { let ws_width = config.calculate_ws_width()?; - self.set_tx_clock(config.calculate_clock()); + let clocks = config.calculate_clock(); + self.configure_tx_mclk(config.clock_source, &clocks); + self.set_tx_bclk(clocks.bclk_divider); self.regs().tx_conf1().modify(|_, w| unsafe { #[allow(clippy::useless_conversion)] w.tx_tdm_ws_width().bits((ws_width - 1).try_into().unwrap()); - w.tx_bits_mod().bits(config.data_format.data_bits() - 1); + w.tx_bits_mod().bits(config.data_format.channel_bits() - 1); w.tx_tdm_chan_bits() - .bits(config.data_format.channel_bits() - 1); + .bits(config.data_format.data_bits() - 1); w.tx_half_sample_bits() .bits((config.data_format.data_bits() * config.channels.count) / 2 - 1) }); @@ -231,7 +93,8 @@ impl Info { w.tx_bit_order().bit(config.bit_order == BitOrder::LsbFirst); w.tx_ws_idle_pol() .bit(config.ws_polarity == Polarity::ActiveHigh); - w.tx_chan_mod().bits(0) + w.tx_chan_mod().bits(0); + w.tx_left_align().bit(config.alignment() == Alignment::Left) }); self.regs().tx_tdm_ctrl().modify(|_, w| unsafe { @@ -264,14 +127,16 @@ impl Info { pub(crate) fn configure_rx(&self, config: &UnitConfig) -> Result<(), ConfigError> { let ws_width = config.calculate_ws_width()?; - self.set_rx_clock(config.calculate_clock()); + let clocks = config.calculate_clock(); + self.configure_rx_mclk(config.clock_source, &clocks); + self.set_rx_bclk(clocks.bclk_divider); self.regs().rx_conf1().modify(|_, w| unsafe { #[allow(clippy::useless_conversion)] w.rx_tdm_ws_width().bits((ws_width - 1).try_into().unwrap()); - w.rx_bits_mod().bits(config.data_format.data_bits() - 1); + w.rx_bits_mod().bits(config.data_format.channel_bits() - 1); w.rx_tdm_chan_bits() - .bits(config.data_format.channel_bits() - 1); + .bits(config.data_format.data_bits() - 1); w.rx_half_sample_bits() .bits((config.data_format.data_bits() * config.channels.count) / 2 - 1) }); @@ -288,7 +153,8 @@ impl Info { .bit(config.endianness == Endianness::BigEndian); w.rx_bit_order().bit(config.bit_order == BitOrder::LsbFirst); w.rx_ws_idle_pol() - .bit(config.ws_polarity == Polarity::ActiveHigh) + .bit(config.ws_polarity == Polarity::ActiveHigh); + w.rx_left_align().bit(config.alignment() == Alignment::Left) }); self.regs().rx_tdm_ctrl().modify(|_, w| unsafe { diff --git a/esp-hal/src/i2s/master/mod.rs b/esp-hal/src/i2s/master/mod.rs index d7c964d0a18..d2856b308c6 100644 --- a/esp-hal/src/i2s/master/mod.rs +++ b/esp-hal/src/i2s/master/mod.rs @@ -166,6 +166,15 @@ pub use super::pdm::{ PdmSlotMode, PdmTxConfig, }; +/// Clock source for the I2S TX/RX module clocks (after the source mux and MCLK divider). +#[cfg(not(i2s_version = "1"))] +pub use crate::clock::ll::I2sClkSclk as I2sClockSource; +/// Selects whether the MCLK pad outputs the TX or RX module clock. +#[cfg(not(i2s_version = "1"))] +pub use crate::clock::ll::I2sMclkOutConfig as MclkOut; +/// Clock source for the I2S module clock (after the source mux and MCLK divider). +#[cfg(i2s_version = "1")] +pub use crate::clock::ll::I2sMclkSclk as I2sClockSource; use crate::{ Async, Blocking, @@ -198,6 +207,31 @@ use crate::{ time::Rate, }; +/// Returns the frequency of a module clock source, in Hz. +/// +/// The transmitter and the receiver select their source from the same set of clocks, so one +/// lookup describes both directions. +pub(crate) fn source_frequency(source: I2sClockSource) -> u32 { + cfg_select! { + i2s_version = "1" => crate::clock::ll::I2sInstance::mclk_source_frequency(source), + _ => crate::clock::ll::I2sInstance::tx_clk_source_frequency(source), + } +} + +/// Returns the largest A coefficient the module-clock divider can hold. +pub(crate) fn mclk_max_denominator() -> u32 { + cfg_select! { + i2s_version = "1" => { + let (_, max) = property!("clock_tree.i2s.mclk.div_a"); + max + } + _ => { + let (_, max) = property!("clock_tree.i2s.tx_clk.div_a"); + max + } + } +} + #[derive(Debug, EnumSetType)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] /// Represents the various interrupt types for the I2S peripheral. @@ -245,7 +279,7 @@ with_i2s_dma_engine! { } impl<'d> I2s<'d, crate::Blocking> { - /// Construct a new I2S instance in TDM mode. + /// Creates a new I2S instance in TDM mode. pub fn new( i2s: I, channel: impl I2sMasterDmaChannel<'d, I>, @@ -254,7 +288,7 @@ impl<'d> I2s<'d, crate::Blocking> { Self::new_internal(i2s, channel.into(), Config::Tdm(config)) } - /// Construct a new I2S instance in PDM mode. + /// Creates a new I2S instance in PDM mode. #[cfg(any(i2s_supports_pdm_tx, i2s_supports_pdm_rx))] pub fn new_pdm( i2s: I, @@ -265,14 +299,9 @@ impl<'d> I2s<'d, crate::Blocking> { } } -pub(crate) const I2S_LL_MCLK_DIVIDER_BIT_WIDTH: usize = property!("i2s.mclk_divider_bit_width"); - -pub(crate) const I2S_LL_MCLK_DIVIDER_MAX: usize = (1 << I2S_LL_MCLK_DIVIDER_BIT_WIDTH) - 1; - /// A structure representing a DMA transfer. /// -/// This structure holds references to the driver instance, DMA buffers, and -/// transfer status. +/// Holds references to the driver instance, DMA buffers, and transfer status. #[instability::unstable] pub struct I2sTxDmaTransfer<'d, Dm, Buf> where @@ -289,7 +318,7 @@ where Dm: DriverMode, Buf: DmaTxBuffer, { - /// Returns true when [Self::wait] will not block. + /// Returns whether [`Self::wait`] will not block. pub fn is_done(&self) -> bool { self.completed || self.i2s_tx.i2s.info().is_tx_done() } @@ -306,7 +335,7 @@ where } } - /// Immediately stop the transfer and return the peripheral and buffer. + /// Immediately stops the transfer and returns the peripheral and buffer. pub fn stop(mut self) -> (I2sTx<'d, Dm>, Buf::Final) { self.i2s_tx.tx_channel.stop_transfer(); self.i2s_tx.i2s.info().tx_stop(); @@ -406,8 +435,7 @@ impl Drop for I2sTxDmaTransfer<'_, Dm, BUF> { /// A structure representing a DMA transfer. /// -/// This structure holds references to the driver instance, DMA buffers, and -/// transfer status. +/// Holds references to the driver instance, DMA buffers, and transfer status. #[instability::unstable] pub struct I2sRxDmaTransfer<'d, Dm, Buf> where @@ -424,7 +452,7 @@ where Dm: DriverMode, Buf: DmaRxBuffer, { - /// Returns true when [Self::wait] will not block. + /// Returns whether [`Self::wait`] will not block. pub fn is_done(&self) -> bool { self.completed || self.i2s_rx.i2s.info().is_rx_done() } @@ -442,7 +470,7 @@ where } } - /// Immediately stop the transfer and return the peripheral and buffer. + /// Immediately stops the transfer and returns the peripheral and buffer. pub fn stop(mut self) -> (I2sRx<'d, Dm>, Buf::Final) { self.i2s_rx.i2s.info().rx_stop(); self.i2s_rx.rx_channel.stop_transfer(); @@ -574,56 +602,165 @@ impl From for Error { } } -/// Supported data formats +/// Supported I2S data formats. +/// +/// Each format defines two dimensions: +/// +/// - **`Data{X}` (on-wire slot width)**: The number of bit-clock (BCLK) cycles allocated to each +/// channel slot on the physical line ([`Self::data_bits`]). This determines the BCLK frequency +/// (`BCLK = sample_rate * channels * data_bits`) and the time duration of each channel slot. +/// - **`Channel{Y}` (in-memory sample width)**: The number of active audio data bits per sample +/// transferred to or from memory via DMA ([`Self::channel_bits`]). +/// +/// ### In-Memory Representation +/// +/// In the DMA memory buffer, samples are stored with a size corresponding to `Channel{Y}`: +/// - 32-bit (`Channel32`): 4 bytes per sample (e.g. `i32` / `u32`). +/// - 24-bit (`Channel24`): 3 bytes per sample (packed 24-bit PCM). +/// - 16-bit (`Channel16`): 2 bytes per sample (e.g. `i16` / `u16`). +/// - 8-bit (`Channel8`): 1 byte per sample (e.g. `i8` / `u8`). +/// +/// ### On-Wire Representation and Padding +/// +/// On the physical I2S lines, each channel occupies `Data{X}` clock cycles: +/// - When `X == Y` (e.g. [`Data16Channel16`], [`Data32Channel32`]), the entire slot carries sample +/// data with no padding. +/// - When `X > Y` (e.g. [`Data32Channel16`]), the `Y`-bit sample occupies `Y` bits of the `X`-bit +/// slot on the wire, and the remaining `X - Y` bits are padded or discarded according to +/// [`Alignment`]: +/// - [`Alignment::Left`] (default): +/// - **TX**: The `Y` sample bits are transmitted first (MSB-aligned within the slot), followed +/// by `X - Y` zero bits. +/// - **RX**: The first `Y` bits from the wire are captured into memory; trailing bits in the +/// slot are discarded. +/// - [`Alignment::Right`]: +/// - **TX**: `X - Y` zero bits are transmitted first, followed by the `Y` sample bits +/// (LSB-aligned within the slot). +/// - **RX**: The leading `X - Y` bits are discarded; the last `Y` bits of the slot are captured +/// into memory. +/// +/// Note: In this driver's naming scheme, `Data{X}` refers to the on-wire slot width, and +/// `Channel{Y}` refers to the in-memory sample data width. (This differs from some datasheets where +/// the on-wire slot is called "slot width" or "channel width", and the sample size is called "data +/// width".) +/// +/// [`Data16Channel16`]: DataFormat::Data16Channel16 +/// [`Data32Channel16`]: DataFormat::Data32Channel16 +/// [`Data32Channel32`]: DataFormat::Data32Channel32 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[cfg(not(i2s_version = "1"))] pub enum DataFormat { - /// 32-bit data width and 32-bit channel width. + /// 32-bit on-wire slot width (32 BCLK cycles) and 32-bit in-memory sample width (4 bytes per + /// sample). Data32Channel32, - /// 32-bit data width and 24-bit channel width. + /// 32-bit on-wire slot width (32 BCLK cycles) and 24-bit in-memory sample width (3 bytes packed + /// per sample). + /// + /// In TX, 24-bit samples from memory are padded to 32 bits on the wire according to + /// [`Alignment`]. In RX, 24 bits are extracted from each 32-bit slot on the wire into + /// memory. Data32Channel24, - /// 32-bit data width and 16-bit channel width. + /// 32-bit on-wire slot width (32 BCLK cycles) and 16-bit in-memory sample width (2 bytes per + /// sample). + /// + /// In TX, 16-bit samples from memory are padded to 32 bits on the wire according to + /// [`Alignment`]. In RX, 16 bits are extracted from each 32-bit slot on the wire into + /// memory. Data32Channel16, - /// 32-bit data width and 8-bit channel width. + /// 32-bit on-wire slot width (32 BCLK cycles) and 8-bit in-memory sample width (1 byte per + /// sample). + /// + /// In TX, 8-bit samples from memory are padded to 32 bits on the wire according to + /// [`Alignment`]. In RX, 8 bits are extracted from each 32-bit slot on the wire into + /// memory. Data32Channel8, - /// 16-bit data width and 16-bit channel width. + /// 16-bit on-wire slot width (16 BCLK cycles) and 16-bit in-memory sample width (2 bytes per + /// sample). Data16Channel16, - /// 16-bit data width and 8-bit channel width. + /// 16-bit on-wire slot width (16 BCLK cycles) and 8-bit in-memory sample width (1 byte per + /// sample). + /// + /// In TX, 8-bit samples from memory are padded to 16 bits on the wire according to + /// [`Alignment`]. In RX, 8 bits are extracted from each 16-bit slot on the wire into + /// memory. Data16Channel8, - /// 8-bit data width and 8-bit channel width. + /// 8-bit on-wire slot width (8 BCLK cycles) and 8-bit in-memory sample width (1 byte per + /// sample). Data8Channel8, } -/// Supported data formats +/// Supported I2S data formats. +/// +/// Each format defines the on-wire slot width (`Data{X}`) and the in-memory sample width +/// (`Channel{Y}`). On the ESP32-S2, each slot on the wire matches the sample data width in memory +/// (`X == Y`). +/// +/// - **`Data{X}` (on-wire slot width)**: The number of bit-clock (BCLK) cycles allocated to each +/// channel slot on the physical line ([`Self::data_bits`]). +/// - **`Channel{Y}` (in-memory sample width)**: The number of audio data bits per sample +/// transferred to or from memory via DMA ([`Self::channel_bits`]). +/// +/// In the DMA memory buffer, samples occupy: +/// - 32-bit ([`Data32Channel32`]): 4 bytes per sample. +/// - 24-bit ([`Data24Channel24`]): 3 bytes per sample. +/// - 16-bit ([`Data16Channel16`]): 2 bytes per sample. +/// - 8-bit ([`Data8Channel8`]): 1 byte per sample. +/// +/// [`Data32Channel32`]: DataFormat::Data32Channel32 +/// [`Data24Channel24`]: DataFormat::Data24Channel24 +/// [`Data16Channel16`]: DataFormat::Data16Channel16 +/// [`Data8Channel8`]: DataFormat::Data8Channel8 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[cfg(esp32s2)] pub enum DataFormat { - /// 32-bit data width and 32-bit channel width. + /// 32-bit on-wire slot width (32 BCLK cycles) and 32-bit in-memory sample width (4 bytes per + /// sample). Data32Channel32, - /// 24-bit data width and 24-bit channel width. + /// 24-bit on-wire slot width (24 BCLK cycles) and 24-bit in-memory sample width (3 bytes packed + /// per sample). Data24Channel24, - /// 16-bit data width and 16-bit channel width. + /// 16-bit on-wire slot width (16 BCLK cycles) and 16-bit in-memory sample width (2 bytes per + /// sample). Data16Channel16, - /// 8-bit data width and 8-bit channel width. + /// 8-bit on-wire slot width (8 BCLK cycles) and 8-bit in-memory sample width (1 byte per + /// sample). Data8Channel8, } -/// Supported data formats +/// Supported I2S data formats. +/// +/// Each format defines the on-wire slot width (`Data{X}`) and the in-memory sample width +/// (`Channel{Y}`). On the ESP32, each slot on the wire matches the sample data width in memory (`X +/// == Y`). +/// +/// - **`Data{X}` (on-wire slot width)**: The number of bit-clock (BCLK) cycles allocated to each +/// channel slot on the physical line ([`Self::data_bits`]). +/// - **`Channel{Y}` (in-memory sample width)**: The number of audio data bits per sample +/// transferred to or from memory via DMA ([`Self::channel_bits`]). +/// +/// In the DMA memory buffer, samples occupy: +/// - 32-bit ([`Data32Channel32`]): 4 bytes per sample. +/// - 16-bit ([`Data16Channel16`]): 2 bytes per sample. +/// +/// [`Data32Channel32`]: DataFormat::Data32Channel32 +/// [`Data16Channel16`]: DataFormat::Data16Channel16 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[cfg(esp32)] pub enum DataFormat { - /// 32-bit data width and 32-bit channel width. + /// 32-bit on-wire slot width (32 BCLK cycles) and 32-bit in-memory sample width (4 bytes per + /// sample). Data32Channel32, - /// 16-bit data width and 16-bit channel width. + /// 16-bit on-wire slot width (16 BCLK cycles) and 16-bit in-memory sample width (2 bytes per + /// sample). Data16Channel16, } #[cfg(not(i2s_version = "1"))] impl DataFormat { - /// Returns the number of data bits for the selected data format. + /// Returns the on-wire slot width in bits (number of BCLK cycles per channel slot). pub fn data_bits(&self) -> u8 { match self { DataFormat::Data32Channel32 => 32, @@ -636,7 +773,8 @@ impl DataFormat { } } - /// Returns the number of channel bits for the selected data format. + /// Returns the in-memory sample width in bits (active audio data bits per sample transferred + /// via DMA). pub fn channel_bits(&self) -> u8 { match self { DataFormat::Data32Channel32 => 32, @@ -652,7 +790,7 @@ impl DataFormat { #[cfg(esp32s2)] impl DataFormat { - /// Returns the number of data bits for the selected data format. + /// Returns the on-wire slot width in bits (number of BCLK cycles per channel slot). pub fn data_bits(&self) -> u8 { match self { DataFormat::Data32Channel32 => 32, @@ -662,7 +800,8 @@ impl DataFormat { } } - /// Returns the number of channel bits for the selected data format. + /// Returns the in-memory sample width in bits (active audio data bits per sample transferred + /// via DMA). pub fn channel_bits(&self) -> u8 { match self { DataFormat::Data32Channel32 => 32, @@ -675,7 +814,7 @@ impl DataFormat { #[cfg(esp32)] impl DataFormat { - /// Returns the number of data bits for the selected data format. + /// Returns the on-wire slot width in bits (number of BCLK cycles per channel slot). pub fn data_bits(&self) -> u8 { match self { DataFormat::Data32Channel32 => 32, @@ -683,7 +822,8 @@ impl DataFormat { } } - /// Returns the number of channel bits for the selected data format. + /// Returns the in-memory sample width in bits (active audio data bits per sample transferred + /// via DMA). pub fn channel_bits(&self) -> u8 { match self { DataFormat::Data32Channel32 => 32, @@ -718,7 +858,7 @@ pub enum Endianness { #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum WsWidth { - /// Word select signal will be kept active for half of the frame + /// Word select signal will be kept active for half of the frame. #[default] HalfFrame, /// Word select signal will be kept active for the length of the first channel (PCM long frame @@ -732,17 +872,31 @@ pub enum WsWidth { Bits(u16), } -/// Represents the polarity of a signal +/// Represents the polarity of a signal. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum Polarity { - /// The signal is high when active + /// The signal is high when active. #[default] ActiveHigh, - /// The signal is low when active + /// The signal is low when active. ActiveLow, } +/// Alignment of sample data within the on-wire slot when the in-memory sample width is less than +/// the on-wire slot width. +/// +/// See [`DataFormat`] for more details on padding and on-wire slot alignment. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum Alignment { + #[default] + /// Left aligned (MSB-aligned within the on-wire slot). + Left, + /// Right aligned (LSB-aligned within the on-wire slot). + Right, +} + /// I2S channels configuration #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] @@ -753,9 +907,9 @@ pub struct Channels { } impl Channels { - /// Two channels will use different data + /// Two channels will use different data. pub const STEREO: Channels = Channels::new_impl(2, 0b11, None); - /// Two channels will use the same data + /// Two channels will use the same data. pub const MONO: Channels = Channels::new_impl(2, 0b01, None); /// Two channels. Left(first) channel will contain data. Right(second) channel will contain /// zeros. @@ -776,7 +930,7 @@ impl Channels { /// disabled channels repeat the data from the last active channel. This field is ignored in /// the receiver unit. /// - /// ## Example + /// # Examples /// /// The following example prepares configuration for 6 channels. Only 1st and 4th channels /// are active. Channels 2-3 will use the same data as the 1st, and channels 5-6 will use the @@ -824,20 +978,28 @@ pub(crate) enum Config { #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[non_exhaustive] pub struct TdmConfig { - /// Receiver unit config + /// Receiver unit config. rx_config: TdmUnitConfig, - /// Transmitter unit config + /// Transmitter unit config. tx_config: TdmUnitConfig, /// Sets `I2S_SIG_LOOPBACK`: TX and RX share the same WS and BCK. signal_loopback: bool, - /// The target sample rate + /// The target sample rate. #[cfg(i2s_version = "1")] sample_rate: Rate, - /// Format of the data + /// Source clock for the shared module clock. + #[cfg(i2s_version = "1")] + clock_source: I2sClockSource, + + /// Selects which module clock is routed to the MCLK pad. + #[cfg(not(i2s_version = "1"))] + mclk_out: MclkOut, + + /// Data format configuring on-wire slot width and in-memory sample width. #[cfg(i2s_version = "1")] data_format: DataFormat, } @@ -850,15 +1012,6 @@ impl Config { Self::Pdm(c) => c.validate(_info).map_err(ConfigError::Pdm), } } - - #[cfg(i2s_version = "1")] - fn calculate_clock(&self) -> I2sClockDividers { - match self { - Self::Tdm(c) => c.calculate_clock(), - #[cfg(any(i2s_supports_pdm_tx, i2s_supports_pdm_rx))] - Self::Pdm(_) => unreachable!(), - } - } } impl TdmConfig { @@ -907,10 +1060,15 @@ impl TdmConfig { #[cfg(i2s_version = "1")] fn calculate_clock(&self) -> I2sClockDividers { - I2sClockDividers::new(self.sample_rate, 2, self.data_format.data_bits()) + I2sClockDividers::new( + self.sample_rate, + 2, + self.data_format.data_bits(), + self.clock_source, + ) } - /// Assign the given value to the `sample_rate` field in both units. + /// Assigns the given value to the `sample_rate` field in both units. #[must_use] #[cfg(not(i2s_version = "1"))] pub fn with_sample_rate(self, sample_rate: Rate) -> Self { @@ -921,7 +1079,7 @@ impl TdmConfig { } } - /// Assign the given value to the `channels` field in both units. + /// Assigns the given value to the `channels` field in both units. #[must_use] pub fn with_channels(self, channels: Channels) -> Self { Self { @@ -931,7 +1089,9 @@ impl TdmConfig { } } - /// Assign the given value to the `data_format` field in both units. + /// Assigns the given data format to both units. + /// + /// See [`DataFormat`] for details on on-wire slot width and in-memory sample width. #[must_use] #[cfg(not(i2s_version = "1"))] pub fn with_data_format(self, data_format: DataFormat) -> Self { @@ -942,7 +1102,7 @@ impl TdmConfig { } } - /// Assign the given value to the `ws_width` field in both units. + /// Assigns the given value to the `ws_width` field in both units. #[must_use] pub fn with_ws_width(self, ws_width: WsWidth) -> Self { Self { @@ -952,7 +1112,7 @@ impl TdmConfig { } } - /// Assign the given value to the `ws_polarity` field in both units. + /// Assigns the given value to the `ws_polarity` field in both units. #[must_use] pub fn with_ws_polarity(self, ws_polarity: Polarity) -> Self { Self { @@ -962,7 +1122,7 @@ impl TdmConfig { } } - /// Assign the given value to the `msb_shift` field in both units. + /// Assigns the given value to the `msb_shift` field in both units. #[must_use] pub fn with_msb_shift(self, msb_shift: bool) -> Self { Self { @@ -972,7 +1132,7 @@ impl TdmConfig { } } - /// Assign the given value to the `endianness` field in both units. + /// Assigns the given value to the `endianness` field in both units. #[cfg(not(esp32))] #[must_use] pub fn with_endianness(self, endianness: Endianness) -> Self { @@ -983,7 +1143,7 @@ impl TdmConfig { } } - /// Assign the given value to the `bit_order` field in both units. + /// Assigns the given value to the `bit_order` field in both units. #[cfg(not(i2s_version = "1"))] #[must_use] pub fn with_bit_order(self, bit_order: BitOrder) -> Self { @@ -993,6 +1153,17 @@ impl TdmConfig { ..self } } + + /// Assigns the given value to the `alignment` field in both units. + #[cfg(not(i2s_version = "1"))] + #[must_use] + pub fn with_alignment(self, alignment: Alignment) -> Self { + Self { + rx_config: self.rx_config.with_alignment(alignment), + tx_config: self.tx_config.with_alignment(alignment), + ..self + } + } } #[allow(clippy::derivable_impls)] @@ -1005,6 +1176,10 @@ impl Default for TdmConfig { #[cfg(i2s_version = "1")] sample_rate: Rate::from_hz(44100), #[cfg(i2s_version = "1")] + clock_source: I2sClockSource::default(), + #[cfg(not(i2s_version = "1"))] + mclk_out: MclkOut::default(), + #[cfg(i2s_version = "1")] data_format: DataFormat::Data16Channel16, } } @@ -1015,44 +1190,55 @@ impl Default for TdmConfig { #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[non_exhaustive] pub struct TdmUnitConfig { - /// The target sample rate + /// The target sample rate. #[cfg(not(i2s_version = "1"))] sample_rate: Rate, - /// I2S channels configuration + /// Source clock for this unit's module clock. + #[cfg(not(i2s_version = "1"))] + clock_source: I2sClockSource, + + /// I2S channels configuration. channels: Channels, - /// Format of the data + /// Data format configuring on-wire slot width and in-memory sample width. #[cfg(not(i2s_version = "1"))] data_format: DataFormat, - /// Duration for which WS signal is kept active + /// Duration for which WS signal is kept active. ws_width: WsWidth, - /// Polarity of WS signal + /// Polarity of WS signal. ws_polarity: Polarity, - /// Data signal will lag by one bit relative to the WS signal + /// Data signal will lag by one bit relative to the WS signal. msb_shift: bool, - /// Byte order of the data + /// Byte order of the data. #[cfg(not(esp32))] endianness: Endianness, - /// Bit order of the data + /// Bit order of the data. #[cfg(not(i2s_version = "1"))] bit_order: BitOrder, + + /// Alignment of sample data within the on-wire slot. Only relevant when sample width is less + /// than slot width. + #[cfg(not(i2s_version = "1"))] + alignment: Alignment, } /// Alias for [`TdmUnitConfig`] (TDM mode unit configuration). pub type UnitConfig = TdmUnitConfig; impl TdmUnitConfig { - /// TDM Philips standard configuration with two 16-bit active channels + /// TDM Philips standard configuration with two 16-bit active channels. pub fn new_tdm_philips() -> Self { Self { #[cfg(not(i2s_version = "1"))] sample_rate: Rate::from_hz(44100), + #[cfg(not(i2s_version = "1"))] + clock_source: I2sClockSource::default(), channels: Channels::STEREO, #[cfg(not(i2s_version = "1"))] data_format: DataFormat::Data16Channel16, @@ -1063,22 +1249,24 @@ impl TdmUnitConfig { endianness: Endianness::LittleEndian, #[cfg(not(i2s_version = "1"))] bit_order: BitOrder::MsbFirst, + #[cfg(not(i2s_version = "1"))] + alignment: Alignment::Left, } } - /// TDM MSB standard configuration with two 16-bit active channels + /// TDM MSB standard configuration with two 16-bit active channels. pub fn new_tdm_msb() -> Self { Self::new_tdm_philips().with_msb_shift(false) } - /// TDM PCM short frame standard configuration with two 16-bit active channels + /// TDM PCM short frame standard configuration with two 16-bit active channels. pub fn new_tdm_pcm_short() -> Self { Self::new_tdm_philips() .with_ws_width(WsWidth::Bit) .with_ws_polarity(Polarity::ActiveHigh) } - /// TDM PCM long frame standard configuration with two 16-bit active channels + /// TDM PCM long frame standard configuration with two 16-bit active channels. #[cfg(not(i2s_version = "1"))] pub fn new_tdm_pcm_long() -> Self { Self::new_tdm_philips() @@ -1123,6 +1311,7 @@ impl TdmUnitConfig { self.sample_rate, self.channels.count, self.data_format.data_bits(), + self.clock_source, ) } } @@ -1138,13 +1327,13 @@ impl Default for TdmUnitConfig { #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum ConfigError { - /// Provided [Channels] configuration has no active channels or has over 16 total channels + /// Provided [Channels] configuration has no active channels or has over 16 total channels. #[cfg(not(i2s_version = "1"))] ChannelsOutOfRange, - /// Requested WS signal width is out of range + /// Requested WS signal width is out of range. #[cfg(not(i2s_version = "1"))] WsWidthOutOfRange, - /// PDM configuration error + /// PDM configuration error. #[cfg(any(i2s_supports_pdm_tx, i2s_supports_pdm_rx))] Pdm(PdmError), } @@ -1182,7 +1371,7 @@ impl core::fmt::Display for ConfigError { } } -/// Instance of the I2S peripheral driver +/// Instance of the I2S peripheral driver. #[non_exhaustive] pub struct I2s<'d, Dm> where @@ -1207,10 +1396,9 @@ where doc = "Registers an interrupt handler for the peripheral on the current core." )] #[doc = ""] - /// Note that this will replace any previously registered interrupt - /// handlers. + /// Replaces any previously registered interrupt handlers. /// - /// You can restore the default/unhandled interrupt handler by using + /// The default/unhandled interrupt handler can be restored with /// [crate::interrupt::DEFAULT_INTERRUPT_HANDLER] #[instability::unstable] pub fn set_interrupt_handler(&mut self, handler: InterruptHandler) { @@ -1218,7 +1406,7 @@ where self.i2s_tx.i2s.set_interrupt_handler(handler); } - /// Listen for the given interrupts + /// Listens for the given interrupts. #[instability::unstable] pub fn listen(&mut self, interrupts: impl Into>) { // tx.i2s and rx.i2s is the same, we could use either one @@ -1228,7 +1416,7 @@ where .enable_listen(interrupts.into(), true); } - /// Unlisten the given interrupts + /// Unlistens from the given interrupts. #[instability::unstable] pub fn unlisten(&mut self, interrupts: impl Into>) { // tx.i2s and rx.i2s is the same, we could use either one @@ -1238,14 +1426,14 @@ where .enable_listen(interrupts.into(), false); } - /// Gets asserted interrupts + /// Returns the asserted interrupts. #[instability::unstable] pub fn interrupts(&mut self) -> EnumSet { // tx.i2s and rx.i2s is the same, we could use either one self.i2s_tx.i2s.info().interrupts() } - /// Resets asserted interrupts + /// Resets asserted interrupts. #[instability::unstable] pub fn clear_interrupts(&mut self, interrupts: impl Into>) { // tx.i2s and rx.i2s is the same, we could use either one @@ -1286,20 +1474,25 @@ impl<'d> I2s<'d, Blocking> { i2s.info().set_master(); i2s.info().configure(&config)?; - match &config { - Config::Tdm(_) => { - i2s.info().update_tx(); - i2s.info().update_rx(); - } + + let clock = i2s.info().clock_instance; + let (req_tx, req_rx) = match &config { + Config::Tdm(_) => (true, true), #[cfg(any(i2s_supports_pdm_tx, i2s_supports_pdm_rx))] - Config::Pdm(c) => { - if c.tx.is_some() { - i2s.info().update_tx(); - } - if c.rx.is_some() { - i2s.info().update_rx(); - } - } + Config::Pdm(c) => (c.tx.is_some(), c.rx.is_some()), + }; + + // `tx_update` / `rx_update` copy APB registers into the I2S clock domain. The + // module clock of that direction must run, or the self-clearing bit never + // clears. + let rx_clk_guard = req_rx.then(|| I2sDirClkGuard::request_rx(clock)); + let tx_clk_guard = req_tx.then(|| I2sDirClkGuard::request_tx(clock)); + + if req_tx { + i2s.info().update_tx(); + } + if req_rx { + i2s.info().update_rx(); } Ok(Self { @@ -1307,6 +1500,9 @@ impl<'d> I2s<'d, Blocking> { i2s: unsafe { i2s.clone_unchecked() }, rx_channel: channel.rx, guard: rx_guard, + clk_guard: rx_clk_guard, + #[cfg(not(i2s_version = "1"))] + mclk_out_guard: None, #[cfg(i2s_version = "1")] data_format: match config { Config::Tdm(c) => c.data_format, @@ -1318,6 +1514,9 @@ impl<'d> I2s<'d, Blocking> { i2s, tx_channel: channel.tx, guard: tx_guard, + clk_guard: tx_clk_guard, + #[cfg(not(i2s_version = "1"))] + mclk_out_guard: None, #[cfg(i2s_version = "1")] data_format: match config { Config::Tdm(c) => c.data_format, @@ -1335,6 +1534,9 @@ impl<'d> I2s<'d, Blocking> { i2s: self.i2s_rx.i2s, rx_channel: self.i2s_rx.rx_channel.into_async(), guard: self.i2s_rx.guard, + clk_guard: self.i2s_rx.clk_guard, + #[cfg(not(i2s_version = "1"))] + mclk_out_guard: self.i2s_rx.mclk_out_guard, #[cfg(i2s_version = "1")] data_format: self.i2s_rx.data_format, }, @@ -1342,6 +1544,9 @@ impl<'d> I2s<'d, Blocking> { i2s: self.i2s_tx.i2s, tx_channel: self.i2s_tx.tx_channel.into_async(), guard: self.i2s_tx.guard, + clk_guard: self.i2s_tx.clk_guard, + #[cfg(not(i2s_version = "1"))] + mclk_out_guard: self.i2s_tx.mclk_out_guard, #[cfg(i2s_version = "1")] data_format: self.i2s_tx.data_format, }, @@ -1397,6 +1602,21 @@ where self.i2s_tx.i2s.info().mclk.connect_to(&mclk); + self.request_mclk_out() + } + + /// Requests the MCLK pad output, on the chips that gate it as a separate clock. + #[cfg(all(not(esp32), i2s_version = "1"))] + fn request_mclk_out(self) -> Self { + self + } + + /// Requests the MCLK pad output, on the chips that gate it as a separate clock. + #[cfg(all(not(esp32), not(i2s_version = "1")))] + fn request_mclk_out(mut self) -> Self { + let guard = I2sMclkOutGuard::request(self.i2s_tx.i2s.info().clock_instance); + self.i2s_tx.mclk_out_guard = Some(guard.clone()); + self.i2s_rx.mclk_out_guard = Some(guard); self } @@ -1442,7 +1662,7 @@ where } } -/// I2S TX channel +/// I2S TX channel. pub struct I2sTx<'d, Dm> where Dm: DriverMode, @@ -1450,6 +1670,9 @@ where i2s: AnyI2s<'d>, tx_channel: ChannelTx as DmaChannel>::Tx>, _guard: PeripheralGuard, + _clk_guard: Option, + #[cfg(not(i2s_version = "1"))] + _mclk_out_guard: Option, #[cfg(i2s_version = "1")] data_format: DataFormat, } @@ -1467,7 +1690,7 @@ impl<'d, Dm> I2sTx<'d, Dm> where Dm: DriverMode, { - /// Perform a DMA write. + /// Performs a DMA write. #[allow(clippy::type_complexity)] #[instability::unstable] pub fn write( @@ -1493,7 +1716,7 @@ where }) } - /// Change the I2S Tx unit configuration. + /// Changes the I2S Tx unit configuration. pub fn apply_config(&mut self, tx_config: &UnitConfig) -> Result<(), ConfigError> { tx_config.validate()?; self.i2s.info().configure_tx( @@ -1504,7 +1727,7 @@ where } } -/// I2S RX channel +/// I2S RX channel. pub struct I2sRx<'d, Dm> where Dm: DriverMode, @@ -1512,6 +1735,9 @@ where i2s: AnyI2s<'d>, rx_channel: ChannelRx as DmaChannel>::Rx>, _guard: PeripheralGuard, + _clk_guard: Option, + #[cfg(not(i2s_version = "1"))] + _mclk_out_guard: Option, #[cfg(i2s_version = "1")] data_format: DataFormat, } @@ -1529,12 +1755,12 @@ impl<'d, Dm> I2sRx<'d, Dm> where Dm: DriverMode, { - /// Perform a DMA read. + /// Performs a DMA read. /// /// The number of read bytes might be less than the capacity of the provided buffer since the /// peripheral might not completely fill each descriptor's buffer. /// - /// This will return a [I2sRxDmaTransfer] + /// Returns an [`I2sRxDmaTransfer`]. pub fn read( mut self, mut buffer: BUF, @@ -1564,7 +1790,7 @@ where }) } - /// Change the I2S Rx unit configuration. + /// Changes the I2S Rx unit configuration. pub fn apply_config(&mut self, rx_config: &UnitConfig) -> Result<(), ConfigError> { rx_config.validate()?; self.i2s.info().configure_rx( @@ -1607,6 +1833,7 @@ for_each_i2s! { pdm_rx: $pdm_rx, pcm2pdm: $pcm2pdm, pdm2pcm: $pdm2pcm, + clock_instance: crate::clock::ll::I2sInstance::$sys, }; &INFO } @@ -1648,6 +1875,95 @@ impl AnyI2s<'_> { } } +/// Keeps the module clock of one direction enabled. +/// +/// Both directions share a single module clock on `i2s_version = "1"`, and the clock tree counts +/// the requests, so a guard per direction is correct on every chip. +pub(crate) struct I2sDirClkGuard { + clock: crate::clock::ll::I2sInstance, + #[cfg(not(i2s_version = "1"))] + tx: bool, +} + +impl I2sDirClkGuard { + pub(crate) fn request_tx(clock: crate::clock::ll::I2sInstance) -> Self { + Self::request(clock, true) + } + + fn request_rx(clock: crate::clock::ll::I2sInstance) -> Self { + Self::request(clock, false) + } + + fn request(clock: crate::clock::ll::I2sInstance, tx: bool) -> Self { + crate::clock::ll::ClockTree::with(|clocks| { + cfg_select! { + i2s_version = "1" => { + let _ = tx; + clock.request_mclk(clocks); + } + _ => { + if tx { + clock.request_tx_clk(clocks); + } else { + clock.request_rx_clk(clocks); + } + } + } + }); + + Self { + clock, + #[cfg(not(i2s_version = "1"))] + tx, + } + } +} + +impl Drop for I2sDirClkGuard { + fn drop(&mut self) { + crate::clock::ll::ClockTree::with(|clocks| { + cfg_select! { + i2s_version = "1" => self.clock.release_mclk(clocks), + _ => { + if self.tx { + self.clock.release_tx_clk(clocks); + } else { + self.clock.release_rx_clk(clocks); + } + } + } + }); + } +} + +/// Keeps the MCLK pad output enabled. +#[cfg(not(i2s_version = "1"))] +pub(crate) struct I2sMclkOutGuard { + clock: crate::clock::ll::I2sInstance, +} + +#[cfg(not(i2s_version = "1"))] +impl I2sMclkOutGuard { + fn request(clock: crate::clock::ll::I2sInstance) -> Self { + crate::clock::ll::ClockTree::with(|clocks| clock.request_mclk_out(clocks)); + Self { clock } + } +} + +#[cfg(not(i2s_version = "1"))] +impl Clone for I2sMclkOutGuard { + fn clone(&self) -> Self { + Self::request(self.clock) + } +} + +#[cfg(not(i2s_version = "1"))] +impl Drop for I2sMclkOutGuard { + fn drop(&mut self) { + crate::clock::ll::ClockTree::with(|clocks| self.clock.release_mclk_out(clocks)); + } +} + pub(crate) mod private { use super::*; @@ -1658,6 +1974,9 @@ pub(crate) mod private { pub i2s: AnyI2s<'d>, pub tx_channel: ChannelTx as DmaChannel>::Tx>, pub(crate) guard: PeripheralGuard, + pub(crate) clk_guard: Option, + #[cfg(not(i2s_version = "1"))] + pub(crate) mclk_out_guard: Option, #[cfg(i2s_version = "1")] pub(crate) data_format: DataFormat, } @@ -1672,6 +1991,9 @@ pub(crate) mod private { i2s: self.i2s, tx_channel: self.tx_channel, _guard: PeripheralGuard::new(peripheral), + _clk_guard: self.clk_guard, + #[cfg(not(i2s_version = "1"))] + _mclk_out_guard: self.mclk_out_guard, #[cfg(i2s_version = "1")] data_format: self.data_format, } @@ -1710,12 +2032,12 @@ pub(crate) mod private { self } - /// Connect the PDM clock pin (maps to the WS output signal). + /// Connects the PDM clock pin (maps to the WS output signal). pub fn with_clk(self, clk: impl PeripheralOutput<'d>) -> Self { self.with_ws(clk) } - /// Connect a second PDM TX data line (line 1, two-line DAC mode, HW v2+). + /// Connects a second PDM TX data line (line 1, two-line DAC mode, HW v2+). #[cfg(all(i2s_supports_pdm_tx, not(i2s_version = "1")))] pub fn with_dout2(self, dout: impl PeripheralOutput<'d>) -> Result { let dout = dout.into(); @@ -1737,6 +2059,9 @@ pub(crate) mod private { pub i2s: AnyI2s<'d>, pub rx_channel: ChannelRx as DmaChannel>::Rx>, pub(crate) guard: PeripheralGuard, + pub(crate) clk_guard: Option, + #[cfg(not(i2s_version = "1"))] + pub(crate) mclk_out_guard: Option, #[cfg(i2s_version = "1")] pub(crate) data_format: DataFormat, } @@ -1751,6 +2076,9 @@ pub(crate) mod private { i2s: self.i2s, rx_channel: self.rx_channel, _guard: PeripheralGuard::new(peripheral), + _clk_guard: self.clk_guard, + #[cfg(not(i2s_version = "1"))] + _mclk_out_guard: self.mclk_out_guard, #[cfg(i2s_version = "1")] data_format: self.data_format, } @@ -1789,12 +2117,12 @@ pub(crate) mod private { self } - /// Connect the PDM clock pin (maps to the WS output signal). + /// Connects the PDM clock pin (maps to the WS output signal). pub fn with_clk(self, clk: impl PeripheralOutput<'d>) -> Self { self.with_ws(clk) } - /// Connect a PDM RX data line (`line` 0..=`pdm_max_rx_lines`-1). + /// Connects a PDM RX data line (`line` 0..=`pdm_max_rx_lines`-1). #[cfg(i2s_supports_pdm_rx)] pub fn with_din_line( self, @@ -1813,6 +2141,10 @@ pub(crate) mod private { } } + /// The divider from the module clock source to MCLK and BCLK. + /// + /// MCLK is `sclk / (mclk_divider + numerator / denominator)`, and BCLK is + /// `MCLK / bclk_divider`. pub struct I2sClockDividers { pub(crate) mclk_divider: u32, pub(crate) bclk_divider: u32, @@ -1821,30 +2153,35 @@ pub(crate) mod private { } impl I2sClockDividers { - pub fn new(sample_rate: Rate, channels: u8, data_bits: u8) -> I2sClockDividers { + pub fn new( + sample_rate: Rate, + channels: u8, + data_bits: u8, + source: I2sClockSource, + ) -> I2sClockDividers { // this loosely corresponds to `i2s_std_calculate_clock` and // `i2s_ll_tx_set_mclk` in esp-idf // If data_bits is a power of two, use 256 as the mclk_multiple // If data_bits is 24, use 192 (24 * 8) as the mclk_multiple let mclk_multiple = if data_bits == 24 { 192 } else { 256 }; - let sclk = crate::soc::i2s_sclk_frequency(); let rate = sample_rate.as_hz(); let bclk = rate * channels as u32 * data_bits as u32; let mclk = rate * mclk_multiple; - I2sClockDividers::from_frequencies(sclk, mclk, mclk / bclk) + I2sClockDividers::from_frequencies(source_frequency(source), mclk, mclk / bclk) } pub(crate) fn from_frequencies(sclk: u32, mclk: u32, bclk_divider: u32) -> Self { - let divider = FractionalDivider::new(sclk, mclk, I2S_LL_MCLK_DIVIDER_MAX as u32); + let divider = FractionalDivider::new(sclk, mclk, super::mclk_max_denominator()); I2sClockDividers { mclk_divider: divider.integer, bclk_divider, - denominator: divider.denominator, + // An integer divider is described as `0 / 1`, not as `0 / 0`. + denominator: divider.denominator.max(1), numerator: divider.numerator, } } diff --git a/esp-hal/src/i2s/mod.rs b/esp-hal/src/i2s/mod.rs index 8e18d3a9cad..9fc26aac640 100644 --- a/esp-hal/src/i2s/mod.rs +++ b/esp-hal/src/i2s/mod.rs @@ -2,9 +2,6 @@ pub mod master; -#[cfg(i2s_clock_configured_by_hp_sys_clkrst)] -mod hp_sys_clkrst; - #[cfg(any(i2s_supports_pdm_tx, i2s_supports_pdm_rx))] pub mod pdm; diff --git a/esp-hal/src/i2s/parallel.rs b/esp-hal/src/i2s/parallel.rs index 3962b313890..5e392ce54a9 100644 --- a/esp-hal/src/i2s/parallel.rs +++ b/esp-hal/src/i2s/parallel.rs @@ -2,31 +2,31 @@ //! # Parallel Interface (via I2S) //! //! ## Overview -//! The I2S parallel interface allows for high-speed data transfer between the -//! ESP32 and external devices. It is commonly used to external devices such as -//! LED matrix, LCD display, and Printer. Only TX is implemented. Each -//! unit can have up to 8 or 16 data signals (depending on your target hardware) -//! plus 1 clock signal. +//! The I2S parallel interface provides high-speed data transfer between the +//! ESP32 and external devices. It is commonly used with devices such as LED +//! matrices, LCD displays, and printers. Only TX is implemented. Each +//! unit can have up to 8 or 16 data signals (depending on the target hardware) +//! plus one clock signal. //! //! ## Notes //! //! Data output is interleaved: -//! - 8bit: [A, B, C, D] is output as [C, D, A, B] (i.e., swapped as 16bit words) -//! - 16bit: [A, B, C, D] is output as [B, A, D, C] (i.e., 16bit words are swapped) +//! - 8-bit: [A, B, C, D] is output as [C, D, A, B] (i.e., swapped as 16-bit words) +//! - 16-bit: [A, B, C, D] is output as [B, A, D, C] (i.e., 16-bit words are swapped) #![cfg_attr(esp32, doc = "")] #![cfg_attr( esp32, - doc = "I2S0 does not support true 8bit parallel output, so if you want to do 8bit" + doc = "I2S0 does not support true 8-bit parallel output, so if you want to do 8-bit" )] #![cfg_attr( esp32, - doc = "you should use I2S1. If you have to use I2S0, it will only output the even" + doc = "you should use I2S1. If you have to use I2S0, it only outputs the even" )] -#![cfg_attr(esp32, doc = "bytes! so [A, B, C, D] will be output as [A, C]!!!!")] +#![cfg_attr(esp32, doc = "bytes! so [A, B, C, D] is output as [A, C]!")] #![cfg_attr(esp32, doc = "")] //! ## Configuration //! -//! The driver uses DMA (Direct Memory Access) for efficient data transfer and +//! The driver uses DMA for efficient data transfer and //! supports various configurations, such as different data formats, standards //! (e.g., Philips) and pin configurations. It relies on other peripheral //! modules, such as @@ -67,7 +67,7 @@ //! let mut tx_buf = dma_tx_buffer!(BUFFER_SIZE).unwrap(); //! for (i, data) in tx_buf.as_mut_slice().chunks_mut(4).enumerate() { //! let offset = i * 4; -//! // i2s parallel driver expects the buffer to be interleaved +//! // I2S parallel driver expects the buffer to be interleaved //! data[0] = (offset + 2) as u8; //! data[1] = (offset + 3) as u8; //! data[2] = offset as u8; @@ -92,6 +92,8 @@ use core::{ ops::{Deref, DerefMut}, }; +use enumset::{EnumSet, EnumSetType}; + use crate::{ Async, Blocking, @@ -105,6 +107,7 @@ use crate::{ interconnect::{self, PeripheralOutput}, }, i2s::AnyI2s, + interrupt::InterruptHandler, pac::i2s0::RegisterBlock, peripherals::{I2S0, I2S1}, system::PeripheralGuard, @@ -119,6 +122,7 @@ pub trait TxPins<'d> { /// Represents a group of 16 output pins configured for 16-bit parallel data /// transmission. +#[instability::unstable] pub struct TxSixteenBits<'d> { pins: [interconnect::OutputSignal<'d>; 16], } @@ -184,13 +188,14 @@ impl<'d> TxPins<'d> for TxSixteenBits<'d> { /// Represents a group of 8 output pins configured for 8-bit parallel data /// transmission. +#[instability::unstable] pub struct TxEightBits<'d> { pins: [interconnect::OutputSignal<'d>; 8], } impl<'d> TxEightBits<'d> { #[expect(clippy::too_many_arguments)] - /// Creates a new `TxSEightBits` instance with the provided output pins. + /// Creates a new [`TxEightBits`] instance with the provided output pins. pub fn new( pin_0: impl PeripheralOutput<'d>, pin_1: impl PeripheralOutput<'d>, @@ -231,7 +236,84 @@ impl<'d> TxPins<'d> for TxEightBits<'d> { } } -/// I2S Parallel Interface +/// Interrupts from the I2S parallel peripheral. +#[derive(Debug, EnumSetType)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[non_exhaustive] +#[instability::unstable] +pub enum I2sParallelInterrupt { + /// The DMA finishes the out descriptor chain (OUT_DONE). + Done, + + /// The DMA uses a descriptor with the suc_eof flag set (OUT_EOF). + /// + /// The peripheral sets the OUT_EOF flag for every descriptor with suc_eof + /// set. This interrupt also works on a circular DMA chain. On a circular + /// chain, the transfer does not end. The peripheral does not set + /// OUT_TOTAL_EOF on a circular chain. + Eof, + + /// The DMA gets a descriptor with an error (OUT_DSCR_ERR). + DescriptorError, + + /// The DMA sends all the data of the transfer (OUT_TOTAL_EOF). + /// + /// On a circular DMA chain, the transfer does not end. The peripheral does + /// not set OUT_TOTAL_EOF on a circular chain. Use [`Self::Eof`] with a + /// circular chain. + TotalEof, +} + +fn internal_listen(regs: &RegisterBlock, interrupts: EnumSet, enable: bool) { + regs.int_ena().modify(|_, w| { + for interrupt in interrupts { + match interrupt { + I2sParallelInterrupt::Done => w.out_done().bit(enable), + I2sParallelInterrupt::Eof => w.out_eof().bit(enable), + I2sParallelInterrupt::DescriptorError => w.out_dscr_err().bit(enable), + I2sParallelInterrupt::TotalEof => w.out_total_eof().bit(enable), + }; + } + w + }); +} + +fn internal_interrupts(regs: &RegisterBlock) -> EnumSet { + let mut result = EnumSet::new(); + let ints = regs.int_st().read(); + + if ints.out_done().bit() { + result.insert(I2sParallelInterrupt::Done); + } + if ints.out_eof().bit() { + result.insert(I2sParallelInterrupt::Eof); + } + if ints.out_dscr_err().bit() { + result.insert(I2sParallelInterrupt::DescriptorError); + } + if ints.out_total_eof().bit() { + result.insert(I2sParallelInterrupt::TotalEof); + } + + result +} + +fn internal_clear_interrupts(regs: &RegisterBlock, interrupts: EnumSet) { + regs.int_clr().write(|w| { + for interrupt in interrupts { + match interrupt { + I2sParallelInterrupt::Done => w.out_done().clear_bit_by_one(), + I2sParallelInterrupt::Eof => w.out_eof().clear_bit_by_one(), + I2sParallelInterrupt::DescriptorError => w.out_dscr_err().clear_bit_by_one(), + I2sParallelInterrupt::TotalEof => w.out_total_eof().clear_bit_by_one(), + }; + } + w + }); +} + +/// I2S parallel interface +#[instability::unstable] pub struct I2sParallel<'d, Dm> where Dm: DriverMode, @@ -239,6 +321,7 @@ where instance: AnyI2s<'d>, tx_channel: ChannelTx>, _guard: PeripheralGuard, + _clk_guard: crate::i2s::master::I2sDirClkGuard, } impl<'d> I2sParallel<'d, Blocking> { @@ -266,30 +349,77 @@ impl<'d> I2sParallel<'d, Blocking> { i2s.ws_signal().connect_to(&clock_pin); pins.configure(&i2s); + let clk_guard = crate::i2s::master::I2sDirClkGuard::request_tx(i2s.clock_instance()); Self { instance: i2s, tx_channel: channel, _guard: guard, + _clk_guard: clk_guard, } } - /// Converts the I2S instance into async mode. + /// Converts the I2S parallel instance into [`Async`] mode. pub fn into_async(self) -> I2sParallel<'d, Async> { I2sParallel { instance: self.instance, tx_channel: self.tx_channel.into_async(), _guard: self._guard, + _clk_guard: self._clk_guard, } } + + /// Sets the interrupt handler for the I2S parallel peripheral. + /// + /// The new handler removes the old handler. This method does not turn on + /// the interrupt sources. Use [`Self::listen`] to turn on interrupt + /// sources. + #[instability::unstable] + pub fn set_interrupt_handler(&mut self, handler: InterruptHandler) { + self.instance.set_interrupt_handler(handler); + } + + /// Turns on the given interrupt sources. + #[instability::unstable] + pub fn listen(&mut self, interrupts: impl Into>) { + internal_listen(self.instance.regs(), interrupts.into(), true); + } + + /// Turns off the given interrupt sources. + #[instability::unstable] + pub fn unlisten(&mut self, interrupts: impl Into>) { + internal_listen(self.instance.regs(), interrupts.into(), false); + } + + /// Returns the interrupt sources that are set. + #[instability::unstable] + pub fn interrupts(&mut self) -> EnumSet { + internal_interrupts(self.instance.regs()) + } + + /// Clears the interrupt flags of the given interrupt sources. + #[instability::unstable] + pub fn clear_interrupts(&mut self, interrupts: impl Into>) { + internal_clear_interrupts(self.instance.regs(), interrupts.into()); + } +} + +impl crate::private::Sealed for I2sParallel<'_, Blocking> {} + +#[instability::unstable] +impl crate::interrupt::InterruptConfigurable for I2sParallel<'_, Blocking> { + fn set_interrupt_handler(&mut self, handler: crate::interrupt::InterruptHandler) { + I2sParallel::set_interrupt_handler(self, handler); + } } impl<'d> I2sParallel<'d, Async> { - /// Converts the I2S instance into async mode. + /// Converts the I2S parallel instance into [`Blocking`] mode. pub fn into_blocking(self) -> I2sParallel<'d, Blocking> { I2sParallel { instance: self.instance, tx_channel: self.tx_channel.into_blocking(), _guard: self._guard, + _clk_guard: self._clk_guard, } } } @@ -298,7 +428,15 @@ impl<'d, Dm> I2sParallel<'d, Dm> where Dm: DriverMode, { - /// Write data to the I2S peripheral + /// Starts a DMA transfer that writes the buffer to the I2S parallel + /// interface and returns an [`I2sParallelTransfer`] that can be used to + /// wait for the transfer to complete. + /// + /// # Errors + /// + /// Returns a [`DmaError`] when the buffer cannot be prepared for the + /// transfer or the transfer cannot be started. On error, the driver and + /// the buffer are returned together with the error. pub fn send( mut self, mut data: BUF, @@ -321,8 +459,9 @@ where } } -/// Represents an ongoing (or potentially finished) transfer using the i2s -/// parallel interface +/// Represents an ongoing (or potentially finished) transfer using the I2S +/// parallel interface. +#[instability::unstable] pub struct I2sParallelTransfer<'d, BUF, Dm> where BUF: DmaTxBuffer, @@ -337,12 +476,13 @@ where BUF: DmaTxBuffer, Dm: DriverMode, { - /// Returns true when [Self::wait] will not block. + /// Returns whether the transfer is complete. pub fn is_done(&self) -> bool { self.i2s.instance.is_tx_done() } - /// Wait for the transfer to finish + /// Waits for the transfer to finish and returns the driver and the + /// buffer. pub fn wait(mut self) -> (I2sParallel<'d, Dm>, BUF::Final) { self.i2s.instance.tx_wait_done(); let i2s = unsafe { ManuallyDrop::take(&mut self.i2s) }; @@ -357,11 +497,61 @@ where } } +/// Interrupt management for an ongoing transfer. +/// +/// The driver itself has been consumed by [`I2sParallel::send`], so these +/// methods take `&self` and allow an interrupt handler to manage the +/// interrupt sources through the transfer object. +#[instability::unstable] +impl<'d, BUF> I2sParallelTransfer<'d, BUF, Blocking> +where + BUF: DmaTxBuffer, +{ + /// Sets the interrupt handler for the I2S parallel peripheral. + /// + /// The new handler removes the old handler. This method does not turn on + /// the interrupt sources. Use [`Self::listen`] to turn on interrupt + /// sources. + pub fn set_interrupt_handler(&mut self, handler: InterruptHandler) { + self.i2s.instance.set_interrupt_handler(handler); + } + + /// Turns on the given interrupt sources. + pub fn listen(&self, interrupts: impl Into>) { + internal_listen(self.i2s.instance.regs(), interrupts.into(), true); + } + + /// Turns off the given interrupt sources. + pub fn unlisten(&self, interrupts: impl Into>) { + internal_listen(self.i2s.instance.regs(), interrupts.into(), false); + } + + /// Clears the interrupt flags of the given interrupt sources. + pub fn clear_interrupts(&self, interrupts: impl Into>) { + internal_clear_interrupts(self.i2s.instance.regs(), interrupts.into()); + } + + /// Returns the interrupt sources that are set. + pub fn interrupts(&self) -> EnumSet { + internal_interrupts(self.i2s.instance.regs()) + } +} + impl I2sParallelTransfer<'_, BUF, Async> where BUF: DmaTxBuffer, { - /// Wait for the transfer to finish + /// Waits for [`Self::is_done`] to return true. + /// + /// # Errors + /// + /// Returns a [`DmaError`] when the transfer ends with a descriptor error. + /// + /// # Cancellation Safety + /// + /// This method is cancellation safe. Dropping the future does not stop + /// the transfer, and the method can be called again to wait for the + /// transfer to complete. pub async fn wait_for_done(&mut self) -> Result<(), DmaError> { DmaTxFuture::new(&mut self.i2s.tx_channel).await } @@ -416,33 +606,38 @@ pub struct I2sClockDividers { pub numerator: u32, } -fn calculate_clock(sample_rate: Rate, data_bits: u8) -> I2sClockDividers { +fn calculate_clock( + sample_rate: Rate, + data_bits: u8, + clock_source: crate::i2s::master::I2sClockSource, +) -> I2sClockDividers { // this loosely corresponds to `i2s_std_calculate_clock` and // `i2s_ll_tx_set_mclk` in esp-idf, adjusted for parallel interface clocking - let sclk = crate::soc::i2s_sclk_frequency(); + let sclk = crate::i2s::master::source_frequency(clock_source); let mclk = sample_rate.as_hz() * 2; let bclk_divider: u32 = if data_bits == 8 { 2 } else { 1 }; - let divider = FractionalDivider::new( - sclk, - mclk, - crate::i2s::master::I2S_LL_MCLK_DIVIDER_MAX as u32, - ); + let divider = FractionalDivider::new(sclk, mclk, crate::i2s::master::mclk_max_denominator()); I2sClockDividers { mclk_divider: divider.integer, bclk_divider, - denominator: divider.denominator, + // An integer divider is described as `0 / 1`, not as `0 / 0`. + denominator: divider.denominator.max(1), numerator: divider.numerator, } } + #[doc(hidden)] pub trait PrivateInstance: crate::private::Sealed { fn regs(&self) -> &RegisterBlock; fn peripheral(&self) -> crate::system::Peripheral; fn ws_signal(&self) -> OutputSignal; fn data_out_signal(&self, i: usize, bits: u8) -> OutputSignal; + fn clock_instance(&self) -> crate::clock::ll::I2sInstance; + + fn set_interrupt_handler(&self, handler: crate::interrupt::InterruptHandler); fn rx_reset(&self) { self.regs().conf().toggle(|w, bit| w.rx_reset().bit(bit)); @@ -520,25 +715,19 @@ pub trait PrivateInstance: crate::private::Sealed { }); } - fn set_clock(&self, clock_settings: I2sClockDividers) { - self.regs().clkm_conf().modify(|r, w| unsafe { - w.bits(r.bits() | (property!("i2s.default_clock_source") << 21)) - // select PLL_160M - }); - - #[cfg(esp32)] - self.regs() - .clkm_conf() - .modify(|_, w| w.clka_ena().clear_bit()); - - self.regs().clkm_conf().modify(|_, w| unsafe { - w.clk_en().set_bit(); - w.clkm_div_num().bits(clock_settings.mclk_divider as u8) - }); - - self.regs().clkm_conf().modify(|_, w| unsafe { - w.clkm_div_a().bits(clock_settings.denominator as u8); - w.clkm_div_b().bits(clock_settings.numerator as u8) + fn set_clock( + &self, + clock_settings: I2sClockDividers, + clock_source: crate::i2s::master::I2sClockSource, + ) { + crate::clock::ll::ClockTree::with(|clocks| { + let config = crate::clock::ll::I2sMclkConfig::new( + clock_source, + clock_settings.mclk_divider, + clock_settings.denominator, + clock_settings.numerator, + ); + self.clock_instance().configure_mclk(clocks, config); }); self.regs().sample_rate_conf().modify(|_, w| unsafe { @@ -548,7 +737,8 @@ pub trait PrivateInstance: crate::private::Sealed { } fn setup(&self, frequency: Rate, bits: u8) { - self.set_clock(calculate_clock(frequency, bits)); + let clock_source = crate::i2s::master::I2sClockSource::default(); + self.set_clock(calculate_clock(frequency, bits, clock_source), clock_source); // Initialize I2S dev self.rx_reset(); @@ -655,6 +845,15 @@ impl PrivateInstance for I2S0<'_> { other => panic!("Invalid I2S0 Dout pin {}", other), } } + + fn set_interrupt_handler(&self, handler: crate::interrupt::InterruptHandler) { + self.disable_peri_interrupt_on_all_cores(); + self.bind_peri_interrupt(handler); + } + + fn clock_instance(&self) -> crate::clock::ll::I2sInstance { + crate::clock::ll::I2sInstance::I2s0 + } } impl PrivateInstance for I2S1<'_> { @@ -707,6 +906,15 @@ impl PrivateInstance for I2S1<'_> { other => panic!("Invalid I2S1 Dout pin {}", other), } } + + fn set_interrupt_handler(&self, handler: crate::interrupt::InterruptHandler) { + self.disable_peri_interrupt_on_all_cores(); + self.bind_peri_interrupt(handler); + } + + fn clock_instance(&self) -> crate::clock::ll::I2sInstance { + crate::clock::ll::I2sInstance::I2s1 + } } impl PrivateInstance for AnyI2s<'_> { @@ -719,6 +927,8 @@ impl PrivateInstance for AnyI2s<'_> { fn peripheral(&self) -> crate::system::Peripheral; fn ws_signal(&self) -> OutputSignal; fn data_out_signal(&self, i: usize, bits: u8) -> OutputSignal ; + fn set_interrupt_handler(&self, handler: crate::interrupt::InterruptHandler); + fn clock_instance(&self) -> crate::clock::ll::I2sInstance; } } } @@ -768,7 +978,11 @@ for_each_i2s! { } impl<'d> I2sParallel<'d, crate::Blocking> { - /// Create a new I2S Parallel Interface + /// Creates a new [`I2sParallel`] instance. + /// + /// # Panics + /// + /// Panics if the DMA channel is not compatible with the I2S instance. pub fn new( i2s: I, channel: impl I2sParallelDmaChannel<'d, I>, diff --git a/esp-hal/src/i2s/pdm/clock.rs b/esp-hal/src/i2s/pdm/clock.rs index 8b1601a8e4b..3eaf19ac0ce 100644 --- a/esp-hal/src/i2s/pdm/clock.rs +++ b/esp-hal/src/i2s/pdm/clock.rs @@ -1,7 +1,10 @@ //! PDM clock calculations. use super::{PdmDownsampleRate, PdmError, PdmRxClockConfig, PdmTxClockConfig}; -use crate::{i2s::master::private::I2sClockDividers, soc, time::Rate}; +use crate::{ + i2s::master::{private::I2sClockDividers, source_frequency}, + time::Rate, +}; pub(crate) const PDM_BCK_FACTOR: u32 = 64; pub(crate) const PDM_TX_BCLK_DIV_MIN: u32 = 8; @@ -50,7 +53,7 @@ pub(crate) fn calculate_tx_clock( }; let mclk = bclk * bclk_div; - let sclk = soc::i2s_sclk_frequency(); + let sclk = source_frequency(clk.clock_source); let mut dividers = calculate_mclk_dividers(sclk, mclk)?; dividers.bclk_divider = bclk_div; @@ -81,7 +84,7 @@ pub(crate) fn calculate_rx_clock( let bclk_div = clk.bclk_div.max(PDM_RX_BCLK_DIV_MIN).max(bclk_limit); let mclk = bclk * bclk_div; - let sclk = soc::i2s_sclk_frequency(); + let sclk = source_frequency(clk.clock_source); let mut dividers = calculate_mclk_dividers(sclk, mclk)?; dividers.bclk_divider = bclk_div; @@ -105,6 +108,7 @@ impl PdmTxClockConfig { up_sample_fp: 960, up_sample_fs: 480, bclk_div: PDM_TX_BCLK_DIV_MIN, + clock_source: Default::default(), } } @@ -115,6 +119,7 @@ impl PdmTxClockConfig { up_sample_fp: 960, up_sample_fs: sample_rate.as_hz() / 100, bclk_div: 13, + clock_source: Default::default(), } } } @@ -126,6 +131,7 @@ impl PdmRxClockConfig { sample_rate, downsample_rate: PdmDownsampleRate::Dsr8s, bclk_div: PDM_RX_BCLK_DIV_MIN, + clock_source: Default::default(), } } } diff --git a/esp-hal/src/i2s/pdm/mod.rs b/esp-hal/src/i2s/pdm/mod.rs index 48f4f42ff4e..aefc63e3e66 100644 --- a/esp-hal/src/i2s/pdm/mod.rs +++ b/esp-hal/src/i2s/pdm/mod.rs @@ -142,7 +142,7 @@ impl PdmSlotMask { /// Line 3, right slot. pub const LINE3_RIGHT: Self = Self(1 << 6); - /// Create a mask from raw slot bits. + /// Creates a new mask from raw slot bits. pub const fn from_bits(bits: u16) -> Self { Self(bits) } @@ -176,7 +176,7 @@ pub enum PdmDownsampleRate { #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum PdmSigScaling { - /// Divide input by 2. + /// Divides input by 2. Div2, /// Multiply input by 1. #[default] @@ -223,6 +223,8 @@ pub struct PdmTxClockConfig { pub up_sample_fs: u32, /// Bit clock divider. pub bclk_div: u32, + /// Source clock for the I2S module clock. + pub clock_source: crate::i2s::master::I2sClockSource, } /// PDM TX slot / filter configuration. @@ -247,7 +249,7 @@ pub struct PdmTxSlotConfig { #[cfg(not(i2s_version = "1"))] /// Output line routing mode. pub line_mode: PdmTxLineMode, - /// Enable the TX high-pass filter. + /// Enables the TX high-pass filter. pub hp_en: bool, /// High-pass filter cut-off frequency in Hz. pub hp_cut_off_freq_hz: f32, @@ -322,6 +324,8 @@ pub struct PdmRxClockConfig { /// Bit clock divider. pub bclk_div: u32, + /// Source clock for the I2S module clock. + pub clock_source: crate::i2s::master::I2sClockSource, } /// PDM RX slot configuration. @@ -339,7 +343,7 @@ pub struct PdmRxSlotConfig { pub data_format: PdmDataFormat, #[cfg(i2s_supports_pdm_rx_hp_filter)] - /// Enable the RX high-pass filter. + /// Enables the RX high-pass filter. pub hp_en: bool, #[cfg(i2s_supports_pdm_rx_hp_filter)] @@ -414,7 +418,7 @@ impl PdmTxConfig { } } - /// Validate TX configuration against hardware capabilities. + /// Validates TX configuration against hardware capabilities. pub fn validate(&self, info: &Info) -> Result<(), PdmError> { if self.slot.data_format == PdmDataFormat::Pcm && !info.pcm2pdm { return Err(PdmError::PcmFormatUnsupported); @@ -468,7 +472,7 @@ impl PdmRxConfig { } } - /// Validate RX configuration against hardware capabilities. + /// Validates RX configuration against hardware capabilities. pub fn validate(&self, info: &Info) -> Result<(), PdmError> { if self.slot.data_format == PdmDataFormat::Pcm && !info.pdm2pcm { return Err(PdmError::PcmFormatUnsupported); @@ -487,7 +491,7 @@ fn default_rx_slot(mode: PdmSlotMode) -> PdmRxSlotConfig { } } -/// PDM mode configuration (simplex TX and/or RX). +/// PDM mode configuration (simplex TX, RX, or both). #[derive(Debug, Clone, Copy, PartialEq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub struct PdmConfig { @@ -495,6 +499,9 @@ pub struct PdmConfig { pub tx: Option, /// Optional RX unit configuration. pub rx: Option, + /// Selects which module clock is routed to the MCLK pad. + #[cfg(not(i2s_version = "1"))] + pub mclk_out: crate::i2s::master::MclkOut, } impl PdmConfig { @@ -504,6 +511,8 @@ impl PdmConfig { Self { tx: Some(tx), rx: None, + #[cfg(not(i2s_version = "1"))] + mclk_out: crate::i2s::master::MclkOut::Tx, } } @@ -513,10 +522,12 @@ impl PdmConfig { Self { tx: None, rx: Some(rx), + #[cfg(not(i2s_version = "1"))] + mclk_out: crate::i2s::master::MclkOut::Rx, } } - /// Validate that exactly one direction is configured and that the settings + /// Validates that exactly one direction is configured and that the settings /// are valid for the given I2S instance. pub fn validate(&self, info: &Info) -> Result<(), PdmError> { if self.tx.is_none() && self.rx.is_none() { diff --git a/esp-hal/src/i2s/pdm/regs_v1.rs b/esp-hal/src/i2s/pdm/regs_v1.rs index b3381a9753a..323167f7ae4 100644 --- a/esp-hal/src/i2s/pdm/regs_v1.rs +++ b/esp-hal/src/i2s/pdm/regs_v1.rs @@ -32,7 +32,8 @@ fn configure_tx(i2s: &Info, config: &super::PdmTxConfig) -> Result<(), PdmError> let pcm = config.slot.data_format == PdmDataFormat::Pcm; let clock = clock::calculate_tx_clock(&config.clock, pcm)?; - i2s.set_clock(clock.dividers); + i2s.configure_mclk(config.clock.clock_source, &clock.dividers); + i2s.set_bclk(clock.dividers.bclk_divider); let is_mono = config.slot.slot_mode == PdmSlotMode::Mono; let regs = i2s.regs(); @@ -116,7 +117,8 @@ fn configure_rx(i2s: &Info, config: &super::PdmRxConfig) -> Result<(), PdmError> let slot_mask = config.slot.slot_mask.bits(); let clock = clock::calculate_rx_clock(&config.clock, pcm, slot_mask)?; - i2s.set_clock(clock.dividers); + i2s.configure_mclk(config.clock.clock_source, &clock.dividers); + i2s.set_bclk(clock.dividers.bclk_divider); let is_mono = config.slot.slot_mode == PdmSlotMode::Mono; let regs = i2s.regs(); diff --git a/esp-hal/src/i2s/pdm/regs_v2.rs b/esp-hal/src/i2s/pdm/regs_v2.rs index f8edd38f082..175889d04fe 100644 --- a/esp-hal/src/i2s/pdm/regs_v2.rs +++ b/esp-hal/src/i2s/pdm/regs_v2.rs @@ -14,6 +14,8 @@ use super::{ use crate::i2s::master::Info; pub(crate) fn configure_pdm(i2s: &Info, config: &PdmConfig) -> Result<(), PdmError> { + i2s.configure_mclk_pad(config.mclk_out); + if let Some(tx) = &config.tx { configure_tx(i2s, tx)?; } @@ -96,23 +98,7 @@ fn configure_tx(i2s: &Info, config: &super::PdmTxConfig) -> Result<(), PdmError> }); } - cfg_select! { - i2s_clock_configured_by_pcr => { - crate::peripherals::PCR::regs() - .i2s_rx_clkm_conf() - .modify(|_, w| w.i2s_mclk_sel().clear_bit()); - } - i2s_clock_configured_by_hp_sys_clkrst => { - // MCLK mux is configured in `hp_sys_clkrst::set_tx_clock` via `Info::peripheral`. - } - _ => { - i2s.regs() - .rx_clkm_conf() - .modify(|_, w| w.mclk_sel().clear_bit()); - } - } - - set_pdm_tx_clock(i2s, &clock); + set_pdm_tx_clock(i2s, config.clock.clock_source, &clock); i2s.regs().tx_conf().modify(|_, w| { w.tx_pdm_en().set_bit(); @@ -125,7 +111,7 @@ fn configure_tx(i2s: &Info, config: &super::PdmTxConfig) -> Result<(), PdmError> Ok(()) } -/// Expand a stereo slot mask to include both slots on every active PDM line. +/// Expands a stereo slot mask to include both slots on every active PDM line. fn stereo_pdm_rx_slot_mask(slot_mask: u16) -> u16 { let mut stereo_mask = 0u16; for i in 0..8 { @@ -189,25 +175,10 @@ fn configure_rx(i2s: &Info, config: &super::PdmRxConfig) -> Result<(), PdmError> .rx_tdm_ctrl() .modify(|r, w| unsafe { w.bits((r.bits() & 0xFFFF0000) | u32::from(slot_mask)) }); - cfg_select! { - i2s_clock_configured_by_pcr => { - crate::peripherals::PCR::regs() - .i2s_rx_clkm_conf() - .modify(|_, w| w.i2s_mclk_sel().set_bit()); - } - i2s_clock_configured_by_hp_sys_clkrst => { - // MCLK mux is configured in `hp_sys_clkrst::set_rx_clock` via `Info::peripheral`. - } - _ => { - i2s.regs() - .rx_clkm_conf() - .modify(|_, w| w.mclk_sel().set_bit()); - } - } + i2s.configure_rx_mclk(config.clock.clock_source, &clock.dividers); + i2s.set_rx_bclk(clock.dividers.bclk_divider); - i2s.set_rx_clock(clock.dividers); - - #[cfg(all(i2s_supports_pdm2pcm, esp32p4))] + #[cfg(all(i2s_supports_pdm2pcm, i2s_supports_pdm_rx_hp_filter))] { let dsr16 = config.clock.downsample_rate == super::PdmDownsampleRate::Dsr16s; let freq_x10 = (config.slot.hp_cut_off_freq_hz * 10.0) as u32; @@ -228,7 +199,7 @@ fn configure_rx(i2s: &Info, config: &super::PdmRxConfig) -> Result<(), PdmError> i2s.regs().rx_conf().modify(|_, w| { w.rx_pdm_en().set_bit(); w.rx_tdm_en().clear_bit(); - #[cfg(all(i2s_supports_pdm2pcm, not(esp32p4)))] + #[cfg(all(i2s_supports_pdm2pcm, not(i2s_supports_pdm_rx_hp_filter)))] { w.rx_pdm2pcm_en().bit(pcm); w.rx_pdm_sinc_dsr_16_en() @@ -240,41 +211,11 @@ fn configure_rx(i2s: &Info, config: &super::PdmRxConfig) -> Result<(), PdmError> Ok(()) } -fn set_pdm_tx_clock(i2s: &Info, clock: &clock::PdmTxClockResult) { - set_pdm_tx_clock_common(i2s, clock); - #[cfg(not(any(i2s_clock_configured_by_pcr, i2s_clock_configured_by_hp_sys_clkrst)))] - apply_tx_pdm_clock_workaround(i2s, clock.dividers.mclk_divider); -} - -fn set_pdm_tx_clock_common(i2s: &Info, clock: &clock::PdmTxClockResult) { - use crate::i2s::master::private::I2sClockDividers; - let dividers = I2sClockDividers { - mclk_divider: clock.dividers.mclk_divider, - bclk_divider: clock.dividers.bclk_divider, - denominator: clock.dividers.denominator, - numerator: clock.dividers.numerator, - }; - i2s.set_tx_clock(dividers); -} - -#[cfg(not(any(i2s_clock_configured_by_pcr, i2s_clock_configured_by_hp_sys_clkrst)))] -fn apply_tx_pdm_clock_workaround(i2s: &Info, mclk_div: u32) { - i2s.regs() - .tx_clkm_conf() - .modify(|_, w| unsafe { w.tx_clkm_div_num().bits(2) }); - i2s.regs().tx_clkm_div_conf().modify(|_, w| unsafe { - w.tx_clkm_div_yn1().clear_bit(); - w.tx_clkm_div_y().bits(1); - w.tx_clkm_div_z().bits(0); - w.tx_clkm_div_x().bits(0) - }); - i2s.regs().tx_clkm_div_conf().modify(|_, w| unsafe { - w.tx_clkm_div_yn1().clear_bit(); - w.tx_clkm_div_y().bits(1); - w.tx_clkm_div_z().bits(0); - w.tx_clkm_div_x().bits(1) - }); - i2s.regs() - .tx_clkm_conf() - .modify(|_, w| unsafe { w.tx_clkm_div_num().bits(mclk_div as u8) }); +fn set_pdm_tx_clock( + i2s: &Info, + source: crate::i2s::master::I2sClockSource, + clock: &clock::PdmTxClockResult, +) { + i2s.configure_tx_mclk(source, &clock.dividers); + i2s.set_tx_bclk(clock.dividers.bclk_divider); } diff --git a/esp-hal/src/interrupt/__rtos_implementation.rs b/esp-hal/src/interrupt/__rtos_implementation.rs new file mode 100644 index 00000000000..0bfd5f0e57f --- /dev/null +++ b/esp-hal/src/interrupt/__rtos_implementation.rs @@ -0,0 +1,252 @@ +//! Private implementation details of the RTOS that owns context switching. +//! +//! A context switch runs at [`Priority::min`][super::Priority::min]. It is the last action of a +//! CPU before the CPU returns to the interrupted context. An RTOS registers its context-switch +//! handler here, then asks a CPU to run the handler. +//! +//! These functions are not part of the application API. +#![cfg_attr( + context_switch_source = "software0", + doc = "\nA CPU switches its own tasks through the `Software0` CPU-internal interrupt. The HAL + defines the handler of that interrupt." +)] +#![cfg_attr( + context_switch_source = "clint", + doc = "\nA CPU switches its own tasks through the machine software interrupt of the CLINT." +)] +#![cfg_attr( + context_switch_source = "from_cpu", + doc = "\nA CPU switches its own tasks through the `FROM_CPU_INTR0` interrupt. The HAL reserves + that interrupt." +)] +#![cfg_attr( + multi_core, + doc = "\nA CPU switches the tasks of the other CPU through [`Ipc`][super::ipc::Ipc]." +)] + +use crate::system::Cpu; +#[cfg(xtensa)] +use crate::trapframe::TrapFrame; + +/// The signature of a context-switch handler. +/// +/// On RISC-V, the handler runs as a direct-bound interrupt handler, and returns from the +/// interrupt itself. On Xtensa, the vectored dispatcher calls the handler with the trap frame, +/// and the interrupt returns to the context in that trap frame. +pub type ContextSwitchHandler = cfg_select! { + riscv => { + unsafe extern "C" fn() + } + xtensa => { + extern "C" fn(&mut TrapFrame) + } +}; + +/// Registers the context-switch handler of `core`. +/// +/// A CPU accepts one context-switch handler. [`request_context_switch`] therefore takes no +/// handler of its own, and never waits. +/// +/// # Panics +/// +/// Panics if `core` already has a context-switch handler. +#[cfg_attr( + not(context_switch_source = "ipc"), + doc = "\nIn debug builds, panics if `core` is not the current CPU. A CPU-local interrupt + carries the context switch, and only that CPU can enable the interrupt.\n" +)] +/// # Safety +/// +/// On RISC-V, the interrupt jumps to `handler` with the interrupted `t0` in `mscratch`. +/// `handler` must restore `t0` from that CSR, save and restore every other register it +/// modifies, and return with `mret`. +/// +/// On Xtensa, the interrupt returns to the context in the trap frame. `handler` must leave a +/// context that the CPU can run. +pub unsafe fn set_context_switch_handler(core: Cpu, handler: ContextSwitchHandler) { + cfg_select! { + context_switch_source = "ipc" => {} + _ => { + debug_assert_eq!(core, Cpu::current(), "A CPU installs its own handler"); + unsafe { local::install(handler) }; + } + } + + // A CPU-local interrupt cannot reach the other CPU. Dual-core chips that keep + // that interrupt for a local switch still register the same handler with IPC. + #[cfg(multi_core)] + unsafe { + super::ipc::set_context_switch_handler(core, handler); + } +} + +/// Asks `core` to run its context-switch handler. +/// +/// The handler runs at [`Priority::min`][super::Priority::min]. The call does not wait. +/// +/// # Panics +/// +/// In debug builds, panics if `core` has no context-switch handler. +#[cfg_attr( + multi_core, + doc = "\nIn debug builds, panics if `core` is the APP CPU and that CPU is not running." +)] +#[inline] +pub fn request_context_switch(core: Cpu) { + cfg_select! { + context_switch_source = "ipc" => { + super::ipc::request_context_switch(core); + } + multi_core => { + if core == Cpu::current() { + local::trigger(); + } else { + super::ipc::request_context_switch(core); + } + } + _ => { + debug_assert_eq!(core, Cpu::current(), "A CPU switches its own tasks"); + local::trigger(); + } + } +} + +/// The `Software0` context-switch path. +#[cfg(context_switch_source = "software0")] +mod local { + use portable_atomic::{AtomicPtr, Ordering}; + + use super::*; + use crate::ram; + + /// `Software0` is CPU interrupt 7, which runs at the minimum priority. + const SW_INTERRUPT: u32 = 1 << 7; + + static HANDLER: AtomicPtr<()> = AtomicPtr::new(core::ptr::null_mut()); + + pub(super) unsafe fn install(handler: ContextSwitchHandler) { + HANDLER.store(handler as *mut (), Ordering::Release); + unsafe { xtensa_lx::interrupt::enable_mask(SW_INTERRUPT) }; + } + + #[inline] + pub(super) fn trigger() { + unsafe { xtensa_lx::interrupt::set(SW_INTERRUPT) }; + } + + /// The vectored dispatcher clears the request before it calls this handler. + #[ram] + #[unsafe(export_name = "Software0")] + extern "C" fn context_switch(context: &mut TrapFrame) { + let handler = HANDLER.load(Ordering::Acquire); + debug_assert!(!handler.is_null(), "The CPU has no context switch handler"); + + let handler = unsafe { core::mem::transmute::<*mut (), ContextSwitchHandler>(handler) }; + handler(context); + } +} + +/// The RISC-V context-switch path. +/// +/// A CPU takes the context switch in a handler that this module binds directly to the +/// interrupt. The handler borrows `t0` only, and keeps the interrupted value in `mscratch`. +/// That CSR is free, because the hardware clears `mstatus.MIE` on trap entry, and nothing here +/// enables interrupts again. +#[cfg(any(context_switch_source = "from_cpu", context_switch_source = "clint"))] +mod local { + use portable_atomic::{AtomicPtr, Ordering}; + + use super::*; + use crate::interrupt; + + cfg_select! { + context_switch_source = "clint" => { + use crate::{interrupt::CpuInterrupt, peripherals::CLINT}; + } + _ => { + use crate::{ + interrupt::software::SoftwareInterrupt, + peripherals::{FROM_CPU_INTR0, Interrupt}, + }; + } + } + + /// The address of the register that clears the request. + static REQUEST: AtomicPtr = AtomicPtr::new(core::ptr::null_mut()); + static HANDLER: AtomicPtr<()> = AtomicPtr::new(core::ptr::null_mut()); + + pub(super) unsafe fn install(handler: ContextSwitchHandler) { + HANDLER.store(handler as *mut (), Ordering::Release); + + cfg_select! { + context_switch_source = "clint" => { + REQUEST.store(CLINT::regs().msip().as_ptr(), Ordering::Release); + + // Both controllers serve the machine software interrupt as interrupt 3. The + // CLIC applies the priority of that line to it, and needs the line enabled. + // The PLIC does not serve the interrupt at all: `mie` enables it, and the run + // level masks it. + interrupt::bind_cpu_interrupt(CpuInterrupt::Interrupt3, stub); + #[cfg(interrupt_controller = "clic")] + interrupt::enable_cpu_interrupt( + CpuInterrupt::Interrupt3, + interrupt::Priority::min(), + ); + } + _ => { + let regs = cfg_select! { + soc_has_intpri => crate::peripherals::INTPRI::regs(), + _ => crate::peripherals::SYSTEM::regs(), + }; + REQUEST.store(regs.cpu_intr_from_cpu(0).as_ptr(), Ordering::Release); + + interrupt::enable_direct_inner( + Interrupt::FROM_CPU_INTR0, + interrupt::Priority::min(), + interrupt::IPC_INTERRUPT, + stub, + ); + } + } + } + + #[inline] + pub(super) fn trigger() { + cfg_select! { + context_switch_source = "clint" => { + CLINT::regs().msip().write(|w| w.msip().set_bit()); + } + _ => { + SoftwareInterrupt::new(unsafe { FROM_CPU_INTR0::steal() }).raise(); + } + } + } + + /// Clears the request, then jumps to the context-switch handler. + #[cfg_attr( + not(interrupt_controller = "clic"), + unsafe(link_section = ".trap.rust") + )] + #[cfg_attr(interrupt_controller = "clic", unsafe(link_section = ".rwtext"))] + #[unsafe(naked)] + unsafe extern "C" fn stub() { + core::arch::naked_asm!( + " + csrw mscratch, t0 + + # Clear the request before the switch, so that a request raised for the next + # switch survives. + la t0, {request} + lw t0, 0(t0) + sw zero, 0(t0) + + # The handler restores t0 from mscratch and returns with mret. + la t0, {handler} + lw t0, 0(t0) + jr t0 + ", + request = sym REQUEST, + handler = sym HANDLER, + ) + } +} diff --git a/esp-hal/src/interrupt/ipc/mod.rs b/esp-hal/src/interrupt/ipc/mod.rs new file mode 100644 index 00000000000..de5f26ae5e9 --- /dev/null +++ b/esp-hal/src/interrupt/ipc/mod.rs @@ -0,0 +1,233 @@ +#![cfg_attr(docsrs, procmacros::doc_replace)] +//! # Inter-Processor Call (IPC) +//! +//! ## Overview +//! +//! [`Ipc`] posts a function to a CPU, then raises that CPU's IPC interrupt. The interrupt +//! handler runs the posted function at [`Priority::min`][super::Priority::min]. +//! +//! The same interrupt also carries a context switch. A CPU asks the other CPU to switch tasks +//! through this interrupt. The context-switch handler of the RTOS that owns scheduling runs +//! after the posted function, and chooses the context that the interrupt returns to. A posted +//! function and a context switch do not wait for each other. A posted function alone does not +//! make a CPU switch tasks. +//! +//! ## Configuration +#![cfg_attr( + xtensa, + doc = " The HAL reserves `FROM_CPU_INTR0` and `FROM_CPU_INTR1` for this path." +)] +#![cfg_attr( + riscv, + doc = " Each CPU takes the call in its machine software interrupt. The path needs no peripheral interrupt." +)] +//! [`crate::init`] installs the handler on the PRO CPU. The start of the APP CPU installs the +//! handler on that CPU. +//! +//! ## Usage +//! +//! [`Ipc::new`] creates a handle from the `IPC` peripheral singleton, and +//! [`Ipc::call_function`] posts a function to a CPU. +//! +//! The posted function runs in an interrupt handler. The handler saves the registers that the +//! calling convention lets the callee clobber, except the floating-point registers. The posted +//! function must not use those registers, and must be callable with the cache disabled. +//! +//! ## Examples +//! +//! ### Run a Function on the PRO CPU +//! +//! ```rust, no_run +//! # {before_snippet} +//! use esp_hal::{interrupt::ipc::Ipc, system::Cpu}; +//! +//! fn on_cpu() { +//! // Runs on the selected CPU at minimum interrupt priority. +//! } +//! +//! let ipc = Ipc::new(peripherals.IPC); +//! ipc.call_function(Cpu::ProCpu, on_cpu); +//! # {after_snippet} +//! ``` + +use portable_atomic::{AtomicPtr, Ordering}; + +use crate::{ + interrupt::__rtos_implementation::ContextSwitchHandler, + peripherals::IPC, + system::Cpu, +}; + +#[cfg_attr(riscv, path = "riscv.rs")] +#[cfg_attr(xtensa, path = "xtensa.rs")] +mod implem; + +pub(crate) use implem::install; +use implem::raise; + +#[cfg(riscv)] +pub(crate) use self::implem::install_app; + +/// The IPC state of one CPU. +/// +/// Every CPU has its own handler, which reads the fields at constant addresses. +#[repr(C)] +struct CoreState { + /// The function that [`Ipc::call_function`] posts, or null if the CPU has none. + callback: AtomicPtr<()>, + + /// The context-switch handler that the CPU runs, or null if the CPU has none pending. + /// + /// [`request_context_switch`] copies `context_switch_handler` here. A posted function alone + /// therefore does not make the CPU switch tasks. + pending_context_switch: AtomicPtr<()>, + + /// The context-switch handler of the CPU, or null if no RTOS registered one. + /// + /// This field is set once, and holds the only handler that the CPU accepts. + context_switch_handler: AtomicPtr<()>, + + /// The address of the register that clears the request of this CPU. + #[cfg(riscv)] + request: AtomicPtr, +} + +impl CoreState { + const fn new() -> Self { + Self { + callback: AtomicPtr::new(core::ptr::null_mut()), + pending_context_switch: AtomicPtr::new(core::ptr::null_mut()), + context_switch_handler: AtomicPtr::new(core::ptr::null_mut()), + #[cfg(riscv)] + request: AtomicPtr::new(core::ptr::null_mut()), + } + } +} + +static STATE: [CoreState; Cpu::COUNT] = [const { CoreState::new() }; Cpu::COUNT]; + +/// Handle that posts a function to a CPU through the IPC interrupt. +/// +/// Copies of this handle share one state table. +#[derive(Clone, Copy, Debug)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[non_exhaustive] +pub struct Ipc; + +impl Ipc { + /// Creates a new [`Ipc`] handle. + /// + /// The constructor does not install an interrupt handler. [`crate::init`] installs the IPC + /// path. + pub const fn new(_ipc: IPC<'_>) -> Self { + Self + } + + /// Runs `handler` on `core`. + /// + /// `handler` runs in an interrupt handler at [`Priority::min`][super::Priority::min]. This + /// call does not wait for `handler` to return, and a context switch does not delay it. + /// + /// The interrupt handler saves the registers that the calling convention lets the callee + /// clobber, except the floating-point registers. `handler` must not use those registers, and + /// must be callable with the cache disabled. + /// + /// A CPU holds one posted function at a time. If `core` already holds one, this call behaves + /// as follows: + /// + /// - If `core` holds `handler`, that function has not run yet, and it runs after this call. The + /// two calls coalesce into one run, and this call returns. A caller that needs a run of its + /// own must wait for the pending run. + /// - If `core` holds a different function, this call waits until `core` takes that function. + /// `core` takes it in a minimum-priority interrupt. That interrupt cannot run in an + /// interrupt-free context, and cannot run on the APP CPU while that CPU is in reset. The wait + /// never ends in those cases. + /// + /// # Panics + /// + /// In debug builds, panics if `core` is the APP CPU and that CPU is not running. + pub fn call_function(self, core: Cpu, handler: fn()) { + let handler = handler as *mut (); + assert_target_runs(core); + + while let Err(pending) = STATE[core as usize].callback.compare_exchange( + core::ptr::null_mut(), + handler, + Ordering::AcqRel, + Ordering::Acquire, + ) { + // The IPC handler takes the callback before it runs it, so a pending copy of `handler` + // has not run yet. It runs after this call, which covers this call, too. + if pending == handler { + break; + } + + core::hint::spin_loop(); + } + + raise(core); + } +} + +/// Registers the context-switch handler of `core`. +/// +/// A CPU accepts one context-switch handler. [`request_context_switch`] therefore takes no +/// handler of its own, and never waits. +/// +/// # Panics +/// +/// Panics if `core` already has a context-switch handler. +/// +/// # Safety +/// +/// See [`__rtos_implementation::set_context_switch_handler`]. +/// +/// [`__rtos_implementation::set_context_switch_handler`]: +/// super::__rtos_implementation::set_context_switch_handler +pub(crate) unsafe fn set_context_switch_handler(core: Cpu, handler: ContextSwitchHandler) { + unwrap!( + STATE[core as usize] + .context_switch_handler + .compare_exchange( + core::ptr::null_mut(), + handler as *mut (), + Ordering::Release, + Ordering::Relaxed, + ), + "A CPU accepts one context switch handler" + ); +} + +/// Asks `core` to run its context-switch handler. +/// +/// The handler runs at [`Priority::min`][super::Priority::min], after the function that +/// [`Ipc::call_function`] posts. The call does not wait, not even for a pending posted function. +/// +/// # Panics +/// +/// In debug builds, panics if `core` has no context-switch handler, or if `core` is the APP CPU +/// and that CPU is not running. +#[inline] +pub(crate) fn request_context_switch(core: Cpu) { + assert_target_runs(core); + + let state = &STATE[core as usize]; + + // A CPU accepts one context switch handler, so this needs no read-modify-write: the store + // is idempotent, and the IPC handler takes the handler before it runs it, which makes the + // handler run at least once after this store. + let handler = state.context_switch_handler.load(Ordering::Relaxed); + debug_assert!(!handler.is_null(), "The CPU has no context switch handler"); + state + .pending_context_switch + .store(handler, Ordering::Release); + + raise(core); +} + +fn assert_target_runs(core: Cpu) { + debug_assert!( + core != Cpu::AppCpu || crate::soc::cpu_control::is_running(Cpu::AppCpu), + "IPC target APP core is not running" + ); +} diff --git a/esp-hal/src/interrupt/ipc/riscv.rs b/esp-hal/src/interrupt/ipc/riscv.rs new file mode 100644 index 00000000000..b000ceb9b29 --- /dev/null +++ b/esp-hal/src/interrupt/ipc/riscv.rs @@ -0,0 +1,182 @@ +//! The IPC of a dual-core RISC-V chip. +//! +//! A CPU reaches its own CLINT through one alias, and the CLINT of the other CPU through +//! another alias. The machine software interrupt therefore carries the call in both directions. + +use portable_atomic::Ordering; + +use super::{CoreState, STATE}; +use crate::{ + interrupt::{CpuInterrupt, Priority}, + peripherals::{CLINT, CLINT_OTHER_CORE}, + system::Cpu, +}; + +/// The CLIC line that serves the machine software interrupt. +const CLINT_INTERRUPT: CpuInterrupt = CpuInterrupt::Interrupt3; + +pub(super) fn raise(core: Cpu) { + if core == Cpu::current() { + CLINT::regs() + } else { + CLINT_OTHER_CORE::regs() + } + .msip() + .write(|w| w.msip().set_bit()); +} + +/// Installs the IPC interrupt handler of the PRO CPU. +/// +/// [`crate::init`] calls this function. +pub(crate) fn install() { + install_core(Cpu::ProCpu); +} + +/// Installs the IPC interrupt handler of the APP CPU. +/// +/// Direct binding writes CPU-local registers. The APP CPU must therefore call this function +/// itself, after it sets up vectoring. +pub(crate) fn install_app() { + install_core(Cpu::AppCpu); +} + +fn install_core(core: Cpu) { + debug_assert_eq!(core, Cpu::current()); + + let handler = match core { + Cpu::ProCpu => ipc_handler::<0>, + Cpu::AppCpu => ipc_handler::<1>, + }; + + // The handler clears the request through the alias of its own CLINT. + STATE[core as usize] + .request + .store(CLINT::regs().msip().as_ptr(), Ordering::Relaxed); + + // The CLIC serves the machine software interrupt as interrupt 3, and applies the + // priority of that line to it. The interrupt is core-local, so it needs no matrix + // entry. + crate::interrupt::bind_cpu_interrupt(CLINT_INTERRUPT, handler); + crate::interrupt::enable_cpu_interrupt(CLINT_INTERRUPT, Priority::min()); +} + +/// Handles the IPC interrupt of one CPU. +/// +/// The handler clears the request, runs the posted function, then jumps to the context-switch +/// handler. It borrows `ra`, `t0`, and `t1` only. `t0` goes to `mscratch`. That CSR is free, +/// because the hardware clears `mstatus.MIE` on trap entry, and nothing here enables +/// interrupts again. +#[cfg_attr( + not(interrupt_controller = "clic"), + unsafe(link_section = ".trap.rust") +)] +#[cfg_attr(interrupt_controller = "clic", unsafe(link_section = ".rwtext"))] +#[unsafe(naked)] +unsafe extern "C" fn ipc_handler() { + core::arch::naked_asm!( + " + csrw mscratch, t0 + addi sp, sp, -16 + sw t1, 0(sp) + + # Load the address of `STATE[CORE]`. + la t1, {state} + {base} + + # Clear the request before taking the work, so that a request raised for the next + # run survives. + lw t0, {request}(t1) + sw zero, 0(t0) + + # The callback returns here, so it runs first. A CPU rarely has one, so the callback + # runs out of line: a taken branch costs two cycles, and the context switch that the + # scheduler asks for on every yield must not pay them. + lw t0, {callback}(t1) + bnez t0, 3f + + 1: + lw t0, {pending_context_switch}(t1) + sw zero, {pending_context_switch}(t1) + + lw t1, 0(sp) + addi sp, sp, 16 + + beqz t0, 2f + # The context switch handler restores t0 from mscratch and returns with mret. + jr t0 + 2: + csrr t0, mscratch + mret + + 3: + # `callback_handler` takes the callback from `t1`, and may clobber `ra`, `t0` and `t1`. + sw ra, 4(sp) + la t0, {callback_handler} + jalr ra, 0(t0) + lw ra, 4(sp) + la t1, {state} + {base} + j 1b + ", + state = sym STATE, + base = const CORE * size_of::(), + callback = const core::mem::offset_of!(CoreState, callback), + pending_context_switch = const core::mem::offset_of!(CoreState, pending_context_switch), + request = const core::mem::offset_of!(CoreState, request), + callback_handler = sym callback_handler, + ) +} + +/// Runs the posted function of one CPU, then returns to [`ipc_handler`]. +/// +/// `t1` holds the address of the `CoreState` of the CPU. This function saves the registers +/// that the RISC-V calling convention lets the callee clobber, except `ra`, `t0`, and `t1`, +/// which [`ipc_handler`] saves. It leaves `mscratch` alone, because the context-switch handler +/// that runs next reads the interrupted `t0` from it. +#[cfg_attr( + not(interrupt_controller = "clic"), + unsafe(link_section = ".trap.rust") +)] +#[cfg_attr(interrupt_controller = "clic", unsafe(link_section = ".rwtext"))] +#[unsafe(naked)] +unsafe extern "C" fn callback_handler() { + core::arch::naked_asm!( + " + addi sp, sp, -64 + sw ra, 0(sp) + sw t2, 4(sp) + sw t3, 8(sp) + sw t4, 12(sp) + sw t5, 16(sp) + sw t6, 20(sp) + sw a0, 24(sp) + sw a1, 28(sp) + sw a2, 32(sp) + sw a3, 36(sp) + sw a4, 40(sp) + sw a5, 44(sp) + sw a6, 48(sp) + sw a7, 52(sp) + + lw t0, {callback}(t1) + sw zero, {callback}(t1) + jalr ra, 0(t0) + + lw ra, 0(sp) + lw t2, 4(sp) + lw t3, 8(sp) + lw t4, 12(sp) + lw t5, 16(sp) + lw t6, 20(sp) + lw a0, 24(sp) + lw a1, 28(sp) + lw a2, 32(sp) + lw a3, 36(sp) + lw a4, 40(sp) + lw a5, 44(sp) + lw a6, 48(sp) + lw a7, 52(sp) + addi sp, sp, 64 + ret + ", + callback = const core::mem::offset_of!(CoreState, callback), + ) +} diff --git a/esp-hal/src/interrupt/ipc/xtensa.rs b/esp-hal/src/interrupt/ipc/xtensa.rs new file mode 100644 index 00000000000..0246eee8bd8 --- /dev/null +++ b/esp-hal/src/interrupt/ipc/xtensa.rs @@ -0,0 +1,88 @@ +//! The IPC of a dual-core Xtensa chip. +//! +//! The CPUs have no interrupt that reaches the other CPU. Each CPU therefore takes the call in +//! a `FROM_CPU` interrupt of its own. + +use portable_atomic::Ordering; + +use super::STATE; +use crate::{ + interrupt::{Priority, software::SoftwareInterrupt}, + peripherals::{FROM_CPU_INTR0, FROM_CPU_INTR1, Interrupt}, + ram, + system::Cpu, + trapframe::TrapFrame, +}; + +pub(super) fn raise(core: Cpu) { + match core { + Cpu::ProCpu => SoftwareInterrupt::new(unsafe { FROM_CPU_INTR0::steal() }).raise(), + Cpu::AppCpu => SoftwareInterrupt::new(unsafe { FROM_CPU_INTR1::steal() }).raise(), + } +} + +fn interrupt(core: Cpu) -> Interrupt { + match core { + Cpu::ProCpu => Interrupt::FROM_CPU_INTR0, + Cpu::AppCpu => Interrupt::FROM_CPU_INTR1, + } +} + +/// Installs the IPC interrupt handler of both CPUs. +/// +/// [`crate::init`] calls this function. +pub(crate) fn install() { + install_core(Cpu::ProCpu); + + // The second CPU uses a different interrupt, so it needs a vector entry of its own. + // Mapping an interrupt writes the interrupt matrix, which is shared. The startup code + // of the second CPU only enables CPU interrupts (see `start_core1_init`, which avoids + // `setup_interrupts` for this reason), so the mapping survives. + install_core(Cpu::AppCpu); +} + +fn install_core(core: Cpu) { + let handler = crate::interrupt::InterruptHandler::new( + // The vectored dispatcher calls every handler with the trap frame. + unsafe { + core::mem::transmute::( + ipc_handler as fn(&mut TrapFrame), + ) + }, + Priority::min(), + ); + + crate::interrupt::bind_vector(interrupt(core), handler); + crate::interrupt::enable_on_cpu(core, interrupt(core), Priority::min()); +} + +#[ram] +fn ipc_handler(context: &mut TrapFrame) { + let core = Cpu::current(); + + // This is the only place that clears the request. A second clear would drop a request + // that arrived while a handler was running. + match core { + Cpu::ProCpu => SoftwareInterrupt::new(unsafe { FROM_CPU_INTR0::steal() }).reset(), + Cpu::AppCpu => SoftwareInterrupt::new(unsafe { FROM_CPU_INTR1::steal() }).reset(), + } + + let state = &STATE[core as usize]; + + // The callback returns here, so it runs first. + let callback = state.callback.swap(core::ptr::null_mut(), Ordering::AcqRel); + if !callback.is_null() { + let callback = unsafe { core::mem::transmute::<*mut (), fn()>(callback) }; + callback(); + } + + // The context switch chooses the context that the interrupt returns to, so it runs last. + let handler = state + .pending_context_switch + .swap(core::ptr::null_mut(), Ordering::AcqRel); + if !handler.is_null() { + let handler = + unsafe { core::mem::transmute::<*mut (), extern "C" fn(&mut TrapFrame)>(handler) }; + handler(context); + } +} diff --git a/esp-hal/src/interrupt/mod.rs b/esp-hal/src/interrupt/mod.rs index 78803ba7300..f70d571e968 100644 --- a/esp-hal/src/interrupt/mod.rs +++ b/esp-hal/src/interrupt/mod.rs @@ -1,4 +1,3 @@ -#![cfg_attr(docsrs, procmacros::doc_replace)] //! # Interrupt support //! //! This module contains code to configure and handle peripheral interrupts. @@ -18,33 +17,50 @@ //! ## Usage //! //! Peripheral drivers manage interrupts for you. Where appropriate, a `set_interrupt_handler` -//! function is provided, which allows you to register a function to handle interrupts at a priority -//! level of your choosing. Interrupt handler functions need to be marked by the [`#[handler]`] +//! function is provided to register a function that handles interrupts at a chosen priority +//! level. Interrupt handler functions need to be marked by the [`#[handler]`][crate::handler] //! attribute. These drivers also provide `listen` and `unlisten` functions that control whether an //! interrupt will be generated for the matching event or not. For more information and examples, //! consult the documentation of the specific peripheral drivers. //! //! If you are writing your own peripheral driver, you will need to first register interrupt -//! handlers using the [peripheral singletons'] `bind_X_interrupt` functions. You can use the -//! matching `enable` and `disable` functions to control the peripheral interrupt in the interrupt -//! matrix, or you can, depending on the peripheral, set or clear the appropriate enable bits in the -//! `int_ena` register. +//! handlers using the [peripheral singletons'][crate::peripherals::I2C0] `bind_X_interrupt` +//! functions. You can use the matching `enable` and `disable` functions to control the peripheral +//! interrupt in the interrupt matrix, or you can, depending on the peripheral, set or clear the +//! appropriate enable bits in the `int_ena` register. //! -//! [`#[handler]`]: crate::handler -//! [peripheral singletons']: crate::peripherals::I2C0 -//! -//! ## Software interrupts +//! ## Software Interrupts //! //! The [`software`] module implements software interrupts using peripheral interrupt signals. #![cfg_attr( multi_core, - doc = "This mechanism can be used to implement efficient cross-core communication." + doc = "Those signals can also carry cross-core communication." +)] +#![cfg_attr( + all(feature = "rt", multi_core), + doc = " +## Inter-Processor Call (IPC) + +The [`ipc`] module posts a function to a CPU, and raises the IPC interrupt of that CPU. +" +)] +#![cfg_attr( + all(feature = "rt", multi_core, xtensa), + doc = "The HAL reserves `FROM_CPU_INTR0` and `FROM_CPU_INTR1` for this path." +)] +#![cfg_attr( + all(feature = "rt", single_core, context_switch_source = "from_cpu"), + doc = "The HAL reserves `FROM_CPU_INTR0` to switch tasks." +)] +#![cfg_attr( + all(feature = "rt", context_switch_source = "software0"), + doc = " +## Context Switching + +The HAL defines the `Software0` interrupt handler, and switches tasks in that interrupt. +" )] -#[cfg(riscv)] -pub use self::riscv::*; -#[cfg(xtensa)] -pub use self::xtensa::*; use crate::{peripherals::Interrupt, system::Cpu}; cfg_select! { @@ -58,15 +74,22 @@ cfg_select! { } } -#[cfg(riscv)] -mod riscv; -#[cfg(xtensa)] -mod xtensa; +#[cfg_attr(riscv, path = "riscv.rs")] +#[cfg_attr(xtensa, path = "xtensa.rs")] +mod arch; +pub use arch::*; use crate::pac; -unstable_driver! { +unstable_module! { pub mod software; + + #[cfg(all(feature = "rt", multi_core))] + pub mod ipc; + + #[cfg(feature = "rt")] + #[doc(hidden)] + pub mod __rtos_implementation; } #[cfg(feature = "rt")] @@ -90,29 +113,25 @@ pub const DEFAULT_INTERRUPT_HANDLER: InterruptHandler = InterruptHandler::new( Priority::min(), ); -/// Trait implemented by drivers which allow the user to set an -/// [InterruptHandler] +/// Trait implemented by drivers that support registering an +/// [`InterruptHandler`]. #[instability::unstable] pub trait InterruptConfigurable: crate::private::Sealed { - #[cfg_attr( - not(multi_core), - doc = "Registers an interrupt handler for the peripheral." - )] - #[cfg_attr( - multi_core, - doc = "Registers an interrupt handler for the peripheral on the current core." - )] + #[doc = cfg_select! { + multi_core => "Registers an interrupt handler for the peripheral on the current core.", + _ => "Registers an interrupt handler for the peripheral.", + }] #[doc = ""] - /// Note that this will replace any previously registered interrupt - /// handlers. Some peripherals offer a shared interrupt handler for - /// multiple purposes. It's the users duty to honor this. + /// Replaces any previously registered interrupt handlers. Some peripherals + /// offer a shared interrupt handler for multiple purposes. The caller must + /// honor this constraint. /// - /// You can restore the default/unhandled interrupt handler by using - /// [DEFAULT_INTERRUPT_HANDLER] + /// The default/unhandled interrupt handler can be restored with + /// [`DEFAULT_INTERRUPT_HANDLER`]. fn set_interrupt_handler(&mut self, handler: InterruptHandler); } -/// Represents an ISR callback function +/// Represents an ISR callback function. #[derive(Copy, Clone, Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[instability::unstable] @@ -121,7 +140,7 @@ pub struct IsrCallback { } impl IsrCallback { - /// Construct a new callback from the callback function. + /// Creates a new callback from the callback function. pub fn new(f: extern "C" fn()) -> Self { // a valid fn pointer is non zero Self { f } @@ -146,7 +165,7 @@ impl PartialEq for IsrCallback { } } -/// An interrupt handler +/// An interrupt handler. #[cfg_attr( multi_core, doc = r" @@ -163,7 +182,7 @@ pub struct InterruptHandler { } impl InterruptHandler { - /// Creates a new [InterruptHandler] which will call the given function at + /// Creates a new [`InterruptHandler`] which will call the given function at /// the given priority. pub const fn new(f: extern "C" fn(), prio: Priority) -> Self { Self { f, prio } @@ -175,7 +194,7 @@ impl InterruptHandler { IsrCallback::new(self.f) } - /// Priority to be used when registering the interrupt + /// Returns the priority used when registering the interrupt. #[inline] pub fn priority(&self) -> Priority { self.prio @@ -192,7 +211,7 @@ pub struct InterruptStatus { } impl InterruptStatus { - /// Get status of a particular peripheral interrupt + /// Returns the status of a particular peripheral interrupt. #[instability::unstable] #[inline] pub fn is_pending(interrupt: Interrupt) -> bool { @@ -210,67 +229,41 @@ impl InterruptStatus { match cpu { Cpu::ProCpu => { cfg_select! { - esp32s31 => { - if word == 5 { - // Discontiguous, cannot be part of the standard status array - return INTERRUPT_CORE0::regs().core_0_intr_status5().read().bits() - & 0x1ff; - } - INTERRUPT_CORE0::regs() - .core_0_intr_status(word) - .read() - .bits() - } esp32p4 => { if word == 4 { // Discontiguous, cannot be part of the standard status array return INTERRUPT_CORE0::regs().core_0_intr_status4().read().bits(); } - INTERRUPT_CORE0::regs() - .core_0_intr_status(word) - .read() - .bits() } - _ => INTERRUPT_CORE0::regs() - .core_0_intr_status(word) - .read() - .bits(), + _ => {} } + + INTERRUPT_CORE0::regs() + .core_0_intr_status(word) + .read() + .bits() } #[cfg(multi_core)] Cpu::AppCpu => { cfg_select! { - esp32s31 => { - if word == 5 { - // Discontiguous, cannot be part of the standard status array - return INTERRUPT_CORE1::regs().core_1_intr_status5().read().bits() - & 0x1ff; - } - INTERRUPT_CORE1::regs() - .core_1_intr_status(word) - .read() - .bits() - } esp32p4 => { if word == 4 { // Discontiguous, cannot be part of the standard status array return INTERRUPT_CORE1::regs().core_1_intr_status4().read().bits(); } - INTERRUPT_CORE1::regs() - .core_1_intr_status(word) - .read() - .bits() } - _ => INTERRUPT_CORE1::regs() - .core_1_intr_status(word) - .read() - .bits(), + _ => {} } + + INTERRUPT_CORE1::regs() + .core_1_intr_status(word) + .read() + .bits() } } } - /// Get status of peripheral interrupts + /// Returns the status of peripheral interrupts. #[instability::unstable] pub fn current() -> InterruptStatus { let cpu = Cpu::current(); @@ -279,19 +272,19 @@ impl InterruptStatus { } } - /// Is the given interrupt bit set + /// Is the given interrupt bit set. #[instability::unstable] pub fn is_set(&self, interrupt: u8) -> bool { (self.status[interrupt as usize / 32] & (1 << (interrupt % 32))) != 0 } - /// Set the given interrupt status bit + /// Sets the given interrupt status bit. #[instability::unstable] pub fn set(&mut self, interrupt: u8) { self.status[interrupt as usize / 32] |= 1 << (interrupt % 32); } - /// Return an iterator over the set interrupt status bits + /// Returns an iterator over the set interrupt status bits. #[instability::unstable] pub fn iterator(&self) -> InterruptStatusIterator { InterruptStatusIterator { @@ -379,13 +372,16 @@ pub fn bound_handler(interrupt: Interrupt) -> Option { /// Only one interrupt handler can be bound to a peripheral interrupt. #[instability::unstable] pub fn bind_handler(interrupt: Interrupt, handler: InterruptHandler) { + bind_vector(interrupt, handler); + enable(interrupt, handler.priority()); +} + +/// Binds `handler` to `interrupt` without enabling the peripheral interrupt. +pub(crate) fn bind_vector(interrupt: Interrupt, handler: InterruptHandler) { unsafe { let vector = vector_entry(interrupt); - let ptr = (&raw const vector._handler).cast::().cast_mut(); - // On RISC-V MCUs we may be protecting the trap section using a watchpoint. - // If we do, we need to temporarily disable this protection. #[cfg(all(riscv, write_vec_table_monitoring))] if crate::soc::trap_section_protected() { crate::debugger::DEBUGGER_LOCK.lock(|| { @@ -393,21 +389,18 @@ pub fn bind_handler(interrupt: Interrupt, handler: InterruptHandler) { ptr.write_volatile(handler.handler().address()); crate::debugger::restore_watchpoint(1, wp); }); - enable(interrupt, handler.priority()); return; } ptr.write_volatile(handler.handler().address()); } - enable(interrupt, handler.priority()); } /// Enables a peripheral interrupt at a given priority, using vectored CPU interrupts. /// -/// Note that interrupts still need to be enabled globally for interrupts -/// to be serviced. +/// Interrupts must still be enabled globally for interrupts to be serviced. /// -/// Internally, this function maps the interrupt to the appropriate CPU interrupt +/// Internally maps the interrupt to the appropriate CPU interrupt /// for the specified priority level. #[inline] #[instability::unstable] @@ -420,9 +413,9 @@ pub(crate) fn enable_on_cpu(cpu: Cpu, interrupt: Interrupt, level: Priority) { map_raw(cpu, interrupt, cpu_interrupt as u32); } -/// Disable the given peripheral interrupt. +/// Disables the given peripheral interrupt. /// -/// Internally, this function maps the interrupt to a disabled CPU interrupt. +/// Internally maps the interrupt to a disabled CPU interrupt. #[inline] #[instability::unstable] pub fn disable(core: Cpu, interrupt: Interrupt) { @@ -445,7 +438,7 @@ pub(super) fn map_raw(core: Cpu, interrupt: Interrupt, cpu_interrupt: u32) { } } -/// Get cpu interrupt assigned to peripheral interrupt +/// Returns the CPU interrupt assigned to peripheral interrupt. #[cfg(all(feature = "rt", gpio_driver_supported))] pub(crate) fn mapped_to(cpu: Cpu, interrupt: Interrupt) -> Option { mapped_to_raw(cpu, interrupt as u32) @@ -489,7 +482,7 @@ impl RunLevel { #[procmacros::doc_replace] /// Returns the current run level. /// - /// ## Examples + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -509,9 +502,8 @@ impl RunLevel { /// /// # Safety /// - /// This function must only be used to raise the run level and to restore it - /// to a previous value. It must not be used to arbitrarily lower the - /// run level. + /// Must only be used to raise the run level and to restore it to a previous + /// value. Must not be used to arbitrarily lower the run level. #[inline] #[instability::unstable] pub unsafe fn change(to: Self) -> Self { @@ -519,11 +511,11 @@ impl RunLevel { } #[procmacros::doc_replace] - /// Checks if the run level indicates thread mode. + /// Returns whether the run level indicates thread mode. /// - /// This function can be used to determine if the CPU is executing an interrupt handler. + /// Thread mode means the CPU is not executing an interrupt handler. /// - /// ## Examples + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -574,12 +566,12 @@ impl From for u32 { } } -/// Priority Level Error +/// Priority Level Error. #[derive(Copy, Clone, Debug, PartialEq, Eq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[instability::unstable] pub enum PriorityError { - /// The priority is not valid + /// The priority is not valid. InvalidInterruptPriority, } diff --git a/esp-hal/src/interrupt/riscv.rs b/esp-hal/src/interrupt/riscv.rs index d38d7c25c01..6104af5601d 100644 --- a/esp-hal/src/interrupt/riscv.rs +++ b/esp-hal/src/interrupt/riscv.rs @@ -18,10 +18,21 @@ pub use esp_riscv_rt::TrapFrame; #[cfg_attr(interrupt_controller = "clic", path = "riscv/clic.rs")] mod cpu_int; -// The software-interrupt driver is the only caller on this architecture, and that driver is -// unstable. -#[cfg(feature = "unstable")] -pub(crate) use riscv::interrupt::free; +// riscv::interrupt::free is not safe on C6/H2 +#[inline] +pub(crate) fn free(f: F) -> R +where + F: FnOnce() -> R, +{ + use esp_sync::raw::{RawLock, SingleCoreInterruptLock}; + let irq_token = unsafe { SingleCoreInterruptLock.enter() }; + + let r = f(); + + unsafe { SingleCoreInterruptLock.exit(irq_token) }; + + r +} use crate::{ interrupt::{PriorityError, RunLevel}, @@ -68,11 +79,18 @@ for_each_interrupt!( ); for_each_classified_interrupt!( - (direct_bindable $( ([$class:ident $idx_in_class:literal] $n:literal) ),*) => { + (context_switch ([$class:ident $idx_in_class:literal] $n:literal)) => { + paste::paste! { + pub(crate) const IPC_INTERRUPT: CpuInterrupt = CpuInterrupt::[]; + } + }; + + (direct_bindable $( ([$class:ident $idx_in_class:literal] $n:literal) ),* ) => { paste::paste! { /// Enumeration of CPU interrupts available for direct binding. #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] + #[instability::unstable] pub enum DirectBindableCpuInterrupt { $( #[doc = concat!(" Direct bindable CPU interrupt number ", stringify!($idx_in_class), ".")] @@ -106,21 +124,21 @@ impl CpuInterrupt { VECTORED_CPU_INTERRUPT_RANGE.contains(&(self as u32)) } - /// Enable the CPU interrupt + /// Enables the CPU interrupt. #[inline] #[instability::unstable] pub fn enable(self) { cpu_int::enable_cpu_interrupt_raw(self as u32); } - /// Clear the CPU interrupt status bit + /// Clears the CPU interrupt status bit. #[inline] #[instability::unstable] pub fn clear(self) { cpu_int::clear_raw(self as u32); } - /// Set the interrupt kind (i.e. level or edge) of an CPU interrupt + /// Sets the interrupt kind (i.e. level or edge) of an CPU interrupt. /// /// This is safe to call when the `vectored` feature is enabled. The /// vectored interrupt handler will take care of clearing edge interrupt @@ -131,14 +149,14 @@ impl CpuInterrupt { cpu_int::set_kind_raw(self as u32, kind); } - /// Set the priority level of a CPU interrupt + /// Sets the priority level of a CPU interrupt. #[inline] #[instability::unstable] pub fn set_priority(self, priority: Priority) { cpu_int::set_priority_raw(self as u32, priority); } - /// Get interrupt priority for the CPU + /// Returns the interrupt priority for the CPU. #[inline] #[instability::unstable] pub fn priority(self) -> Priority { @@ -231,7 +249,7 @@ impl Priority { } impl ElevatedRunLevel { - /// Returns the highest run level + /// Returns the highest run level. #[instability::unstable] pub const fn max() -> ElevatedRunLevel { Self::from_priority(Priority::max()) @@ -290,21 +308,21 @@ pub(super) static PRIORITY_TO_INTERRUPT: [CpuInterrupt; VECTOR_COUNT] = const { vector }; -/// Enable an interrupt by directly binding it to an available CPU interrupt +/// Enables an interrupt by directly binding it to an available CPU interrupt. /// -/// ⚠️ This installs a *raw trap handler*, the `handler` user provides is written directly into the -/// CPU interrupt vector table. That means: +/// ⚠️ This installs a *raw trap handler*: the provided `handler` is written +/// directly into the CPU interrupt vector table. That means: /// -/// - Provided handler will be used as an actual trap-handler -/// - It is user's responsibility to: -/// - Save and restore all registers they use. +/// - The provided handler is used as an actual trap handler. +/// - The caller must: +/// - Save and restore all used registers. /// - Clear the interrupt source if necessary. /// - Return using the `mret` instruction. -/// - The handler should be declared as naked function. The compiler will not insert a function -/// prologue/epilogue for the user, normal Rust `fn` will result in an error. +/// - The handler must be declared as a naked function. The compiler does not insert a function +/// prologue or epilogue; a normal Rust `fn` results in an error /// -/// Unless you are sure that you need such low-level control to achieve the lowest possible latency, -/// you most likely want to use [`enable`][crate::interrupt::enable] instead. +/// Unless low-level control is required for the lowest possible latency, +/// [`enable`][crate::interrupt::enable] is usually preferable. #[instability::unstable] pub fn enable_direct( interrupt: Interrupt, @@ -312,6 +330,22 @@ pub fn enable_direct( cpu_interrupt: DirectBindableCpuInterrupt, handler: unsafe extern "C" fn(), ) { + enable_direct_inner(interrupt, level, cpu_interrupt.into(), handler) +} + +pub(crate) fn enable_direct_inner( + interrupt: Interrupt, + level: Priority, + cpu_interrupt: CpuInterrupt, + handler: unsafe extern "C" fn(), +) { + bind_cpu_interrupt(cpu_interrupt, handler); + super::map_raw(Cpu::current(), interrupt, cpu_interrupt as u32); + enable_cpu_interrupt(cpu_interrupt, level); +} + +/// Writes `handler` into the vector table entry of `cpu_interrupt`. +pub(crate) fn bind_cpu_interrupt(cpu_interrupt: CpuInterrupt, handler: unsafe extern "C" fn()) { cfg_select! { interrupt_controller = "clic" => { let clic = unsafe { crate::soc::pac::CLIC::steal() }; @@ -368,8 +402,10 @@ pub fn enable_direct( // Invalidate the cache to make sure the CPU does not read from a stale instruction cache. crate::soc::cache_invalidate_icache_addr(mtvt_table as u32, 48 * 4); } +} - super::map_raw(Cpu::current(), interrupt, cpu_interrupt as u32); +/// Enables `cpu_interrupt` as a level-triggered interrupt at `level`. +pub(crate) fn enable_cpu_interrupt(cpu_interrupt: CpuInterrupt, level: Priority) { cpu_int::set_priority_raw(cpu_interrupt as u32, level); cpu_int::set_kind_raw(cpu_interrupt as u32, InterruptKind::Level); cpu_int::enable_cpu_interrupt_raw(cpu_interrupt as u32); @@ -401,7 +437,7 @@ fn encode_jal_x0(target: usize, pc: usize) -> u32 { // Runlevel APIs -/// Get the current run level (the level below which interrupts are masked). +/// Returns the current run level (the level below which interrupts are masked). pub(crate) fn current_raw_runlevel() -> u32 { cpu_int::current_runlevel() as u32 } @@ -411,9 +447,8 @@ pub(crate) fn current_raw_runlevel() -> u32 { /// /// # Safety /// -/// This function must only be used to raise the runlevel and to restore it -/// to a previous value. It must not be used to arbitrarily lower the -/// runlevel. +/// Must only be used to raise the runlevel and to restore it to a previous +/// value. Must not be used to arbitrarily lower the runlevel. pub(crate) unsafe fn change_current_runlevel(level: RunLevel) -> RunLevel { let previous = cpu_int::change_current_runlevel(level); unwrap!(RunLevel::try_from_u32(previous as u32)) @@ -421,6 +456,14 @@ pub(crate) unsafe fn change_current_runlevel(level: RunLevel) -> RunLevel { fn cpu_wait_mode_on() -> bool { cfg_select! { + // Each core gates its own WAITI clock, cannot unify with soc_has_pcr case. + esp32h4 => { + let conf = crate::peripherals::PCR::regs().cpu_waiti_conf().read(); + match Cpu::current() { + Cpu::ProCpu => conf.cpu0_wait_mode_force_on().bit_is_set(), + Cpu::AppCpu => conf.cpu1_wait_mode_force_on().bit_is_set(), + } + } soc_has_pcr => crate::peripherals::PCR::regs() .cpu_waiti_conf() .read() @@ -439,14 +482,14 @@ fn cpu_wait_mode_on() -> bool { } } -/// Wait for an interrupt to occur. +/// Waits for an interrupt to occur. /// -/// This function causes the current CPU core to execute its Wait For Interrupt -/// (WFI or equivalent) instruction. After executing this function, the CPU core -/// will stop execution until an interrupt occurs. +/// Causes the current CPU core to execute its Wait For Interrupt (WFI or +/// equivalent) instruction. After this call, the CPU core stops execution until +/// an interrupt occurs. /// -/// This function will return immediately when a debugger is attached, so it is intended to be -/// called in a loop. +/// Returns immediately when a debugger is attached; intended to be called in a +/// loop. #[inline(always)] #[instability::unstable] pub fn wait_for_interrupt() { @@ -463,11 +506,11 @@ pub(crate) fn priority_to_cpu_interrupt(_interrupt: Interrupt, level: Priority) PRIORITY_TO_INTERRUPT[(level as usize) - 1] } -/// Setup interrupts ready for vectoring +/// Sets up interrupts ready for vectoring. /// /// # Safety /// -/// This function must be called only during core startup. +/// Must be called only during core startup. #[cfg(any(feature = "rt", all(feature = "unstable", multi_core)))] pub(crate) unsafe fn init_vectoring() { use riscv::register::mtvec; @@ -476,6 +519,13 @@ pub(crate) unsafe fn init_vectoring() { static _vector_table: u32; } + // A machine software interrupt survives a CPU reset, so a request that the previous program + // raised would fire as soon as this core takes interrupts again. + #[cfg(soc_has_clint)] + crate::peripherals::CLINT::regs() + .msip() + .write(|w| w.msip().clear_bit()); + unsafe { let vec_table = (&raw const _vector_table).addr(); @@ -564,7 +614,7 @@ pub(crate) mod rt { /// # Safety /// - /// This function is called from an assembly trap handler. + /// Called from an assembly trap handler. #[doc(hidden)] #[unsafe(link_section = ".trap.rust")] #[unsafe(export_name = "_start_trap_rust_hal")] @@ -642,13 +692,13 @@ pub(crate) mod rt { } cfg_select! { - interrupt_controller = "clic" => { + interrupt_controller = "clic" => unsafe { // In case the target uses the CLIC, it is mandatory to restore `mcause` register // since it contains the former CPU priority. When executing `mret`, // the hardware will restore the former threshold, from `mcause` to // `mintstatus` CSR - unsafe { core::arch::asm!("csrw 0x342, {}", in(reg) mcause.bits()) } - } + core::arch::asm!("csrw 0x342, {}", in(reg) mcause.bits()) + }, _ => { unsafe { change_current_runlevel(level) }; } diff --git a/esp-hal/src/interrupt/riscv/clic.rs b/esp-hal/src/interrupt/riscv/clic.rs index 4aa0bfe4529..02fd4defda1 100644 --- a/esp-hal/src/interrupt/riscv/clic.rs +++ b/esp-hal/src/interrupt/riscv/clic.rs @@ -73,7 +73,7 @@ pub(super) fn change_current_runlevel(level: RunLevel) -> u8 { current_runlevel } -/// Get the current run level (the level below which interrupts are masked). +/// Returns the current run level (the level below which interrupts are masked). pub(crate) fn mil() -> usize { mintstatus::read().mil() } diff --git a/esp-hal/src/interrupt/riscv/plic.rs b/esp-hal/src/interrupt/riscv/plic.rs index 087b2fd71db..3edac2aa489 100644 --- a/esp-hal/src/interrupt/riscv/plic.rs +++ b/esp-hal/src/interrupt/riscv/plic.rs @@ -59,12 +59,19 @@ pub(super) fn current_runlevel() -> u8 { /// /// # Safety /// -/// This function must only be used to raise the runlevel and to restore it -/// to a previous value. It must not be used to arbitrarily lower the -/// runlevel. +/// Must only be used to raise the runlevel and to restore it to a previous +/// value. Must not be used to arbitrarily lower the runlevel. pub(crate) fn change_current_runlevel(level: RunLevel) -> u8 { let prev_interrupt_priority = current_runlevel(); + // The threshold does not mask the machine software interrupt, which carries the context + // switch. That switch runs below every elevated run level, so `mie` masks it here instead. + #[cfg(context_switch_source = "clint")] + match level { + RunLevel::Interrupt(_) => unsafe { riscv::register::mie::clear_msoft() }, + RunLevel::ThreadMode => unsafe { riscv::register::mie::set_msoft() }, + } + // The CPU responds to interrupts `>= level`, but we want to also disable // interrupts at `level` so we set the threshold to `level + 1`. PLIC_MX::regs() diff --git a/esp-hal/src/interrupt/software.rs b/esp-hal/src/interrupt/software.rs index c03778631c9..338864d7222 100644 --- a/esp-hal/src/interrupt/software.rs +++ b/esp-hal/src/interrupt/software.rs @@ -1,16 +1,22 @@ #![cfg_attr(docsrs, procmacros::doc_replace)] //! # Software Interrupts //! -//! The [`SoftwareInterrupt`] struct allows raising or resetting software -//! interrupts using the [`raise()`][SoftwareInterrupt::raise] and -//! [`reset()`][SoftwareInterrupt::reset] methods. -//! +//! [`SoftwareInterrupt`] raises or resets software interrupts with +//! [`raise()`][SoftwareInterrupt::raise] and [`reset()`][SoftwareInterrupt::reset]. +#![cfg_attr( + all(feature = "rt", multi_core), + doc = "The HAL reserves `FROM_CPU_INTR0` and `FROM_CPU_INTR1` for inter-processor call (IPC)." +)] +#![cfg_attr( + all(feature = "rt", single_core, context_switch_source = "from_cpu"), + doc = "The HAL reserves `FROM_CPU_INTR0` to switch tasks." +)] //! ## Examples //! //! ```rust, no_run //! # {before_snippet} //! // Take the interrupt you want to use. -//! let mut int0 = SoftwareInterrupt::new(peripherals.FROM_CPU_INTR0); +//! let mut int0 = SoftwareInterrupt::new(peripherals.FROM_CPU_INTR2); //! //! // Set up the interrupt handler. Do this in a critical section so the global //! // contains the interrupt object before the interrupt is triggered. @@ -26,7 +32,7 @@ //! // ... somewhere outside of your main function //! //! // Define a shared handle to the software interrupt. -//! static SWINT0: Mutex>>> = Mutex::new(RefCell::new(None)); +//! static SWINT0: Mutex>>> = Mutex::new(RefCell::new(None)); //! //! #[esp_hal::handler] //! fn swint0_handler() { @@ -57,7 +63,7 @@ pub struct SoftwareInterrupt<'d, const NUM: u8> { } impl<'d, const NUM: u8> SoftwareInterrupt<'d, NUM> { - /// Create a software interrupt driver. + /// Creates a new software interrupt driver. #[inline] pub const fn new(instance: impl Instance + 'd) -> Self { core::mem::forget(instance); // needed to make `new` const @@ -66,7 +72,7 @@ impl<'d, const NUM: u8> SoftwareInterrupt<'d, NUM> { } } - /// Sets the interrupt handler for this software-interrupt + /// Sets the interrupt handler for this software-interrupt. #[instability::unstable] pub fn set_interrupt_handler(&mut self, handler: InterruptHandler) { let interrupt; @@ -86,7 +92,7 @@ impl<'d, const NUM: u8> SoftwareInterrupt<'d, NUM> { interrupt::bind_handler(interrupt, handler); } - /// Trigger this software-interrupt + /// Triggers this software-interrupt. #[crate::ram] pub fn raise(&self) { let regs = cfg_select! { @@ -125,7 +131,7 @@ impl<'d, const NUM: u8> SoftwareInterrupt<'d, NUM> { crate::interrupt::InterruptStatus::is_pending(interrupt) } - /// Resets this software-interrupt + /// Resets this software-interrupt. pub fn reset(&self) { cfg_select! { soc_has_intpri => { diff --git a/esp-hal/src/interrupt/xtensa.rs b/esp-hal/src/interrupt/xtensa.rs index d5a6fbc694f..9b86d49fbb1 100644 --- a/esp-hal/src/interrupt/xtensa.rs +++ b/esp-hal/src/interrupt/xtensa.rs @@ -10,8 +10,8 @@ use crate::{ /// Enumeration of available CPU interrupts /// -/// It's possible to create one handler per priority level. (e.g -/// `level1_interrupt`) +/// It is possible to create one handler per priority level (e.g. +/// `level1_interrupt`). #[derive(Debug, Copy, Clone)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[repr(u32)] @@ -107,21 +107,21 @@ impl CpuInterrupt { true } - /// Enable the CPU interrupt + /// Enables the CPU interrupt. #[inline] #[instability::unstable] pub fn enable(self) { enable_cpu_interrupt_raw(self as u32); } - /// Clear the CPU interrupt status bit + /// Clears the CPU interrupt status bit. #[inline] #[instability::unstable] pub fn clear(self) { unsafe { xtensa_lx::interrupt::clear(1 << self as u32) }; } - /// Get interrupt priority for the CPU + /// Returns the interrupt priority for the CPU. #[inline] #[instability::unstable] pub fn priority(self) -> Priority { @@ -287,7 +287,7 @@ pub(crate) fn enable_cpu_interrupt_raw(cpu_interrupt: u32) { // Runlevel APIs -/// Get the current run level (the level below which interrupts are masked). +/// Returns the current run level (the level below which interrupts are masked). pub(crate) fn current_raw_runlevel() -> u32 { xtensa_lx::interrupt::get_level() } @@ -297,9 +297,8 @@ pub(crate) fn current_raw_runlevel() -> u32 { /// /// # Safety /// -/// This function must only be used to raise the runlevel and to restore it -/// to a previous value. It must not be used to arbitrarily lower the -/// runlevel. +/// Must only be used to raise the runlevel and to restore it to a previous +/// value. Must not be used to arbitrarily lower the runlevel. pub(crate) unsafe fn change_current_runlevel(level: RunLevel) -> RunLevel { let token: u32; unsafe { @@ -332,11 +331,11 @@ pub(crate) unsafe fn change_current_runlevel(level: RunLevel) -> RunLevel { unwrap!(RunLevel::try_from_u32(token & 0x0F)) } -/// Wait for an interrupt to occur. +/// Waits for an interrupt to occur. /// -/// This function causes the current CPU core to execute its Wait For Interrupt -/// (WFI or equivalent) instruction. After executing this function, the CPU core -/// will stop execution until an interrupt occurs. +/// Causes the current CPU core to execute its Wait For Interrupt (WFI or +/// equivalent) instruction. After this call, the CPU core stops execution until +/// an interrupt occurs. #[inline(always)] #[instability::unstable] pub fn wait_for_interrupt() { @@ -398,11 +397,11 @@ cfg_select! { } } -/// Setup interrupts ready for vectoring +/// Sets up interrupts ready for vectoring. /// /// # Safety /// -/// This function must be called only during core startup. +/// Must be called only during core startup. #[cfg(any(feature = "rt", all(feature = "unstable", multi_core)))] pub(crate) unsafe fn init_vectoring() { // Enable vectored interrupts. No configuration is needed because these interrupts have diff --git a/esp-hal/src/lcd_cam/cam.rs b/esp-hal/src/lcd_cam/cam.rs index fb975d6e313..dd6552dfc20 100644 --- a/esp-hal/src/lcd_cam/cam.rs +++ b/esp-hal/src/lcd_cam/cam.rs @@ -1,4 +1,21 @@ -#![cfg_attr(docsrs, procmacros::doc_replace)] +#![cfg_attr(docsrs, procmacros::doc_replace( + "dma_channel" => { + cfg(lcd_cam_dma_engine = "AHB_GDMA") => "DMA_CH0", + cfg(lcd_cam_dma_engine = "AXI_GDMA") => "DMA_AXI_CH0", + }, + "mclk_pin" => gpio_for_signal!(CAM_CLK, "GPIO15"), + "vsync_pin" => gpio_for_signal!(CAM_V_SYNC, "GPIO6"), + "href_pin" => gpio_for_signal!(CAM_H_ENABLE, "GPIO7"), + "pclk_pin" => gpio_for_signal!(CAM_PCLK, "GPIO13"), + "data0_pin" => gpio_for_signal!(CAM_DATA_0, "GPIO11"), + "data1_pin" => gpio_for_signal!(CAM_DATA_1, "GPIO9"), + "data2_pin" => gpio_for_signal!(CAM_DATA_2, "GPIO8"), + "data3_pin" => gpio_for_signal!(CAM_DATA_3, "GPIO10"), + "data4_pin" => gpio_for_signal!(CAM_DATA_4, "GPIO12"), + "data5_pin" => gpio_for_signal!(CAM_DATA_5, "GPIO18"), + "data6_pin" => gpio_for_signal!(CAM_DATA_6, "GPIO17"), + "data7_pin" => gpio_for_signal!(CAM_DATA_7, "GPIO16"), +))] //! # Camera - Master or Slave Mode //! //! ## Overview @@ -22,32 +39,51 @@ //! //! # let dma_buf = dma_rx_stream_buffer!(20 * 1000, 1000); //! -//! let mclk_pin = peripherals.GPIO15; -//! let vsync_pin = peripherals.GPIO6; -//! let href_pin = peripherals.GPIO7; -//! let pclk_pin = peripherals.GPIO13; +//! let mclk_pin = peripherals.__mclk_pin__; +//! let vsync_pin = peripherals.__vsync_pin__; +//! let href_pin = peripherals.__href_pin__; +//! let pclk_pin = peripherals.__pclk_pin__; //! //! let config = Config::default().with_frequency(Rate::from_mhz(20)); //! //! let lcd_cam = LcdCam::new(peripherals.LCD_CAM); -//! let mut camera = Camera::new(lcd_cam.cam, peripherals.DMA_CH0, config)? +//! let mut camera = Camera::new(lcd_cam.cam, peripherals.__dma_channel__, config)? //! .with_master_clock(mclk_pin) // Remove this for slave mode //! .with_pixel_clock(pclk_pin) //! .with_vsync(vsync_pin) //! .with_h_enable(href_pin) -//! .with_data0(peripherals.GPIO11) -//! .with_data1(peripherals.GPIO9) -//! .with_data2(peripherals.GPIO8) -//! .with_data3(peripherals.GPIO10) -//! .with_data4(peripherals.GPIO12) -//! .with_data5(peripherals.GPIO18) -//! .with_data6(peripherals.GPIO17) -//! .with_data7(peripherals.GPIO16); +//! .with_data0(peripherals.__data0_pin__) +//! .with_data1(peripherals.__data1_pin__) +//! .with_data2(peripherals.__data2_pin__) +//! .with_data3(peripherals.__data3_pin__) +//! .with_data4(peripherals.__data4_pin__) +//! .with_data5(peripherals.__data5_pin__) +//! .with_data6(peripherals.__data6_pin__) +//! .with_data7(peripherals.__data7_pin__); //! //! let transfer = camera.receive(dma_buf).map_err(|e| e.0)?; //! //! # {after_snippet} //! ``` +//! +//! ## Asynchronous Reception +//! +//! [`Camera::into_async`] enables DMA interrupt-driven EOF waits. The EOF +//! boundary is selected by [`Config::with_eof_mode`]. Call +//! [`CameraTransfer::stop`] after waiting to return the camera and buffer. +//! +//! ```rust, no_run +//! # {before_snippet} +//! # use esp_hal::{dma_rx_buffer, lcd_cam::{LcdCam, cam::{Camera, Config, EofMode}}}; +//! # let camera = Camera::new(LcdCam::new(peripherals.LCD_CAM).cam, +//! # peripherals.__dma_channel__, Config::default().with_eof_mode(EofMode::ByteLen(2499)))?; +//! # let buffer = dma_rx_buffer!(2500).unwrap(); +//! let camera = camera.into_async(); +//! let mut transfer = camera.receive(buffer).map_err(|(error, _, _)| error)?; +//! transfer.wait_for_dma_eof().await?; +//! let (camera, buffer) = transfer.stop(); +//! # {after_snippet} +//! ``` use core::{ mem::ManuallyDrop, @@ -55,8 +91,10 @@ use core::{ }; use crate::{ + Async, Blocking, - dma::{ChannelRx, DmaError, DmaPeripheral, DmaRxBuffer}, + DriverMode, + dma::{ChannelRx, DmaError, DmaPeripheral, DmaRxBuffer, asynch::DmaRxFuture}, gpio::{ InputConfig, InputSignal, @@ -64,7 +102,15 @@ use crate::{ OutputSignal, interconnect::{PeripheralInput, PeripheralOutput}, }, - lcd_cam::{BitOrder, ByteOrder, CamDmaRxChannel, ClockError, ErasedRxChannel, calculate_clkm}, + lcd_cam::{ + BitOrder, + ByteOrder, + CamDmaRxChannel, + ClockError, + ErasedRxChannel, + calculate_clkm, + ll, + }, pac, peripherals::LCD_CAM, soc::clocks::{ClockTree, LcdCamCamClockConfig, LcdCamInstance}, @@ -76,11 +122,11 @@ use crate::{ #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum EofMode { - /// Generate GDMA SUC EOF by data byte length. + /// Generates GDMA SUC EOF by data byte length. /// /// When the length of received data reaches this value + 1, GDMA in_suc_eof is triggered. ByteLen(u16), - /// Generate GDMA SUC EOF by the vsync signal + /// Generates GDMA SUC EOF by the vsync signal. VsyncSignal, } @@ -112,7 +158,7 @@ pub enum VsyncFilterThreshold { pub enum VhdeMode { /// VSYNC + HSYNC mode is selected, in this mode, /// the signals of VSYNC, HSYNC and DE are used to control the data. - /// For this case, users need to wire the three signal lines. + /// For this case, the VSYNC, HSYNC, and DE signal lines must be wired. VsyncHsync, /// DE mode is selected, the signals of VSYNC and @@ -150,12 +196,12 @@ impl Drop for Cam<'_> { } /// Represents the camera interface with DMA support. -pub struct Camera<'d> { +pub struct Camera<'d, Dm: DriverMode = Blocking> { cam: Cam<'d>, - rx_channel: ChannelRx>, + rx_channel: ChannelRx>, } -impl<'d> Camera<'d> { +impl<'d> Camera<'d, Blocking> { /// Creates a new `Camera` instance with DMA support. pub fn new( cam: Cam<'d>, @@ -172,6 +218,26 @@ impl<'d> Camera<'d> { Ok(this) } + /// Reconfigures the DMA channel for asynchronous operation. + pub fn into_async(self) -> Camera<'d, Async> { + Camera { + cam: self.cam, + rx_channel: self.rx_channel.into_async(), + } + } +} + +impl<'d> Camera<'d, Async> { + /// Reconfigures the DMA channel for blocking operation. + pub fn into_blocking(self) -> Camera<'d, Blocking> { + Camera { + cam: self.cam, + rx_channel: self.rx_channel.into_blocking(), + } + } +} + +impl<'d, Dm: DriverMode> Camera<'d, Dm> { fn regs(&self) -> &pac::lcd_cam::RegisterBlock { self.cam.lcd_cam.register_block() } @@ -180,8 +246,7 @@ impl<'d> Camera<'d> { /// /// # Errors /// - /// [`ConfigError::Clock`] will be returned if the frequency passed in - /// `Config` is too low. + /// [`ConfigError::Clock`] when the frequency passed in `Config` is too low. pub fn apply_config(&mut self, config: &Config) -> Result<(), ConfigError> { let sources = property!("clock_tree.lcd_cam.cam_clock.sclk"); let (i, divider) = calculate_clkm( @@ -198,22 +263,6 @@ impl<'d> Camera<'d> { return Err(ConfigError::LineInterrupt); } - self.regs().cam_ctrl().write(|w| { - // Force enable the clock for all configuration registers. - unsafe { - if let Some(threshold) = config.vsync_filter_threshold { - w.cam_vsync_filter_thres().bits(threshold as _); - } - w.cam_byte_order() - .bit(config.byte_order != ByteOrder::default()); - w.cam_bit_order() - .bit(config.bit_order != BitOrder::default()); - w.cam_vs_eof_en() - .bit(matches!(config.eof_mode, EofMode::VsyncSignal)); - w.cam_line_int_en().bit(config.line_interrupt.is_some()); - w.cam_stop_en().clear_bit() - } - }); ClockTree::with(|clocks| { LcdCamInstance::LcdCam.configure_cam_clock(clocks, clock_config); if !self.cam.clock_requested { @@ -222,6 +271,21 @@ impl<'d> Camera<'d> { } }); + self.regs().cam_ctrl().modify(|_, w| unsafe { + w.cam_vsync_filter_thres().bits( + config + .vsync_filter_threshold + .map_or(0, |threshold| threshold as _), + ); + w.cam_byte_order() + .bit(config.byte_order != ByteOrder::default()); + w.cam_bit_order() + .bit(config.bit_order != BitOrder::default()); + w.cam_vs_eof_en() + .bit(matches!(config.eof_mode, EofMode::VsyncSignal)); + w.cam_line_int_en().bit(config.line_interrupt.is_some()); + w.cam_stop_en().clear_bit() + }); self.regs().cam_ctrl1().write(|w| unsafe { w.cam_2byte_en().bit(config.enable_2byte_mode); w.cam_vh_de_mode_en() @@ -240,9 +304,7 @@ impl<'d> Camera<'d> { w.cam_vsync_inv().bit(config.invert_vsync) }); - self.regs() - .cam_rgb_yuv() - .write(|w| w.cam_conv_bypass().clear_bit()); + ll::set_cam_conv_bypass(self.regs()); self.regs() .cam_ctrl() @@ -250,9 +312,7 @@ impl<'d> Camera<'d> { Ok(()) } -} -impl<'d> Camera<'d> { /// Configures the master clock (MCLK) pin for the camera interface. pub fn with_master_clock(self, mclk: impl PeripheralOutput<'d>) -> Self { let mclk = mclk.into(); @@ -405,7 +465,7 @@ impl<'d> Camera<'d> { pub fn receive( mut self, mut buf: BUF, - ) -> Result, (DmaError, Self, BUF)> { + ) -> Result, (DmaError, Self, BUF)> { // Reset Camera control unit and Async Rx FIFO self.regs() .cam_ctrl1() @@ -445,19 +505,21 @@ impl<'d> Camera<'d> { Ok(CameraTransfer { camera: ManuallyDrop::new(self), buffer_view: ManuallyDrop::new(buf.into_view()), + eof_error: None, }) } } /// Represents an ongoing (or potentially stopped) transfer from the Camera to a /// DMA buffer. -pub struct CameraTransfer<'d, BUF: DmaRxBuffer> { - camera: ManuallyDrop>, +pub struct CameraTransfer<'d, BUF: DmaRxBuffer, Dm: DriverMode = Blocking> { + camera: ManuallyDrop>, buffer_view: ManuallyDrop, + eof_error: Option, } -impl<'d, BUF: DmaRxBuffer> CameraTransfer<'d, BUF> { - /// Returns true when [Self::wait] will not block. +impl<'d, BUF: DmaRxBuffer, Dm: DriverMode> CameraTransfer<'d, BUF, Dm> { + /// Returns whether [`Self::wait`] will not block. pub fn is_done(&self) -> bool { // This peripheral doesn't really "complete". As long the camera (or anything // pretending to be :D) sends data, it will receive it and pass it to the DMA. @@ -484,7 +546,7 @@ impl<'d, BUF: DmaRxBuffer> CameraTransfer<'d, BUF> { } /// Stops this transfer on the spot and returns the peripheral and buffer. - pub fn stop(mut self) -> (Camera<'d>, BUF::Final) { + pub fn stop(mut self) -> (Camera<'d, Dm>, BUF::Final) { self.stop_peripherals(); let (camera, view) = self.release(); (camera, BUF::from_view(view)) @@ -492,10 +554,10 @@ impl<'d, BUF: DmaRxBuffer> CameraTransfer<'d, BUF> { /// Waits for the transfer to stop and returns the peripheral and buffer. /// - /// Note: The camera doesn't really "finish" its transfer, so what you're - /// really waiting for here is a DMA Error. You typically just want to - /// call [Self::stop] once you have the data you need. - pub fn wait(mut self) -> (Result<(), DmaError>, Camera<'d>, BUF::Final) { + /// The camera does not really "finish" its transfer, so this typically + /// waits for a DMA error. Call [`Self::stop`] once the needed data is + /// available. + pub fn wait(mut self) -> (Result<(), DmaError>, Camera<'d, Dm>, BUF::Final) { while !self.is_done() {} // Stop the DMA as it doesn't know that the camera has stopped. @@ -503,18 +565,17 @@ impl<'d, BUF: DmaRxBuffer> CameraTransfer<'d, BUF> { // Note: There is no "done" interrupt to clear. - let (camera, view) = self.release(); - - let result = if camera.rx_channel.has_error() { - Err(DmaError::DescriptorError) - } else { - Ok(()) + let result = match self.eof_error { + Some(error) => Err(error), + None if self.camera.rx_channel.has_error() => Err(DmaError::DescriptorError), + None => Ok(()), }; + let (camera, view) = self.release(); (result, camera, BUF::from_view(view)) } - fn release(mut self) -> (Camera<'d>, BUF::View) { + fn release(mut self) -> (Camera<'d, Dm>, BUF::View) { // SAFETY: Since forget is called on self, we know that self.camera and // self.buffer_view won't be touched again. let result = unsafe { @@ -538,7 +599,41 @@ impl<'d, BUF: DmaRxBuffer> CameraTransfer<'d, BUF> { } } -impl Deref for CameraTransfer<'_, BUF> { +impl CameraTransfer<'_, BUF, Async> { + /// Waits for a DMA EOF or receive error in this transfer. + /// + /// The EOF boundary is configured by [`Config::with_eof_mode`]. + /// Reception can start partway through a frame, so EOF alone does not + /// guarantee that a complete frame has been received. + /// + /// This does not stop the camera or DMA. Call [`Self::stop`] to return + /// the camera and buffer. After a successful wait, another call can wait + /// for a later EOF. Receive errors are retained for this transfer. + /// EOF status is latched: multiple EOFs before the wait consumes the status + /// are reported as one event. + /// + /// # Errors + /// + /// Returns [`DmaError::DescriptorError`] if DMA reports an invalid + /// descriptor, descriptor exhaustion, or an error EOF. + /// Receive errors take precedence over a pending EOF. + /// + /// # Cancellation Safety + /// + /// Dropping the future does not stop the camera or DMA. The wait can be retried. + pub async fn wait_for_dma_eof(&mut self) -> Result<(), DmaError> { + if let Some(error) = self.eof_error { + return Err(error); + } + let result = DmaRxFuture::new(&mut self.camera.rx_channel).await; + if let Err(error) = result { + self.eof_error = Some(error); + } + result + } +} + +impl Deref for CameraTransfer<'_, BUF, Dm> { type Target = BUF::View; fn deref(&self) -> &Self::Target { @@ -546,13 +641,13 @@ impl Deref for CameraTransfer<'_, BUF> { } } -impl DerefMut for CameraTransfer<'_, BUF> { +impl DerefMut for CameraTransfer<'_, BUF, Dm> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.buffer_view } } -impl Drop for CameraTransfer<'_, BUF> { +impl Drop for CameraTransfer<'_, BUF, Dm> { fn drop(&mut self) { self.stop_peripherals(); @@ -572,7 +667,7 @@ pub struct Config { /// The pixel clock frequency for the camera interface. frequency: Rate, - /// Enable 16 bit mode (instead of 8 bit). + /// Enables 16 bit mode (instead of 8 bit). enable_2byte_mode: bool, /// The byte order for the camera data. @@ -596,16 +691,16 @@ pub struct Config { /// This is a 7 bit value which means a max of 128 lines. line_interrupt: Option, - /// Invert VSYNC signal, valid in high level. + /// Inverts VSYNC signal, valid in high level. invert_vsync: bool, - /// Invert HSYNC signal, valid in high level. + /// Inverts HSYNC signal, valid in high level. invert_hsync: bool, - /// Invert H_ENABLE signal (Also known as "Data Enable"), valid in high level. + /// Inverts H_ENABLE signal (Also known as "Data Enable"), valid in high level. invert_h_enable: bool, - /// Invert PCLK signal. + /// Inverts PCLK signal. invert_pixel_clock: bool, } diff --git a/esp-hal/src/lcd_cam/lcd/dpi.rs b/esp-hal/src/lcd_cam/lcd/dpi.rs index d98bb94074a..b152c7dc3f5 100644 --- a/esp-hal/src/lcd_cam/lcd/dpi.rs +++ b/esp-hal/src/lcd_cam/lcd/dpi.rs @@ -1,4 +1,29 @@ -#![cfg_attr(docsrs, procmacros::doc_replace)] +#![cfg_attr(docsrs, procmacros::doc_replace( + "dma_channel" => { + cfg(lcd_cam_dma_engine = "AHB_GDMA") => "DMA_CH0", + cfg(lcd_cam_dma_engine = "AXI_GDMA") => "DMA_AXI_CH0", + }, + "vsync_pin" => gpio_for_signal!(LCD_V_SYNC, "GPIO3"), + "hsync_pin" => gpio_for_signal!(LCD_H_SYNC, "GPIO46"), + "de_pin" => gpio_for_signal!(LCD_H_ENABLE, "GPIO43"), + "pclk_pin" => gpio_for_signal!(LCD_PCLK, "GPIO9"), + "data0_pin" => gpio_for_signal!(LCD_DATA_0, "GPIO10"), + "data1_pin" => gpio_for_signal!(LCD_DATA_1, "GPIO11"), + "data2_pin" => gpio_for_signal!(LCD_DATA_2, "GPIO12"), + "data3_pin" => gpio_for_signal!(LCD_DATA_3, "GPIO13"), + "data4_pin" => gpio_for_signal!(LCD_DATA_4, "GPIO14"), + "data5_pin" => gpio_for_signal!(LCD_DATA_5, "GPIO21"), + "data6_pin" => gpio_for_signal!(LCD_DATA_6, "GPIO8"), + "data7_pin" => gpio_for_signal!(LCD_DATA_7, "GPIO18"), + "data8_pin" => gpio_for_signal!(LCD_DATA_8, "GPIO45"), + "data9_pin" => gpio_for_signal!(LCD_DATA_9, "GPIO38"), + "data10_pin" => gpio_for_signal!(LCD_DATA_10, "GPIO39"), + "data11_pin" => gpio_for_signal!(LCD_DATA_11, "GPIO40"), + "data12_pin" => gpio_for_signal!(LCD_DATA_12, "GPIO41"), + "data13_pin" => gpio_for_signal!(LCD_DATA_13, "GPIO42"), + "data14_pin" => gpio_for_signal!(LCD_DATA_14, "GPIO2"), + "data15_pin" => gpio_for_signal!(LCD_DATA_15, "GPIO1"), +))] //! # LCD - RGB/Digital Parallel Interface Mode //! //! ## Overview @@ -26,7 +51,7 @@ //! # }; //! # use esp_hal::dma_loop_buffer; //! -//! # let channel = peripherals.DMA_CH0; +//! # let channel = peripherals.__dma_channel__; //! # let mut dma_buf = dma_loop_buffer!(32); //! //! let lcd_cam = LcdCam::new(peripherals.LCD_CAM); @@ -61,29 +86,29 @@ //! .with_disable_black_region(false); //! //! let mut dpi = Dpi::new(lcd_cam.lcd, channel, config)? -//! .with_vsync(peripherals.GPIO3) -//! .with_hsync(peripherals.GPIO46) -//! .with_de(peripherals.GPIO17) -//! .with_pclk(peripherals.GPIO9) +//! .with_vsync(peripherals.__vsync_pin__) +//! .with_hsync(peripherals.__hsync_pin__) +//! .with_de(peripherals.__de_pin__) +//! .with_pclk(peripherals.__pclk_pin__) //! // Blue -//! .with_data0(peripherals.GPIO10) -//! .with_data1(peripherals.GPIO11) -//! .with_data2(peripherals.GPIO12) -//! .with_data3(peripherals.GPIO13) -//! .with_data4(peripherals.GPIO14) +//! .with_data0(peripherals.__data0_pin__) +//! .with_data1(peripherals.__data1_pin__) +//! .with_data2(peripherals.__data2_pin__) +//! .with_data3(peripherals.__data3_pin__) +//! .with_data4(peripherals.__data4_pin__) //! // Green -//! .with_data5(peripherals.GPIO21) -//! .with_data6(peripherals.GPIO8) -//! .with_data7(peripherals.GPIO18) -//! .with_data8(peripherals.GPIO45) -//! .with_data9(peripherals.GPIO38) -//! .with_data10(peripherals.GPIO39) +//! .with_data5(peripherals.__data5_pin__) +//! .with_data6(peripherals.__data6_pin__) +//! .with_data7(peripherals.__data7_pin__) +//! .with_data8(peripherals.__data8_pin__) +//! .with_data9(peripherals.__data9_pin__) +//! .with_data10(peripherals.__data10_pin__) //! // Red -//! .with_data11(peripherals.GPIO40) -//! .with_data12(peripherals.GPIO41) -//! .with_data13(peripherals.GPIO42) -//! .with_data14(peripherals.GPIO2) -//! .with_data15(peripherals.GPIO1); +//! .with_data11(peripherals.__data11_pin__) +//! .with_data12(peripherals.__data12_pin__) +//! .with_data13(peripherals.__data13_pin__) +//! .with_data14(peripherals.__data14_pin__) +//! .with_data15(peripherals.__data15_pin__); //! //! let color: u16 = 0b11111_000000_00000; // RED //! for chunk in dma_buf.chunks_mut(2) { @@ -100,7 +125,10 @@ use core::{ ops::{Deref, DerefMut}, }; +use enumset::{EnumSet, EnumSetType}; + use crate::{ + Async, Blocking, DriverMode, dma::{ChannelTx, DmaError, DmaPeripheral, DmaTxBuffer}, @@ -110,13 +138,28 @@ use crate::{ ByteOrder, ClockError, ErasedTxChannel, + Instance, + LCD_VSYNC_WAKER, + LcdCamInterrupt, LcdDmaTxChannel, lcd::{ClockConfig, ClockMode, DelayMode, Lcd}, + ll, }, pac, time::Rate, }; +/// LCD interrupt sources relevant to an RGB/DPI transfer. +/// +/// These sources can be polled without enabling the CPU interrupt. +#[derive(Debug, EnumSetType)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[instability::unstable] +pub enum DpiInterrupt { + /// The LCD has started outputting a new frame. + Vsync, +} + /// Errors that can occur when configuring the DPI peripheral. #[derive(Debug, Clone, Copy, PartialEq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] @@ -135,7 +178,7 @@ impl<'d, Dm> Dpi<'d, Dm> where Dm: DriverMode, { - /// Create a new instance of the RGB/DPI driver. + /// Creates a new instance of the RGB/DPI driver. pub fn new( lcd: Lcd<'d, Dm>, channel: impl LcdDmaTxChannel<'d>, @@ -159,16 +202,18 @@ where /// /// # Errors /// - /// [`ConfigError::Clock`] variant will be returned if the frequency passed - /// in `Config` is too low. + /// [`ConfigError::Clock`] when the frequency passed in `Config` is too low. pub fn apply_config(&mut self, config: &Config) -> Result<(), ConfigError> { self.lcd .configure_clocks(&ClockConfig { clock_mode: config.clock_mode, - // Due to https://www.espressif.com/sites/default/files/documentation/esp32-s3_errata_en.pdf - // the LCD_PCLK divider must be at least 2. To make up for this the user - // provided frequency is doubled to match. - frequency: config.frequency * 2, + // ESP32-S3 errata requires LCD_PCLK to divide LCD_CLK by at least 2. + // Double the requested frequency so the extra divider still matches. + frequency: if cfg!(esp32s3) { + config.frequency * 2 + } else { + config.frequency + }, }) .map_err(ConfigError::Clock)?; @@ -176,23 +221,17 @@ where .lcd_user() .modify(|_, w| w.lcd_reset().set_bit()); - self.regs() - .lcd_rgb_yuv() - .write(|w| w.lcd_conv_bypass().clear_bit()); + ll::set_lcd_conv_bypass(self.regs()); self.regs().lcd_user().modify(|_, w| { if config.format.enable_2byte_mode { - w.lcd_8bits_order().bit(false); w.lcd_byte_order() .bit(config.format.byte_order == ByteOrder::Inverted); } else { - w.lcd_8bits_order() - .bit(config.format.byte_order == ByteOrder::Inverted); w.lcd_byte_order().bit(false); } w.lcd_bit_order() .bit(config.format.bit_order == BitOrder::Inverted); - w.lcd_2byte_en().bit(config.format.enable_2byte_mode); // Only valid in Intel8080 mode. w.lcd_cmd().clear_bit(); @@ -201,42 +240,31 @@ where // This needs to be explicitly set for RGB mode. w.lcd_dout().set_bit() }); + ll::set_8bits_order( + self.regs(), + !config.format.enable_2byte_mode && config.format.byte_order == ByteOrder::Inverted, + ); + ll::set_2byte_mode(self.regs(), config.format.enable_2byte_mode); let timing = &config.timing; - self.regs().lcd_ctrl().modify(|_, w| unsafe { - // Enable RGB mode, and input VSYNC, HSYNC, and DE signals. - w.lcd_rgb_mode_en().set_bit(); - - w.lcd_hb_front() - .bits((timing.horizontal_blank_front_porch as u16).saturating_sub(1)); - w.lcd_va_height() - .bits((timing.vertical_active_height as u16).saturating_sub(1)); - w.lcd_vt_height() - .bits((timing.vertical_total_height as u16).saturating_sub(1)) - }); - self.regs().lcd_ctrl1().modify(|_, w| unsafe { - w.lcd_vb_front() - .bits((timing.vertical_blank_front_porch as u8).saturating_sub(1)); - w.lcd_ha_width() - .bits((timing.horizontal_active_width as u16).saturating_sub(1)); - w.lcd_ht_width() - .bits((timing.horizontal_total_width as u16).saturating_sub(1)) - }); - self.regs().lcd_ctrl2().modify(|_, w| unsafe { - w.lcd_vsync_width() - .bits((timing.vsync_width as u8).saturating_sub(1)); - w.lcd_vsync_idle_pol().bit(config.vsync_idle_level.into()); - w.lcd_de_idle_pol().bit(config.de_idle_level.into()); - w.lcd_hs_blank_en().bit(config.hs_blank_en); - w.lcd_hsync_width() - .bits((timing.hsync_width as u8).saturating_sub(1)); - w.lcd_hsync_idle_pol().bit(config.hsync_idle_level.into()); - w.lcd_hsync_position().bits(timing.hsync_position as u8) - }); - + ll::configure_rgb_timing( + self.regs(), + (timing.horizontal_blank_front_porch as u16).saturating_sub(1), + (timing.vertical_active_height as u16).saturating_sub(1), + (timing.vertical_total_height as u16).saturating_sub(1), + (timing.vertical_blank_front_porch as u16).saturating_sub(1), + (timing.horizontal_active_width as u16).saturating_sub(1), + (timing.horizontal_total_width as u16).saturating_sub(1), + (timing.vsync_width as u16).saturating_sub(1), + config.vsync_idle_level.into(), + config.de_idle_level.into(), + config.hs_blank_en, + (timing.hsync_width as u8).saturating_sub(1), + config.hsync_idle_level.into(), + timing.hsync_position as u8, + ); self.regs().lcd_misc().modify(|_, w| unsafe { - // TODO: Find out what this field actually does. - // Set the threshold for Async Tx FIFO full event. (5 bits) + #[cfg(not(esp32s31))] w.lcd_afifo_threshold_num().bits((1 << 5) - 1); // Doesn't matter for RGB mode. @@ -250,30 +278,13 @@ where // Enable blank region when LCD sends data out. w.lcd_bk_en().bit(!config.disable_black_region) }); - self.regs().lcd_dly_mode().modify(|_, w| unsafe { - w.lcd_de_mode().bits(config.de_mode as u8); - w.lcd_hsync_mode().bits(config.hsync_mode as u8); - w.lcd_vsync_mode().bits(config.vsync_mode as u8); - w - }); - self.regs().lcd_data_dout_mode().modify(|_, w| unsafe { - w.dout0_mode().bits(config.output_bit_mode as u8); - w.dout1_mode().bits(config.output_bit_mode as u8); - w.dout2_mode().bits(config.output_bit_mode as u8); - w.dout3_mode().bits(config.output_bit_mode as u8); - w.dout4_mode().bits(config.output_bit_mode as u8); - w.dout5_mode().bits(config.output_bit_mode as u8); - w.dout6_mode().bits(config.output_bit_mode as u8); - w.dout7_mode().bits(config.output_bit_mode as u8); - w.dout8_mode().bits(config.output_bit_mode as u8); - w.dout9_mode().bits(config.output_bit_mode as u8); - w.dout10_mode().bits(config.output_bit_mode as u8); - w.dout11_mode().bits(config.output_bit_mode as u8); - w.dout12_mode().bits(config.output_bit_mode as u8); - w.dout13_mode().bits(config.output_bit_mode as u8); - w.dout14_mode().bits(config.output_bit_mode as u8); - w.dout15_mode().bits(config.output_bit_mode as u8) - }); + ll::set_sync_delay( + self.regs(), + config.de_mode as u8, + config.hsync_mode as u8, + config.vsync_mode as u8, + ); + ll::set_data_bit_delay(self.regs(), config.output_bit_mode as u8); self.regs() .lcd_user() @@ -282,7 +293,7 @@ where Ok(()) } - /// Assign the VSYNC pin for the LCD_CAM. + /// Assigns the VSYNC pin for the LCD_CAM. /// /// Sets the specified pin to push-pull output and connects it to the VSYNC /// signal. @@ -295,7 +306,7 @@ where self } - /// Assign the HSYNC pin for the LCD_CAM. + /// Assigns the HSYNC pin for the LCD_CAM. /// /// Sets the specified pin to push-pull output and connects it to the HSYNC /// signal. @@ -308,7 +319,7 @@ where self } - /// Assign the DE pin for the LCD_CAM. + /// Assigns the DE pin for the LCD_CAM. /// /// Sets the specified pin to push-pull output and connects it to the DE /// signal. @@ -321,7 +332,7 @@ where self } - /// Assign the PCLK pin for the LCD_CAM. + /// Assigns the PCLK pin for the LCD_CAM. /// /// Sets the specified pin to push-pull output and connects it to the PCLK /// signal. @@ -344,7 +355,7 @@ where self } - /// Assign the DATA_0 pin for the LCD_CAM. + /// Assigns the DATA_0 pin for the LCD_CAM. /// /// Sets the specified pin to push-pull output and connects it to the DATA_0 /// signal. @@ -352,7 +363,7 @@ where self.with_data_pin(OutputSignal::LCD_DATA_0, pin) } - /// Assign the DATA_1 pin for the LCD_CAM. + /// Assigns the DATA_1 pin for the LCD_CAM. /// /// Sets the specified pin to push-pull output and connects it to the DATA_1 /// signal. @@ -360,7 +371,7 @@ where self.with_data_pin(OutputSignal::LCD_DATA_1, pin) } - /// Assign the DATA_2 pin for the LCD_CAM. + /// Assigns the DATA_2 pin for the LCD_CAM. /// /// Sets the specified pin to push-pull output and connects it to the DATA_2 /// signal. @@ -368,7 +379,7 @@ where self.with_data_pin(OutputSignal::LCD_DATA_2, pin) } - /// Assign the DATA_3 pin for the LCD_CAM. + /// Assigns the DATA_3 pin for the LCD_CAM. /// /// Sets the specified pin to push-pull output and connects it to the DATA_3 /// signal. @@ -376,7 +387,7 @@ where self.with_data_pin(OutputSignal::LCD_DATA_3, pin) } - /// Assign the DATA_4 pin for the LCD_CAM. + /// Assigns the DATA_4 pin for the LCD_CAM. /// /// Sets the specified pin to push-pull output and connects it to the DATA_4 /// signal. @@ -384,7 +395,7 @@ where self.with_data_pin(OutputSignal::LCD_DATA_4, pin) } - /// Assign the DATA_5 pin for the LCD_CAM. + /// Assigns the DATA_5 pin for the LCD_CAM. /// /// Sets the specified pin to push-pull output and connects it to the DATA_5 /// signal. @@ -392,7 +403,7 @@ where self.with_data_pin(OutputSignal::LCD_DATA_5, pin) } - /// Assign the DATA_6 pin for the LCD_CAM. + /// Assigns the DATA_6 pin for the LCD_CAM. /// /// Sets the specified pin to push-pull output and connects it to the DATA_6 /// signal. @@ -400,7 +411,7 @@ where self.with_data_pin(OutputSignal::LCD_DATA_6, pin) } - /// Assign the DATA_7 pin for the LCD_CAM. + /// Assigns the DATA_7 pin for the LCD_CAM. /// /// Sets the specified pin to push-pull output and connects it to the DATA_7 /// signal. @@ -408,7 +419,7 @@ where self.with_data_pin(OutputSignal::LCD_DATA_7, pin) } - /// Assign the DATA_8 pin for the LCD_CAM. + /// Assigns the DATA_8 pin for the LCD_CAM. /// /// Sets the specified pin to push-pull output and connects it to the DATA_8 /// signal. @@ -416,7 +427,7 @@ where self.with_data_pin(OutputSignal::LCD_DATA_8, pin) } - /// Assign the DATA_9 pin for the LCD_CAM. + /// Assigns the DATA_9 pin for the LCD_CAM. /// /// Sets the specified pin to push-pull output and connects it to the DATA_9 /// signal. @@ -424,7 +435,7 @@ where self.with_data_pin(OutputSignal::LCD_DATA_9, pin) } - /// Assign the DATA_10 pin for the LCD_CAM. + /// Assigns the DATA_10 pin for the LCD_CAM. /// /// Sets the specified pin to push-pull output and connects it to the /// DATA_10 signal. @@ -432,7 +443,7 @@ where self.with_data_pin(OutputSignal::LCD_DATA_10, pin) } - /// Assign the DATA_11 pin for the LCD_CAM. + /// Assigns the DATA_11 pin for the LCD_CAM. /// /// Sets the specified pin to push-pull output and connects it to the /// DATA_11 signal. @@ -440,7 +451,7 @@ where self.with_data_pin(OutputSignal::LCD_DATA_11, pin) } - /// Assign the DATA_12 pin for the LCD_CAM. + /// Assigns the DATA_12 pin for the LCD_CAM. /// /// Sets the specified pin to push-pull output and connects it to the /// DATA_12 signal. @@ -448,7 +459,7 @@ where self.with_data_pin(OutputSignal::LCD_DATA_12, pin) } - /// Assign the DATA_13 pin for the LCD_CAM. + /// Assigns the DATA_13 pin for the LCD_CAM. /// /// Sets the specified pin to push-pull output and connects it to the /// DATA_13 signal. @@ -456,7 +467,7 @@ where self.with_data_pin(OutputSignal::LCD_DATA_13, pin) } - /// Assign the DATA_14 pin for the LCD_CAM. + /// Assigns the DATA_14 pin for the LCD_CAM. /// /// Sets the specified pin to push-pull output and connects it to the /// DATA_14 signal. @@ -464,7 +475,7 @@ where self.with_data_pin(OutputSignal::LCD_DATA_14, pin) } - /// Assign the DATA_15 pin for the LCD_CAM. + /// Assigns the DATA_15 pin for the LCD_CAM. /// /// Sets the specified pin to push-pull output and connects it to the /// DATA_15 signal. @@ -481,16 +492,10 @@ where next_frame_en: bool, mut buf: TX, ) -> Result, (DmaError, Self, TX)> { - let result = unsafe { - self.tx_channel - .prepare_transfer(DmaPeripheral::LCD_CAM, &mut buf) - } - .and_then(|_| self.tx_channel.start_transfer()); - if let Err(err) = result { - return Err((err, self, buf)); - } + Instance::clear_interrupts(LcdCamInterrupt::LcdVsync.into()); - // Reset LCD control unit and Async Tx FIFO + // Reset before DMA start. AXI-GDMA can fill the LCD AFIFO immediately; a later + // FIFO reset would drop the first pixels of the frame. self.regs() .lcd_user() .modify(|_, w| w.lcd_reset().set_bit()); @@ -504,6 +509,15 @@ where w.lcd_next_frame_en().bit(next_frame_en) }); + let result = unsafe { + self.tx_channel + .prepare_transfer(DmaPeripheral::LCD_CAM, &mut buf) + } + .and_then(|_| self.tx_channel.start_transfer()); + if let Err(err) = result { + return Err((err, self, buf)); + } + // Start the transfer. self.regs().lcd_user().modify(|_, w| { w.lcd_update().set_bit(); @@ -525,7 +539,33 @@ pub struct DpiTransfer<'d, BUF: DmaTxBuffer, Dm: DriverMode> { } impl<'d, BUF: DmaTxBuffer, Dm: DriverMode> DpiTransfer<'d, BUF, Dm> { - /// Returns true when [Self::wait] will not block. + /// Returns the asserted LCD interrupt sources for this transfer. + /// + /// Each source is a latched flag, so repeated events before clearing are + /// reported as one. This reads raw status and does not require interrupt + /// listening to be enabled. + #[instability::unstable] + pub fn interrupts(&self) -> EnumSet { + let sources = Instance::interrupts(); + let mut interrupts = EnumSet::new(); + if sources.contains(LcdCamInterrupt::LcdVsync) { + interrupts.insert(DpiInterrupt::Vsync); + } + interrupts + } + + /// Clears the selected LCD interrupt sources. + #[instability::unstable] + pub fn clear_interrupts(&self, interrupts: impl Into>) { + let interrupts = interrupts.into(); + let mut sources = EnumSet::new(); + if interrupts.contains(DpiInterrupt::Vsync) { + sources.insert(LcdCamInterrupt::LcdVsync); + } + Instance::clear_interrupts(sources); + } + + /// Returns whether [`Self::wait`] will not block. pub fn is_done(&self) -> bool { self.dpi.regs().lcd_user().read().lcd_start().bit_is_clear() } @@ -539,8 +579,8 @@ impl<'d, BUF: DmaTxBuffer, Dm: DriverMode> DpiTransfer<'d, BUF, Dm> { /// Waits for the transfer to finish and returns the peripheral and buffer. /// - /// Note: If you specified `next_frame_en` as true in [Dpi::send], you're - /// just waiting for a DMA error when you call this. + /// If `next_frame_en` was specified as true in [`Dpi::send`], this waits + /// for a DMA error. pub fn wait(mut self) -> (Result<(), DmaError>, Dpi<'d, Dm>, BUF::Final) { while !self.is_done() { core::hint::spin_loop(); @@ -588,6 +628,67 @@ impl<'d, BUF: DmaTxBuffer, Dm: DriverMode> DpiTransfer<'d, BUF, Dm> { } } +impl DpiTransfer<'_, BUF, Blocking> { + /// Waits for a pending LCD VSYNC event and clears it. + /// + /// If a VSYNC event is already pending, this returns immediately. The + /// transfer must remain active for another VSYNC to occur. Clear + /// [`DpiInterrupt::Vsync`] with [`Self::clear_interrupts`] first to wait for + /// a fresh event. + #[instability::unstable] + pub fn wait_for_vsync(&mut self) { + let vsync = LcdCamInterrupt::LcdVsync; + while !Instance::interrupts().contains(vsync) { + core::hint::spin_loop(); + } + Instance::clear_interrupts(vsync.into()); + } +} + +impl DpiTransfer<'_, BUF, Async> { + /// Waits for the next pending LCD VSYNC event and clears it. + /// + /// If a VSYNC event is already pending, this returns immediately. The + /// transfer must remain active for another VSYNC to occur. Clear + /// [`DpiInterrupt::Vsync`] with [`Self::clear_interrupts`] first to wait for + /// a fresh event. + #[instability::unstable] + pub async fn wait_for_vsync(&mut self) { + use core::{ + future::Future, + pin::Pin, + task::{Context, Poll}, + }; + + #[must_use = "futures do nothing unless you `.await` or poll them"] + struct VsyncFuture; + + impl Future for VsyncFuture { + type Output = (); + + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + let vsync = LcdCamInterrupt::LcdVsync; + if Instance::interrupts().contains(vsync) { + Instance::clear_interrupts(vsync.into()); + Poll::Ready(()) + } else { + LCD_VSYNC_WAKER.register(cx.waker()); + Instance::listen(vsync.into()); + Poll::Pending + } + } + } + + impl Drop for VsyncFuture { + fn drop(&mut self) { + Instance::unlisten(LcdCamInterrupt::LcdVsync.into()); + } + } + + VsyncFuture.await + } +} + impl Deref for DpiTransfer<'_, BUF, Dm> { type Target = BUF::View; @@ -700,9 +801,9 @@ pub struct Format { /// The timing numbers for the driver to follow. /// -/// Note: The names of the fields in this struct don't match what you -/// would typically find in an LCD's datasheet. Carefully read the doc on each -/// field to understand what to set it to. +/// The names of the fields in this struct do not match what is typically found +/// in an LCD datasheet. Carefully read the doc on each field to understand what +/// to set it to. #[derive(Debug, Clone, Copy, PartialEq, Default)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub struct FrameTiming { @@ -719,7 +820,7 @@ pub struct FrameTiming { /// This is the number of PCLKs between the start of the line and the start /// of active data in the line. /// - /// Note: This includes `hsync_width`. + /// Includes `hsync_width`. /// /// Max is 2048 (11 bits). pub horizontal_blank_front_porch: usize, @@ -743,7 +844,7 @@ pub struct FrameTiming { /// This is the number of (blank/invalid) lines before the start of the /// frame. /// - /// Note: This includes `vsync_width`. + /// Includes `vsync_width`. /// /// Max is 256 (8 bits). pub vertical_blank_front_porch: usize, diff --git a/esp-hal/src/lcd_cam/lcd/i8080.rs b/esp-hal/src/lcd_cam/lcd/i8080.rs index 4a3296a6316..801fbb7ae6d 100644 --- a/esp-hal/src/lcd_cam/lcd/i8080.rs +++ b/esp-hal/src/lcd_cam/lcd/i8080.rs @@ -1,4 +1,19 @@ -#![cfg_attr(docsrs, procmacros::doc_replace)] +#![cfg_attr(docsrs, procmacros::doc_replace( + "dma_channel" => { + cfg(lcd_cam_dma_engine = "AHB_GDMA") => "DMA_CH0", + cfg(lcd_cam_dma_engine = "AXI_GDMA") => "DMA_AXI_CH0", + }, + "dc_pin" => gpio_for_signal!(LCD_DC, "GPIO0"), + "wrx_pin" => gpio_for_signal!(LCD_PCLK, "GPIO47"), + "data0_pin" => gpio_for_signal!(LCD_DATA_0, "GPIO9"), + "data1_pin" => gpio_for_signal!(LCD_DATA_1, "GPIO46"), + "data2_pin" => gpio_for_signal!(LCD_DATA_2, "GPIO3"), + "data3_pin" => gpio_for_signal!(LCD_DATA_3, "GPIO8"), + "data4_pin" => gpio_for_signal!(LCD_DATA_4, "GPIO18"), + "data5_pin" => gpio_for_signal!(LCD_DATA_5, "GPIO17"), + "data6_pin" => gpio_for_signal!(LCD_DATA_6, "GPIO16"), + "data7_pin" => gpio_for_signal!(LCD_DATA_7, "GPIO15"), +))] //! # LCD - I8080/MOTO6800 Mode. //! //! ## Overview @@ -26,23 +41,77 @@ //! //! let config = Config::default().with_frequency(Rate::from_mhz(20)); //! -//! let mut i8080 = I8080::new(lcd_cam.lcd, peripherals.DMA_CH0, config)? -//! .with_dc(peripherals.GPIO0) -//! .with_wrx(peripherals.GPIO47) -//! .with_data0(peripherals.GPIO9) -//! .with_data1(peripherals.GPIO46) -//! .with_data2(peripherals.GPIO3) -//! .with_data3(peripherals.GPIO8) -//! .with_data4(peripherals.GPIO18) -//! .with_data5(peripherals.GPIO17) -//! .with_data6(peripherals.GPIO16) -//! .with_data7(peripherals.GPIO15); +//! let mut i8080 = I8080::new(lcd_cam.lcd, peripherals.__dma_channel__, config)? +//! .with_dc(peripherals.__dc_pin__) +//! .with_wrx(peripherals.__wrx_pin__) +//! .with_data0(peripherals.__data0_pin__) +//! .with_data1(peripherals.__data1_pin__) +//! .with_data2(peripherals.__data2_pin__) +//! .with_data3(peripherals.__data3_pin__) +//! .with_data4(peripherals.__data4_pin__) +//! .with_data5(peripherals.__data5_pin__) +//! .with_data6(peripherals.__data6_pin__) +//! .with_data7(peripherals.__data7_pin__); //! //! dma_buf.fill(&[0x55]); //! let transfer = i8080.send(0x3Au8, 0, dma_buf)?; // RGB565 //! transfer.wait(); //! # {after_snippet} //! ``` +//! +//! ## Interrupts +//! +//! The I8080 driver owns two interrupt domains: the LCD half of the LCD_CAM +//! peripheral, and the DMA TX channel it was created with. The LCD sources +//! fire on the `LCD_CAM` interrupt, while the DMA sources fire on the DMA +//! channel's own interrupt, so each domain binds its own handler and controls +//! its sources separately. Handlers are registered with +//! [`I8080::set_interrupt_handler`] and [`I8080::set_dma_interrupt_handler`], +//! and sources are enabled with [`I8080::listen`] and [`I8080::listen_dma`]. +//! +//! ### Notifying on descriptor completion +//! +//! In continuous output mode the transfer does not finish, but every +//! descriptor with the `suc_eof` bit set raises the DMA channel's +//! [`DmaTxInterrupt::Eof`] source once its +//! data has been sent: +//! +//! ```rust, no_run +//! # {before_snippet} +//! # use esp_hal::dma::{DmaTxBuf, DmaTxInterrupt}; +//! # use esp_hal::dma_tx_buffer; +//! # use esp_hal::handler; +//! # use esp_hal::lcd_cam::{LcdCam, lcd::i8080::{Config, I8080}}; +//! # use esp_hal::time::Rate; +//! # +//! # static EOF_COUNT: core::sync::atomic::AtomicUsize = +//! # core::sync::atomic::AtomicUsize::new(0); +//! # let mut dma_buf = dma_tx_buffer!(32678)?; +//! # let lcd_cam = LcdCam::new(peripherals.LCD_CAM); +//! # let config = Config::default().with_frequency(Rate::from_mhz(20)); +//! # let mut i8080 = I8080::new(lcd_cam.lcd, peripherals.__dma_channel__, config)? +//! # .with_dc(peripherals.__dc_pin__) +//! # .with_wrx(peripherals.__wrx_pin__); +//! # dma_buf.fill(&[0x55]); +//! +//! #[handler] +//! fn dma_handler() { +//! EOF_COUNT.fetch_add(1, core::sync::atomic::Ordering::Relaxed); +//! // The source is cleared through the transfer, see below. +//! } +//! +//! // Binding the handler must happen before listening for DMA sources, and +//! // before `send` consumes the driver. +//! i8080.set_dma_interrupt_handler(dma_handler); +//! i8080.listen_dma(DmaTxInterrupt::Eof); +//! +//! let transfer = i8080.send(0x3Au8, 0, dma_buf)?; // RGB565 +//! +//! // In `dma_handler`, clear the source through the transfer: +//! // transfer.clear_interrupts_dma(DmaTxInterrupt::Eof); +//! transfer.wait(); +//! # {after_snippet} +//! ``` use core::{ fmt::Formatter, @@ -50,10 +119,12 @@ use core::{ ops::{Deref, DerefMut}, }; +use enumset::{EnumSet, EnumSetType}; + use crate::{ Blocking, DriverMode, - dma::{ChannelTx, DmaError, DmaPeripheral, DmaTxBuffer}, + dma::{ChannelTx, DmaError, DmaPeripheral, DmaTxBuffer, DmaTxInterrupt}, gpio::{OutputConfig, OutputSignal, interconnect::PeripheralOutput}, lcd_cam::{ BitOrder, @@ -65,6 +136,7 @@ use crate::{ Lcd, LcdDmaTxChannel, lcd::{ClockConfig, ClockMode, DelayMode}, + ll, }, pac, time::Rate, @@ -78,6 +150,24 @@ pub enum ConfigError { Clock(ClockError), } +/// Interrupt sources of the LCD half of the LCD_CAM peripheral, as exposed by +/// the [`I8080`] driver. +/// +/// These sources fire on the `LCD_CAM` interrupt, which is bound via +/// [`I8080::set_interrupt_handler`]. The DMA TX channel's sources fire on the +/// channel's own interrupt instead; see [`I8080::set_dma_interrupt_handler`] +/// and [`DmaTxInterrupt`]. +#[derive(Debug, EnumSetType)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[instability::unstable] +pub enum I8080Interrupt { + /// The LCD has started outputting a new frame. + Vsync, + + /// A DMA transfer to the LCD has finished. + TransDone, +} + /// Represents the I8080 LCD interface. pub struct I8080<'d, Dm: DriverMode> { lcd: Lcd<'d, Dm>, @@ -112,34 +202,32 @@ where /// /// # Errors /// - /// [`ConfigError::Clock`] variant will be returned if the frequency passed - /// in `Config` is too low. + /// [`ConfigError::Clock`] when the frequency passed in `Config` is too low. pub fn apply_config(&mut self, config: &Config) -> Result<(), ConfigError> { self.lcd .configure_clocks(&ClockConfig { clock_mode: config.clock_mode, - // Due to https://www.espressif.com/sites/default/files/documentation/esp32-s3_errata_en.pdf - // the LCD_PCLK divider must be at least 2. To make up for this the user - // provided frequency is doubled to match. - frequency: config.frequency * 2, + // ESP32-S3 errata requires LCD_PCLK to divide LCD_CLK by at least 2. + // Double the requested frequency so the extra divider still matches. + frequency: if cfg!(esp32s3) { + config.frequency * 2 + } else { + config.frequency + }, }) .map_err(ConfigError::Clock)?; - self.regs() - .lcd_ctrl() - .write(|w| w.lcd_rgb_mode_en().clear_bit()); - self.regs() - .lcd_rgb_yuv() - .write(|w| w.lcd_conv_bypass().clear_bit()); + ll::set_rgb_mode_en(self.regs(), false); + ll::set_lcd_conv_bypass(self.regs()); self.regs().lcd_user().modify(|_, w| { - w.lcd_8bits_order().bit(false); w.lcd_bit_order().bit(false); - w.lcd_byte_order().bit(false); - w.lcd_2byte_en().bit(false) + w.lcd_byte_order().bit(false) }); + ll::set_8bits_order(self.regs(), false); + ll::set_2byte_mode(self.regs(), false); self.regs().lcd_misc().write(|w| unsafe { - // Set the threshold for Async Tx FIFO full event. (5 bits) + #[cfg(not(esp32s31))] w.lcd_afifo_threshold_num().bits(0); // Configure the setup cycles in LCD non-RGB mode. Setup cycles // expected = this value + 1. (6 bit) @@ -169,27 +257,8 @@ where // The default value of LCD_CD w.lcd_cd_idle_edge().bit(config.cd_idle_edge) }); - self.regs() - .lcd_dly_mode() - .write(|w| unsafe { w.lcd_cd_mode().bits(config.cd_mode as u8) }); - self.regs().lcd_data_dout_mode().write(|w| unsafe { - w.dout0_mode().bits(config.output_bit_mode as u8); - w.dout1_mode().bits(config.output_bit_mode as u8); - w.dout2_mode().bits(config.output_bit_mode as u8); - w.dout3_mode().bits(config.output_bit_mode as u8); - w.dout4_mode().bits(config.output_bit_mode as u8); - w.dout5_mode().bits(config.output_bit_mode as u8); - w.dout6_mode().bits(config.output_bit_mode as u8); - w.dout7_mode().bits(config.output_bit_mode as u8); - w.dout8_mode().bits(config.output_bit_mode as u8); - w.dout9_mode().bits(config.output_bit_mode as u8); - w.dout10_mode().bits(config.output_bit_mode as u8); - w.dout11_mode().bits(config.output_bit_mode as u8); - w.dout12_mode().bits(config.output_bit_mode as u8); - w.dout13_mode().bits(config.output_bit_mode as u8); - w.dout14_mode().bits(config.output_bit_mode as u8); - w.dout15_mode().bits(config.output_bit_mode as u8) - }); + ll::set_cd_delay(self.regs(), config.cd_mode as u8); + ll::set_data_bit_delay(self.regs(), config.output_bit_mode as u8); self.regs() .lcd_user() @@ -214,9 +283,7 @@ where /// mode. pub fn set_8bits_order(&mut self, byte_order: ByteOrder) -> &mut Self { let is_inverted = byte_order != ByteOrder::default(); - self.regs() - .lcd_user() - .modify(|_, w| w.lcd_8bits_order().bit(is_inverted)); + ll::set_8bits_order(self.regs(), is_inverted); self } @@ -272,82 +339,82 @@ where self } - /// Associate a DATA 0 pin with the I8080 interface. + /// Associates a DATA 0 pin with the I8080 interface. pub fn with_data0(self, pin: impl PeripheralOutput<'d>) -> Self { self.with_data_pin(OutputSignal::LCD_DATA_0, pin) } - /// Associate a DATA 1 pin with the I8080 interface. + /// Associates a DATA 1 pin with the I8080 interface. pub fn with_data1(self, pin: impl PeripheralOutput<'d>) -> Self { self.with_data_pin(OutputSignal::LCD_DATA_1, pin) } - /// Associate a DATA 2 pin with the I8080 interface. + /// Associates a DATA 2 pin with the I8080 interface. pub fn with_data2(self, pin: impl PeripheralOutput<'d>) -> Self { self.with_data_pin(OutputSignal::LCD_DATA_2, pin) } - /// Associate a DATA 3 pin with the I8080 interface. + /// Associates a DATA 3 pin with the I8080 interface. pub fn with_data3(self, pin: impl PeripheralOutput<'d>) -> Self { self.with_data_pin(OutputSignal::LCD_DATA_3, pin) } - /// Associate a DATA 4 pin with the I8080 interface. + /// Associates a DATA 4 pin with the I8080 interface. pub fn with_data4(self, pin: impl PeripheralOutput<'d>) -> Self { self.with_data_pin(OutputSignal::LCD_DATA_4, pin) } - /// Associate a DATA 5 pin with the I8080 interface. + /// Associates a DATA 5 pin with the I8080 interface. pub fn with_data5(self, pin: impl PeripheralOutput<'d>) -> Self { self.with_data_pin(OutputSignal::LCD_DATA_5, pin) } - /// Associate a DATA 6 pin with the I8080 interface. + /// Associates a DATA 6 pin with the I8080 interface. pub fn with_data6(self, pin: impl PeripheralOutput<'d>) -> Self { self.with_data_pin(OutputSignal::LCD_DATA_6, pin) } - /// Associate a DATA 7 pin with the I8080 interface. + /// Associates a DATA 7 pin with the I8080 interface. pub fn with_data7(self, pin: impl PeripheralOutput<'d>) -> Self { self.with_data_pin(OutputSignal::LCD_DATA_7, pin) } - /// Associate a DATA 8 pin with the I8080 interface. + /// Associates a DATA 8 pin with the I8080 interface. pub fn with_data8(self, pin: impl PeripheralOutput<'d>) -> Self { self.with_data_pin(OutputSignal::LCD_DATA_8, pin) } - /// Associate a DATA 9 pin with the I8080 interface. + /// Associates a DATA 9 pin with the I8080 interface. pub fn with_data9(self, pin: impl PeripheralOutput<'d>) -> Self { self.with_data_pin(OutputSignal::LCD_DATA_9, pin) } - /// Associate a DATA 10 pin with the I8080 interface. + /// Associates a DATA 10 pin with the I8080 interface. pub fn with_data10(self, pin: impl PeripheralOutput<'d>) -> Self { self.with_data_pin(OutputSignal::LCD_DATA_10, pin) } - /// Associate a DATA 11 pin with the I8080 interface. + /// Associates a DATA 11 pin with the I8080 interface. pub fn with_data11(self, pin: impl PeripheralOutput<'d>) -> Self { self.with_data_pin(OutputSignal::LCD_DATA_11, pin) } - /// Associate a DATA 12 pin with the I8080 interface. + /// Associates a DATA 12 pin with the I8080 interface. pub fn with_data12(self, pin: impl PeripheralOutput<'d>) -> Self { self.with_data_pin(OutputSignal::LCD_DATA_12, pin) } - /// Associate a DATA 13 pin with the I8080 interface. + /// Associates a DATA 13 pin with the I8080 interface. pub fn with_data13(self, pin: impl PeripheralOutput<'d>) -> Self { self.with_data_pin(OutputSignal::LCD_DATA_13, pin) } - /// Associate a DATA 14 pin with the I8080 interface. + /// Associates a DATA 14 pin with the I8080 interface. pub fn with_data14(self, pin: impl PeripheralOutput<'d>) -> Self { self.with_data_pin(OutputSignal::LCD_DATA_14, pin) } - /// Associate a DATA 15 pin with the I8080 interface. + /// Associates a DATA 15 pin with the I8080 interface. pub fn with_data15(self, pin: impl PeripheralOutput<'d>) -> Self { self.with_data_pin(OutputSignal::LCD_DATA_15, pin) } @@ -357,8 +424,8 @@ where /// Passing a `Command` will make this an 8-bit transfer and a /// `Command` will make this a 16-bit transfer. /// - /// Note: A 16-bit transfer on an 8-bit bus will silently truncate the 2nd - /// byte and an 8-bit transfer on a 16-bit bus will silently pad each + /// A 16-bit transfer on an 8-bit bus silently truncates the 2nd + /// byte and an 8-bit transfer on a 16-bit bus silently pads each /// byte to 2 bytes. pub fn send + Copy, BUF: DmaTxBuffer>( mut self, @@ -388,19 +455,14 @@ where w.lcd_cmd().set_bit(); w.lcd_cmd_2_cycle_en().clear_bit() }); - self.regs() - .lcd_cmd_val() - .write(|w| unsafe { w.lcd_cmd_value().bits(value.into() as _) }); + ll::write_command(self.regs(), value.into() as u32, None); } Command::Two(first, second) => { self.regs().lcd_user().modify(|_, w| { w.lcd_cmd().set_bit(); w.lcd_cmd_2_cycle_en().set_bit() }); - let cmd = first.into() as u32 | ((second.into() as u32) << 16); - self.regs() - .lcd_cmd_val() - .write(|w| unsafe { w.lcd_cmd_value().bits(cmd) }); + ll::write_command(self.regs(), first.into() as u32, Some(second.into() as u32)); } } @@ -417,11 +479,10 @@ where } else { w.lcd_dummy().clear_bit() } - .lcd_2byte_en() - .bit(is_2byte_mode) }); + ll::set_2byte_mode(self.regs(), is_2byte_mode); - // Use continous mode for DMA. FROM the S3 TRM: + // Use continuous mode for DMA. FROM the S3 TRM: // > In a continuous output, LCD module keeps sending data till: // > i. LCD_CAM_LCD_START is cleared; // > ii. or LCD_CAM_LCD_RESET is set; @@ -456,6 +517,140 @@ where } } +#[instability::unstable] +impl I8080<'_, Blocking> { + /// Maps the LCD sources of the given set onto the peripheral's interrupt + /// sources. + fn map_i8080_to_lcdcam( + interrupts: EnumSet, + ) -> enumset::EnumSet { + use crate::lcd_cam::LcdCamInterrupt; + + let mut sources = enumset::EnumSet::new(); + for interrupt in interrupts { + sources.insert(LcdCamInterrupt::from(interrupt)); + } + sources + } + + /// Maps the peripheral's asserted LCD interrupt sources back to + /// [`I8080Interrupt`]. + /// + /// The mapping is lossy by design: Camera-only [`LcdCamInterrupt`] + /// variants have no `I8080Interrupt` counterpart and are dropped. + fn map_lcdcam_to_i8080( + sources: enumset::EnumSet, + ) -> EnumSet { + let mut interrupts = enumset::EnumSet::new(); + for source in sources { + if let Ok(interrupt) = I8080Interrupt::try_from(source) { + interrupts.insert(interrupt); + } + } + interrupts + } + + /// Registers an interrupt handler for the `LCD_CAM` interrupt. + /// + /// The handler services the sources enabled via [`Self::listen`]. + /// + /// Note that this replaces any previously registered handler for the + /// `LCD_CAM` interrupt, including the one the async driver binds. + pub fn set_interrupt_handler(&mut self, handler: crate::interrupt::InterruptHandler) { + for core in crate::system::Cpu::other() { + crate::interrupt::disable(core, crate::peripherals::Interrupt::LCD_CAM); + } + crate::interrupt::bind_handler(crate::peripherals::Interrupt::LCD_CAM, handler); + } + + /// Registers an interrupt handler for the DMA TX channel used by this + /// driver. + /// + /// The handler services the sources enabled via [`Self::listen_dma`]. It + /// fires on the channel's own interrupt, which is separate from the + /// `LCD_CAM` interrupt used by [`Self::set_interrupt_handler`]. + /// + /// Binding the handler unlistens from and clears all DMA TX interrupt + /// sources, so this function must be called before + /// [`Self::listen_dma`]. It must also be called before [`Self::send`], + /// which consumes the driver. + pub fn set_dma_interrupt_handler(&mut self, handler: crate::interrupt::InterruptHandler) { + self.tx_channel.set_interrupt_handler(handler); + } + + /// Listens for the given LCD interrupt sources. + pub fn listen(&mut self, interrupts: impl Into>) { + Instance::listen(Self::map_i8080_to_lcdcam(interrupts.into())); + } + + /// Stops listening for the given LCD interrupt sources. + pub fn unlisten(&mut self, interrupts: impl Into>) { + Instance::unlisten(Self::map_i8080_to_lcdcam(interrupts.into())); + } + + /// Returns the asserted LCD interrupt sources. + pub fn interrupts(&mut self) -> EnumSet { + Self::map_lcdcam_to_i8080(Instance::interrupts()) + } + + /// Clears the given asserted LCD interrupt sources. + pub fn clear_interrupts(&mut self, interrupts: impl Into>) { + Instance::clear_interrupts(Self::map_i8080_to_lcdcam(interrupts.into())); + } + + /// Listens for the given DMA TX interrupt sources. + /// + /// A handler must have been registered via + /// [`Self::set_dma_interrupt_handler`] first. + pub fn listen_dma(&mut self, interrupts: impl Into>) { + self.tx_channel.listen_out(interrupts.into()); + } + + /// Stops listening for the given DMA TX interrupt sources. + pub fn unlisten_dma(&mut self, interrupts: impl Into>) { + self.tx_channel.unlisten_out(interrupts.into()); + } + + /// Returns the asserted DMA TX interrupt sources. + pub fn interrupts_dma(&mut self) -> EnumSet { + self.tx_channel.pending_out_interrupts() + } + + /// Clears the given asserted DMA TX interrupt sources. + pub fn clear_interrupts_dma(&mut self, interrupts: impl Into>) { + self.tx_channel.clear_out(interrupts.into()); + } +} + +/// Variant-for-variant mapping onto the peripheral's interrupt sources. +/// +/// This is total: every [`I8080Interrupt`] source has an +/// [`LcdCamInterrupt`] counterpart. Camera-only [`LcdCamInterrupt`] +/// variants are simply not reachable from [`I8080Interrupt`]. +impl From for crate::lcd_cam::LcdCamInterrupt { + fn from(value: I8080Interrupt) -> Self { + match value { + I8080Interrupt::Vsync => crate::lcd_cam::LcdCamInterrupt::LcdVsync, + I8080Interrupt::TransDone => crate::lcd_cam::LcdCamInterrupt::LcdTransDone, + } + } +} + +/// Lossy reverse mapping: Camera-only [`LcdCamInterrupt`] variants have no +/// [`I8080Interrupt`] counterpart and are dropped. +impl TryFrom for I8080Interrupt { + type Error = (); + + fn try_from(value: crate::lcd_cam::LcdCamInterrupt) -> Result { + match value { + crate::lcd_cam::LcdCamInterrupt::LcdVsync => Ok(I8080Interrupt::Vsync), + crate::lcd_cam::LcdCamInterrupt::LcdTransDone => Ok(I8080Interrupt::TransDone), + crate::lcd_cam::LcdCamInterrupt::CamVsync => Err(()), + crate::lcd_cam::LcdCamInterrupt::CamHs => Err(()), + } + } +} + impl core::fmt::Debug for I8080<'_, Dm> { fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { f.debug_struct("I8080").finish() @@ -470,7 +665,7 @@ pub struct I8080Transfer<'d, BUF: DmaTxBuffer, Dm: DriverMode> { } impl<'d, BUF: DmaTxBuffer, Dm: DriverMode> I8080Transfer<'d, BUF, Dm> { - /// Returns true when [Self::wait] will not block. + /// Returns whether [`Self::wait`] will not block. pub fn is_done(&self) -> bool { self.i8080 .regs() @@ -489,8 +684,8 @@ impl<'d, BUF: DmaTxBuffer, Dm: DriverMode> I8080Transfer<'d, BUF, Dm> { /// Waits for the transfer to finish and returns the peripheral and buffer. /// - /// Note: This also clears the transfer interrupt so it can be used in - /// interrupt handlers to "handle" the interrupt. + /// Also clears the transfer interrupt so it can be used in + /// interrupt handlers to handle the interrupt. pub fn wait(mut self) -> (Result<(), DmaError>, I8080<'d, Dm>, BUF::Final) { while !self.is_done() {} @@ -545,7 +740,7 @@ impl DerefMut for I8080Transfer<'_, BUF, Dm> { } impl I8080Transfer<'_, BUF, crate::Async> { - /// Waits for [Self::is_done] to return true. + /// Waits for [`Self::is_done`] to return true. pub async fn wait_for_done(&mut self) { use core::{ future::Future, @@ -584,6 +779,54 @@ impl I8080Transfer<'_, BUF, crate::Async> { } } +/// Interrupt management for an ongoing transfer. +/// +/// The driver itself has been consumed by [`I8080::send`], so these methods +/// take `&self` and allow an interrupt handler to manage the interrupt +/// sources through the transfer object. +#[instability::unstable] +impl I8080Transfer<'_, BUF, Blocking> { + /// Listens for the given LCD interrupt sources. + pub fn listen(&self, interrupts: impl Into>) { + Instance::listen(I8080::map_i8080_to_lcdcam(interrupts.into())); + } + + /// Stops listening for the given LCD interrupt sources. + pub fn unlisten(&self, interrupts: impl Into>) { + Instance::unlisten(I8080::map_i8080_to_lcdcam(interrupts.into())); + } + + /// Returns the asserted LCD interrupt sources. + pub fn interrupts(&self) -> EnumSet { + I8080::map_lcdcam_to_i8080(Instance::interrupts()) + } + + /// Clears the given asserted LCD interrupt sources. + pub fn clear_interrupts(&self, interrupts: impl Into>) { + Instance::clear_interrupts(I8080::map_i8080_to_lcdcam(interrupts.into())); + } + + /// Listens for the given DMA TX interrupt sources. + pub fn listen_dma(&self, interrupts: impl Into>) { + self.i8080.tx_channel.listen_out(interrupts.into()); + } + + /// Stops listening for the given DMA TX interrupt sources. + pub fn unlisten_dma(&self, interrupts: impl Into>) { + self.i8080.tx_channel.unlisten_out(interrupts.into()); + } + + /// Returns the asserted DMA TX interrupt sources. + pub fn interrupts_dma(&self) -> EnumSet { + self.i8080.tx_channel.pending_out_interrupts() + } + + /// Clears the given asserted DMA TX interrupt sources. + pub fn clear_interrupts_dma(&self, interrupts: impl Into>) { + self.i8080.tx_channel.clear_out(interrupts.into()); + } +} + impl Drop for I8080Transfer<'_, BUF, Dm> { fn drop(&mut self) { self.stop_peripherals(); @@ -611,7 +854,7 @@ pub struct Config { /// Setup cycles expected, must be at least 1. (6 bits) setup_cycles: usize, - /// Hold cycles expected, must be at least 1. (13 bits) + /// Holds cycles expected, must be at least 1. (13 bits) hold_cycles: usize, /// The default value of LCD_CD. diff --git a/esp-hal/src/lcd_cam/lcd/mod.rs b/esp-hal/src/lcd_cam/lcd/mod.rs index 2cb1bcbc8b6..a5baa7b2c0b 100644 --- a/esp-hal/src/lcd_cam/lcd/mod.rs +++ b/esp-hal/src/lcd_cam/lcd/mod.rs @@ -74,8 +74,14 @@ impl<'d, Dm: DriverMode> Lcd<'d, Dm> { self.regs().lcd_clock().write(|w| unsafe { // Force enable the clock for all configuration registers. w.clk_en().set_bit(); - w.lcd_clk_equ_sysclk().clear_bit(); - w.lcd_clkcnt_n().bits(2 - 1); // Must not be 0. + if cfg!(esp32s3) { + // ESP32-S3 errata: LCD_PCLK must divide LCD_CLK by at least 2. + w.lcd_clk_equ_sysclk().clear_bit(); + w.lcd_clkcnt_n().bits(2 - 1); // Must not be 0. + } else { + // ESP32-S31: PCLK tracks LCD_CLK. + w.lcd_clk_equ_sysclk().set_bit(); + } w.lcd_ck_idle_edge() .bit(config.clock_mode.polarity == Polarity::IdleHigh); w.lcd_ck_out_edge() diff --git a/esp-hal/src/lcd_cam/ll.rs b/esp-hal/src/lcd_cam/ll.rs new file mode 100644 index 00000000000..e52455e0041 --- /dev/null +++ b/esp-hal/src/lcd_cam/ll.rs @@ -0,0 +1,202 @@ +//! Chip-specific LCD_CAM register helpers. + +use crate::pac; + +pub(super) fn set_lcd_conv_bypass(regs: &pac::lcd_cam::RegisterBlock) { + regs.lcd_rgb_yuv().write(|w| { + cfg_select! { + esp32s31 => w.lcd_conv_enable().clear_bit(), + _ => w.lcd_conv_bypass().clear_bit(), + } + }); +} + +pub(super) fn set_cam_conv_bypass(regs: &pac::lcd_cam::RegisterBlock) { + regs.cam_rgb_yuv().write(|w| { + cfg_select! { + esp32s31 => w.cam_conv_enable().clear_bit(), + _ => w.cam_conv_bypass().clear_bit(), + } + }); +} + +pub(super) fn set_rgb_mode_en(regs: &pac::lcd_cam::RegisterBlock, enable: bool) { + let reg = cfg_select! { + esp32s3 => regs.lcd_ctrl(), + esp32s31 => regs.lcd_misc(), + }; + reg.modify(|_, w| w.lcd_rgb_mode_en().bit(enable)); +} + +pub(super) fn set_2byte_mode(regs: &pac::lcd_cam::RegisterBlock, enable: bool) { + regs.lcd_user().modify(|_, w| { + cfg_select! { + esp32s31 => unsafe { w.lcd_byte_mode().bits(if enable { 1 } else { 0 }) }, + _ => w.lcd_2byte_en().bit(enable), + } + }); +} + +pub(super) fn set_8bits_order(regs: &pac::lcd_cam::RegisterBlock, inverted: bool) { + regs.lcd_user().modify(|_, w| { + cfg_select! { + esp32s31 => unsafe { + w.lcd_dout_byte_swizzle_enable().bit(inverted); + w.lcd_dout_byte_swizzle_mode().bits(0) + }, + _ => w.lcd_8bits_order().bit(inverted), + } + }); +} + +pub(super) fn set_cd_delay(regs: &pac::lcd_cam::RegisterBlock, mode: u8) { + let reg = cfg_select! { + esp32s31 => regs.lcd_dly_mode_cfg1(), + _ => regs.lcd_dly_mode(), + }; + reg.write(|w| unsafe { w.lcd_cd_mode().bits(mode) }); +} + +pub(super) fn set_data_bit_delay(regs: &pac::lcd_cam::RegisterBlock, mode: u8) { + let dout_0_15 = cfg_select! { + esp32s31 => regs.lcd_dly_mode_cfg2(), + _ => regs.lcd_data_dout_mode(), + }; + + dout_0_15.write(|w| unsafe { + w.dout0_mode().bits(mode); + w.dout1_mode().bits(mode); + w.dout2_mode().bits(mode); + w.dout3_mode().bits(mode); + w.dout4_mode().bits(mode); + w.dout5_mode().bits(mode); + w.dout6_mode().bits(mode); + w.dout7_mode().bits(mode); + w.dout8_mode().bits(mode); + w.dout9_mode().bits(mode); + w.dout10_mode().bits(mode); + w.dout11_mode().bits(mode); + w.dout12_mode().bits(mode); + w.dout13_mode().bits(mode); + w.dout14_mode().bits(mode); + w.dout15_mode().bits(mode) + }); + + #[cfg(rgb_display_output_lines = "24")] + regs.lcd_dly_mode_cfg1().modify(|_, w| unsafe { + w.dout16_mode().bits(mode); + w.dout17_mode().bits(mode); + w.dout18_mode().bits(mode); + w.dout19_mode().bits(mode); + w.dout20_mode().bits(mode); + w.dout21_mode().bits(mode); + w.dout22_mode().bits(mode); + w.dout23_mode().bits(mode) + }); +} + +pub(super) fn set_sync_delay( + regs: &pac::lcd_cam::RegisterBlock, + de_mode: u8, + hsync_mode: u8, + vsync_mode: u8, +) { + let reg = cfg_select! { + esp32s31 => regs.lcd_dly_mode_cfg1(), + _ => regs.lcd_dly_mode(), + }; + + reg.modify(|_, w| unsafe { + w.lcd_de_mode().bits(de_mode); + w.lcd_hsync_mode().bits(hsync_mode); + w.lcd_vsync_mode().bits(vsync_mode) + }); +} + +pub(super) fn write_command(regs: &pac::lcd_cam::RegisterBlock, first: u32, second: Option) { + cfg_select! { + esp32s3 => { + let value = match second { + Some(second) => first | (second << 16), + None => first, + }; + regs.lcd_cmd_val() + .write(|w| unsafe { w.lcd_cmd_value().bits(value) }); + } + _ => { + regs.lcd_first_cmd_val() + .write(|w| unsafe { w.lcd_first_cmd_value().bits(first) }); + if let Some(second) = second { + regs.lcd_latter_cmd_val() + .write(|w| unsafe { w.lcd_latter_cmd_value().bits(second) }); + } + } + } +} + +#[expect(clippy::too_many_arguments)] +pub(super) fn configure_rgb_timing( + regs: &pac::lcd_cam::RegisterBlock, + hb_front: u16, + va_height: u16, + vt_height: u16, + vb_front: u16, + ha_width: u16, + ht_width: u16, + vsync_width: u16, + vsync_idle_high: bool, + de_idle_high: bool, + hs_blank_en: bool, + hsync_width: u8, + hsync_idle_high: bool, + hsync_position: u8, +) { + cfg_select! { + esp32s3 => { + regs.lcd_ctrl().modify(|_, w| unsafe { + w.lcd_rgb_mode_en().set_bit(); + w.lcd_hb_front().bits(hb_front); + w.lcd_va_height().bits(va_height); + w.lcd_vt_height().bits(vt_height) + }); + regs.lcd_ctrl1().modify(|_, w| unsafe { + w.lcd_vb_front().bits(vb_front as u8); + w.lcd_ha_width().bits(ha_width); + w.lcd_ht_width().bits(ht_width) + }); + regs.lcd_ctrl2().modify(|_, w| unsafe { + w.lcd_vsync_width().bits(vsync_width as u8); + w.lcd_vsync_idle_pol().bit(vsync_idle_high); + w.lcd_de_idle_pol().bit(de_idle_high); + w.lcd_hs_blank_en().bit(hs_blank_en); + w.lcd_hsync_width().bits(hsync_width); + w.lcd_hsync_idle_pol().bit(hsync_idle_high); + w.lcd_hsync_position().bits(hsync_position) + }); + } + _ => { + regs.lcd_misc().modify(|_, w| w.lcd_rgb_mode_en().set_bit()); + regs.lcd_rgb_blank().write(|w| unsafe { + w.lcd_hb_front().bits(hb_front); + w.lcd_vb_front().bits(vb_front) + }); + regs.lcd_rgb_vertical().write(|w| unsafe { + w.lcd_va_height().bits(va_height); + w.lcd_vt_height().bits(vt_height) + }); + regs.lcd_rgb_horizontal().write(|w| unsafe { + w.lcd_ha_width().bits(ha_width); + w.lcd_ht_width().bits(ht_width) + }); + regs.lcd_rgb_ctrl().write(|w| unsafe { + w.lcd_vsync_width().bits(vsync_width); + w.lcd_vsync_idle_pol().bit(vsync_idle_high); + w.lcd_de_idle_pol().bit(de_idle_high); + w.lcd_hs_blank_en().bit(hs_blank_en); + w.lcd_hsync_width().bits(hsync_width); + w.lcd_hsync_idle_pol().bit(hsync_idle_high); + w.lcd_hsync_position().bits(hsync_position) + }); + } + } +} diff --git a/esp-hal/src/lcd_cam/mod.rs b/esp-hal/src/lcd_cam/mod.rs index 91d39d67649..738a93f3f84 100644 --- a/esp-hal/src/lcd_cam/mod.rs +++ b/esp-hal/src/lcd_cam/mod.rs @@ -7,6 +7,9 @@ use core::marker::PhantomData; +use enumset::{EnumSet, EnumSetType}; +use esp_sync::RawMutex; + use crate::{ Async, Blocking, @@ -21,6 +24,7 @@ use crate::{ pub mod cam; pub mod lcd; +pub(crate) mod ll; /// DMA TX channel trait for LCD (I8080, DPI) peripherals. /// @@ -103,8 +107,7 @@ impl<'d> LcdCam<'d, Blocking> { /// Registers an interrupt handler for the LCD_CAM peripheral. /// - /// Note that this will replace any previously registered interrupt - /// handlers. + /// Replaces any previously registered interrupt handlers. #[instability::unstable] pub fn set_interrupt_handler(&mut self, handler: InterruptHandler) { for core in crate::system::Cpu::other() { @@ -142,7 +145,7 @@ pub enum BitOrder { /// Do not change bit order. #[default] Native = 0, - /// Invert bit order. + /// Inverts bit order. Inverted = 1, } @@ -153,47 +156,135 @@ pub enum ByteOrder { /// Do not change byte order. #[default] Native = 0, - /// Invert byte order. + /// Inverts byte order. Inverted = 1, } pub(crate) static LCD_DONE_WAKER: AtomicWaker = AtomicWaker::new(); +pub(crate) static LCD_VSYNC_WAKER: AtomicWaker = AtomicWaker::new(); +static INT_ENA_LOCK: RawMutex = RawMutex::new(); #[handler] fn interrupt_handler() { // TODO: this is a shared interrupt with Camera and here we ignore that! - if Instance::is_lcd_done_set() { + let status = LCD_CAM::regs().lc_dma_int_st().read(); + if status.lcd_trans_done_int_st().bit_is_set() { Instance::unlisten_lcd_done(); - LCD_DONE_WAKER.wake() + LCD_DONE_WAKER.wake(); + } + if status.lcd_vsync_int_st().bit_is_set() { + Instance::unlisten(LcdCamInterrupt::LcdVsync.into()); + LCD_VSYNC_WAKER.wake(); } } pub(crate) struct Instance; -// NOTE: the LCD_CAM interrupt registers are shared between LCD and Camera and -// this is only implemented for the LCD side, when the Camera is implemented a -// CriticalSection will be needed to protect these shared registers. +/// The interrupt sources of the LCD_CAM DMA interrupt registers. +/// +/// This type is `pub(crate)` today. If the Camera driver ever needs its own +/// listen API, it can be promoted to a public `LcdCamInterrupt` without +/// renaming. +#[derive(Debug, EnumSetType)] +pub(crate) enum LcdCamInterrupt { + /// The LCD has started outputting a new frame. + LcdVsync, + + /// A DMA transfer to the LCD has finished. + LcdTransDone, + + /// The camera has received a VSYNC pulse. + CamVsync, + + /// The camera has received an HSYNC pulse. + CamHs, +} + +// LCD and Camera share the interrupt registers. Serialize INT_ENA updates +// across cores and interrupt contexts. impl Instance { - fn enable_listenlcd_done(en: bool) { - LCD_CAM::regs() - .lc_dma_int_ena() - .modify(|_, w| w.lcd_trans_done_int_ena().bit(en)); + fn enable_listen(sources: EnumSet, en: bool) { + INT_ENA_LOCK.lock(|| { + LCD_CAM::regs().lc_dma_int_ena().modify(|_, w| { + for source in sources { + match source { + LcdCamInterrupt::LcdVsync => { + w.lcd_vsync_int_ena().bit(en); + } + LcdCamInterrupt::LcdTransDone => { + w.lcd_trans_done_int_ena().bit(en); + } + LcdCamInterrupt::CamVsync => { + w.cam_vsync_int_ena().bit(en); + } + LcdCamInterrupt::CamHs => { + w.cam_hs_int_ena().bit(en); + } + } + } + w + }); + }); + } + + pub(crate) fn listen(sources: EnumSet) { + Self::enable_listen(sources, true); + } + + pub(crate) fn unlisten(sources: EnumSet) { + Self::enable_listen(sources, false); + } + + pub(crate) fn interrupts() -> EnumSet { + let raw = LCD_CAM::regs().lc_dma_int_raw().read(); + let mut sources = EnumSet::new(); + if raw.lcd_vsync_int_raw().bit() { + sources.insert(LcdCamInterrupt::LcdVsync); + } + if raw.lcd_trans_done_int_raw().bit() { + sources.insert(LcdCamInterrupt::LcdTransDone); + } + if raw.cam_vsync_int_raw().bit() { + sources.insert(LcdCamInterrupt::CamVsync); + } + if raw.cam_hs_int_raw().bit() { + sources.insert(LcdCamInterrupt::CamHs); + } + sources + } + + pub(crate) fn clear_interrupts(sources: EnumSet) { + LCD_CAM::regs().lc_dma_int_clr().write(|w| { + for source in sources { + match source { + LcdCamInterrupt::LcdVsync => { + w.lcd_vsync_int_clr().set_bit(); + } + LcdCamInterrupt::LcdTransDone => { + w.lcd_trans_done_int_clr().set_bit(); + } + LcdCamInterrupt::CamVsync => { + w.cam_vsync_int_clr().set_bit(); + } + LcdCamInterrupt::CamHs => { + w.cam_hs_int_clr().set_bit(); + } + } + } + w + }); } pub(crate) fn listen_lcd_done() { - Self::enable_listenlcd_done(true); + Self::listen(LcdCamInterrupt::LcdTransDone.into()); } pub(crate) fn unlisten_lcd_done() { - Self::enable_listenlcd_done(false); + Self::unlisten(LcdCamInterrupt::LcdTransDone.into()); } pub(crate) fn is_lcd_done_set() -> bool { - LCD_CAM::regs() - .lc_dma_int_raw() - .read() - .lcd_trans_done_int_raw() - .bit() + Self::interrupts().contains(LcdCamInterrupt::LcdTransDone) } } pub(crate) struct ClockDivider { @@ -223,7 +314,7 @@ impl ClockDivider { #[derive(Debug, Clone, Copy, PartialEq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum ClockError { - /// Desired frequency was too low for the dividers to divide to + /// Desired frequency was too low for the dividers to divide to. FrequencyTooLow, } diff --git a/esp-hal/src/ledc/channel.rs b/esp-hal/src/ledc/channel.rs index fff2c411a59..e130e8e0149 100644 --- a/esp-hal/src/ledc/channel.rs +++ b/esp-hal/src/ledc/channel.rs @@ -27,11 +27,11 @@ use crate::{ #[derive(Debug, Clone, Copy, PartialEq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum FadeError { - /// Start duty % out of range + /// Starts duty % out of range. StartDuty, - /// End duty % out of range + /// Ends duty % out of range. EndDuty, - /// Duty % change from start to end is out of range + /// Duty % change from start to end is out of range. DutyRange, /// Duration too long for timer frequency and duty resolution Duration, @@ -99,13 +99,13 @@ pub trait ChannelIFace<'a, S: TimerSpeed + 'a> where Channel<'a, S>: ChannelHW, { - /// Configure channel + /// Configures channel. fn configure(&mut self, config: config::Config<'a, S>) -> Result<(), Error>; - /// Set channel duty HW + /// Sets channel duty HW. fn set_duty(&self, duty_pct: u8) -> Result<(), Error>; - /// Start a duty-cycle fade + /// Starts a duty-cycle fade. fn start_duty_fade( &self, start_duty_pct: u8, @@ -113,23 +113,23 @@ where duration_ms: u16, ) -> Result<(), Error>; - /// Check whether a duty-cycle fade is running + /// Returns whether a duty-cycle fade is running. fn is_duty_fade_running(&self) -> bool; } /// Channel HW interface pub trait ChannelHW { - /// Configure Channel HW except for the duty which is set via + /// Configures Channel HW except for the duty which is set via /// [`Self::set_duty_hw`]. fn configure_hw(&mut self) -> Result<(), Error>; - /// Configure the hardware for the channel with a specific pin + /// Configures the hardware for the channel with a specific pin /// configuration. fn configure_hw_with_drive_mode(&mut self, cfg: DriveMode) -> Result<(), Error>; - /// Set channel duty HW + /// Sets channel duty HW. fn set_duty_hw(&self, duty: u32); - /// Start a duty-cycle fade HW + /// Starts a duty-cycle fade HW. fn start_duty_fade_hw( &self, start_duty: u32, @@ -139,7 +139,7 @@ pub trait ChannelHW { duty_per_cycle: u16, ); - /// Check whether a duty-cycle fade is running HW + /// Returns whether a duty-cycle fade is running HW. fn is_duty_fade_running_hw(&self) -> bool; } @@ -152,7 +152,7 @@ pub struct Channel<'a, S: TimerSpeed> { } impl<'a, S: TimerSpeed> Channel<'a, S> { - /// Return a new channel + /// Returns a new channel. pub fn new(number: Number, output_pin: impl PeripheralOutput<'a>) -> Self { let ledc = LEDC::regs(); Channel { @@ -168,7 +168,7 @@ impl<'a, S: TimerSpeed> ChannelIFace<'a, S> for Channel<'a, S> where Channel<'a, S>: ChannelHW, { - /// Configure channel + /// Configures channel. fn configure(&mut self, config: config::Config<'a, S>) -> Result<(), Error> { self.timer = Some(config.timer); @@ -178,7 +178,7 @@ where Ok(()) } - /// Set duty % of channel + /// Sets duty % of channel. fn set_duty(&self, duty_pct: u8) -> Result<(), Error> { let duty_exp; if let Some(timer) = self.timer { @@ -204,9 +204,9 @@ where Ok(()) } - /// Start a duty fade from one % to another. + /// Starts a duty fade from one % to another. /// - /// There's a constraint on the combination of timer frequency, timer PWM + /// There is a constraint on the combination of timer frequency, timer PWM /// duty resolution (the bit count), the fade "range" (abs(start-end)), and /// the duration: /// @@ -214,8 +214,7 @@ where /// /// Small percentage changes, long durations, coarse PWM resolutions (that /// is, low bit counts), and high timer frequencies will all be more likely - /// to fail this requirement. If it does fail, this function will return - /// an error Result. + /// to fail this requirement. If it does fail, returns an error. fn start_duty_fade( &self, start_duty_pct: u8, @@ -355,7 +354,7 @@ impl ChannelHW for Channel<'_, S> where S: crate::ledc::timer::TimerSpeed, { - /// Configure Channel HW + /// Configures Channel HW. fn configure_hw(&mut self) -> Result<(), Error> { self.configure_hw_with_drive_mode(DriveMode::PushPull) } @@ -384,14 +383,14 @@ where Ok(()) } - /// Set duty in channel HW + /// Sets duty in channel HW. fn set_duty_hw(&self, duty: u32) { low_level::set_duty_hw(self.ledc, self.number, S::IS_HS, duty); self.start_duty_without_fading(); self.update_channel(); } - /// Start a duty-cycle fade HW + /// Starts a duty-cycle fade HW. fn start_duty_fade_hw( &self, start_duty: u32, diff --git a/esp-hal/src/ledc/mod.rs b/esp-hal/src/ledc/mod.rs index d3b2c34d91c..fdfc32b0912 100644 --- a/esp-hal/src/ledc/mod.rs +++ b/esp-hal/src/ledc/mod.rs @@ -20,7 +20,7 @@ //! //! ### Low Speed Channel //! -//! The following example will configure the Low Speed Channel0 to 24kHz output +//! The following example will configure the Low Speed Channel0 to 24 kHz output //! with 10% duty using the ABPClock and turn on LED with the option to change //! LED intensity depending on `duty` value. Possible values (`u32`) are in //! range 0..100. @@ -120,7 +120,7 @@ impl Speed for LowSpeed { } impl<'d> Ledc<'d> { - /// Return a new LEDC + /// Returns a new LEDC. pub fn new(_instance: LEDC<'d>) -> Self { if PeripheralClockControl::enable(PeripheralEnable::Ledc) { PeripheralClockControl::reset(PeripheralEnable::Ledc); @@ -134,17 +134,17 @@ impl<'d> Ledc<'d> { Ledc { _instance, ledc } } - /// Set global slow clock source + /// Sets global slow clock source. pub fn set_global_slow_clock(&mut self, clock_source: LSGlobalClkSource) { low_level::set_global_slow_clock(self.ledc, clock_source); } - /// Return a new timer + /// Returns a new timer. pub fn timer(&self, number: timer::Number) -> Timer<'d, S> { Timer::new(self.ledc, number) } - /// Return a new channel + /// Returns a new channel. pub fn channel( &self, number: channel::Number, diff --git a/esp-hal/src/ledc/timer.rs b/esp-hal/src/ledc/timer.rs index 26f9f8b33ad..5dbb10a262b 100644 --- a/esp-hal/src/ledc/timer.rs +++ b/esp-hal/src/ledc/timer.rs @@ -29,7 +29,7 @@ pub enum Error { } #[cfg(ledc_version = "1")] -/// Clock source for HS Timers +/// Clock source for HS Timers. #[derive(PartialEq, Eq, Copy, Clone, Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum HSClockSource { @@ -38,7 +38,7 @@ pub enum HSClockSource { // TODO RefTick, } -/// Clock source for LS Timers +/// Clock source for LS Timers. #[derive(PartialEq, Eq, Copy, Clone, Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum LSClockSource { @@ -187,34 +187,34 @@ impl TimerSpeed for HighSpeed { /// Interface for Timers pub trait TimerIFace { - /// Return the frequency of the timer + /// Returns the frequency of the timer. fn freq(&self) -> Option; - /// Configure the timer + /// Configures the timer. fn configure(&mut self, config: config::Config) -> Result<(), Error>; - /// Check if the timer has been configured + /// Returns whether the timer has been configured. fn is_configured(&self) -> bool; - /// Return the duty resolution of the timer + /// Returns the duty resolution of the timer. fn duty(&self) -> Option; - /// Return the timer number + /// Returns the timer number. fn number(&self) -> Number; - /// Return the timer frequency, or 0 if not configured + /// Returns the timer frequency, or 0 if not configured. fn frequency(&self) -> u32; } /// Interface for HW configuration of timer pub trait TimerHW { - /// Get the current source timer frequency from the HW + /// Returns the current source timer frequency from the HW. fn freq_hw(&self) -> Option; - /// Configure the HW for the timer + /// Configures the HW for the timer. fn configure_hw(&self, divisor: u32); - /// Update the timer in HW + /// Updates the timer in HW. fn update_hw(&self); } @@ -234,12 +234,12 @@ impl<'a, S: TimerSpeed> TimerIFace for Timer<'a, S> where Timer<'a, S>: TimerHW, { - /// Return the frequency of the timer + /// Returns the frequency of the timer. fn freq(&self) -> Option { self.freq_hw() } - /// Configure the timer + /// Configures the timer. fn configure(&mut self, config: config::Config) -> Result<(), Error> { self.duty = Some(config.duty); self.clock_source = Some(config.clock_source); @@ -272,29 +272,29 @@ where Ok(()) } - /// Check if the timer has been configured + /// Returns whether the timer has been configured. fn is_configured(&self) -> bool { self.configured } - /// Return the duty resolution of the timer + /// Returns the duty resolution of the timer. fn duty(&self) -> Option { self.duty } - /// Return the timer number + /// Returns the timer number. fn number(&self) -> Number { self.number } - /// Return the timer frequency + /// Returns the timer frequency. fn frequency(&self) -> u32 { self.frequency } } impl<'a, S: TimerSpeed> Timer<'a, S> { - /// Create a new instance of a timer + /// Creates a new instance of a timer. pub fn new(ledc: &'a pac::ledc::RegisterBlock, number: Number) -> Self { Timer { ledc, @@ -311,12 +311,12 @@ impl<'a, S: TimerSpeed> Timer<'a, S> { /// Timer HW implementation for LowSpeed timers impl TimerHW for Timer<'_, LowSpeed> { - /// Get the current source timer frequency from the HW + /// Returns the current source timer frequency from the HW. fn freq_hw(&self) -> Option { self.clock_source.map(low_level::ls_freq_hw) } - /// Configure the HW for the timer + /// Configures the HW for the timer. fn configure_hw(&self, divisor: u32) { let duty = unwrap!(self.duty) as u8; #[cfg(soc_has_clock_node_ref_tick)] @@ -326,7 +326,7 @@ impl TimerHW for Timer<'_, LowSpeed> { low_level::ls_configure_hw(self.ledc, self.number, divisor, duty, use_ref_tick); } - /// Update the timer in HW + /// Updates the timer in HW. fn update_hw(&self) { low_level::ls_update_hw(self.ledc, self.number); } @@ -335,12 +335,12 @@ impl TimerHW for Timer<'_, LowSpeed> { #[cfg(ledc_version = "1")] /// Timer HW implementation for HighSpeed timers impl TimerHW for Timer<'_, HighSpeed> { - /// Get the current source timer frequency from the HW + /// Returns the current source timer frequency from the HW. fn freq_hw(&self) -> Option { self.clock_source.map(low_level::hs_freq_hw) } - /// Configure the HW for the timer + /// Configures the HW for the timer. fn configure_hw(&self, divisor: u32) { let duty = unwrap!(self.duty) as u8; low_level::hs_configure_hw( @@ -352,7 +352,7 @@ impl TimerHW for Timer<'_, HighSpeed> { ); } - /// Update the timer in HW + /// Updates the timer in HW. fn update_hw(&self) { low_level::hs_update_hw(); } diff --git a/esp-hal/src/lib.rs b/esp-hal/src/lib.rs index 01544ddb2f4..d9ead268237 100644 --- a/esp-hal/src/lib.rs +++ b/esp-hal/src/lib.rs @@ -18,7 +18,7 @@ //! //! The HAL implements both [`Blocking`] _and_ [`Async`] APIs for all applicable peripherals. //! Where applicable, driver implement the [embedded-hal] and -//! [embedded-hal-async] traits. Drivers that don't currently have a stable API +//! [embedded-hal-async] traits. Drivers that do not currently have a stable API //! are marked as `unstable` in the documentation. //! //! ### Peripheral singletons @@ -31,9 +31,9 @@ //! These singletons, by default, represent peripherals for the entire lifetime //! of the program. To allow for reusing peripherals, the HAL provides a //! `reborrow` method on each peripheral singleton. This method creates a new -//! handle to the peripheral with a shorter lifetime. This allows you to pass -//! the handle to a driver, while still keeping the original handle alive. Once -//! you drop the driver, you will be able to reborrow the peripheral again. +//! handle to the peripheral with a shorter lifetime. This lets the handle be +//! passed to a driver while keeping the original handle alive. Once the driver +//! is dropped, the peripheral can be reborrowed again. #![cfg_attr( // Feature-gated so that this doesn't prevent gradual device bringup. Any // stable driver would serve the purpose here, so this block will be part @@ -41,7 +41,7 @@ i2c_master_driver_supported, doc = r#" For example, if you want to use the [`I2c`](i2c::master::I2c) driver and you -don't intend to drop the driver, you can pass the peripheral singleton to +do not intend to drop the driver, you can pass the peripheral singleton to the driver by value: ```rust, ignore @@ -89,7 +89,7 @@ let mut i2c = I2c::new(peripherals.I2C0, /* ... */); //! ## Creating a Project //! //! We have a [book] that explains the full esp-hal ecosystem -//! and how to get started, it's advisable to give that a read +//! and how to get started, it is advisable to give that a read //! before proceeding. We also have a [training] that covers some common //! scenarios with examples. //! @@ -149,9 +149,9 @@ fn main() -> ! { )] //! ## Additional configuration //! -//! We've exposed some configuration options that don't fit into cargo +//! Some configuration options do not fit into cargo //! features. These can be set via environment variables, or via cargo's `[env]` -//! section inside `.cargo/config.toml`. Note that unstable options can only be +//! section inside `.cargo/config.toml`. Unstable options can only be //! enabled when the `unstable` feature is enabled for the crate. Below is a //! table of tunable parameters for this crate: #![doc = ""] @@ -161,7 +161,7 @@ fn main() -> ! { //! //! You should never use `core::mem::forget` on any type defined in [esp crates]. //! Many types heavily rely on their `Drop` implementation to not leave the -//! hardware in undefined state which can cause undefined behaviour in your program. +//! hardware in undefined state which can cause undefined behavior in your program. //! //! You might want to consider using [`#[deny(clippy::mem_forget)`](https://rust-lang.github.io/rust-clippy/v0.0.212/index.html#mem_forget) in your project. //! @@ -259,7 +259,7 @@ use core::marker::PhantomData; pub use esp_metadata_generated::chip; use esp_rom_sys as _; -#[cfg_attr(esp32s31, allow(unused))] +#[allow(unused)] pub(crate) use unstable_driver; pub(crate) use unstable_module; @@ -293,6 +293,10 @@ pub mod clock; pub mod gpio; #[cfg(i2c_master_driver_supported)] pub mod i2c; +// The I2S driver is unstable, but its clock tree nodes are part of every build. +#[cfg(i2s_driver_supported)] +#[path = "i2s/clocks/mod.rs"] +mod i2s_clocks; pub mod peripherals; #[cfg(all( feature = "unstable", @@ -345,6 +349,8 @@ unstable_module! { pub mod analog; #[cfg(any(systimer_driver_supported, timergroup_driver_supported))] pub mod timer; + #[cfg(temp_sensor_driver_supported)] + pub mod tsens; #[cfg(soc_has_lpwr)] pub mod rtc_cntl; #[cfg(dma_driver_supported)] @@ -368,9 +374,13 @@ unstable_driver! { pub mod aes; #[cfg(assist_debug_driver_supported)] pub mod assist_debug; + #[cfg(canfd_driver_supported)] + pub mod canfd; pub mod delay; #[cfg(ecc_driver_supported)] pub mod ecc; + #[cfg(flash_driver_supported)] + pub mod flash; #[cfg(hmac_driver_supported)] pub mod hmac; #[cfg(i2s_driver_supported)] @@ -399,8 +409,6 @@ unstable_driver! { pub mod touch; #[cfg(soc_has_trace0)] pub mod trace; - #[cfg(soc_has_tsens)] - pub mod tsens; #[cfg(twai_driver_supported)] pub mod twai; #[cfg(any( @@ -439,7 +447,7 @@ trait RegisterToggle { /// Toggles bits in the register, applying the given operation to set and clear them. /// - /// This method is more efficient than two modify calls, as it will not read the register + /// More efficient than two modify calls, because it does not read the register /// value twice. fn toggle(&self, op: impl Fn(&mut W, bool) -> &mut W); } @@ -466,7 +474,7 @@ WARNING: use --release We *strongly* recommend using release profile when building esp-hal. The dev profile can potentially be one or more orders of magnitude slower than release, and may cause issues with timing-sensitive - peripherals and/or devices. + peripherals or devices. "} /// A marker trait for driver modes. @@ -477,7 +485,7 @@ WARNING: use --release pub trait DriverMode: crate::private::Sealed {} #[procmacros::doc_replace] -/// Marker type signalling that a driver is initialized in blocking mode. +/// Marker type signaling that a driver is initialized in blocking mode. /// /// Drivers are constructed in blocking mode by default. To learn about the /// differences between blocking and async drivers, see the [`Async`] mode @@ -508,7 +516,7 @@ let blocking_uart = uart.into_blocking(); pub struct Blocking; #[procmacros::doc_replace] -/// Marker type signalling that a driver is initialized in async mode. +/// Marker type signaling that a driver is initialized in async mode. /// /// Drivers are constructed in blocking mode by default. To set up an async /// driver, a [`Blocking`] driver must be converted to an `Async` driver using @@ -539,12 +547,11 @@ let uart = Uart::new(peripherals.UART0, Config::default())? /// available in async mode, as they are handled by the driver's interrupt /// handlers. /// -/// Note that async functions usually take up more space than their blocking -/// counterparts, and they are generally slower. This is because async functions -/// are implemented using a state machine that is driven by interrupts and is -/// polled by a runtime. For short operations, the overhead of the state machine -/// can be significant. Consider using the blocking functions on the async -/// driver for small transfers. +/// Async functions usually take up more space than their blocking counterparts, +/// and they are generally slower. This is because async functions are implemented +/// using a state machine that is driven by interrupts and is polled by a runtime. +/// For short operations, the overhead of the state machine can be significant. +/// Consider using the blocking functions on the async driver for small transfers. /// /// When initializing an async driver, the driver disables user-specified /// interrupt handlers, and sets up internal interrupt handlers that drive the @@ -638,12 +645,12 @@ pub(crate) static ESP_HAL_LOCK: esp_sync::RawMutex = esp_sync::RawMutex::new(); #[procmacros::doc_replace] /// System configuration. /// -/// This `struct` is marked with `#[non_exhaustive]` and can't be instantiated +/// This `struct` is marked with `#[non_exhaustive]` and cannot be instantiated /// directly. This is done to prevent breaking changes when new fields are added /// to the `struct`. Instead, use the [`Config::default()`] method to create a /// new instance. /// -/// ## Examples +/// # Examples /// /// ### Default initialization /// @@ -670,7 +677,7 @@ pub struct Config { } impl Config { - /// Apply a clock configuration. + /// Applies a clock configuration. #[cfg_attr( feature = "unstable", doc = r" @@ -686,7 +693,7 @@ With the `unstable` feature enabled, this function accepts both [`ClockConfig`] } } - /// Apply a clock configuration. + /// Applies a clock configuration. #[cfg(not(feature = "unstable"))] pub fn with_cpu_clock(self, cpu_clock: CpuClock) -> Self { Self { @@ -699,8 +706,7 @@ With the `unstable` feature enabled, this function accepts both [`ClockConfig`] /// /// # Panics /// - /// This function will panic if the CPU clock configuration is not **exactly** one of the - /// [`CpuClock`] presets. + /// Panics if the CPU clock configuration is not **exactly** one of the [`CpuClock`] presets #[cfg_attr(feature = "unstable", deprecated(note = "Use `clock_config` instead."))] // TODO: mention ClockTree APIs once they are exposed to the user. pub fn cpu_clock(&self) -> CpuClock { unwrap!( @@ -717,12 +723,11 @@ With the `unstable` feature enabled, this function accepts both [`ClockConfig`] } #[procmacros::doc_replace] -/// Initialize the system. +/// Initializes the system. /// -/// This function sets up the CPU clock and watchdog, then, returns the -/// peripherals and clocks. +/// Sets up the CPU clock and watchdog, then returns the peripherals and clocks. /// -/// # Example +/// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -745,7 +750,7 @@ pub fn init(config: Config) -> Peripherals { ); #[cfg(soc_cpu_has_branch_predictor)] - crate::soc::enable_branch_predictor(); + crate::soc::branch_predictor::enable(); // Have we already overflown the stack? #[cfg(init_stack_ptr_range_check)] @@ -793,5 +798,8 @@ pub fn init(config: Config) -> Peripherals { #[cfg(all(riscv, write_vec_table_monitoring))] crate::soc::setup_trap_section_protection(); + #[cfg(all(feature = "unstable", multi_core))] + crate::interrupt::ipc::install(); + peripherals } diff --git a/esp-hal/src/macros.rs b/esp-hal/src/macros.rs index e2cd266b4f5..b3c36ccfcd6 100644 --- a/esp-hal/src/macros.rs +++ b/esp-hal/src/macros.rs @@ -139,7 +139,7 @@ macro_rules! any_peripheral { $(#[$meta])* /// - /// This struct is a type-erased version of a peripheral singleton. It is useful + /// A type-erased version of a peripheral singleton. Useful /// for creating arrays of peripherals, or avoiding generics. Peripheral singletons /// can be type erased by using their `From` implementation. /// @@ -155,7 +155,7 @@ macro_rules! any_peripheral { /// /// # Safety /// - /// You must ensure that you're only using one instance of this type at a time. + /// The caller must ensure that only one instance of this type is used at a time. #[inline] #[allow(unused)] pub unsafe fn clone_unchecked(&self) -> Self { unsafe { @@ -164,8 +164,8 @@ macro_rules! any_peripheral { /// Creates a new peripheral reference with a shorter lifetime. /// - /// Use this method if you would like to keep working with the peripheral after - /// you dropped the driver that consumes this. + /// Use this method to keep working with the peripheral after + /// dropping the driver that consumes this. /// /// See [Peripheral singleton] section for more information. /// @@ -299,7 +299,7 @@ include!(concat!(env!("OUT_DIR"), "/version_macro.rs")); /// /// Version branches should be listed in descending order. /// -/// # Example +/// # Examples /// /// ```rust,no_run /// # {before_snippet} @@ -323,15 +323,15 @@ macro_rules! at_least_version { /// Macro to ignore tokens. /// -/// This is useful when we need existence of a metavariable (to expand a -/// repetition), but we don't need to use it. +/// This is useful when a metavariable must exist (to expand a +/// repetition), but need not be used. #[macro_export] #[doc(hidden)] macro_rules! ignore { ($($item:tt)*) => {}; } -/// Define a piece of (Espressif-specific) metadata that external tools may +/// Defines a piece of (Espressif-specific) metadata that external tools may /// parse. /// /// The symbol name be formatted as `_ESP_METADATA__`. @@ -447,11 +447,11 @@ macro_rules! assign_resources { } impl<$group_lt> $group_struct<$group_lt> { - /// Unsafely create an instance of the assigned peripherals out of thin air. + /// Unsafely creates an instance of the assigned peripherals out of thin air. /// /// # Safety /// - /// You must ensure that you're only using one instance of the contained peripherals at a time. + /// The caller must ensure that only one instance of the contained peripherals is used at a time. pub unsafe fn steal() -> Self { unsafe { Self { @@ -462,8 +462,8 @@ macro_rules! assign_resources { /// Creates a new reference to the peripheral group with a shorter lifetime. /// - /// Use this method if you would like to keep working with the peripherals after - /// you dropped the drivers that consume this. + /// Use this method to keep working with the peripherals after + /// dropping the drivers that consume this. pub fn reborrow(&mut self) -> $group_struct<'_> { $group_struct { $($resource_name: self.$resource_name.reborrow()),* @@ -480,11 +480,11 @@ macro_rules! assign_resources { } impl<$struct_lt> $struct_name<$struct_lt> { - /// Unsafely create an instance of the assigned peripherals out of thin air. + /// Unsafely creates an instance of the assigned peripherals out of thin air. /// /// # Safety /// - /// You must ensure that you're only using one instance of the contained peripherals at a time. + /// The caller must ensure that only one instance of the contained peripherals is used at a time. pub unsafe fn steal() -> Self { unsafe { Self { @@ -495,8 +495,8 @@ macro_rules! assign_resources { /// Creates a new reference to the assigned peripherals with a shorter lifetime. /// - /// Use this method if you would like to keep working with the peripherals after - /// you dropped the drivers that consume this. + /// Use this method to keep working with the peripherals after + /// dropping the drivers that consume this. pub fn reborrow(&mut self) -> $struct_name<'_> { $struct_name { $($group_name: self.$group_name.reborrow()),* @@ -618,6 +618,43 @@ pub(crate) use impl_dma_channel_trait; #[cfg(feature = "unstable")] use procmacros::doc_replace; +/// Reads the RISC-V CSR that `csr` numbers. +/// +/// The `riscv` crate names no debug CSR and no Espressif custom CSR, so the retention code reads +/// them by number. `csr` is an `asm!` `const` operand, so it must be a constant expression. +/// +/// # Safety +/// +/// The caller must make sure that the CSR exists on this chip, and that the read has no effect +/// that the caller does not expect. +#[cfg(all(cpu_retention = "software", supports_cpu_power_down))] +macro_rules! read_csr { + ($csr:expr) => {{ + let value: u32; + core::arch::asm!("csrr {0}, {1}", out(reg) value, const $csr); + value + }}; +} +#[cfg(all(cpu_retention = "software", supports_cpu_power_down))] +pub(crate) use read_csr; + +/// Writes `value` to the RISC-V CSR that `csr` numbers. +/// +/// `csr` is an `asm!` `const` operand, so it must be a constant expression. +/// +/// # Safety +/// +/// The caller must make sure that the CSR exists on this chip, and that the write has no effect +/// that the caller does not expect. +#[cfg(all(cpu_retention = "software", supports_cpu_power_down))] +macro_rules! write_csr { + ($csr:expr, $value:expr) => { + core::arch::asm!("csrw {1}, {0}", in(reg) $value, const $csr) + }; +} +#[cfg(all(cpu_retention = "software", supports_cpu_power_down))] +pub(crate) use write_csr; + /// Macro to allow using unstable HAL features conditionally. Other crates can /// use this to "detect" the esp-hal/unstable feature. #[macro_export] diff --git a/esp-hal/src/mcpwm/mod.rs b/esp-hal/src/mcpwm/mod.rs index 15c992ee372..328ab2351ee 100644 --- a/esp-hal/src/mcpwm/mod.rs +++ b/esp-hal/src/mcpwm/mod.rs @@ -125,7 +125,7 @@ impl PwmClockGuard { } } -/// The MCPWM peripheral +/// The MCPWM peripheral. #[non_exhaustive] pub struct McPwm<'d, PWM> { _inner: PWM, @@ -151,9 +151,19 @@ impl<'d, PWM: PwmPeripheral + 'd> McPwm<'d, PWM> { let register_block = unsafe { &*PWM::block() }; // set prescaler - register_block - .clk_cfg() - .write(|w| unsafe { w.clk_prescale().bits(peripheral_clock.prescaler) }); + // TODO: configure dividers through clock tree + cfg_select! { + soc_has_pcr => { + crate::peripherals::PCR::regs() + .pwm_clk_conf() + .modify(|_, w| unsafe { w.pwm_div_num().bits(peripheral_clock.prescaler) }); + } + _ => { + register_block + .clk_cfg() + .write(|w| unsafe { w.clk_prescale().bits(peripheral_clock.prescaler) }); + } + } // enable clock register_block.clk().write(|w| w.en().set_bit()); @@ -170,7 +180,7 @@ impl<'d, PWM: PwmPeripheral + 'd> McPwm<'d, PWM> { } } -/// Clock configuration of the MCPWM peripheral +/// Clocks configuration of the MCPWM peripheral. #[derive(Copy, Clone)] pub struct PeripheralClockConfig { frequency: Rate, @@ -184,7 +194,7 @@ impl PeripheralClockConfig { Rate::from_hz(clocks::McpwmInstance::Mcpwm0.function_clock_frequency()) } - /// Get a clock configuration with the given prescaler. + /// Returns a clock configuration with the given prescaler. /// /// With standard system clock configurations the input clock to the MCPWM /// peripheral is `160 MHz`. @@ -200,13 +210,11 @@ impl PeripheralClockConfig { } } - /// Get a clock configuration with the given frequency. + /// Returns a clock configuration with the given frequency. /// - /// ### Note: - /// This will try to select an appropriate prescaler for the + /// Tries to select an appropriate prescaler for the /// [`PeripheralClockConfig::with_prescaler`] method. - /// If the calculated prescaler is not in the range `0..u8::MAX` - /// [`FrequencyError`] will be returned. + /// [`FrequencyError`] when the calculated prescaler is not in the range `0..u8::MAX`. /// /// With standard system clock configurations the input clock to the MCPWM /// peripheral is `160 MHz`. @@ -229,15 +237,14 @@ impl PeripheralClockConfig { Ok(Self::with_prescaler(prescaler as u8)) } - /// Get the peripheral clock frequency. + /// Returns the peripheral clock frequency. /// - /// ### Note: - /// The actual value is rounded down to the nearest `u32` value + /// The actual value is rounded down to the nearest `u32` value. pub fn frequency(&self) -> Rate { self.frequency } - /// Get a timer clock configuration with the given prescaler. + /// Returns a timer clock configuration with the given prescaler. /// /// The resulting timer frequency depends on the chosen /// [`timer::PwmWorkingMode`]. @@ -255,12 +262,10 @@ impl PeripheralClockConfig { timer::TimerClockConfig::with_prescaler(self, period, mode, prescaler) } - /// Get a timer clock configuration with the given frequency. + /// Returns a timer clock configuration with the given frequency. /// - /// ### Note: - /// This will try to select an appropriate prescaler for the timer. - /// If the calculated prescaler is not in the range `0..u8::MAX` - /// [`FrequencyError`] will be returned. + /// Tries to select an appropriate prescaler for the timer. + /// [`FrequencyError`] when the calculated prescaler is not in the range `0..u8::MAX`. /// /// See [`PeripheralClockConfig::timer_clock_with_prescaler`] for how the /// frequency is calculated. @@ -275,16 +280,16 @@ impl PeripheralClockConfig { } /// Target frequency could not be set. -/// Check how the frequency is calculated in the corresponding method docs. +/// See how the frequency is calculated in the corresponding method docs. #[derive(Copy, Clone, Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub struct FrequencyError; -/// A MCPWM peripheral +/// A MCPWM peripheral. pub trait PwmPeripheral: crate::private::Sealed { - /// Get a pointer to the peripheral RegisterBlock + /// Returns a pointer to the peripheral RegisterBlock. fn block() -> *const RegisterBlock; - /// Get operator GPIO mux output signal + /// Returns the operator GPIO mux output signal. fn output_signal() -> OutputSignal; /// Peripheral fn peripheral() -> Peripheral; diff --git a/esp-hal/src/mcpwm/operator.rs b/esp-hal/src/mcpwm/operator.rs index 8d035a44baa..ca14e71ee16 100644 --- a/esp-hal/src/mcpwm/operator.rs +++ b/esp-hal/src/mcpwm/operator.rs @@ -28,8 +28,9 @@ pub enum PWMStream { PWMB, } -/// Configuration for MCPWM Operator DeadTime -/// It's recommended to reference the technical manual for configuration +/// Configuration for MCPWM Operator DeadTime. +/// +/// It is recommended to reference the technical manual for configuration. #[derive(Copy, Clone)] pub struct DeadTimeCfg { cfg_reg: u32, @@ -59,7 +60,7 @@ impl DeadTimeCfg { const S7: u32 = 0b00_0000_0100_0000_0000; /// DEB_MODE const _S8: u32 = 0b00_0000_0001_0000_0000; - /// Use PT_clk instead of PWM_clk + /// Selects PT_clk instead of PWM_clk. const CLK_SEL: u32 = 0b10_0000_0000_0000_0000; /// Uses the following configuration: @@ -97,8 +98,8 @@ impl DeadTimeCfg { self } - /// Sets FED/RED output inverter - /// Inverts the output of the FED/RED module (excl DEB mode feedback) + /// Sets FED/RED output inverter. + /// Inverts the output of the FED/RED module (excl DEB mode feedback). #[must_use] pub const fn invert_output(self, fed: bool, red: bool) -> Self { self.set_flag(Self::S3, fed).set_flag(Self::S2, red) @@ -119,8 +120,8 @@ impl DeadTimeCfg { ) } - /// Set PWMA/PWMB stream to bypass everything except output_swap - /// This means no deadtime is applied when enabled + /// Sets PWMA/PWMB stream to bypass everything except output_swap. + /// This means no deadtime is applied when enabled. #[must_use] pub const fn set_bypass(self, stream: PWMStream, enable: bool) -> Self { self.set_flag( @@ -132,13 +133,13 @@ impl DeadTimeCfg { ) } - /// Select Between PWMClk & PT_Clk + /// Selects Between PWMClk & PT_Clk. #[must_use] pub const fn select_clock(self, pwm_clock: bool) -> Self { self.set_flag(Self::CLK_SEL, pwm_clock) } - /// Select which stream is used for the input of FED/RED + /// Selects which stream is used for the input of FED/RED. #[must_use] pub const fn select_input(self, fed: PWMStream, red: PWMStream) -> Self { self.set_flag( @@ -158,7 +159,7 @@ impl DeadTimeCfg { } } -/// A MCPWM operator +/// A MCPWM operator. /// /// The PWM Operator submodule has the following functions: /// * Generates a PWM signal pair, based on timing references obtained from the corresponding PWM @@ -188,10 +189,9 @@ impl<'d, const OP: u8, PWM: PwmPeripheral> Operator<'d, OP, PWM> { } } - /// Select a [`Timer`] to be the timing reference for this operator + /// Selects a [`Timer`] to be the timing reference for this operator. /// - /// ### Note: - /// By default TIMER0 is used + /// By default TIMER0 is used. pub fn set_timer(&mut self, timer: &Timer) { let _ = timer; // SAFETY: @@ -207,7 +207,7 @@ impl<'d, const OP: u8, PWM: PwmPeripheral> Operator<'d, OP, PWM> { }); } - /// Use the A output with the given pin and configuration + /// Configures the A output with the given pin and configuration. pub fn with_pin_a( self, pin: impl PeripheralOutput<'d>, @@ -216,7 +216,7 @@ impl<'d, const OP: u8, PWM: PwmPeripheral> Operator<'d, OP, PWM> { PwmPin::new(pin, config) } - /// Use the B output with the given pin and configuration + /// Configures the B output with the given pin and configuration. pub fn with_pin_b( self, pin: impl PeripheralOutput<'d>, @@ -225,7 +225,7 @@ impl<'d, const OP: u8, PWM: PwmPeripheral> Operator<'d, OP, PWM> { PwmPin::new(pin, config) } - /// Use both the A and the B output with the given pins and configurations + /// Configures both the A and B outputs with the given pins and configurations. pub fn with_pins( self, pin_a: impl PeripheralOutput<'d>, @@ -236,7 +236,7 @@ impl<'d, const OP: u8, PWM: PwmPeripheral> Operator<'d, OP, PWM> { (PwmPin::new(pin_a, config_a), PwmPin::new(pin_b, config_b)) } - /// Link two pins using the deadtime generator + /// Links two pins using the deadtime generator. /// /// This is useful for complementary or mirrored signals with or without /// configured deadtime @@ -274,7 +274,7 @@ impl PwmPinConfig { /// [`PwmUpdateMethod::empty`] pub const EMPTY: Self = Self::new(PwmActions::empty(), PwmUpdateMethod::empty()); - /// Get a configuration using the given `PwmActions` and `PwmUpdateMethod` + /// Returns a configuration using the given `PwmActions` and `PwmUpdateMethod`. pub const fn new(actions: PwmActions, update_method: PwmUpdateMethod) -> Self { PwmPinConfig { actions, @@ -283,7 +283,7 @@ impl PwmPinConfig { } } -/// A pin driven by an MCPWM operator +/// A pin driven by an MCPWM operator. pub struct PwmPin<'d, PWM, const OP: u8, const IS_A: bool> { pin: OutputSignal<'d>, phantom: PhantomData, @@ -310,7 +310,7 @@ impl<'d, PWM: PwmPeripheral, const OP: u8, const IS_A: bool> PwmPin<'d, PWM, OP, pin } - /// Configure what actions should be taken on timing events + /// Configures what actions should be taken on timing events. pub fn set_actions(&mut self, value: PwmActions) { // SAFETY: // We only write to our GENx_x register @@ -322,7 +322,7 @@ impl<'d, PWM: PwmPeripheral, const OP: u8, const IS_A: bool> PwmPin<'d, PWM, OP, ch.gen_((!IS_A) as usize).write(|w| unsafe { w.bits(bits) }); } - /// Set how a new timestamp syncs with the timer + /// Sets how a new timestamp syncs with the timer. pub fn set_update_method(&mut self, update_method: PwmUpdateMethod) { // SAFETY: // We only write to our GENx_x_UPMETHOD register @@ -343,7 +343,7 @@ impl<'d, PWM: PwmPeripheral, const OP: u8, const IS_A: bool> PwmPin<'d, PWM, OP, }); } - /// Write a new timestamp. + /// Writes a new timestamp. /// The written value will take effect according to the set /// [`PwmUpdateMethod`]. pub fn set_timestamp(&mut self, value: u16) { @@ -366,7 +366,7 @@ impl<'d, PWM: PwmPeripheral, const OP: u8, const IS_A: bool> PwmPin<'d, PWM, OP, } } - /// Get the old timestamp. + /// Returns the old timestamp. /// The value of the timestamp will take effect according to the set /// [`PwmUpdateMethod`]. pub fn timestamp(&self) -> u16 { @@ -389,7 +389,7 @@ impl<'d, PWM: PwmPeripheral, const OP: u8, const IS_A: bool> PwmPin<'d, PWM, OP, } } - /// Get the period of the timer. + /// Returns the period of the timer. pub fn period(&self) -> u16 { // SAFETY: // We only grant access to our CFG0 register with the lifetime of &mut self @@ -417,23 +417,23 @@ impl<'d, PWM: PwmPeripheral, const OP: u8, const IS_A: bool> PwmPin<'d, PWM, OP, } } -/// Implement no error type for the PwmPin because the method are infallible +/// Implements no error type for the PwmPin because the method are infallible. impl embedded_hal::pwm::ErrorType for PwmPin<'_, PWM, OP, IS_A> { type Error = core::convert::Infallible; } -/// Implement the trait SetDutyCycle for PwmPin +/// Implements the trait SetDutyCycle for PwmPin. impl embedded_hal::pwm::SetDutyCycle for PwmPin<'_, PWM, OP, IS_A> { - /// Get the max duty of the PwmPin + /// Returns the max duty of the PwmPin. fn max_duty_cycle(&self) -> u16 { self.period() } - /// Set the max duty of the PwmPin + /// Sets the max duty of the PwmPin. fn set_duty_cycle(&mut self, duty: u16) -> Result<(), core::convert::Infallible> { self.set_timestamp(duty); Ok(()) @@ -512,38 +512,38 @@ impl<'d, PWM: PwmPeripheral, const OP: u8> LinkedPins<'d, PWM, OP> { LinkedPins { pin_a, pin_b } } - /// Configure what actions should be taken on timing events + /// Configures what actions should be taken on timing events. pub fn set_actions_a(&mut self, value: PwmActions) { self.pin_a.set_actions(value) } - /// Configure what actions should be taken on timing events + /// Configures what actions should be taken on timing events. pub fn set_actions_b(&mut self, value: PwmActions) { self.pin_b.set_actions(value) } - /// Set how a new timestamp syncs with the timer + /// Sets how a new timestamp syncs with the timer. pub fn set_update_method_a(&mut self, update_method: PwmUpdateMethod) { self.pin_a.set_update_method(update_method) } - /// Set how a new timestamp syncs with the timer + /// Sets how a new timestamp syncs with the timer. pub fn set_update_method_b(&mut self, update_method: PwmUpdateMethod) { self.pin_b.set_update_method(update_method) } - /// Write a new timestamp. + /// Writes a new timestamp. /// The written value will take effect according to the set /// [`PwmUpdateMethod`]. pub fn set_timestamp_a(&mut self, value: u16) { self.pin_a.set_timestamp(value) } - /// Write a new timestamp. + /// Writes a new timestamp. /// The written value will take effect according to the set /// [`PwmUpdateMethod`]. pub fn set_timestamp_b(&mut self, value: u16) { self.pin_b.set_timestamp(value) } - /// Configure the deadtime generator + /// Configures the deadtime generator. pub fn set_deadtime_cfg(&mut self, config: DeadTimeCfg) { #[cfg(esp32s3)] let dt_cfg = unsafe { Self::ch() }.db_cfg(); @@ -552,7 +552,7 @@ impl<'d, PWM: PwmPeripheral, const OP: u8> LinkedPins<'d, PWM, OP> { dt_cfg.write(|w| unsafe { w.bits(config.cfg_reg) }); } - /// Set the deadtime generator rising edge delay + /// Sets the deadtime generator rising edge delay. pub fn set_rising_edge_deadtime(&mut self, dead_time: u16) { #[cfg(esp32s3)] let dt_red = unsafe { Self::ch() }.db_red_cfg(); @@ -560,7 +560,7 @@ impl<'d, PWM: PwmPeripheral, const OP: u8> LinkedPins<'d, PWM, OP> { let dt_red = unsafe { Self::ch() }.dt_red_cfg(); dt_red.write(|w| unsafe { w.red().bits(dead_time) }); } - /// Set the deadtime generator falling edge delay + /// Sets the deadtime generator falling edge delay. pub fn set_falling_edge_deadtime(&mut self, dead_time: u16) { #[cfg(esp32s3)] let dt_fed = unsafe { Self::ch() }.db_fed_cfg(); @@ -575,22 +575,21 @@ impl<'d, PWM: PwmPeripheral, const OP: u8> LinkedPins<'d, PWM, OP> { } } -/// An action the operator applies to an output +/// An action the operator applies to an output. #[non_exhaustive] #[repr(u32)] pub enum UpdateAction { - /// Clear the output by setting it to a low level. + /// Clears the output by setting it to a low level. SetLow = 1, - /// Set the output to a high level. + /// Sets the output to a high level. SetHigh = 2, - /// Change the current output level to the opposite value. + /// Changes the current output level to the opposite value. /// If it is currently pulled high, pull it low, or vice versa. Toggle = 3, } -/// Settings for what actions should be taken on timing events +/// Settings for what actions should be taken on timing events. /// -/// ### Note: /// The hardware supports using a timestamp A event to trigger an action on /// output B or vice versa. For clearer ownership semantics this HAL does not /// support such configurations. @@ -618,17 +617,17 @@ impl PwmActions { PwmActions(0) } - /// Choose an `UpdateAction` for an `UTEZ` event + /// Chooses an `UpdateAction` for an `UTEZ` event. pub const fn on_up_counting_timer_equals_zero(self, action: UpdateAction) -> Self { self.with_value_at_offset(action as u32, 0) } - /// Choose an `UpdateAction` for an `UTEP` event + /// Chooses an `UpdateAction` for an `UTEP` event. pub const fn on_up_counting_timer_equals_period(self, action: UpdateAction) -> Self { self.with_value_at_offset(action as u32, 2) } - /// Choose an `UpdateAction` for an `UTEA`/`UTEB` event + /// Chooses an `UpdateAction` for an `UTEA`/`UTEB` event. pub const fn on_up_counting_timer_equals_timestamp(self, action: UpdateAction) -> Self { match IS_A { true => self.with_value_at_offset(action as u32, 4), @@ -636,8 +635,8 @@ impl PwmActions { } } - /// Choose an `UpdateAction` for an `UTEA`/`UTEB` event where you can - /// specify which of the A/B to use + /// Chooses an `UpdateAction` for an `UTEA`/`UTEB` event, specifying which + /// of the A/B timestamps to use. pub const fn on_up_counting_timer_equals_ch_timestamp( self, action: UpdateAction, @@ -648,17 +647,17 @@ impl PwmActions { } } - /// Choose an `UpdateAction` for an `DTEZ` event + /// Chooses an `UpdateAction` for an `DTEZ` event. pub const fn on_down_counting_timer_equals_zero(self, action: UpdateAction) -> Self { self.with_value_at_offset(action as u32, 12) } - /// Choose an `UpdateAction` for an `DTEP` event + /// Chooses an `UpdateAction` for an `DTEP` event. pub const fn on_down_counting_timer_equals_period(self, action: UpdateAction) -> Self { self.with_value_at_offset(action as u32, 14) } - /// Choose an `UpdateAction` for an `DTEA`/`DTEB` event + /// Chooses an `UpdateAction` for an `DTEA`/`DTEB` event. pub const fn on_down_counting_timer_equals_timestamp(self, action: UpdateAction) -> Self { match IS_A { true => self.with_value_at_offset(action as u32, 16), @@ -666,8 +665,8 @@ impl PwmActions { } } - /// Choose an `UpdateAction` for an `DTEA`/`DTEB` event where you can - /// specify which of the A/B to use + /// Chooses an `UpdateAction` for an `DTEA`/`DTEB` event, specifying which + /// of the A/B timestamps to use. pub const fn on_down_counting_timer_equals_ch_timestamp( self, action: UpdateAction, @@ -691,11 +690,11 @@ impl PwmActions { pub struct PwmUpdateMethod(u8); impl PwmUpdateMethod { - /// New timestamp will be applied immediately - pub const SYNC_IMMEDIATLY: Self = Self::empty(); - /// New timestamp will be applied when timer is equal to zero + /// New timestamp will be applied immediately. + pub const SYNC_IMMEDIATELY: Self = Self::empty(); + /// New timestamp will be applied when timer is equal to zero. pub const SYNC_ON_ZERO: Self = Self::empty().sync_on_timer_equals_zero(); - /// New timestamp will be applied when timer is equal to period + /// New timestamp will be applied when timer is equal to period. pub const SYNC_ON_PERIOD: Self = Self::empty().sync_on_timer_equals_period(); /// `PwmUpdateMethod` with no sync triggers. @@ -704,13 +703,13 @@ impl PwmUpdateMethod { PwmUpdateMethod(0) } - /// Enable syncing new timestamp values when timer is equal to zero + /// Enables syncing new timestamp values when timer is equal to zero. pub const fn sync_on_timer_equals_zero(mut self) -> Self { self.0 |= 0b0001; self } - /// Enable syncing new timestamp values when timer is equal to period + /// Enables syncing new timestamp values when timer is equal to period. pub const fn sync_on_timer_equals_period(mut self) -> Self { self.0 |= 0b0010; self diff --git a/esp-hal/src/mcpwm/timer.rs b/esp-hal/src/mcpwm/timer.rs index 14053aefb94..1729301b063 100644 --- a/esp-hal/src/mcpwm/timer.rs +++ b/esp-hal/src/mcpwm/timer.rs @@ -13,7 +13,7 @@ use crate::{ time::Rate, }; -/// A MCPWM timer +/// A MCPWM timer. /// /// Every timer of a particular [`MCPWM`](super::McPwm) peripheral can be used /// as a timing reference for every @@ -33,13 +33,12 @@ impl Timer { } } - /// Apply the given timer configuration. + /// Applies the given timer configuration. /// - /// ### Note: /// The prescaler and period configuration will be applied immediately by /// default and before setting the [`PwmWorkingMode`]. - /// If the timer is already running you might want to call [`Timer::stop`] - /// and/or [`Timer::set_counter`] first + /// If the timer is already running, call [`Timer::stop`] + /// or [`Timer::set_counter`] first /// (if the new period is larger than the current counter value this will /// cause weird behavior). /// @@ -67,13 +66,13 @@ impl Timer { }); } - /// Stop the timer in its current state + /// Stops the timer in its current state. pub fn stop(&mut self) { // freeze the timer self.cfg1().write(|w| unsafe { w.mod_().bits(0) }); } - /// Set the timer counter to the provided value + /// Sets the timer counter to the provided value. pub fn set_counter(&mut self, phase: u16, direction: CounterDirection) { // SAFETY: // We only write to our TIMERx_SYNC register @@ -88,7 +87,7 @@ impl Timer { }); } - /// Read the counter value and counter direction of the timer + /// Reads the counter value and counter direction of the timer. pub fn status(&self) -> (u16, CounterDirection) { // SAFETY: // We only read from our TIMERx_STATUS register @@ -114,7 +113,7 @@ impl Timer { } } -/// Clock configuration of a MCPWM timer +/// Clocks configuration of a MCPWM timer. /// /// Use [`PeripheralClockConfig::timer_clock_with_prescaler`](super::PeripheralClockConfig::timer_clock_with_prescaler) or /// [`PeripheralClockConfig::timer_clock_with_frequency`](super::PeripheralClockConfig::timer_clock_with_frequency) to it. @@ -185,7 +184,7 @@ impl TimerClockConfig { }) } - /// Set the method for updating the PWM period + /// Sets the method for updating the PWM period. pub fn with_period_updating_method(self, method: PeriodUpdatingMethod) -> Self { Self { period_updating_method: method, @@ -193,10 +192,9 @@ impl TimerClockConfig { } } - /// Get the timer clock frequency. + /// Returns the timer clock frequency. /// - /// ### Note: - /// The actual value is rounded down to the nearest `u32` value + /// The actual value is rounded down to the nearest `u32` value. pub fn frequency(&self) -> Rate { self.frequency } @@ -238,13 +236,13 @@ pub enum PwmWorkingMode { UpDown = 3, } -/// The direction the timer counter is changing +/// The direction the timer counter is changing. #[derive(Debug)] #[repr(u8)] pub enum CounterDirection { - /// The timer counter is increasing + /// The timer counter is increasing. Increasing = 0, - /// The timer counter is decreasing + /// The timer counter is decreasing. Decreasing = 1, } diff --git a/esp-hal/src/mipi_dsi/dbi.rs b/esp-hal/src/mipi_dsi/dbi.rs index 09837a9707b..f427b9f2ac7 100644 --- a/esp-hal/src/mipi_dsi/dbi.rs +++ b/esp-hal/src/mipi_dsi/dbi.rs @@ -59,7 +59,7 @@ impl<'bus, 'd> DsiDbi<'bus, 'd> { self.virtual_channel } - /// Send a DCS write command with zero or more parameters. + /// Sends a DCS write command with zero or more parameters. /// /// Uses a short-write packet for 0 or 1 parameters, a long-write packet /// otherwise. @@ -130,7 +130,7 @@ impl<'bus, 'd> DsiDbi<'bus, 'd> { Ok(()) } - /// Issue a DCS read command (BTA) and drain the response into `out`. + /// Issues a DCS read command (BTA) and drains the response into `out`. /// /// Returns the number of bytes placed into `out`. pub fn read_cmd(&mut self, cmd: u8, out: &mut [u8]) -> Result { diff --git a/esp-hal/src/mipi_dsi/dpi.rs b/esp-hal/src/mipi_dsi/dpi.rs index 9a364515b9b..f219e72f3d1 100644 --- a/esp-hal/src/mipi_dsi/dpi.rs +++ b/esp-hal/src/mipi_dsi/dpi.rs @@ -25,8 +25,8 @@ use crate::{ /// Channel index used by the static VDMA block-done ISR. /// -/// Set before the channel is started; read by the ISR which cannot capture -/// runtime state. A single MIPI-DSI instance is the only VDMA user, so +/// Must be set before the channel is started. The ISR reads this value and cannot +/// capture runtime state. A single MIPI-DSI instance is the only VDMA user, so /// this value is stable for the lifetime of `DsiDpi`. static VDMA_ISR_CHANNEL: atomic::AtomicU8 = atomic::AtomicU8::new(0); @@ -225,10 +225,10 @@ impl<'d> DsiDpi<'d> { // upstream PLL reference count is maintained correctly. let (_dpi_clk_config, real_dpi_mhz) = ClockTree::with(|clocks| { // Obtain source frequency (div_num = 0 → no division applied yet). - let src_hz = MipiDsiInstance::dpi_clk_config_frequency( - clocks, - MipiDsiDpiClkConfig::new(config.dpi_clk_src, 0), - ); + let src_hz = MipiDsiInstance::dpi_clk_config_frequency(MipiDsiDpiClkConfig::new( + config.dpi_clk_src, + 0, + )); let src_mhz = src_hz as f32 / 1_000_000.0; let div = ((src_mhz / config.pixel_clock_mhz) + 0.5) as u32; let div = div.max(1); @@ -433,13 +433,13 @@ impl<'d> DsiDpi<'d> { /// Returns a mutable slice to the back (not-currently-displayed) frame buffer. /// /// With a single frame buffer this is the same buffer the DMA may be - /// reading — the caller is responsible for synchronisation in that case. + /// reading — the caller is responsible for synchronization in that case. pub fn framebuffer_mut(&mut self) -> &mut [u8] { let back = (self.current_fb + 1) % self.num_fbs; unsafe { core::slice::from_raw_parts_mut(self.fb_ptrs[back], self.fb_size) } } - /// Flip the back buffer to the display. + /// Flips the back buffer to the display. /// /// Flushes the rendered back buffer from CPU cache to PSRAM, then updates /// the source address in every LLI so the DMA switches to the new pixels @@ -472,11 +472,11 @@ impl<'d> DsiDpi<'d> { self.current_fb = back; } - /// Block until the DSI bridge signals the start of the next vertical blank. + /// Blocks until the DSI bridge signals the start of the next vertical blank. /// - /// Use this to pace rendering to the display refresh rate. Any vsync event + /// Use this to pace rendering to the display refresh rate. Any vsync event /// that is already pending (i.e. fired while the CPU was busy rendering) - /// will be returned immediately. + /// returns immediately. pub fn wait_for_vsync(&mut self) { let bridge = MIPI_DSI_BRIDGE::regs(); while !bridge.int_raw().read().vsync().bit_is_set() {} diff --git a/esp-hal/src/mipi_dsi/mod.rs b/esp-hal/src/mipi_dsi/mod.rs index 67971e5111b..35507f14082 100644 --- a/esp-hal/src/mipi_dsi/mod.rs +++ b/esp-hal/src/mipi_dsi/mod.rs @@ -85,7 +85,7 @@ pub struct Config { /// APLL is not yet modelled in the clock tree and cannot be selected here. phy_pll_refclk: MipiDsiPhyPllRefclkConfig, - /// Keep the clock lane continuously in HS mode (`true`) or use auto mode + /// Keeps the clock lane continuously in HS mode (`true`) or uses auto mode /// where the DSI host manages HS↔LP transitions (`false`). force_clock_lane_hs: bool, } @@ -146,7 +146,7 @@ pub struct MipiDsi<'d> { } impl<'d> MipiDsi<'d> { - /// Initialise the MIPI DSI bus. + /// Initializes the MIPI DSI bus. /// /// Enables APB clock, resets the bridge, powers up the D-PHY LDO, /// configures D-PHY PLL, and polls for PLL lock + lane-stopped status @@ -186,7 +186,7 @@ impl<'d> MipiDsi<'d> { MipiDsiInstance::MipiDsi.configure_phy_pll_refclk(clocks, config.phy_pll_refclk); MipiDsiInstance::MipiDsi.request_phy_pll_refclk(clocks); - MipiDsiInstance::phy_pll_refclk_config_frequency(clocks, config.phy_pll_refclk) + MipiDsiInstance::phy_pll_refclk_config_frequency(config.phy_pll_refclk) }); let ref_freq_mhz = ref_freq_hz as f32 / 1_000_000.0; @@ -312,12 +312,12 @@ impl<'d> MipiDsi<'d> { }) } - /// Attach a command-mode (DBI) interface for panel init sequences. + /// Attaches a command-mode (DBI) interface for panel init sequences. pub fn dbi(&mut self, virtual_channel: u8) -> dbi::DsiDbi<'_, 'd> { dbi::DsiDbi::new(self, virtual_channel) } - /// Enter video-mode (DPI) streaming. + /// Enters video-mode (DPI) streaming. /// /// Consumes `self`; the returned [`DsiDpi`] keeps clocks enabled for the /// lifetime of the streaming session. @@ -336,7 +336,7 @@ impl<'d> MipiDsi<'d> { // ── D-PHY power ─────────────────────────────────────────────────────────────── -/// Power up the internal LDO that supplies VDD_MIPI_DPHY at 2.5 V. +/// Powers up the internal LDO that supplies VDD_MIPI_DPHY at 2.5 V. /// /// On ESP32-P4 the DPHY power rail (VDD_MIPI_DPHY) is driven by PMU /// internal LDO channel 3 (VO3), which maps to the `ext_ldo_p0_0p2a` @@ -359,7 +359,7 @@ pub(crate) fn dphy_ldo_power_on() { rom::ets_delay_us(500); } -/// Shut down the D-PHY and disable its LDO. +/// Shuts down the D-PHY and disables its LDO. /// /// Mirrors `dphy_ldo_power_on` in reverse: reset the PHY digital and /// analog sections, power off the DSI host, then clear the LDO `xpd` bit @@ -431,10 +431,10 @@ fn hs_freq_range(lane_mbps: f32) -> u8 { .map_or(0x00, |&(_, sel)| sel) } -/// Compute PLL M and N divisors. +/// Computes PLL M and N divisors. /// /// Constraint: 5 MHz ≤ f_ref/N ≤ 40 MHz, M must be even. -/// Returns `(M, N, actual_lane_rate_mbps)` or `None` if no solution found. +/// Returns `(M, N, actual_lane_rate_mbps)` or `None` if no solution is found. fn compute_pll(ref_freq_mhz: f32, target_mbps: f32) -> Option<(u16, u8, f32)> { let min_n = ((ref_freq_mhz / 40.0) as u8).max(1); let max_n = (ref_freq_mhz / 5.0) as u8; @@ -470,7 +470,7 @@ fn compute_pll(ref_freq_mhz: f32, target_mbps: f32) -> Option<(u16, u8, f32)> { // ── Helpers ─────────────────────────────────────────────────────────────────── -/// Round a positive f32 to the nearest u8 without using `f32::round()`. +/// Rounds a positive f32 to the nearest u8 without using `f32::round()`. #[inline] fn fround_u8(x: f32) -> u8 { (x + 0.5) as u8 diff --git a/esp-hal/src/mipi_dsi/vdma.rs b/esp-hal/src/mipi_dsi/vdma.rs index 31c46dd9591..a692aeca318 100644 --- a/esp-hal/src/mipi_dsi/vdma.rs +++ b/esp-hal/src/mipi_dsi/vdma.rs @@ -117,7 +117,7 @@ impl VdmaLinkItem { self._res3.set(0); } - /// Update the source address in this LLI. + /// Updates the source address in this LLI. /// /// Safe to call while the DMA is running: the controller latches `sar_lo` /// at the **start** of each block, so an in-flight block is unaffected and @@ -138,13 +138,13 @@ impl VdmaLinkItem { } } -/// Handle for a single VDMA channel dedicated to the DSI bridge. +/// Handles for a single VDMA channel dedicated to the DSI bridge. pub(super) struct VdmaChannel { channel_id: u8, } impl VdmaChannel { - /// Initialise the VDMA controller and configure channel `channel_id` + /// Initializes the VDMA controller and configures channel `channel_id` /// (0-indexed, 0–3) for mem→DSI linked-list transfers. /// /// The caller must hold the `Vdma` peripheral guard before calling this. @@ -180,7 +180,7 @@ impl VdmaChannel { Self { channel_id } } - /// Point the channel's LLP at `item` and enable the channel. + /// Points the channel's LLP at `item` and enables the channel. pub(super) fn start(&mut self, item: &VdmaLinkItem) { let addr = item as *const VdmaLinkItem as u32; debug_assert_eq!(addr & 0x3F, 0, "LLI must be 64-byte aligned"); diff --git a/esp-hal/src/parl_io.rs b/esp-hal/src/parl_io.rs index 1a594c7f873..6402267ed0e 100644 --- a/esp-hal/src/parl_io.rs +++ b/esp-hal/src/parl_io.rs @@ -35,7 +35,7 @@ //! ); //! let mut rx_clk_pin = NoPin; //! -//! // Set up Parallel IO for 1MHz data input, with DMA and bit packing +//! // Set up Parallel IO for 1 MHz data input, with DMA and bit packing //! // configuration //! let parl_io = ParlIo::new(peripherals.PARL_IO, dma_channel)?; //! @@ -81,7 +81,7 @@ //! //! let mut pin_conf = TxPinConfigWithValidPin::new(tx_pins, peripherals.GPIO5); //! -//! // Set up Parallel IO for 1MHz data input, with DMA and bit packing +//! // Set up Parallel IO for 1 MHz data input, with DMA and bit packing //! // configuration //! let parl_io = ParlIo::new( //! peripherals.PARL_IO, @@ -120,6 +120,7 @@ use core::{ }; use enumset::{EnumSet, EnumSetType}; +use esp_sync::RawMutex; use private::*; use crate::{ @@ -134,7 +135,9 @@ use crate::{ DmaError, DmaPeripheral, DmaRxBuffer, + DmaRxInterrupt, DmaTxBuffer, + DmaTxInterrupt, }, gpio::{ self, @@ -154,7 +157,10 @@ use crate::{ // TODO: C5 has the option for unlimited DMA transfers const MAX_DMA_SIZE: usize = 65535; -/// Interrupts generated by the peripheral +/// Interrupt sources of the PARL_IO peripheral. +/// +/// The [`ParlIoTx`] and [`ParlIoRx`] drivers expose the sources of their own +/// unit via [`ParlIoTxInterrupt`] and [`ParlIoRxInterrupt`]. #[derive(Debug, EnumSetType)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum ParlIoInterrupt { @@ -168,6 +174,84 @@ pub enum ParlIoInterrupt { TxEof, } +/// Interrupt sources of the PARL_IO TX unit. +/// +/// These sources fire on the `PARL_IO` interrupt, which is bound via +/// [`ParlIo::set_interrupt_handler`]. +#[derive(Debug, EnumSetType)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum ParlIoTxInterrupt { + /// Triggered when TX FIFO is empty. This interrupt indicates that there + /// might be error in the data sent by TX. + FifoReEmpty, + /// Triggered when TX finishes sending a complete frame of data. + Eof, +} + +/// Interrupt sources of the PARL_IO RX unit. +/// +/// These sources fire on the `PARL_IO` interrupt, which is bound via +/// [`ParlIo::set_interrupt_handler`]. +#[derive(Debug, EnumSetType)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum ParlIoRxInterrupt { + /// Triggered when RX FIFO is full. This interrupt indicates that there + /// might be error in the data received by RX. + FifoWOvf, +} + +/// Variant-for-variant mapping onto the peripheral's interrupt sources. +/// +/// This is total: every [`ParlIoTxInterrupt`] source has a +/// [`ParlIoInterrupt`] counterpart. +impl From for ParlIoInterrupt { + fn from(value: ParlIoTxInterrupt) -> Self { + match value { + ParlIoTxInterrupt::FifoReEmpty => ParlIoInterrupt::TxFifoReEmpty, + ParlIoTxInterrupt::Eof => ParlIoInterrupt::TxEof, + } + } +} + +/// Lossy reverse mapping: RX-only [`ParlIoInterrupt`] variants have no +/// [`ParlIoTxInterrupt`] counterpart and are dropped. +impl TryFrom for ParlIoTxInterrupt { + type Error = (); + + fn try_from(value: ParlIoInterrupt) -> Result { + match value { + ParlIoInterrupt::TxFifoReEmpty => Ok(ParlIoTxInterrupt::FifoReEmpty), + ParlIoInterrupt::TxEof => Ok(ParlIoTxInterrupt::Eof), + ParlIoInterrupt::RxFifoWOvf => Err(()), + } + } +} + +/// Variant-for-variant mapping onto the peripheral's interrupt sources. +/// +/// This is total: every [`ParlIoRxInterrupt`] source has a +/// [`ParlIoInterrupt`] counterpart. +impl From for ParlIoInterrupt { + fn from(value: ParlIoRxInterrupt) -> Self { + match value { + ParlIoRxInterrupt::FifoWOvf => ParlIoInterrupt::RxFifoWOvf, + } + } +} + +/// Lossy reverse mapping: TX-only [`ParlIoInterrupt`] variants have no +/// [`ParlIoRxInterrupt`] counterpart and are dropped. +impl TryFrom for ParlIoRxInterrupt { + type Error = (); + + fn try_from(value: ParlIoInterrupt) -> Result { + match value { + ParlIoInterrupt::RxFifoWOvf => Ok(ParlIoRxInterrupt::FifoWOvf), + _ => Err(()), + } + } +} + /// Parallel IO errors #[derive(Debug, Clone, Copy, PartialEq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] @@ -175,7 +259,7 @@ pub enum ParlIoInterrupt { pub enum Error { /// General DMA error DmaError(DmaError), - /// Maximum transfer size (32736) exceeded + /// Maximum transfer size exceeded MaxDmaTransferSizeExceeded, } @@ -206,13 +290,13 @@ pub enum BitPackOrder { } #[cfg(parl_io_version = "1")] -/// Enable Mode +/// Selects how the RX enable signal is interpreted. #[derive(Debug, Clone, Copy, PartialEq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum EnableMode { - /// Enable at high level + /// Enables at high level. HighLevel, - /// Enable at low level + /// Enables at low level. LowLevel, /// Positive pulse start (data bit included) & Positive pulse end (data bit /// included) @@ -286,11 +370,11 @@ impl EnableMode { } #[cfg(parl_io_version = "2")] -/// Enable Mode +/// Selects how the RX enable signal is interpreted. #[derive(Debug, Clone, Copy, PartialEq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum EnableMode { - /// Enable at high level + /// Enables at high level. HighLevel, /// Positive pulse start (data bit included) & Positive pulse end (data bit /// included) @@ -348,7 +432,7 @@ pub struct RxConfig { frequency: Rate, /// Configures the packing order to pack bits into 1 byte when data - /// bus width is 4/2/1 bit. + /// bus width is 4, 2, or 1 bit. bit_order: BitPackOrder, /// RX threshold of a timeout counter. @@ -370,6 +454,21 @@ impl Default for RxConfig { } } +/// Selects the source of the TX EOF event. +/// +/// Only available on chips with `PARL_IO` version 2 (e.g. the ESP32-C5). +#[cfg(parl_io_version = "2")] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[non_exhaustive] +pub enum TxEofSource { + /// The TX EOF event is generated once the configured number of bits has + /// been transmitted (reset default). + BitLen, + /// The TX EOF event is generated by the DMA channel's EOF signal. + DmaEof, +} + /// PARL_IO TX configuration #[derive(Debug, Clone, Copy, procmacros::BuilderLite)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] @@ -385,8 +484,12 @@ pub struct TxConfig { sample_edge: SampleEdge, /// Configures the unpacking order to unpack bits from 1 byte when - /// data bus width is 4/2/1 bit. + /// data bus width is 4, 2, or 1 bit. bit_order: BitPackOrder, + + /// Configures the source of the TX EOF event. + #[cfg(parl_io_version = "2")] + eof_source: TxEofSource, } impl Default for TxConfig { @@ -396,6 +499,8 @@ impl Default for TxConfig { idle_value: 0, sample_edge: SampleEdge::Normal, bit_order: BitPackOrder::Msb, + #[cfg(parl_io_version = "2")] + eof_source: TxEofSource::BitLen, } } } @@ -421,7 +526,51 @@ impl core::fmt::Display for ConfigError { } } -/// Used to configure no pin as clock output +/// PCR value that selects the clock from the GPIO pad. +const PCR_PAD_CLK_SEL: u8 = 3; + +fn apply_clock_divider(is_tx: bool, frequency: Rate) -> Result<(), ConfigError> { + let pcr = PCR::regs(); + let using_pad_clock = if is_tx { + pcr.parl_clk_tx_conf().read().parl_clk_tx_sel().bits() == PCR_PAD_CLK_SEL + } else { + pcr.parl_clk_rx_conf().read().parl_clk_rx_sel().bits() == PCR_PAD_CLK_SEL + }; + + if using_pad_clock { + // The GPIO pad supplies the unit clock. `TxConfig`/`RxConfig` frequency is the + // internal divider target and must not be applied to the pad clock. + return Ok(()); + } + + if frequency.as_hz() > 40_000_000 { + return Err(ConfigError::UnreachableClockRate); + } + + let source_hz = if is_tx { + ParlIoInstance::ParlIo.tx_clock_frequency() + } else { + ParlIoInstance::ParlIo.rx_clock_frequency() + }; + // The unit clock is the source clock divided by `div_num + 1`. + let divider = source_hz / frequency.as_hz(); + if divider == 0 || divider - 1 > 0xFFFF { + return Err(ConfigError::UnreachableClockRate); + } + let div_num = (divider - 1) as u16; + + if is_tx { + pcr.parl_clk_tx_conf() + .modify(|_, w| unsafe { w.parl_clk_tx_div_num().bits(div_num) }); + } else { + pcr.parl_clk_rx_conf() + .modify(|_, w| unsafe { w.parl_clk_rx_div_num().bits(div_num) }); + } + + Ok(()) +} + +/// Implements a clock pin that connects no signal. impl TxClkPin for NoPin { fn configure(&mut self) { OutputSignal::PARL_TX_CLK.connect_to(self); @@ -433,12 +582,12 @@ impl RxClkPin for NoPin { } } -/// Wraps a GPIO pin which will be used as the clock output signal +/// Wraps a GPIO pin used as the clock output signal. pub struct ClkOutPin<'d> { pin: interconnect::OutputSignal<'d>, } impl<'d> ClkOutPin<'d> { - /// Create a ClkOutPin + /// Creates a new [`ClkOutPin`]. pub fn new(pin: impl PeripheralOutput<'d>) -> Self { Self { pin: pin.into() } } @@ -452,12 +601,12 @@ impl TxClkPin for ClkOutPin<'_> { } } -/// Wraps a GPIO pin which will be used as the TX clock input signal +/// Wraps a GPIO pin used as the TX clock input signal. pub struct ClkInPin<'d> { pin: interconnect::InputSignal<'d>, } impl<'d> ClkInPin<'d> { - /// Create a new ClkInPin + /// Creates a new [`ClkInPin`]. pub fn new(pin: impl PeripheralInput<'d>) -> Self { Self { pin: pin.into() } } @@ -474,13 +623,13 @@ impl TxClkPin for ClkInPin<'_> { } } -/// Wraps a GPIO pin which will be used as the RX clock input signal +/// Wraps a GPIO pin used as the RX clock input signal. pub struct RxClkInPin<'d> { pin: interconnect::InputSignal<'d>, sample_edge: SampleEdge, } impl<'d> RxClkInPin<'d> { - /// Create a new RxClkInPin + /// Creates a new [`RxClkInPin`]. pub fn new(pin: impl PeripheralInput<'d>, sample_edge: SampleEdge) -> Self { Self { pin: pin.into(), @@ -516,7 +665,7 @@ impl<'d, P> TxPinConfigWithValidPin<'d, P> where P: NotContainsValidSignalPin + TxPins + ConfigurePins + 'd, { - /// Create a [TxPinConfigWithValidPin] + /// Creates a new [`TxPinConfigWithValidPin`]. pub fn new(tx_pins: P, valid_pin: impl PeripheralOutput<'d>) -> Self { Self { tx_pins, @@ -541,11 +690,10 @@ where .apply_output_config(&gpio::OutputConfig::default()); self.valid_pin.set_output_enable(true); - #[cfg(esp32c5)] + #[cfg(parl_io_has_tx_cs)] { - // C5 has a dedicated chip select signal. This signal is active low, and we need to - // invert it to end up with the same behaviour as older chips. - // TODO: this needs to be turned into metadata. + // The dedicated chip-select output is active low. Invert it so the pin is + // active high, as on chips that use a data line. use crate::gpio::interconnect::OutputSignal; let valid_pin = core::mem::replace( @@ -573,7 +721,7 @@ impl

TxPinConfigIncludingValidPin

where P: ContainsValidSignalPin + TxPins + ConfigurePins, { - /// Create a new [TxPinConfigIncludingValidPin] + /// Creates a new [`TxPinConfigIncludingValidPin`]. pub fn new(tx_pins: P) -> Self { Self { tx_pins } } @@ -608,7 +756,7 @@ macro_rules! tx_pins { impl<'d> $name<'d> { - /// Create a new TX pin + /// Creates a new TX pin. #[allow(clippy::too_many_arguments)] pub fn new( $( @@ -660,7 +808,7 @@ tx_pins!( P6 = PARL_TX_DATA6, P7 = PARL_TX_DATA7 ); -#[cfg(parl_io_version = "1")] +#[cfg(parl_io_max_data_width = "16")] tx_pins!( TxSixteenBits, 16, @@ -686,15 +834,18 @@ impl NotContainsValidSignalPin for TxOneBit<'_> {} impl NotContainsValidSignalPin for TxTwoBits<'_> {} impl NotContainsValidSignalPin for TxFourBits<'_> {} -#[cfg(any(esp32c5, esp32c6))] +#[cfg(any(parl_io_has_tx_cs, parl_io_max_data_width = "16"))] impl NotContainsValidSignalPin for TxEightBits<'_> {} -#[cfg(esp32h2)] +#[cfg(all(parl_io_max_data_width = "8", not(parl_io_has_tx_cs)))] impl ContainsValidSignalPin for TxEightBits<'_> {} -#[cfg(parl_io_version = "1")] +#[cfg(all(parl_io_max_data_width = "16", not(parl_io_has_tx_cs)))] impl ContainsValidSignalPin for TxSixteenBits<'_> {} +#[cfg(all(parl_io_max_data_width = "16", parl_io_has_tx_cs))] +impl NotContainsValidSignalPin for TxSixteenBits<'_> {} + /// Pin configuration with an additional pin for the valid signal. pub struct RxPinConfigWithValidPin<'d, P> where @@ -709,7 +860,7 @@ impl<'d, P> RxPinConfigWithValidPin<'d, P> where P: NotContainsValidSignalPin + RxPins + ConfigurePins, { - /// Create a new [RxPinConfigWithValidPin] + /// Creates a new [`RxPinConfigWithValidPin`]. pub fn new(rx_pins: P, valid_pin: impl PeripheralInput<'d>, enable_mode: EnableMode) -> Self { Self { rx_pins, @@ -736,6 +887,7 @@ where self.valid_pin.set_input_enable(true); Instance::rx_valid_pin_signal().connect_to(&self.valid_pin); + Instance::set_rx_valid_line(); Instance::set_rx_sw_en(false); if let Some(sel) = self.enable_mode.pulse_submode_sel() { Instance::set_rx_pulse_submode_sel(sel); @@ -762,7 +914,7 @@ impl

RxPinConfigIncludingValidPin

where P: ContainsValidSignalPin + RxPins + ConfigurePins, { - /// Create a new [RxPinConfigIncludingValidPin] + /// Creates a new [`RxPinConfigIncludingValidPin`]. pub fn new(rx_pins: P, enable_mode: EnableMode) -> Self { Self { rx_pins, @@ -782,6 +934,7 @@ where { fn configure(&mut self) { self.rx_pins.configure(); + Instance::set_rx_valid_line(); Instance::set_rx_sw_en(false); if let Some(sel) = self.enable_mode.pulse_submode_sel() { Instance::set_rx_pulse_submode_sel(sel); @@ -809,7 +962,7 @@ macro_rules! rx_pins { impl<'d> $name<'d> { - /// Create a new RX pin + /// Creates a new RX pin. #[allow(clippy::too_many_arguments)] pub fn new( $( @@ -860,7 +1013,7 @@ rx_pins!( P6 = PARL_RX_DATA6, P7 = PARL_RX_DATA7 ); -#[cfg(parl_io_version = "1")] +#[cfg(parl_io_max_data_width = "16")] rx_pins!( RxSixteenBits, 16, @@ -886,20 +1039,25 @@ impl NotContainsValidSignalPin for RxOneBit<'_> {} impl NotContainsValidSignalPin for RxTwoBits<'_> {} impl NotContainsValidSignalPin for RxFourBits<'_> {} -#[cfg(any(esp32c5, esp32c6))] +#[cfg(parl_io_max_data_width = "16")] impl NotContainsValidSignalPin for RxEightBits<'_> {} -#[cfg(esp32h2)] +#[cfg(parl_io_max_data_width = "8")] impl ContainsValidSignalPin for RxEightBits<'_> {} -#[cfg(parl_io_version = "1")] +#[cfg(parl_io_max_data_width = "16")] impl ContainsValidSignalPin for RxSixteenBits<'_> {} impl<'d, Dm> TxCreator<'d, Dm> where Dm: DriverMode, { - /// Configure TX to use the given pins and settings + /// Configures TX to use the given pins and settings. + /// + /// # Errors + /// + /// Returns [`ConfigError::UnreachableClockRate`] when the requested + /// frequency cannot be reached. pub fn with_config( self, mut tx_pins: P, @@ -911,12 +1069,15 @@ where CP: TxClkPin + 'd, { tx_pins.configure(); - clk_pin.configure(); let mut this = ParlIoTx { tx_channel: self.tx_channel, _guard: ParlIoTxGuard::new(self._guard), }; + // Configure the clock pin after the clock tree enables the TX clock. The guard + // selects an internal source. `ClkInPin` then switches the source to the GPIO + // pad, and that selection must remain in effect. + clk_pin.configure(); this.apply_config(&config)?; Ok(this) @@ -946,7 +1107,12 @@ impl<'d, Dm> RxCreator<'d, Dm> where Dm: DriverMode, { - /// Configure RX to use the given pins and settings + /// Configures RX to use the given pins and settings. + /// + /// # Errors + /// + /// Returns [`ConfigError::UnreachableClockRate`] when the requested + /// frequency cannot be reached. pub fn with_config( self, mut rx_pins: P, @@ -961,12 +1127,15 @@ where Instance::set_rx_sample_mode(SampleMode::InternalSoftwareEnable); rx_pins.configure(); - clk_pin.configure(); let mut this = ParlIoRx { rx_channel: self.rx_channel, _guard: ParlIoRxGuard::new(self._guard), }; + // Configure the clock pin after the clock tree enables the RX clock. The guard + // selects an internal source. `RxClkInPin` then switches the source to the GPIO + // pad, and that selection must remain in effect. + clk_pin.configure(); this.apply_config(&config)?; Ok(this) @@ -1012,16 +1181,25 @@ fn internal_set_interrupt_handler(handler: InterruptHandler) { } } +// NOTE: the PARL_IO interrupt enable register is shared between the TX and RX +// units, and can also be touched by interrupt handlers (e.g. the async driver's +// waker handler or a user handler managing the transfer through the transfer +// object). `listen`/`unlisten` are read-modify-writes, so they must run inside +// a reentrancy-safe lock to avoid losing enable bits to concurrent updates. +static INTERRUPT_LOCK: RawMutex = RawMutex::new(); + fn internal_listen(interrupts: EnumSet, enable: bool) { - PARL_IO::regs().int_ena().write(|w| { - for interrupt in interrupts { - match interrupt { - ParlIoInterrupt::TxFifoReEmpty => w.tx_fifo_rempty().bit(enable), - ParlIoInterrupt::RxFifoWOvf => w.rx_fifo_wovf().bit(enable), - ParlIoInterrupt::TxEof => w.tx_eof().bit(enable), - }; - } - w + INTERRUPT_LOCK.lock(|| { + PARL_IO::regs().int_ena().modify(|_, w| { + for interrupt in interrupts { + match interrupt { + ParlIoInterrupt::TxFifoReEmpty => w.tx_fifo_rempty().bit(enable), + ParlIoInterrupt::RxFifoWOvf => w.rx_fifo_wovf().bit(enable), + ParlIoInterrupt::TxEof => w.tx_eof().bit(enable), + }; + } + w + }); }); } @@ -1070,7 +1248,12 @@ where } impl<'d> ParlIo<'d, Blocking> { - /// Create a new instance of [ParlIo] + /// Creates a new instance of [ParlIo]. + /// + /// # Errors + /// + /// Returns [`Error::DmaError`] when the DMA channel is not compatible + /// with the PARL_IO peripheral. pub fn new( _parl_io: PARL_IO<'d>, dma_channel: impl ParlIoDmaChannel<'d>, @@ -1092,7 +1275,7 @@ impl<'d> ParlIo<'d, Blocking> { }) } - /// Convert to an async version. + /// Converts to an async version. pub fn into_async(self) -> ParlIo<'d, Async> { internal_set_interrupt_handler(interrupt_handler); @@ -1109,7 +1292,7 @@ impl<'d> ParlIo<'d, Blocking> { } /// Sets the interrupt handler, enables it with - /// [crate::interrupt::Priority::min()] + /// [`crate::interrupt::Priority::min()`]. /// /// Interrupts are not enabled at the peripheral level here. #[instability::unstable] @@ -1117,25 +1300,75 @@ impl<'d> ParlIo<'d, Blocking> { internal_set_interrupt_handler(handler); } - /// Listen for the given interrupts + /// Listens for the given interrupts. pub fn listen(&mut self, interrupts: impl Into>) { internal_listen(interrupts.into(), true); } - /// Unlisten the given interrupts + /// Unlistens from the given interrupts. pub fn unlisten(&mut self, interrupts: impl Into>) { internal_listen(interrupts.into(), false); } - /// Gets asserted interrupts + /// Returns the asserted interrupts. pub fn interrupts(&mut self) -> EnumSet { internal_interrupts() } - /// Resets asserted interrupts + /// Resets asserted interrupts. pub fn clear_interrupts(&mut self, interrupts: EnumSet) { internal_clear_interrupts(interrupts); } + + /// Maps the TX sources of the given set onto the peripheral's interrupt + /// sources. + fn map_tx_to_parl_io(interrupts: EnumSet) -> EnumSet { + let mut sources = EnumSet::new(); + for interrupt in interrupts { + sources.insert(ParlIoInterrupt::from(interrupt)); + } + sources + } + + /// Maps the peripheral's asserted interrupt sources back to + /// [`ParlIoTxInterrupt`]. + /// + /// The mapping is lossy by design: RX-only [`ParlIoInterrupt`] variants + /// have no [`ParlIoTxInterrupt`] counterpart and are dropped. + fn map_parl_io_to_tx(sources: EnumSet) -> EnumSet { + let mut interrupts = EnumSet::new(); + for source in sources { + if let Ok(interrupt) = ParlIoTxInterrupt::try_from(source) { + interrupts.insert(interrupt); + } + } + interrupts + } + + /// Maps the RX sources of the given set onto the peripheral's interrupt + /// sources. + fn map_rx_to_parl_io(interrupts: EnumSet) -> EnumSet { + let mut sources = EnumSet::new(); + for interrupt in interrupts { + sources.insert(ParlIoInterrupt::from(interrupt)); + } + sources + } + + /// Maps the peripheral's asserted interrupt sources back to + /// [`ParlIoRxInterrupt`]. + /// + /// The mapping is lossy by design: TX-only [`ParlIoInterrupt`] variants + /// have no [`ParlIoRxInterrupt`] counterpart and are dropped. + fn map_parl_io_to_rx(sources: EnumSet) -> EnumSet { + let mut interrupts = EnumSet::new(); + for source in sources { + if let Ok(interrupt) = ParlIoRxInterrupt::try_from(source) { + interrupts.insert(interrupt); + } + } + interrupts + } } impl crate::private::Sealed for ParlIo<'_, Blocking> {} @@ -1148,7 +1381,7 @@ impl crate::interrupt::InterruptConfigurable for ParlIo<'_, Blocking> { } impl<'d> ParlIo<'d, Async> { - /// Convert to a blocking version. + /// Converts to a blocking version. pub fn into_blocking(self) -> ParlIo<'d, Blocking> { ParlIo { tx: TxCreator { @@ -1167,11 +1400,17 @@ impl<'d, Dm> ParlIoTx<'d, Dm> where Dm: DriverMode, { - /// Perform a DMA write. + /// Performs a DMA write. /// - /// This will return a [ParlIoTxTransfer] + /// Returns a [`ParlIoTxTransfer`] that can be used to wait for the + /// transfer to complete. /// - /// The maximum amount of data to be sent is 32736 bytes. + /// # Errors + /// + /// Returns [`Error::MaxDmaTransferSizeExceeded`] when more than 65535 + /// bytes are requested. + /// Returns [`Error::DmaError`] when the DMA transfer cannot be prepared + /// or started. pub fn write( mut self, number_of_bytes: usize, @@ -1214,31 +1453,161 @@ where }) } - /// Change the bus configuration. + /// Changes the bus configuration. + /// + /// # Errors + /// + /// Returns [`ConfigError::UnreachableClockRate`] when the requested + /// frequency cannot be reached. pub fn apply_config(&mut self, config: &TxConfig) -> Result<(), ConfigError> { - if config.frequency.as_hz() > 40_000_000 { - return Err(ConfigError::UnreachableClockRate); - } - - let frequency = ParlIoInstance::ParlIo.tx_clock_frequency(); - let divider = frequency / config.frequency.as_hz(); - if divider > 0xFFFF { - return Err(ConfigError::UnreachableClockRate); - } - let divider = divider as u16; - - PCR::regs() - .parl_clk_tx_conf() - .modify(|_, w| unsafe { w.parl_clk_tx_div_num().bits(divider) }); + apply_clock_divider(true, config.frequency)?; Instance::set_tx_idle_value(config.idle_value); Instance::set_tx_sample_edge(config.sample_edge); Instance::set_tx_bit_order(config.bit_order); + #[cfg(parl_io_version = "2")] + Instance::set_tx_eof_gen_sel(config.eof_source); Ok(()) } } +/// DMA interrupt management for the TX driver. +/// +/// These methods manage the DMA TX channel's own interrupt, which is separate +/// from the PARL_IO interrupt managed by [`ParlIo`]'s interrupt methods. +#[instability::unstable] +impl<'d> ParlIoTx<'d, Blocking> { + /// Listens for the given PARL_IO TX interrupt sources. + /// + /// The handler serving these sources must have been registered via + /// [`ParlIo::set_interrupt_handler`]. + pub fn listen(&mut self, interrupts: impl Into>) { + internal_listen(ParlIo::map_tx_to_parl_io(interrupts.into()), true); + } + + /// Stops listening for the given PARL_IO TX interrupt sources. + pub fn unlisten(&mut self, interrupts: impl Into>) { + internal_listen(ParlIo::map_tx_to_parl_io(interrupts.into()), false); + } + + /// Returns the asserted PARL_IO TX interrupt sources. + pub fn interrupts(&mut self) -> EnumSet { + ParlIo::map_parl_io_to_tx(internal_interrupts()) + } + + /// Clears the given asserted PARL_IO TX interrupt sources. + pub fn clear_interrupts(&mut self, interrupts: impl Into>) { + internal_clear_interrupts(ParlIo::map_tx_to_parl_io(interrupts.into())); + } + + /// Registers an interrupt handler for the DMA TX channel used by this + /// driver. + /// + /// The handler services the sources enabled via [`Self::listen_dma`]. It + /// fires on the channel's own interrupt, which is separate from the + /// PARL_IO interrupt used by [`ParlIo::set_interrupt_handler`]. + /// + /// Binding the handler unlistens from and clears all DMA TX interrupt + /// sources, so this function must be called before + /// [`Self::listen_dma`]. It must also be called before [`Self::write`], + /// which consumes the driver. + pub fn set_dma_interrupt_handler(&mut self, handler: InterruptHandler) { + self.tx_channel.set_interrupt_handler(handler); + } + + /// Listens for the given DMA TX interrupt sources. + /// + /// A handler must have been registered via + /// [`Self::set_dma_interrupt_handler`] first. + pub fn listen_dma(&mut self, interrupts: impl Into>) { + self.tx_channel.listen_out(interrupts.into()); + } + + /// Stops listening for the given DMA TX interrupt sources. + pub fn unlisten_dma(&mut self, interrupts: impl Into>) { + self.tx_channel.unlisten_out(interrupts.into()); + } + + /// Returns the asserted DMA TX interrupt sources. + pub fn interrupts_dma(&mut self) -> EnumSet { + self.tx_channel.pending_out_interrupts() + } + + /// Clears the given asserted DMA TX interrupt sources. + pub fn clear_interrupts_dma(&mut self, interrupts: impl Into>) { + self.tx_channel.clear_out(interrupts.into()); + } +} + +/// DMA interrupt management for the RX driver. +/// +/// These methods manage the DMA RX channel's own interrupt, which is separate +/// from the PARL_IO interrupt managed by [`ParlIo`]'s interrupt methods. +#[instability::unstable] +impl<'d> ParlIoRx<'d, Blocking> { + /// Listens for the given PARL_IO RX interrupt sources. + /// + /// The handler serving these sources must have been registered via + /// [`ParlIo::set_interrupt_handler`]. + pub fn listen(&mut self, interrupts: impl Into>) { + internal_listen(ParlIo::map_rx_to_parl_io(interrupts.into()), true); + } + + /// Stops listening for the given PARL_IO RX interrupt sources. + pub fn unlisten(&mut self, interrupts: impl Into>) { + internal_listen(ParlIo::map_rx_to_parl_io(interrupts.into()), false); + } + + /// Returns the asserted PARL_IO RX interrupt sources. + pub fn interrupts(&mut self) -> EnumSet { + ParlIo::map_parl_io_to_rx(internal_interrupts()) + } + + /// Clears the given asserted PARL_IO RX interrupt sources. + pub fn clear_interrupts(&mut self, interrupts: impl Into>) { + internal_clear_interrupts(ParlIo::map_rx_to_parl_io(interrupts.into())); + } + + /// Registers an interrupt handler for the DMA RX channel used by this + /// driver. + /// + /// The handler services the sources enabled via [`Self::listen_dma`]. It + /// fires on the channel's own interrupt, which is separate from the + /// PARL_IO interrupt used by [`ParlIo::set_interrupt_handler`]. + /// + /// Binding the handler unlistens from and clears all DMA RX interrupt + /// sources, so this function must be called before + /// [`Self::listen_dma`]. It must also be called before [`Self::read`], + /// which consumes the driver. + pub fn set_dma_interrupt_handler(&mut self, handler: InterruptHandler) { + self.rx_channel.set_interrupt_handler(handler); + } + + /// Listens for the given DMA RX interrupt sources. + /// + /// A handler must have been registered via + /// [`Self::set_dma_interrupt_handler`] first. + pub fn listen_dma(&mut self, interrupts: impl Into>) { + self.rx_channel.listen_in(interrupts.into()); + } + + /// Stops listening for the given DMA RX interrupt sources. + pub fn unlisten_dma(&mut self, interrupts: impl Into>) { + self.rx_channel.unlisten_in(interrupts.into()); + } + + /// Returns the asserted DMA RX interrupt sources. + pub fn interrupts_dma(&mut self) -> EnumSet { + self.rx_channel.pending_in_interrupts() + } + + /// Clears the given asserted DMA RX interrupt sources. + pub fn clear_interrupts_dma(&mut self, interrupts: impl Into>) { + self.rx_channel.clear_in(interrupts.into()); + } +} + /// Represents an ongoing (or potentially finished) transfer using the PARL_IO /// TX. pub struct ParlIoTxTransfer<'d, BUF: DmaTxBuffer, Dm: DriverMode> { @@ -1247,7 +1616,7 @@ pub struct ParlIoTxTransfer<'d, BUF: DmaTxBuffer, Dm: DriverMode> { } impl<'d, BUF: DmaTxBuffer, Dm: DriverMode> ParlIoTxTransfer<'d, BUF, Dm> { - /// Returns true when [Self::wait] will not block. + /// Returns whether [`Self::wait`] returns immediately. pub fn is_done(&self) -> bool { Instance::is_tx_eof() } @@ -1285,6 +1654,61 @@ impl<'d, BUF: DmaTxBuffer, Dm: DriverMode> ParlIoTxTransfer<'d, BUF, Dm> { } } +/// Interrupt management for an ongoing transfer. +/// +/// The driver itself has been consumed by [`ParlIoTx::write`], so these +/// methods take `&self` and allow an interrupt handler to manage the +/// interrupt sources through the transfer object. +#[instability::unstable] +impl<'d, BUF> ParlIoTxTransfer<'d, BUF, Blocking> +where + BUF: DmaTxBuffer, +{ + /// Listens for the given PARL_IO TX interrupt sources. + pub fn listen(&self, interrupts: impl Into>) { + internal_listen(ParlIo::map_tx_to_parl_io(interrupts.into()), true); + } + + /// Stops listening for the given PARL_IO TX interrupt sources. + pub fn unlisten(&self, interrupts: impl Into>) { + internal_listen(ParlIo::map_tx_to_parl_io(interrupts.into()), false); + } + + /// Returns the asserted PARL_IO TX interrupt sources. + pub fn interrupts(&self) -> EnumSet { + ParlIo::map_parl_io_to_tx(internal_interrupts()) + } + + /// Clears the interrupt flags of the given PARL_IO TX interrupt sources. + pub fn clear_interrupts(&self, interrupts: impl Into>) { + internal_clear_interrupts(ParlIo::map_tx_to_parl_io(interrupts.into())); + } + + /// Listens for the given DMA TX interrupt sources. + /// + /// A handler must have been registered via + /// [`ParlIoTx::set_dma_interrupt_handler`] before the transfer was + /// started. + pub fn listen_dma(&self, interrupts: impl Into>) { + self.parl_io.tx_channel.listen_out(interrupts.into()); + } + + /// Stops listening for the given DMA TX interrupt sources. + pub fn unlisten_dma(&self, interrupts: impl Into>) { + self.parl_io.tx_channel.unlisten_out(interrupts.into()); + } + + /// Returns the asserted DMA TX interrupt sources. + pub fn interrupts_dma(&self) -> EnumSet { + self.parl_io.tx_channel.pending_out_interrupts() + } + + /// Clears the given asserted DMA TX interrupt sources. + pub fn clear_interrupts_dma(&self, interrupts: impl Into>) { + self.parl_io.tx_channel.clear_out(interrupts.into()); + } +} + impl Deref for ParlIoTxTransfer<'_, BUF, Dm> { type Target = BUF::View; @@ -1319,17 +1743,24 @@ impl<'d, Dm> ParlIoRx<'d, Dm> where Dm: DriverMode, { - /// Perform a DMA read. + /// Performs a DMA read. /// - /// This will return a [ParlIoRxTransfer] + /// Returns a [`ParlIoRxTransfer`] that can be used to wait for the + /// transfer to complete. /// - /// When the number of bytes is specified, the maximum amount of data is - /// 32736 bytes and the transfer ends when the number of specified bytes - /// is received. + /// When the number of bytes is specified, the transfer ends when the + /// number of specified bytes is received. /// - /// When the number of bytes is unspecified, there's no limit the amount of + /// When the number of bytes is unspecified, there is no limit to the amount of /// data transferred and the transfer ends when the enable signal /// signals the end or the DMA buffer runs out of space. + /// + /// # Errors + /// + /// Returns [`Error::MaxDmaTransferSizeExceeded`] when more than 65535 + /// bytes are requested. + /// Returns [`Error::DmaError`] when the DMA transfer cannot be prepared + /// or started. pub fn read( mut self, number_of_bytes: Option, @@ -1377,22 +1808,14 @@ where }) } - /// Change the bus configuration. + /// Changes the bus configuration. + /// + /// # Errors + /// + /// Returns [`ConfigError::UnreachableClockRate`] when the requested + /// frequency cannot be reached. pub fn apply_config(&mut self, config: &RxConfig) -> Result<(), ConfigError> { - if config.frequency.as_hz() > 40_000_000 { - return Err(ConfigError::UnreachableClockRate); - } - - let frequency = ParlIoInstance::ParlIo.rx_clock_frequency(); - let divider = frequency / config.frequency.as_hz(); - if divider > 0xffff { - return Err(ConfigError::UnreachableClockRate); - } - let divider = divider as u16; - - PCR::regs() - .parl_clk_rx_conf() - .modify(|_, w| unsafe { w.parl_clk_rx_div_num().bits(divider) }); + apply_clock_divider(false, config.frequency)?; Instance::set_rx_bit_order(config.bit_order); Instance::set_rx_timeout_ticks(config.timeout_ticks); @@ -1411,7 +1834,7 @@ pub struct ParlIoRxTransfer<'d, BUF: DmaRxBuffer, Dm: DriverMode> { } impl<'d, BUF: DmaRxBuffer, Dm: DriverMode> ParlIoRxTransfer<'d, BUF, Dm> { - /// Returns true when [Self::wait] will not block. + /// Returns whether [`Self::wait`] returns immediately. pub fn is_done(&self) -> bool { if self.dma_result.is_some() { return true; @@ -1483,7 +1906,62 @@ impl Drop for ParlIoRxTransfer<'_, BUF, Dm> { } } -/// Creates a TX channel +/// Interrupt management for an ongoing RX transfer. +/// +/// The driver itself has been consumed by [`ParlIoRx::read`], so these +/// methods take `&self` and allow an interrupt handler to manage the +/// interrupt sources through the transfer object. +#[instability::unstable] +impl<'d, BUF> ParlIoRxTransfer<'d, BUF, Blocking> +where + BUF: DmaRxBuffer, +{ + /// Listens for the given PARL_IO RX interrupt sources. + pub fn listen(&self, interrupts: impl Into>) { + internal_listen(ParlIo::map_rx_to_parl_io(interrupts.into()), true); + } + + /// Stops listening for the given PARL_IO RX interrupt sources. + pub fn unlisten(&self, interrupts: impl Into>) { + internal_listen(ParlIo::map_rx_to_parl_io(interrupts.into()), false); + } + + /// Returns the asserted PARL_IO RX interrupt sources. + pub fn interrupts(&self) -> EnumSet { + ParlIo::map_parl_io_to_rx(internal_interrupts()) + } + + /// Clears the interrupt flags of the given PARL_IO RX interrupt sources. + pub fn clear_interrupts(&self, interrupts: impl Into>) { + internal_clear_interrupts(ParlIo::map_rx_to_parl_io(interrupts.into())); + } + + /// Listens for the given DMA RX interrupt sources. + /// + /// A handler must have been registered via + /// [`ParlIoRx::set_dma_interrupt_handler`] before the transfer was + /// started. + pub fn listen_dma(&self, interrupts: impl Into>) { + self.parl_io.rx_channel.listen_in(interrupts.into()); + } + + /// Stops listening for the given DMA RX interrupt sources. + pub fn unlisten_dma(&self, interrupts: impl Into>) { + self.parl_io.rx_channel.unlisten_in(interrupts.into()); + } + + /// Returns the asserted DMA RX interrupt sources. + pub fn interrupts_dma(&self) -> EnumSet { + self.parl_io.rx_channel.pending_in_interrupts() + } + + /// Clears the given asserted DMA RX interrupt sources. + pub fn clear_interrupts_dma(&self, interrupts: impl Into>) { + self.parl_io.rx_channel.clear_in(interrupts.into()); + } +} + +/// TX channel builder for parallel IO. pub struct TxCreator<'d, Dm> where Dm: DriverMode, @@ -1492,7 +1970,7 @@ where _guard: GenericPeripheralGuard<{ Peripheral::ParlIo as u8 }>, } -/// Creates a RX channel +/// RX channel builder for parallel IO. pub struct RxCreator<'d, Dm> where Dm: DriverMode, @@ -1568,7 +2046,13 @@ pub mod asynch { } impl ParlIoTxTransfer<'_, BUF, crate::Async> { - /// Waits for [Self::is_done] to return true. + /// Waits for [`Self::is_done`] to return true. + /// + /// # Cancellation Safety + /// + /// This method is cancellation safe. Dropping the future does not + /// stop the transfer, and this method can be called again to wait + /// for completion. pub async fn wait_for_done(&mut self) { let future = TxDoneFuture::new(); future.await; @@ -1576,7 +2060,13 @@ pub mod asynch { } impl ParlIoRxTransfer<'_, BUF, crate::Async> { - /// Waits for [Self::is_done] to return true. + /// Waits for [`Self::is_done`] to return true. + /// + /// # Cancellation Safety + /// + /// This method is cancellation safe. Dropping the future does not + /// stop the transfer, and this method can be called again to wait + /// for completion. pub async fn wait_for_done(&mut self) { if self.dma_result.is_some() { return; @@ -1588,7 +2078,9 @@ pub mod asynch { } mod private { - use super::{BitPackOrder, SampleEdge}; + #[cfg(parl_io_version = "2")] + use super::TxEofSource; + use super::{BitPackOrder, ParlIoInterrupt, SampleEdge}; use crate::{ gpio::{InputSignal, OutputSignal}, peripherals::PARL_IO, @@ -1618,10 +2110,12 @@ mod private { #[cfg(parl_io_version = "2")] pub(super) enum WidSel { - Bits8 = 3, - Bits4 = 2, - Bits2 = 1, - Bits1 = 0, + Bits8 = 3, + Bits4 = 2, + Bits2 = 1, + Bits1 = 0, + #[cfg(parl_io_max_data_width = "16")] + Bits16 = 4, } pub(super) enum SampleMode { @@ -1632,9 +2126,9 @@ mod private { /// Generation of GDMA SUC EOF pub(super) enum EofMode { - /// Generate GDMA SUC EOF by data byte length + /// Generates GDMA SUC EOF by data byte length. ByteLen, - /// Generate GDMA SUC EOF by the external enable signal + /// Generates GDMA SUC EOF by the external enable signal. EnableSignal, } @@ -1732,6 +2226,14 @@ mod private { InputSignal::PARL_RX_DATA15 } + pub fn set_rx_valid_line() { + let reg_block = PARL_IO::regs(); + + reg_block + .rx_cfg1() + .modify(|_, w| unsafe { w.rx_ext_en_sel().bits(15) }); + } + pub fn set_rx_sw_en(value: bool) { let reg_block = PARL_IO::regs(); @@ -1827,15 +2329,11 @@ mod private { } pub fn listen_tx_done() { - let reg_block = PARL_IO::regs(); - - reg_block.int_ena().modify(|_, w| w.tx_eof().set_bit()); + super::internal_listen(ParlIoInterrupt::TxEof.into(), true); } pub fn unlisten_tx_done() { - let reg_block = PARL_IO::regs(); - - reg_block.int_ena().modify(|_, w| w.tx_eof().clear_bit()); + super::internal_listen(ParlIoInterrupt::TxEof.into(), false); } pub fn is_tx_done_set() -> bool { @@ -1926,7 +2424,8 @@ mod private { pub fn tx_valid_pin_signal() -> OutputSignal { cfg_select! { - esp32c5 => OutputSignal::PARL_TX_CS, + parl_io_has_tx_cs => OutputSignal::PARL_TX_CS, + parl_io_max_data_width = "16" => OutputSignal::PARL_TX_DATA15, _ => OutputSignal::PARL_TX_DATA7, } } @@ -1939,6 +2438,14 @@ mod private { .modify(|_, w| w.tx_valid_output_en().bit(value)); } + pub fn set_tx_eof_gen_sel(value: TxEofSource) { + let reg_block = PARL_IO::regs(); + + reg_block + .tx_genrl_cfg() + .modify(|_, w| w.tx_eof_gen_sel().bit(matches!(value, TxEofSource::DmaEof))); + } + pub fn set_rx_bit_width(width: WidSel) { let reg_block = PARL_IO::regs(); @@ -1948,7 +2455,23 @@ mod private { } pub fn rx_valid_pin_signal() -> InputSignal { - InputSignal::PARL_RX_DATA7 + cfg_select! { + parl_io_max_data_width = "16" => InputSignal::PARL_RX_DATA15, + _ => InputSignal::PARL_RX_DATA7, + } + } + + pub fn set_rx_valid_line() { + // The external-enable line select resets to 7. A 16-line bus uses line 15. + let line = cfg_select! { + parl_io_max_data_width = "16" => 15, + _ => 7, + }; + let reg_block = PARL_IO::regs(); + + reg_block + .rx_mode_cfg() + .modify(|_, w| unsafe { w.rx_ext_en_sel().bits(line) }); } pub fn set_rx_sw_en(value: bool) { @@ -2049,15 +2572,11 @@ mod private { } pub fn listen_tx_done() { - let reg_block = PARL_IO::regs(); - - reg_block.int_ena().modify(|_, w| w.tx_eof().set_bit()); + super::internal_listen(ParlIoInterrupt::TxEof.into(), true); } pub fn unlisten_tx_done() { - let reg_block = PARL_IO::regs(); - - reg_block.int_ena().modify(|_, w| w.tx_eof().clear_bit()); + super::internal_listen(ParlIoInterrupt::TxEof.into(), false); } pub fn is_tx_done_set() -> bool { diff --git a/esp-hal/src/pcnt/channel.rs b/esp-hal/src/pcnt/channel.rs index f86edc455a9..b5be983909b 100644 --- a/esp-hal/src/pcnt/channel.rs +++ b/esp-hal/src/pcnt/channel.rs @@ -1,36 +1,37 @@ //! # PCNT - Channel Configuration //! //! ## Overview -//! The `channel` module allows users to configure and manage individual -//! channels of the `PCNT` peripheral. It provides methods to set various -//! parameters for each channel, such as control modes for signal edges, action -//! on control level, and configurations for positive and negative edge count -//! modes. +//! The `channel` module configures the two channels of a PCNT unit: control +//! modes for signal edges, action on control level, and positive/negative edge +//! count modes. use core::marker::PhantomData; pub use crate::pac::pcnt::unit::conf0::{CTRL_MODE as CtrlMode, EDGE_MODE as EdgeMode}; use crate::{ - gpio::{InputSignal, interconnect::PeripheralInput}, - peripherals::PCNT, - system::GenericPeripheralGuard, + gpio::{ + InputSignal, + interconnect::{self, PeripheralInput}, + }, + pcnt::AnyPcntUnit, + system::PeripheralGuard, }; /// Represents a channel within a pulse counter unit. -pub struct Channel<'d, const UNIT: usize, const NUM: usize> { - _phantom: PhantomData<&'d ()>, +pub struct Channel<'d, const NUM: usize> { + unit: AnyPcntUnit<'d>, // Individual channels are not Send, since they share registers. _not_send: PhantomData<*const ()>, - _guard: GenericPeripheralGuard<{ crate::system::Peripheral::Pcnt as u8 }>, + _guard: PeripheralGuard, } -impl Channel<'_, UNIT, NUM> { - /// return a new Channel - pub(super) fn new() -> Self { - let guard = GenericPeripheralGuard::new(); +impl<'d, const NUM: usize> Channel<'d, NUM> { + pub(super) fn new(unit: AnyPcntUnit<'d>) -> Self { + const { ::core::assert!(NUM < 2) }; + let guard = PeripheralGuard::new(unit.info().peripheral); Self { - _phantom: PhantomData, + unit, _not_send: PhantomData, _guard: guard, } @@ -42,8 +43,11 @@ impl Channel<'_, UNIT, NUM> { /// * `low` - The behaviour of the channel when the control signal is low. /// * `high` - The behaviour of the channel when the control signal is high. pub fn set_ctrl_mode(&self, low: CtrlMode, high: CtrlMode) { - let pcnt = PCNT::regs(); - let conf0 = pcnt.unit(UNIT).conf0(); + let conf0 = self + .unit + .register_block() + .unit(self.unit.info().unit) + .conf0(); conf0.modify(|_, w| { w.ch_hctrl_mode(NUM as u8).variant(high); @@ -57,8 +61,11 @@ impl Channel<'_, UNIT, NUM> { /// * `neg_edge` - The effect on the counter when the input signal goes 1 -> 0. /// * `pos_edge` - The effect on the counter when the input signal goes 0 -> 1. pub fn set_input_mode(&self, neg_edge: EdgeMode, pos_edge: EdgeMode) { - let pcnt = PCNT::regs(); - let conf0 = pcnt.unit(UNIT).conf0(); + let conf0 = self + .unit + .register_block() + .unit(self.unit.info().unit) + .conf0(); conf0.modify(|_, w| { w.ch_neg_mode(NUM as u8).variant(neg_edge); @@ -67,122 +74,20 @@ impl Channel<'_, UNIT, NUM> { } /// Set the control signal (pin/high/low) for this channel - pub fn set_ctrl_signal<'d>(&self, source: impl PeripheralInput<'d>) -> &Self { - let signal = match UNIT { - 0 => match NUM { - 0 => InputSignal::PCNT0_CTRL_CH0, - 1 => InputSignal::PCNT0_CTRL_CH1, - _ => unreachable!(), - }, - 1 => match NUM { - 0 => InputSignal::PCNT1_CTRL_CH0, - 1 => InputSignal::PCNT1_CTRL_CH1, - _ => unreachable!(), - }, - 2 => match NUM { - 0 => InputSignal::PCNT2_CTRL_CH0, - 1 => InputSignal::PCNT2_CTRL_CH1, - _ => unreachable!(), - }, - 3 => match NUM { - 0 => InputSignal::PCNT3_CTRL_CH0, - 1 => InputSignal::PCNT3_CTRL_CH1, - _ => unreachable!(), - }, - #[cfg(esp32)] - 4 => match NUM { - 0 => InputSignal::PCNT4_CTRL_CH0, - 1 => InputSignal::PCNT4_CTRL_CH1, - _ => unreachable!(), - }, - #[cfg(esp32)] - 5 => match NUM { - 0 => InputSignal::PCNT5_CTRL_CH0, - 1 => InputSignal::PCNT5_CTRL_CH1, - _ => unreachable!(), - }, - #[cfg(esp32)] - 6 => match NUM { - 0 => InputSignal::PCNT6_CTRL_CH0, - 1 => InputSignal::PCNT6_CTRL_CH1, - _ => unreachable!(), - }, - #[cfg(esp32)] - 7 => match NUM { - 0 => InputSignal::PCNT7_CTRL_CH0, - 1 => InputSignal::PCNT7_CTRL_CH1, - _ => unreachable!(), - }, - _ => unreachable!(), - }; - - if signal as usize <= property!("gpio.input_signal_max") { - let source = source.into(); - source.set_input_enable(true); - signal.connect_to(&source); - } else { - warn!("Signal {:?} out of range", signal); - } - self + pub fn set_ctrl_signal(&self, source: impl PeripheralInput<'d>) -> &Self { + let signal = self.unit.info().ctrl_ch[NUM]; + self.connect_input(signal, source.into()) } /// Set the edge signal (pin/high/low) for this channel - pub fn set_edge_signal<'d>(&self, source: impl PeripheralInput<'d>) -> &Self { - let signal = match UNIT { - 0 => match NUM { - 0 => InputSignal::PCNT0_SIG_CH0, - 1 => InputSignal::PCNT0_SIG_CH1, - _ => unreachable!(), - }, - 1 => match NUM { - 0 => InputSignal::PCNT1_SIG_CH0, - 1 => InputSignal::PCNT1_SIG_CH1, - _ => unreachable!(), - }, - 2 => match NUM { - 0 => InputSignal::PCNT2_SIG_CH0, - 1 => InputSignal::PCNT2_SIG_CH1, - _ => unreachable!(), - }, - 3 => match NUM { - 0 => InputSignal::PCNT3_SIG_CH0, - 1 => InputSignal::PCNT3_SIG_CH1, - _ => unreachable!(), - }, - #[cfg(esp32)] - 4 => match NUM { - 0 => InputSignal::PCNT4_SIG_CH0, - 1 => InputSignal::PCNT4_SIG_CH1, - _ => unreachable!(), - }, - #[cfg(esp32)] - 5 => match NUM { - 0 => InputSignal::PCNT5_SIG_CH0, - 1 => InputSignal::PCNT5_SIG_CH1, - _ => unreachable!(), - }, - #[cfg(esp32)] - 6 => match NUM { - 0 => InputSignal::PCNT6_SIG_CH0, - 1 => InputSignal::PCNT6_SIG_CH1, - _ => unreachable!(), - }, - #[cfg(esp32)] - 7 => match NUM { - 0 => InputSignal::PCNT7_SIG_CH0, - 1 => InputSignal::PCNT7_SIG_CH1, - _ => unreachable!(), - }, - _ => unreachable!(), - }; + pub fn set_edge_signal(&self, source: impl PeripheralInput<'d>) -> &Self { + let signal = self.unit.info().sig_ch[NUM]; + self.connect_input(signal, source.into()) + } - if signal as usize <= property!("gpio.input_signal_max") { - let source = source.into(); - source.set_input_enable(true); - signal.connect_to(&source); - } else { - warn!("Signal {:?} out of range", signal); - } + fn connect_input(&self, signal: InputSignal, source: interconnect::InputSignal<'d>) -> &Self { + source.set_input_enable(true); + signal.connect_to(&source); self } } diff --git a/esp-hal/src/pcnt/mod.rs b/esp-hal/src/pcnt/mod.rs index e202c084963..94ecfb5fab4 100644 --- a/esp-hal/src/pcnt/mod.rs +++ b/esp-hal/src/pcnt/mod.rs @@ -2,16 +2,17 @@ //! # Pulse Counter (PCNT) //! //! ## Overview -//! The PCNT module is designed to count the number of rising -//! and/or falling edges of input signals. They may contain multiple pulse -//! counter units in the module. Each unit is in effect an independent counter -//! with multiple channels, where each channel can increment/decrement the -//! counter on a rising/falling edge. Furthermore, each channel can be -//! configured separately. +//! The PCNT module counts rising and/or falling edges of input signals. Each +//! unit is an independent counter with two channels. Channel edge and control +//! inputs can be configured separately. //! -//! It consists of two main modules: -//! * [channel] -//! * [unit] +//! Units are peripheral singletons (`PCNT0_UNIT0`, `PCNT0_UNIT1`, …, and +//! `PCNT1_UNIT0`, … when the chip has a second register block). Construct a +//! [`Unit`] from a singleton; there is no hub driver. +//! +//! The hardware raises one interrupt per PCNT register block. [`Unit`] emulates +//! per-unit interrupts by installing a shared dispatcher that calls the handler +//! registered on each unit whose status bit is set. //! //! ## Examples //! ### Decoding a quadrature encoder @@ -19,25 +20,21 @@ //! ```rust, no_run //! # {before_snippet} //! # use esp_hal::gpio::{Input, InputConfig, Pull}; -//! # use esp_hal::interrupt::Priority; -//! # use esp_hal::pcnt::{channel, unit, Pcnt}; +//! # use esp_hal::pcnt::{channel, Unit}; //! # use core::{sync::atomic::Ordering, cell::RefCell, cmp::min}; //! # use critical_section::Mutex; //! # use portable_atomic::AtomicI32; //! -//! static UNIT0: Mutex>>> = Mutex::new(RefCell::new(None)); +//! static UNIT0: Mutex>>> = Mutex::new(RefCell::new(None)); //! static VALUE: AtomicI32 = AtomicI32::new(0); //! -//! // Initialize Pulse Counter (PCNT) unit with limits and filter settings -//! let mut pcnt = Pcnt::new(peripherals.PCNT); -//! pcnt.set_interrupt_handler(interrupt_handler); -//! let u0 = pcnt.unit1; +//! let mut u0 = Unit::new(peripherals.PCNT0_UNIT1); +//! u0.set_interrupt_handler(interrupt_handler); //! u0.set_low_limit(Some(-100))?; //! u0.set_high_limit(Some(100))?; //! u0.set_filter(Some(min(10u16 * 80, 1023u16)))?; //! u0.clear(); //! -//! // Set up channels with control and edge signals //! let ch0 = &u0.channel0; //! let config = InputConfig::default().with_pull(Pull::Up); //! let pin_a = Input::new(peripherals.GPIO4, config); @@ -55,14 +52,12 @@ //! ch1.set_ctrl_mode(channel::CtrlMode::Reverse, channel::CtrlMode::Keep); //! ch1.set_input_mode(channel::EdgeMode::Decrement, channel::EdgeMode::Increment); //! -//! // Enable interrupts and resume pulse counter unit //! u0.listen(); //! u0.resume(); //! let counter = u0.counter.clone(); //! //! critical_section::with(|cs| UNIT0.borrow_ref_mut(cs).replace(u0)); //! -//! // Monitor counter value and print updates //! let mut last_value: i32 = 0; //! loop { //! let value: i32 = counter.get() as i32 + VALUE.load(Ordering::SeqCst); @@ -90,109 +85,180 @@ //! } //! # } //! ``` -//! -//! [channel]: channel/index.html -//! [unit]: unit/index.html -use self::unit::Unit; +use esp_sync::RawMutex; + use crate::{ - interrupt::{self, InterruptHandler}, - peripherals::{Interrupt, PCNT}, - system::GenericPeripheralGuard, + gpio::InputSignal, + handler, + interrupt::{InterruptHandler, Priority}, + pac::pcnt::RegisterBlock, + peripherals::Interrupt, + private::CFnPtr, + system::Peripheral, }; pub mod channel; pub mod unit; -/// Pulse Counter (PCNT) peripheral driver. -pub struct Pcnt<'d> { - _instance: PCNT<'d>, - - /// Unit 0 - pub unit0: Unit<'d, 0>, - /// Unit 1 - pub unit1: Unit<'d, 1>, - /// Unit 2 - pub unit2: Unit<'d, 2>, - /// Unit 3 - pub unit3: Unit<'d, 3>, - #[cfg(esp32)] - /// Unit 4 - pub unit4: Unit<'d, 4>, - #[cfg(esp32)] - /// Unit 5 - pub unit5: Unit<'d, 5>, - #[cfg(esp32)] - /// Unit 6 - pub unit6: Unit<'d, 6>, - #[cfg(esp32)] - /// Unit 7 - pub unit7: Unit<'d, 7>, - - _guard: GenericPeripheralGuard<{ crate::system::Peripheral::Pcnt as u8 }>, +pub use unit::Unit; + +/// Immutable per-unit metadata owned by each `PCNTn_UNITm` singleton. +#[doc(hidden)] +pub struct Info { + unit: usize, + peripheral: Peripheral, + interrupt: Interrupt, + dispatcher: InterruptHandler, + register_block: *const RegisterBlock, + /// Guards the registers shared by every unit of this register block. + lock: &'static RawMutex, + sig_ch: [InputSignal; 2], + ctrl_ch: [InputSignal; 2], } -impl<'d> Pcnt<'d> { - /// Return a new PCNT - pub fn new(_instance: PCNT<'d>) -> Self { - let guard = GenericPeripheralGuard::new(); - let pcnt = PCNT::regs(); +unsafe impl Sync for Info {} - let unit_count = pcnt.unit_iter().count() as u8; +/// Mutable per-unit interrupt state. +#[doc(hidden)] +pub struct State { + handler: CFnPtr, +} - // disable filter, all events, and channel settings - for unit in pcnt.unit_iter() { - unit.conf0().write(|w| unsafe { - // All bits are accounted for in the TRM. - w.bits(0) - }); +impl State { + const fn new() -> Self { + Self { + handler: CFnPtr::new(), } + } - // Remove reset bit from units. - pcnt.ctrl().modify(|_, w| { - for i in 0..unit_count { - w.cnt_rst_u(i).clear_bit(); - } + fn store(&self, handler: extern "C" fn()) { + self.handler.store(handler); + } - w.clk_en().set_bit() - }); - - Pcnt { - _instance, - unit0: Unit::new(), - unit1: Unit::new(), - unit2: Unit::new(), - unit3: Unit::new(), - #[cfg(esp32)] - unit4: Unit::new(), - #[cfg(esp32)] - unit5: Unit::new(), - #[cfg(esp32)] - unit6: Unit::new(), - #[cfg(esp32)] - unit7: Unit::new(), - _guard: guard, - } + fn clear(&self) { + self.handler.clear(); } - /// Set the interrupt handler for the PCNT peripheral. - /// - /// Note that this will replace any previously registered interrupt - /// handlers. - #[instability::unstable] - pub fn set_interrupt_handler(&mut self, handler: InterruptHandler) { - for core in crate::system::Cpu::other() { - crate::interrupt::disable(core, Interrupt::PCNT); - } - interrupt::bind_handler(Interrupt::PCNT, handler); + fn invoke(&self) -> bool { + self.handler.call() + } +} + +impl Info { + fn regs(&self) -> &'static RegisterBlock { + unsafe { &*self.register_block } + } + + fn lock(&self, f: impl FnOnce() -> R) -> R { + self.lock.lock(f) + } +} + +/// A peripheral singleton compatible with the PCNT unit driver. +#[doc(hidden)] +pub trait Instance: crate::private::Sealed + any::Degrade { + fn parts(&self) -> (&'static Info, &'static State); +} + +impl Instance for AnyPcntUnit<'_> { + fn parts(&self) -> (&'static Info, &'static State) { + any::delegate!(self, unit => { unit.parts() }) } } -impl crate::private::Sealed for Pcnt<'_> {} +impl AnyPcntUnit<'_> { + fn info(&self) -> &'static Info { + self.parts().0 + } + + fn state(&self) -> &'static State { + self.parts().1 + } + + fn register_block(&self) -> &'static RegisterBlock { + self.info().regs() + } -#[instability::unstable] -impl crate::interrupt::InterruptConfigurable for Pcnt<'_> { - fn set_interrupt_handler(&mut self, handler: InterruptHandler) { - self.set_interrupt_handler(handler); + fn lock(&self, f: impl FnOnce() -> R) -> R { + self.info().lock(f) } } + +fn dispatch(interrupt: Interrupt) { + for_each_pcnt_unit! { + ($peri:ident, $variant:ident, $sys:ident, $regs:ident, $unit:literal, $irq:ident, $sig_ch0:ident, $sig_ch1:ident, $ctrl_ch0:ident, $ctrl_ch1:ident) => { + if Interrupt::$irq == interrupt { + let (info, state) = Instance::parts(&unsafe { crate::peripherals::$peri::steal() }); + if info + .regs() + .int_st() + .read() + .cnt_thr_event_u(info.unit as u8) + .bit() + { + if !state.invoke() { + // Unhandled by the user, make sure the interrupt doesn't stay pending. + info + .regs() + .int_clr() + .write(|w| { + w.cnt_thr_event_u(info.unit as u8).set_bit() + }); + } + } + } + }; + } +} + +for_each_pcnt_unit! { + (interrupt $(($interrupt:ident)),*) => { + $( + paste::paste! { + #[handler(priority = Priority::max())] + fn []() { + dispatch(Interrupt::$interrupt); + } + } + )* + }; + + (regs $(($regs:ident)),*) => { + $( + paste::paste! { + static [<$regs _LOCK>]: RawMutex = RawMutex::new(); + } + )* + }; + + ($peri:ident, $variant:ident, $sys:ident, $regs:ident, $unit:literal, $interrupt:ident, $sig_ch0:ident, $sig_ch1:ident, $ctrl_ch0:ident, $ctrl_ch1:ident) => { + impl crate::pcnt::Instance for crate::peripherals::$peri<'_> { + fn parts(&self) -> (&'static crate::pcnt::Info, &'static crate::pcnt::State) { + static INFO: crate::pcnt::Info = crate::pcnt::Info { + unit: $unit, + peripheral: crate::system::Peripheral::$sys, + interrupt: crate::peripherals::Interrupt::$interrupt, + dispatcher: paste::paste! { [] }, + register_block: crate::peripherals::$regs::ptr(), + lock: paste::paste! { &crate::pcnt::[<$regs _LOCK>] }, + sig_ch: [crate::gpio::InputSignal::$sig_ch0, crate::gpio::InputSignal::$sig_ch1], + ctrl_ch: [crate::gpio::InputSignal::$ctrl_ch0, crate::gpio::InputSignal::$ctrl_ch1], + }; + static STATE: crate::pcnt::State = crate::pcnt::State::new(); + (&INFO, &STATE) + } + } + }; + + (all $(($peri:ident, $variant:ident, $sys:ident, $regs:ident, $unit:literal, $interrupt:ident, $sig_ch0:ident, $sig_ch1:ident, $ctrl_ch0:ident, $ctrl_ch1:ident)),*) => { + crate::any_peripheral! { + /// Any PCNT unit. + pub peripheral AnyPcntUnit<'d> { + $( + $variant(crate::peripherals::$peri<'d>), + )* + } + } + }; +} diff --git a/esp-hal/src/pcnt/unit.rs b/esp-hal/src/pcnt/unit.rs index d495dd8be39..f4da2745661 100644 --- a/esp-hal/src/pcnt/unit.rs +++ b/esp-hal/src/pcnt/unit.rs @@ -1,31 +1,27 @@ //! # PCNT - Unit Module //! //! ## Overview -//! The `unit` module is responsible for configuring and handling individual -//! units of the `PCNT` peripheral. Each unit represents a separate instance of -//! the `PCNT` module, identified by unit numbers like `Unit0`, `Unit1`, and so -//! on. Users can interact with these units to configure settings such as low -//! and high limits, thresholds, and optional filtering. The unit module also -//! enables users to pause, resume, and clear the counter, as well as enable or -//! disable interrupts for specific events associated with the unit. +//! The `unit` module configures and operates a single pulse-counter unit. +//! Construct a [`Unit`] from a `PCNTn_UNITm` singleton. Units can be paused, +//! resumed, and cleared, and can listen for threshold and limit events. -use core::marker::PhantomData; - -use esp_sync::RawMutex; - -use crate::{pcnt::channel::Channel, peripherals::PCNT, system::GenericPeripheralGuard}; +use crate::{ + interrupt::{InterruptConfigurable, InterruptHandler}, + pcnt::{AnyPcntUnit, Instance, channel::Channel}, + system::PeripheralGuard, +}; /// Invalid filter threshold value #[derive(Debug, Clone, Copy, PartialEq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub struct InvalidFilterThreshold; -/// Invalid low limit - must be < 0 +/// Invalid low limit - must be < 0. #[derive(Debug, Clone, Copy, PartialEq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub struct InvalidLowLimit; -/// Invalid high limit - must be > 0 +/// Invalid high limit - must be > 0. #[derive(Debug, Clone, Copy, PartialEq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub struct InvalidHighLimit; @@ -52,7 +48,7 @@ impl From for ZeroMode { 1 => Self::NegZero, 2 => Self::Negative, 3 => Self::Positive, - _ => unreachable!(), // TODO: is this good enough? should we use some default? + _ => unreachable!(), } } } @@ -61,41 +57,67 @@ impl From for ZeroMode { #[derive(Copy, Clone, Debug, Default)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub struct Events { - /// Set when the pulse counter reaches the low limit. + /// Sets when the pulse counter reaches the low limit. pub low_limit: bool, - /// Set when the pulse counter reaches the high limit. + /// Sets when the pulse counter reaches the high limit. pub high_limit: bool, - /// Set when the pulse counter crosses threshold 0. + /// Sets when the pulse counter crosses threshold 0. pub threshold0: bool, - /// Set when the pulse counter crosses threshold 1. + /// Sets when the pulse counter crosses threshold 1. pub threshold1: bool, - /// Set when the pulse counter reaches zero. + /// Sets when the pulse counter reaches zero. pub zero: bool, } /// Represents a pulse counter unit. #[non_exhaustive] -pub struct Unit<'d, const NUM: usize> { +pub struct Unit<'d> { + unit: AnyPcntUnit<'d>, /// The counter for PCNT unit. - pub counter: Counter<'d, NUM>, + pub counter: Counter<'d>, /// The first channel in PCNT unit. - pub channel0: Channel<'d, NUM, 0>, + pub channel0: Channel<'d, 0>, /// The second channel in PCNT unit. - pub channel1: Channel<'d, NUM, 1>, + pub channel1: Channel<'d, 1>, + _guard: PeripheralGuard, } -static MUTEX: RawMutex = RawMutex::new(); +impl<'d> Unit<'d> { + /// Returns a new PCNT unit. + pub fn new(unit: impl Instance + 'd) -> Self { + let (info, _) = unit.parts(); + let guard = PeripheralGuard::new(info.peripheral); + let unit = unit.degrade(); + + let regs = info.regs(); + regs.unit(info.unit).conf0().write(|w| unsafe { w.bits(0) }); + info.lock(|| { + // Make sure the counter is reset + regs.ctrl() + .modify(|_, w| w.cnt_rst_u(info.unit as u8).set_bit()); + let bits = regs.ctrl().read().bits(); + regs.ctrl().write(|w| { + unsafe { w.bits(bits) }; + w.cnt_rst_u(info.unit as u8).clear_bit(); + // Make sure we don't stay paused in case this is a re-created unit + w.cnt_pause_u(info.unit as u8).clear_bit(); + w.clk_en().set_bit() + }); + }); -impl Unit<'_, NUM> { - /// return a new Unit - pub(super) fn new() -> Self { Self { - counter: Counter::new(), - channel0: Channel::new(), - channel1: Channel::new(), + counter: Counter::new(unsafe { unit.clone_unchecked() }), + channel0: Channel::new(unsafe { unit.clone_unchecked() }), + channel1: Channel::new(unsafe { unit.clone_unchecked() }), + unit, + _guard: guard, } } + fn index(&self) -> u8 { + self.unit.info().unit as u8 + } + /// Configures a lower limit to the count value. /// /// When the count drops to this value: @@ -105,10 +127,9 @@ impl Unit<'_, NUM> { /// If None is specified, then no interrupt is triggered and /// the count wraps around after [i16::MIN]. /// - /// Note: The specified value must be negative. + /// The specified value must be negative. pub fn set_low_limit(&self, value: Option) -> Result<(), InvalidLowLimit> { - let pcnt = PCNT::regs(); - let unit = pcnt.unit(NUM); + let unit = self.unit.register_block().unit(self.unit.info().unit); if let Some(value) = value { // low limit must be >= or the limit is -32768 and when that's @@ -136,10 +157,9 @@ impl Unit<'_, NUM> { /// If None is specified, then no interrupt is triggered and /// the count wraps around after [i16::MAX]. /// - /// Note: The specified value must be positive. + /// The specified value must be positive. pub fn set_high_limit(&self, value: Option) -> Result<(), InvalidHighLimit> { - let pcnt = PCNT::regs(); - let unit = pcnt.unit(NUM); + let unit = self.unit.register_block().unit(self.unit.info().unit); if let Some(value) = value { if !value.is_positive() { @@ -160,8 +180,7 @@ impl Unit<'_, NUM> { /// When the count equals this value a threshold0 interrupt is triggered. /// If None is specified, then no interrupt is triggered. pub fn set_threshold0(&self, value: Option) { - let pcnt = PCNT::regs(); - let unit = pcnt.unit(NUM); + let unit = self.unit.register_block().unit(self.unit.info().unit); if let Some(value) = value { unit.conf1() @@ -177,8 +196,7 @@ impl Unit<'_, NUM> { /// When the count equals this value a threshold1 interrupt is triggered. /// If None is specified, then no interrupt is triggered. pub fn set_threshold1(&self, value: Option) { - let pcnt = PCNT::regs(); - let unit = pcnt.unit(NUM); + let unit = self.unit.register_block().unit(self.unit.info().unit); if let Some(value) = value { unit.conf1() @@ -194,10 +212,9 @@ impl Unit<'_, NUM> { /// `threshold` is the minimum number of APB_CLK cycles for a pulse to be /// considered valid. If it is None, the filter is disabled. /// - /// Note: This maximum possible threshold is 1023. + /// The maximum possible threshold is 1023. pub fn set_filter(&self, threshold: Option) -> Result<(), InvalidFilterThreshold> { - let pcnt = PCNT::regs(); - let unit = pcnt.unit(NUM); + let unit = self.unit.register_block().unit(self.unit.info().unit); match threshold { None => { @@ -218,40 +235,50 @@ impl Unit<'_, NUM> { /// Resets the counter value to zero. pub fn clear(&self) { - MUTEX.lock(|| { - let bits = PCNT::regs().ctrl().read().bits(); - PCNT::regs().ctrl().write(|w| { + let n = self.index(); + self.unit.lock(|| { + let regs = self.unit.register_block(); + let bits = regs.ctrl().read().bits(); + regs.ctrl().write(|w| { unsafe { w.bits(bits) }; - w.cnt_rst_u(NUM as u8).set_bit() + w.cnt_rst_u(n).set_bit() }); - PCNT::regs().ctrl().write(|w| { + regs.ctrl().write(|w| { unsafe { w.bits(bits) }; - w.cnt_rst_u(NUM as u8).clear_bit() + w.cnt_rst_u(n).clear_bit() }); }); } - /// Pause the counter + /// Pauses the counter. pub fn pause(&self) { - MUTEX.lock(|| { - PCNT::regs() + let n = self.index(); + self.unit.lock(|| { + self.unit + .register_block() .ctrl() - .modify(|_, w| w.cnt_pause_u(NUM as u8).set_bit()); + .modify(|_, w| w.cnt_pause_u(n).set_bit()); }); } - /// Resume the counter + /// Resumes the counter. pub fn resume(&self) { - MUTEX.lock(|| { - PCNT::regs() + let n = self.index(); + self.unit.lock(|| { + self.unit + .register_block() .ctrl() - .modify(|_, w| w.cnt_pause_u(NUM as u8).clear_bit()); + .modify(|_, w| w.cnt_pause_u(n).clear_bit()); }); } - /// Get the latest events for this unit. + /// Returns the latest events for this unit. pub fn events(&self) -> Events { - let status = PCNT::regs().u_status(NUM).read(); + let status = self + .unit + .register_block() + .u_status(self.unit.info().unit) + .read(); Events { low_limit: status.l_lim().bit(), @@ -262,81 +289,135 @@ impl Unit<'_, NUM> { } } - /// Get the mode of the last zero crossing + /// Returns the mode of the last zero crossing. pub fn zero_mode(&self) -> ZeroMode { - PCNT::regs().u_status(NUM).read().zero_mode().bits().into() + self.unit + .register_block() + .u_status(self.unit.info().unit) + .read() + .zero_mode() + .bits() + .into() } - /// Enable interrupts for this unit. + /// Enables interrupts for this unit. pub fn listen(&self) { - MUTEX.lock(|| { - PCNT::regs() + let n = self.index(); + self.unit.lock(|| { + self.unit + .register_block() .int_ena() - .modify(|_, w| w.cnt_thr_event_u(NUM as u8).set_bit()); + .modify(|_, w| w.cnt_thr_event_u(n).set_bit()); }); } - /// Disable interrupts for this unit. + /// Disables interrupts for this unit. pub fn unlisten(&self) { - MUTEX.lock(|| { - PCNT::regs() + let n = self.index(); + self.unit.lock(|| { + self.unit + .register_block() .int_ena() - .modify(|_, w| w.cnt_thr_event_u(NUM as u8).clear_bit()); + .modify(|_, w| w.cnt_thr_event_u(n).clear_bit()); }); } - /// Returns true if an interrupt is active for this unit. + /// Returns whether an interrupt is active for this unit. pub fn interrupt_is_set(&self) -> bool { - PCNT::regs() + self.unit + .register_block() .int_raw() .read() - .cnt_thr_event_u(NUM as u8) + .cnt_thr_event_u(self.index()) .bit() } - /// Clear the interrupt bit for this unit. + /// Clears the interrupt bit for this unit. pub fn reset_interrupt(&self) { - PCNT::regs() + self.unit + .register_block() .int_clr() - .write(|w| w.cnt_thr_event_u(NUM as u8).set_bit()); + .write(|w| w.cnt_thr_event_u(self.index()).set_bit()); } - /// Get the current counter value. + /// Returns the current counter value. pub fn value(&self) -> i16 { self.counter.get() } + + /// Registers a handler invoked when this unit's interrupt status bit is + /// set. + /// + /// The hardware interrupt is shared by every unit in the same PCNT + /// register block. This method installs a dispatcher on that interrupt + /// and records `handler` for this unit only. + /// + /// This method ignores handler priority. + #[instability::unstable] + pub fn set_interrupt_handler(&mut self, handler: InterruptHandler) { + let info = self.unit.info(); + self.unit.state().store(handler.handler().callback()); + crate::interrupt::bind_handler(info.interrupt, info.dispatcher); + } +} + +impl crate::private::Sealed for Unit<'_> {} + +#[instability::unstable] +impl InterruptConfigurable for Unit<'_> { + fn set_interrupt_handler(&mut self, handler: InterruptHandler) { + self.set_interrupt_handler(handler); + } } -impl Drop for Unit<'_, NUM> { +impl Drop for Unit<'_> { fn drop(&mut self) { - // This is here to prevent the destructuring of Unit. + self.unlisten(); + self.pause(); + let info = self.unit.info(); + info.regs() + .unit(info.unit) + .conf0() + .write(|w| unsafe { w.bits(0) }); + self.unit.state().clear(); } } // The entire Unit is Send but the individual channels are not. -unsafe impl Send for Unit<'_, NUM> {} +unsafe impl Send for Unit<'_> {} /// Represents the counter within a pulse counter unit. -#[derive(Clone)] -pub struct Counter<'d, const NUM: usize> { - _phantom: PhantomData<&'d ()>, +pub struct Counter<'d> { + unit: AnyPcntUnit<'d>, + _guard: PeripheralGuard, +} - _guard: GenericPeripheralGuard<{ crate::system::Peripheral::Pcnt as u8 }>, +impl Clone for Counter<'_> { + fn clone(&self) -> Self { + Self { + unit: unsafe { self.unit.clone_unchecked() }, + _guard: self._guard.clone(), + } + } } -impl Counter<'_, NUM> { - fn new() -> Self { - let guard = GenericPeripheralGuard::new(); +impl<'d> Counter<'d> { + fn new(unit: AnyPcntUnit<'d>) -> Self { + let guard = PeripheralGuard::new(unit.info().peripheral); Self { - _phantom: PhantomData, + unit, _guard: guard, } } - /// Get the current counter value. + /// Returns the current counter value. pub fn get(&self) -> i16 { - let pcnt = PCNT::regs(); - pcnt.u_cnt(NUM).read().cnt().bits() as i16 + self.unit + .register_block() + .u_cnt(self.unit.info().unit) + .read() + .cnt() + .bits() as i16 } } diff --git a/esp-hal/src/peripherals/mod.rs b/esp-hal/src/peripherals/mod.rs index 542235ce686..e64fbfb36d2 100644 --- a/esp-hal/src/peripherals/mod.rs +++ b/esp-hal/src/peripherals/mod.rs @@ -18,11 +18,6 @@ pub(crate) use crate::soc::pac; #[path = "overlay_h2.rs"] mod overlay; -#[cfg(any(esp32p4, esp32s31))] -#[path = "overlay_rmt.rs"] -#[cfg(feature = "unstable")] -mod overlay; - /// Macro to create a peripheral structure. macro_rules! create_peripheral { ($(#[$attr:meta])* $name:ident <= virtual ($($interrupt:ident: { $bind:ident, $enable:ident, $disable:ident }),*)) => { @@ -36,11 +31,11 @@ macro_rules! create_peripheral { } impl $name<'_> { - /// Unsafely create an instance of this peripheral out of thin air. + /// Unsafely creates an instance of this peripheral out of thin air. /// /// # Safety /// - /// You must ensure that you're only using one instance of this type at a time. + /// The caller must ensure that only one instance of this type is used at a time. #[inline] pub unsafe fn steal() -> Self { Self { @@ -52,7 +47,7 @@ macro_rules! create_peripheral { /// /// # Safety /// - /// You must ensure that you're only using one instance of this type at a time. + /// The caller must ensure that only one instance of this type is used at a time. #[inline] #[allow(dead_code)] pub unsafe fn clone_unchecked(&self) -> Self { @@ -61,8 +56,8 @@ macro_rules! create_peripheral { /// Creates a new peripheral reference with a shorter lifetime. /// - /// Use this method if you would like to keep working with the peripheral after - /// you dropped the driver that consumes this. + /// Use this method to keep working with the peripheral after the driver + /// that consumes it is dropped. #[inline] #[allow(dead_code)] pub fn reborrow(&mut self) -> $name<'_> { @@ -73,7 +68,7 @@ macro_rules! create_peripheral { /// Binds an interrupt handler to the corresponding interrupt for this peripheral, and enables the interrupt. /// ///

- /// This function is a very low-level way to work with interrupts. Unless you're writing drivers, this is probably not the interrupt API you want to use. + /// Very low-level interrupt API. Unless writing drivers, this is probably not the interrupt API to use. ///
/// #[instability::unstable] @@ -85,16 +80,16 @@ macro_rules! create_peripheral { #[doc = concat!("Enables the ", stringify!($interrupt), " peripheral interrupt on the given priority level.")] /// ///
- /// This function is a very low-level way to work with interrupts. Unless you're writing drivers, this is probably not the interrupt API you want to use. + /// Very low-level interrupt API. Unless writing drivers, this is probably not the interrupt API to use. ///
#[cfg_attr(multi_core, doc = "The interrupt handler will be enabled on the core that calls this function.")] /// - /// Note that a suitable interrupt handler needs to be set up before the first interrupt - /// is triggered, otherwise the default handler will panic. - #[cfg_attr(not(feature = "unstable"), doc = "To set up an interrupt handler, create a function that has the same (non-mangled) name as the interrupt you want to handle.")] - #[cfg_attr(feature = "unstable", doc = concat!("To set up an interrupt handler, use [`Self::", stringify!($bind), "`] or create a function that has the same (non-mangled) name as the interrupt you want to handle."))] + /// A suitable interrupt handler must be set up before the first interrupt + /// is triggered; otherwise the default handler panics. + #[cfg_attr(not(feature = "unstable"), doc = "To set up an interrupt handler, create a function that has the same (non-mangled) name as the interrupt to handle.")] + #[cfg_attr(feature = "unstable", doc = concat!("To set up an interrupt handler, use [`Self::", stringify!($bind), "`] or create a function that has the same (non-mangled) name as the interrupt to handle."))] /// - /// ## Examples + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -119,7 +114,7 @@ macro_rules! create_peripheral { #[doc = concat!("Disables the ", stringify!($interrupt), " peripheral interrupt handler on the current CPU core.")] /// ///
- /// This function is a very low-level way to work with interrupts. Unless you're writing drivers, this is probably not the interrupt API you want to use. + /// Very low-level interrupt API. Unless writing drivers, this is probably not the interrupt API to use. ///
#[instability::unstable] pub fn $disable(&self) { @@ -130,7 +125,7 @@ macro_rules! create_peripheral { #[doc = concat!("Disables the ", stringify!($interrupt), " peripheral interrupt handler on all cores.")] /// ///
- /// This function is a very low-level way to work with interrupts. Unless you're writing drivers, this is probably not the interrupt API you want to use. + /// Very low-level interrupt API. Unless writing drivers, this is probably not the interrupt API to use. ///
#[allow(dead_code, reason = "Peripheral may be unstable")] pub fn [<$disable _on_all_cores>](&self) { @@ -191,7 +186,7 @@ for_each_peripheral! { // Define the Peripherals struct (singletons $( ( $(#[$cfg:meta])* $name:ident $(($unstable:ident $(#[$unstable_cfg:meta])*))?) ),*) => { // We need a way to ignore the "unstable" marker, but macros can't generate attributes or struct fields. - // The solution is printing an empty doc comment. + // The solution is appending an empty string to a doc comment. macro_rules! ignore { ($any:tt) => {""} } /// The `Peripherals` struct provides access to all of the hardware peripherals on the chip. @@ -225,10 +220,9 @@ for_each_peripheral! { $(#[$cfg])* #[doc = concat!("The ", stringify!($name), " peripheral.")] $( - #[doc = "**This API is marked as unstable** and is only available when the `unstable` + #[doc = concat!("**This API is marked as unstable** and is only available when the `unstable` crate feature is enabled. This comes with no stability guarantees, and could be changed - or removed at any time."] - #[doc = ignore!($unstable)] + or removed at any time.", ignore!($unstable))] #[cfg(feature = "unstable")] #[cfg_attr(docsrs, doc(cfg(feature = "unstable")))] )? @@ -237,10 +231,9 @@ for_each_peripheral! { $( $(#[$unstable_cfg])* #[doc = concat!("The ", stringify!($name), " peripheral.")] - #[doc = "**This API is marked as unstable** and is only available when the `unstable` + #[doc = concat!("**This API is marked as unstable** and is only available when the `unstable` crate feature is enabled. This comes with no stability guarantees, and could be changed - or removed at any time."] - #[doc = ignore!($unstable)] + or removed at any time.", ignore!($unstable))] #[cfg(not(feature = "unstable"))] #[allow(unused)] pub(crate) $name: $name<'static>, @@ -265,11 +258,11 @@ for_each_peripheral! { }) } - /// Unsafely create an instance of this peripheral out of thin air. + /// Unsafely creates an instance of this peripheral out of thin air. /// /// # Safety /// - /// You must ensure that you're only using one instance of this type at a time. + /// The caller must ensure that only one instance of this type is used at a time. #[inline] pub unsafe fn steal() -> Self { unsafe { diff --git a/esp-hal/src/peripherals/overlay_h2.rs b/esp-hal/src/peripherals/overlay_h2.rs index 752cba622f4..eea2ad23399 100644 --- a/esp-hal/src/peripherals/overlay_h2.rs +++ b/esp-hal/src/peripherals/overlay_h2.rs @@ -5,14 +5,14 @@ use crate::efuse::ChipRevision; // RNG must be marked `virtual` for this to work. impl RNG<'_> { - /// Return a reference to the register block + /// Returns a reference to the register block. #[inline(always)] #[instability::unstable] pub const fn regs<'a>() -> &'a RngRegisterBlock { &RngRegisterBlock } - /// Return a reference to the register block + /// Returns a reference to the register block. #[inline(always)] #[instability::unstable] pub fn register_block(&self) -> &RngRegisterBlock { @@ -20,7 +20,7 @@ impl RNG<'_> { } } -/// Register block overlay for the RNG peripheral +/// Registers block overlay for the RNG peripheral. #[instability::unstable] pub struct RngRegisterBlock; diff --git a/esp-hal/src/peripherals/overlay_rmt.rs b/esp-hal/src/peripherals/overlay_rmt.rs deleted file mode 100644 index 4e90fdfda3e..00000000000 --- a/esp-hal/src/peripherals/overlay_rmt.rs +++ /dev/null @@ -1,1026 +0,0 @@ -//! Register-block overlay for ESP32-P4 and ESP32-S31 RMT. -//! -//! The peripheral matches ESP32-S3. The PAC uses different SVD names, so this -//! overlay presents the ESP32-S3 register API. RMT must be `virtual` for this -//! to work. - -use core::ops::Deref; - -use super::*; -use crate::soc::pac::rmt; - -impl RMT<'_> { - /// Return a reference to the register block. - #[inline(always)] - #[instability::unstable] - pub const fn regs<'a>() -> &'a RmtRegisterBlock { - &RmtRegisterBlock - } - - /// Return a reference to the register block. - #[inline(always)] - #[instability::unstable] - pub fn register_block(&self) -> &RmtRegisterBlock { - &RmtRegisterBlock - } -} - -/// Register block overlay for the RMT peripheral. -#[instability::unstable] -pub struct RmtRegisterBlock; - -impl Deref for RmtRegisterBlock { - type Target = rmt::RegisterBlock; - - fn deref(&self) -> &Self::Target { - unsafe { &*pac::RMT::ptr() } - } -} - -impl RmtRegisterBlock { - /// Channel n TX configure register 0. - #[inline] - pub fn ch_tx_conf0(&self, n: usize) -> TxConf0<'_> { - TxConf0(self.chconf0(n)) - } - - /// Channel n RX configure register 0. - #[inline] - pub fn ch_rx_conf0(&self, n: usize) -> ChRxConf0 { - assert!(n < 4); - ChRxConf0 { - ptr: unsafe { - core::ptr::from_ref(Deref::deref(self)) - .cast::() - .add(0x30) - .add(8 * n) - .cast::() - .cast_mut() - }, - } - } - - /// Channel n RX configure register 1. - #[inline] - pub fn ch_rx_conf1(&self, n: usize) -> RxConf1<'_> { - RxConf1(self.chconf1(n)) - } - - /// Channel n TX status register. - #[inline] - pub fn ch_tx_status(&self, n: usize) -> ChStatus<'_> { - ChStatus(self.chstatus(n)) - } - - /// Channel n RX status register. - #[inline] - pub fn ch_rx_status(&self, n: usize) -> ChStatus<'_> { - cfg_select! { - esp32s31 => ChStatus(match n { - 0 => self.ch4status(), - 1 => self.ch5status(), - 2 => self.ch6status(), - 3 => self.ch7status(), - _ => panic!("RMT RX status index must be 0..=3"), - }), - esp32p4 => { - assert!(n < 4); - ChStatus(unsafe { - &*core::ptr::from_ref(Deref::deref(self)) - .cast::() - .add(0x60) - .add(4 * n) - .cast() - }) - } - } - } - - /// Channel n TX event configuration register. - #[inline] - pub fn ch_tx_lim(&self, n: usize) -> TxLim<'_> { - TxLim(Deref::deref(self).ch_tx_lim(n)) - } - - /// Channel n RX event configuration register. - #[inline] - pub fn ch_rx_lim(&self, n: usize) -> RxLim<'_> { - RxLim(Deref::deref(self).ch_rx_lim(n)) - } - - /// Channel n carrier duty register. - #[inline] - pub fn chcarrier_duty(&self, n: usize) -> CarrierDuty<'_> { - CarrierDuty(Deref::deref(self).chcarrier_duty(n)) - } - - /// Channel n RX carrier remove register. - #[inline] - pub fn ch_rx_carrier_rm(&self, n: usize) -> RxCarrierRm<'_> { - RxCarrierRm(Deref::deref(self).ch_rx_carrier_rm(n)) - } - - /// Masked interrupt status. - #[inline] - pub fn int_st(&self) -> IntSt<'_> { - IntSt(Deref::deref(self).int_st()) - } - - /// Raw interrupt status. - #[inline] - pub fn int_raw(&self) -> IntRaw<'_> { - IntRaw(Deref::deref(self).int_raw()) - } - - /// Interrupt enable bits. - #[inline] - pub fn int_ena(&self) -> IntEna<'_> { - IntEna(Deref::deref(self).int_ena()) - } - - /// Interrupt clear bits. - #[inline] - pub fn int_clr(&self) -> IntClr<'_> { - IntClr(Deref::deref(self).int_clr()) - } -} - -/// Bit flag reader with a PAC-like [`bit`](BitFlag::bit) method. -pub struct BitFlag(bool); - -impl BitFlag { - #[inline] - pub fn bit(self) -> bool { - self.0 - } -} - -/// Field reader with a PAC-like [`bits`](FieldVal::bits) method. -pub struct FieldVal(T); - -impl FieldVal { - #[inline] - pub fn bits(self) -> T { - self.0 - } -} - -/// Bit field writer with PAC-like `bit` / `set_bit` / `clear_bit` methods. -pub struct BitProxy<'a, W>(&'a mut W, fn(&mut W, bool)); - -impl<'a, W> BitProxy<'a, W> { - #[inline] - pub fn bit(self, val: bool) -> &'a mut W { - (self.1)(self.0, val); - self.0 - } - - #[inline] - pub fn set_bit(self) -> &'a mut W { - self.bit(true) - } - - #[inline] - pub fn clear_bit(self) -> &'a mut W { - self.bit(false) - } -} - -/// Multi-bit field writer with a PAC-like `bits` method. -pub struct FieldProxy<'a, W, T>(&'a mut W, fn(&mut W, T)); - -impl<'a, W, T> FieldProxy<'a, W, T> { - #[inline] - pub unsafe fn bits(self, val: T) -> &'a mut W { - (self.1)(self.0, val); - self.0 - } -} - -fn overlay_w(w: &mut P) -> &mut O { - unsafe { &mut *core::ptr::from_mut(w).cast() } -} - -macro_rules! bit_proxy { - ($self:ident, $s31:ident, $p4:ident) => { - BitProxy($self, |w, val| { - #[cfg(esp32s31)] - { - w.0.$s31().bit(val); - } - #[cfg(esp32p4)] - { - w.0.$p4().bit(val); - } - }) - }; -} - -macro_rules! field_proxy { - ($self:ident, $s31:ident, $p4:ident) => { - FieldProxy($self, |w, val| { - #[cfg(esp32s31)] - { - let _ = unsafe { w.0.$s31().bits(val) }; - } - #[cfg(esp32p4)] - { - let _ = unsafe { w.0.$p4().bits(val) }; - } - }) - }; -} - -/// Channel TX configure register 0. -pub struct TxConf0<'a>(&'a rmt::CHCONF0); - -/// Reader for [`TxConf0`]. -pub struct TxConf0R(u32); - -/// Writer for [`TxConf0`]. -#[repr(transparent)] -pub struct TxConf0W(rmt::chconf0::W); - -impl TxConf0<'_> { - /// Read the register. - #[inline] - pub fn read(&self) -> TxConf0R { - TxConf0R(self.0.read().bits()) - } - - /// Modify the register. - #[inline] - pub fn modify(&self, f: F) - where - F: for<'a> FnOnce(&TxConf0R, &'a mut TxConf0W) -> &'a mut TxConf0W, - { - self.0.modify(|r, w| { - let overlay_r = TxConf0R(r.bits()); - let _ = f(&overlay_r, overlay_w(w)); - w - }); - } -} - -impl TxConf0R { - #[inline] - pub fn mem_size(&self) -> FieldVal { - FieldVal(((self.0 >> 16) & 0x0f) as u8) - } - - #[inline] - pub fn idle_out_en(&self) -> BitFlag { - BitFlag((self.0 >> 6) & 1 != 0) - } - - #[inline] - pub fn idle_out_lv(&self) -> BitFlag { - BitFlag((self.0 >> 5) & 1 != 0) - } -} - -impl TxConf0W { - #[inline] - pub fn conf_update(&mut self) -> BitProxy<'_, Self> { - bit_proxy!(self, conf_update_ch, conf_update_ch0) - } - - #[inline] - pub fn div_cnt(&mut self) -> FieldProxy<'_, Self, u8> { - field_proxy!(self, div_cnt_ch, div_cnt_ch0) - } - - #[inline] - pub fn mem_size(&mut self) -> FieldProxy<'_, Self, u8> { - field_proxy!(self, mem_size_ch, mem_size_ch0) - } - - #[inline] - pub fn tx_conti_mode(&mut self) -> BitProxy<'_, Self> { - bit_proxy!(self, tx_conti_mode_ch, tx_conti_mode_ch0) - } - - #[inline] - pub fn mem_tx_wrap_en(&mut self) -> BitProxy<'_, Self> { - bit_proxy!(self, mem_tx_wrap_en_ch, mem_tx_wrap_en_ch0) - } - - #[inline] - pub fn carrier_en(&mut self) -> BitProxy<'_, Self> { - bit_proxy!(self, carrier_en_ch, carrier_en_ch0) - } - - #[inline] - pub fn carrier_eff_en(&mut self) -> BitProxy<'_, Self> { - bit_proxy!(self, carrier_eff_en_ch, carrier_eff_en_ch0) - } - - #[inline] - pub fn carrier_out_lv(&mut self) -> BitProxy<'_, Self> { - bit_proxy!(self, carrier_out_lv_ch, carrier_out_lv_ch0) - } - - #[inline] - pub fn idle_out_en(&mut self) -> BitProxy<'_, Self> { - bit_proxy!(self, idle_out_en_ch, idle_out_en_ch0) - } - - #[inline] - pub fn idle_out_lv(&mut self) -> BitProxy<'_, Self> { - bit_proxy!(self, idle_out_lv_ch, idle_out_lv_ch0) - } - - #[inline] - pub fn mem_rd_rst(&mut self) -> BitProxy<'_, Self> { - bit_proxy!(self, mem_rd_rst_ch, mem_rd_rst_ch0) - } - - #[inline] - pub fn apb_mem_rst(&mut self) -> BitProxy<'_, Self> { - bit_proxy!(self, apb_mem_rst_ch, apb_mem_rst_ch0) - } - - #[inline] - pub fn tx_start(&mut self) -> BitProxy<'_, Self> { - bit_proxy!(self, tx_start_ch, tx_start_ch0) - } - - #[inline] - pub fn tx_stop(&mut self) -> BitProxy<'_, Self> { - bit_proxy!(self, tx_stop_ch, tx_stop_ch0) - } -} - -/// RX CONF0 layout (ESP32-S3 `CH_RX_CONF0`). The PAC aliases this register to TX CONF0. -pub struct ChRxConf0 { - ptr: *mut u32, -} - -/// Reader for [`ChRxConf0`]. -pub struct ChRxConf0R(u32); - -/// Writer for [`ChRxConf0`]. -pub struct ChRxConf0W(u32); - -/// Bit writer for [`ChRxConf0`]. -pub struct RxBit<'a> { - w: &'a mut ChRxConf0W, - bit: u8, -} - -/// Field writer for [`ChRxConf0`]. -pub struct RxField<'a> { - w: &'a mut ChRxConf0W, - offset: u8, - width: u8, -} - -impl ChRxConf0R { - #[inline] - pub fn mem_size(&self) -> FieldVal { - FieldVal(((self.0 >> 24) & 0x0f) as u8) - } -} - -impl ChRxConf0W { - #[inline] - pub fn div_cnt(&mut self) -> RxField<'_> { - RxField { - w: self, - offset: 0, - width: 8, - } - } - - #[inline] - pub fn idle_thres(&mut self) -> RxField<'_> { - RxField { - w: self, - offset: 8, - width: 15, - } - } - - #[inline] - pub fn mem_size(&mut self) -> RxField<'_> { - RxField { - w: self, - offset: 24, - width: 4, - } - } - - #[inline] - pub fn carrier_en(&mut self) -> RxBit<'_> { - RxBit { w: self, bit: 28 } - } - - #[inline] - pub fn carrier_out_lv(&mut self) -> RxBit<'_> { - RxBit { w: self, bit: 29 } - } -} - -impl<'a> RxBit<'a> { - #[inline] - pub fn bit(self, val: bool) -> &'a mut ChRxConf0W { - if val { - self.w.0 |= 1 << self.bit; - } else { - self.w.0 &= !(1 << self.bit); - } - self.w - } -} - -impl<'a> RxField<'a> { - #[inline] - pub unsafe fn bits(self, val: impl Into) -> &'a mut ChRxConf0W { - let mask = (1u32 << self.width) - 1; - self.w.0 &= !(mask << self.offset); - self.w.0 |= (u32::from(val.into()) & mask) << self.offset; - self.w - } -} - -impl ChRxConf0 { - #[inline] - pub fn read(&self) -> ChRxConf0R { - ChRxConf0R(unsafe { self.ptr.read_volatile() }) - } - - #[inline] - pub fn modify(&self, f: F) - where - F: for<'a> FnOnce(&ChRxConf0R, &'a mut ChRxConf0W) -> &'a mut ChRxConf0W, - { - let bits = unsafe { self.ptr.read_volatile() }; - let r = ChRxConf0R(bits); - let mut w = ChRxConf0W(bits); - let _ = f(&r, &mut w); - unsafe { self.ptr.write_volatile(w.0) }; - } -} - -/// Channel RX configure register 1. -pub struct RxConf1<'a>(&'a rmt::CHCONF1); - -/// Writer for [`RxConf1`]. -#[repr(transparent)] -pub struct RxConf1W(rmt::chconf1::W); - -impl RxConf1<'_> { - #[inline] - pub fn modify(&self, f: F) - where - F: for<'a> FnOnce(&(), &'a mut RxConf1W) -> &'a mut RxConf1W, - { - self.0.modify(|_, w| { - let _ = f(&(), overlay_w(w)); - w - }); - } -} - -impl RxConf1W { - #[inline] - pub fn conf_update(&mut self) -> BitProxy<'_, Self> { - bit_proxy!(self, conf_update_ch, conf_update_ch4) - } - - #[inline] - pub fn mem_rx_wrap_en(&mut self) -> BitProxy<'_, Self> { - bit_proxy!(self, mem_rx_wrap_en_ch, mem_rx_wrap_en_ch4) - } - - #[inline] - pub fn mem_owner(&mut self) -> BitProxy<'_, Self> { - bit_proxy!(self, mem_owner_ch, mem_owner_ch4) - } - - #[inline] - pub fn mem_wr_rst(&mut self) -> BitProxy<'_, Self> { - bit_proxy!(self, mem_wr_rst_ch, mem_wr_rst_ch4) - } - - #[inline] - pub fn apb_mem_rst(&mut self) -> BitProxy<'_, Self> { - bit_proxy!(self, apb_mem_rst_ch, apb_mem_rst_ch4) - } - - #[inline] - pub fn rx_en(&mut self) -> BitProxy<'_, Self> { - bit_proxy!(self, rx_en_ch, rx_en_ch4) - } - - #[inline] - pub fn rx_filter_en(&mut self) -> BitProxy<'_, Self> { - bit_proxy!(self, rx_filter_en_ch, rx_filter_en_ch4) - } - - #[inline] - pub fn rx_filter_thres(&mut self) -> FieldProxy<'_, Self, u8> { - field_proxy!(self, rx_filter_thres_ch, rx_filter_thres_ch4) - } -} - -/// Channel TX/RX status register. -pub struct ChStatus<'a>(&'a rmt::CHSTATUS); - -/// Reader for [`ChStatus`]. -pub struct StatusR(u32); - -impl ChStatus<'_> { - #[inline] - pub fn read(&self) -> StatusR { - StatusR(self.0.read().bits()) - } -} - -impl StatusR { - #[inline] - pub fn mem_raddr_ex(&self) -> FieldVal { - FieldVal((self.0 & 0x03ff) as u16) - } - - #[inline] - pub fn mem_waddr_ex(&self) -> FieldVal { - self.mem_raddr_ex() - } -} - -/// Channel TX limit register. -pub struct TxLim<'a>(&'a rmt::CH_TX_LIM); - -/// Writer for [`TxLim`]. -#[repr(transparent)] -pub struct TxLimW(rmt::ch_tx_lim::W); - -impl TxLim<'_> { - #[inline] - pub fn modify(&self, f: F) - where - F: for<'a> FnOnce(&(), &'a mut TxLimW) -> &'a mut TxLimW, - { - self.0.modify(|_, w| { - let _ = f(&(), overlay_w(w)); - w - }); - } -} - -impl TxLimW { - #[inline] - pub fn loop_count_reset(&mut self) -> BitProxy<'_, Self> { - BitProxy(self, |w, val| { - w.0.loop_count_reset_ch().bit(val); - }) - } - - #[inline] - pub fn tx_loop_cnt_en(&mut self) -> BitProxy<'_, Self> { - BitProxy(self, |w, val| { - w.0.tx_loop_cnt_en_ch().bit(val); - }) - } - - #[inline] - pub fn tx_loop_num(&mut self) -> FieldProxy<'_, Self, u16> { - FieldProxy(self, |w, val| { - let _ = unsafe { w.0.tx_loop_num_ch().bits(val) }; - }) - } - - #[inline] - pub fn loop_stop_en(&mut self) -> BitProxy<'_, Self> { - BitProxy(self, |w, val| { - w.0.loop_stop_en_ch().bit(val); - }) - } - - #[inline] - pub fn tx_lim(&mut self) -> FieldProxy<'_, Self, u16> { - FieldProxy(self, |w, val| { - let _ = unsafe { w.0.tx_lim_ch().bits(val) }; - }) - } -} - -/// Channel RX limit register. -pub struct RxLim<'a>(&'a rmt::CH_RX_LIM); - -/// Writer for [`RxLim`]. -#[repr(transparent)] -pub struct RxLimW(rmt::ch_rx_lim::W); - -impl RxLim<'_> { - #[inline] - pub fn modify(&self, f: F) - where - F: for<'a> FnOnce(&(), &'a mut RxLimW) -> &'a mut RxLimW, - { - self.0.modify(|_, w| { - let _ = f(&(), overlay_w(w)); - w - }); - } -} - -impl RxLimW { - #[inline] - pub fn rx_lim(&mut self) -> FieldProxy<'_, Self, u16> { - field_proxy!(self, rx_lim_ch, rx_lim_ch4) - } -} - -/// Channel carrier duty register. -pub struct CarrierDuty<'a>(&'a rmt::CHCARRIER_DUTY); - -/// Writer for [`CarrierDuty`]. -#[repr(transparent)] -pub struct CarrierDutyW(rmt::chcarrier_duty::W); - -impl CarrierDuty<'_> { - #[inline] - pub fn write(&self, f: F) - where - F: for<'a> FnOnce(&'a mut CarrierDutyW) -> &'a mut CarrierDutyW, - { - self.0.write(|w| { - let _ = f(overlay_w(w)); - w - }); - } -} - -impl CarrierDutyW { - #[inline] - pub fn carrier_high(&mut self) -> FieldProxy<'_, Self, u16> { - FieldProxy(self, |w, val| { - let _ = unsafe { w.0.carrier_high_ch().bits(val) }; - }) - } - - #[inline] - pub fn carrier_low(&mut self) -> FieldProxy<'_, Self, u16> { - FieldProxy(self, |w, val| { - let _ = unsafe { w.0.carrier_low_ch().bits(val) }; - }) - } -} - -/// Channel RX carrier remove register. -pub struct RxCarrierRm<'a>(&'a rmt::CH_RX_CARRIER_RM); - -/// Writer for [`RxCarrierRm`]. -#[repr(transparent)] -pub struct RxCarrierRmW(rmt::ch_rx_carrier_rm::W); - -impl RxCarrierRm<'_> { - #[inline] - pub fn write(&self, f: F) - where - F: for<'a> FnOnce(&'a mut RxCarrierRmW) -> &'a mut RxCarrierRmW, - { - self.0.write(|w| { - let _ = f(overlay_w(w)); - w - }); - } -} - -impl RxCarrierRmW { - #[inline] - pub fn carrier_high_thres(&mut self) -> FieldProxy<'_, Self, u16> { - FieldProxy(self, |w, val| { - let _ = unsafe { w.0.carrier_high_thres_ch().bits(val) }; - }) - } - - #[inline] - pub fn carrier_low_thres(&mut self) -> FieldProxy<'_, Self, u16> { - FieldProxy(self, |w, val| { - let _ = unsafe { w.0.carrier_low_thres_ch().bits(val) }; - }) - } -} - -/// Masked interrupt status. -pub struct IntSt<'a>(&'a rmt::INT_ST); - -/// Raw interrupt status. -pub struct IntRaw<'a>(&'a rmt::INT_RAW); - -/// Interrupt status reader. -pub struct IntR(u32); - -impl IntSt<'_> { - #[inline] - pub fn read(&self) -> IntR { - IntR(self.0.read().bits()) - } -} - -impl IntRaw<'_> { - #[inline] - pub fn read(&self) -> IntR { - IntR(self.0.read().bits()) - } -} - -impl IntR { - #[inline] - pub fn ch_tx_end(&self, n: u8) -> BitFlag { - BitFlag((self.0 >> n) & 1 != 0) - } - - #[inline] - pub fn ch_tx_err(&self, n: u8) -> BitFlag { - BitFlag((self.0 >> (n + 4)) & 1 != 0) - } - - #[inline] - pub fn ch_tx_thr_event(&self, n: u8) -> BitFlag { - BitFlag((self.0 >> (n + 8)) & 1 != 0) - } - - #[inline] - pub fn ch_tx_loop(&self, n: u8) -> BitFlag { - BitFlag((self.0 >> (n + 12)) & 1 != 0) - } - - #[inline] - pub fn ch_rx_end(&self, n: u8) -> BitFlag { - BitFlag((self.0 >> (n + 16)) & 1 != 0) - } - - #[inline] - pub fn ch_rx_err(&self, n: u8) -> BitFlag { - BitFlag((self.0 >> (n + 20)) & 1 != 0) - } - - #[inline] - pub fn ch_rx_thr_event(&self, n: u8) -> BitFlag { - BitFlag((self.0 >> (n + 24)) & 1 != 0) - } -} - -/// Interrupt enable register. -pub struct IntEna<'a>(&'a rmt::INT_ENA); - -/// Writer for [`IntEna`]. -#[repr(transparent)] -pub struct IntEnaW(rmt::int_ena::W); - -/// Interrupt clear register. -pub struct IntClr<'a>(&'a rmt::INT_CLR); - -/// Writer for [`IntClr`]. -#[repr(transparent)] -pub struct IntClrW(rmt::int_clr::W); - -/// Clustered interrupt bit writer. -pub struct IntBitW<'a, W> { - w: &'a mut W, - n: u8, - set: fn(&mut W, u8, bool), -} - -impl<'a, W> IntBitW<'a, W> { - #[inline] - pub fn bit(self, val: bool) -> &'a mut W { - (self.set)(self.w, self.n, val); - self.w - } -} - -impl IntEna<'_> { - #[inline] - pub fn modify(&self, f: F) - where - F: for<'a> FnOnce(&(), &'a mut IntEnaW) -> &'a mut IntEnaW, - { - self.0.modify(|_, w| { - let _ = f(&(), overlay_w(w)); - w - }); - } -} - -impl IntClr<'_> { - #[inline] - pub fn write(&self, f: F) - where - F: for<'a> FnOnce(&'a mut IntClrW) -> &'a mut IntClrW, - { - self.0.write(|w| { - let _ = f(overlay_w(w)); - w - }); - } -} - -macro_rules! set_tx_int { - ($w:expr, $n:expr, $val:expr, $p4:ident, $s31:ident) => { - paste::paste! { - match $n { - 0 => { - #[cfg(esp32p4)] - { - $w.[]().bit($val); - } - #[cfg(esp32s31)] - { - $w.[]().bit($val); - } - } - 1 => { - #[cfg(esp32p4)] - { - $w.[]().bit($val); - } - #[cfg(esp32s31)] - { - $w.[]().bit($val); - } - } - 2 => { - #[cfg(esp32p4)] - { - $w.[]().bit($val); - } - #[cfg(esp32s31)] - { - $w.[]().bit($val); - } - } - 3 => { - #[cfg(esp32p4)] - { - $w.[]().bit($val); - } - #[cfg(esp32s31)] - { - $w.[]().bit($val); - } - } - _ => unreachable!(), - } - } - }; -} - -macro_rules! set_rx_int { - ($w:expr, $n:expr, $val:expr, $p4:ident, $s31:ident) => { - paste::paste! { - match $n { - 0 => { - #[cfg(esp32p4)] - { - $w.[]().bit($val); - } - #[cfg(esp32s31)] - { - $w.[]().bit($val); - } - } - 1 => { - #[cfg(esp32p4)] - { - $w.[]().bit($val); - } - #[cfg(esp32s31)] - { - $w.[]().bit($val); - } - } - 2 => { - #[cfg(esp32p4)] - { - $w.[]().bit($val); - } - #[cfg(esp32s31)] - { - $w.[]().bit($val); - } - } - 3 => { - #[cfg(esp32p4)] - { - $w.[]().bit($val); - } - #[cfg(esp32s31)] - { - $w.[]().bit($val); - } - } - _ => unreachable!(), - } - } - }; -} - -macro_rules! impl_int_w { - ($ty:ty, $tx_end_p4:ident, $tx_end_s31:ident, $tx_err_p4:ident, $tx_err_s31:ident, $tx_thr_p4:ident, $tx_thr_s31:ident, $tx_loop_p4:ident, $tx_loop_s31:ident, $rx_end_p4:ident, $rx_end_s31:ident, $rx_err_p4:ident, $rx_err_s31:ident, $rx_thr_p4:ident, $rx_thr_s31:ident) => { - impl $ty { - #[inline] - pub fn ch_tx_end(&mut self, n: u8) -> IntBitW<'_, Self> { - IntBitW { - w: self, - n, - set: |w, n, val| set_tx_int!(w.0, n, val, $tx_end_p4, $tx_end_s31), - } - } - - #[inline] - pub fn ch_tx_err(&mut self, n: u8) -> IntBitW<'_, Self> { - IntBitW { - w: self, - n, - set: |w, n, val| set_tx_int!(w.0, n, val, $tx_err_p4, $tx_err_s31), - } - } - - #[inline] - pub fn ch_tx_thr_event(&mut self, n: u8) -> IntBitW<'_, Self> { - IntBitW { - w: self, - n, - set: |w, n, val| set_tx_int!(w.0, n, val, $tx_thr_p4, $tx_thr_s31), - } - } - - #[inline] - pub fn ch_tx_loop(&mut self, n: u8) -> IntBitW<'_, Self> { - IntBitW { - w: self, - n, - set: |w, n, val| set_tx_int!(w.0, n, val, $tx_loop_p4, $tx_loop_s31), - } - } - - #[inline] - pub fn ch_rx_end(&mut self, n: u8) -> IntBitW<'_, Self> { - IntBitW { - w: self, - n, - set: |w, n, val| set_rx_int!(w.0, n, val, $rx_end_p4, $rx_end_s31), - } - } - - #[inline] - pub fn ch_rx_err(&mut self, n: u8) -> IntBitW<'_, Self> { - IntBitW { - w: self, - n, - set: |w, n, val| set_rx_int!(w.0, n, val, $rx_err_p4, $rx_err_s31), - } - } - - #[inline] - pub fn ch_rx_thr_event(&mut self, n: u8) -> IntBitW<'_, Self> { - IntBitW { - w: self, - n, - set: |w, n, val| set_rx_int!(w.0, n, val, $rx_thr_p4, $rx_thr_s31), - } - } - } - }; -} - -impl_int_w!( - IntEnaW, - tx_end, - tx_end_int_ena, - err, - err_int_ena, - tx_thr_event, - tx_thr_event_int_ena, - tx_loop, - tx_loop_int_ena, - rx_end, - rx_end_int_ena, - err, - err_int_ena, - rx_thr_event, - rx_thr_event_int_ena -); - -impl_int_w!( - IntClrW, - tx_end, - tx_end_int_clr, - err, - err_int_clr, - tx_thr_event, - tx_thr_event_int_clr, - tx_loop, - tx_loop_int_clr, - rx_end, - rx_end_int_clr, - err, - err_int_clr, - rx_thr_event, - rx_thr_event_int_clr -); diff --git a/esp-hal/src/private.rs b/esp-hal/src/private.rs index d498d9e34f1..1559b055a97 100644 --- a/esp-hal/src/private.rs +++ b/esp-hal/src/private.rs @@ -5,6 +5,35 @@ use core::{ ops::{Deref, DerefMut}, }; +use portable_atomic::{AtomicPtr, Ordering}; + +/// An optional `extern "C" fn()` stored as an atomic pointer. +pub(crate) struct CFnPtr(AtomicPtr<()>); + +impl CFnPtr { + pub const fn new() -> Self { + Self(AtomicPtr::new(core::ptr::null_mut())) + } + + pub fn store(&self, f: extern "C" fn()) { + self.0.store(f as *mut (), Ordering::Relaxed); + } + + pub fn clear(&self) { + self.0.store(core::ptr::null_mut(), Ordering::Relaxed); + } + + pub fn call(&self) -> bool { + let ptr = self.0.load(Ordering::Relaxed); + if !ptr.is_null() { + unsafe { (core::mem::transmute::<*mut (), extern "C" fn()>(ptr))() }; + true + } else { + false + } + } +} + pub trait Sealed {} #[non_exhaustive] @@ -13,16 +42,16 @@ pub trait Sealed {} pub struct Internal; impl Internal { - /// Obtain magical powers to access internal APIs. + /// Obtains magical powers to access internal APIs. /// /// # Safety /// - /// By calling this function, you accept that you are using an internal - /// API that is not guaranteed to be documented, stable, working + /// Calling this method accepts that this is an internal + /// API that is not guaranteed to be documented, stable, or working, /// and may change at any time. /// - /// You declare that you have tried to look for other solutions, that - /// you have opened a feature request or an issue to discuss the + /// Calling this method also declares that other solutions have been tried, and that + /// a feature request or an issue has been opened to discuss the /// need for this function. pub unsafe fn conjure() -> Self { Self diff --git a/esp-hal/src/psram/esp32.rs b/esp-hal/src/psram/esp32.rs index 9772b3faac5..0b67d587034 100644 --- a/esp-hal/src/psram/esp32.rs +++ b/esp-hal/src/psram/esp32.rs @@ -48,15 +48,11 @@ pub struct PsramConfig { pub psram_vaddr_mode: PsramVaddrMode, } -/// Initialize PSRAM to be used for data. +/// Initializes PSRAM to be used for data. #[procmacros::ram] pub(crate) fn init_psram(config: &mut PsramConfig) -> bool { utils::psram_init(config); - true -} -#[procmacros::ram] -pub(crate) fn map_psram(mut config: PsramConfig) -> Range { if config.size.is_auto() { const MAX_MEM_SIZE: usize = 4 * 1024 * 1024; @@ -67,7 +63,7 @@ pub(crate) fn map_psram(mut config: PsramConfig) -> Range { // probe how much memory we can write/read utils::s_mapping(EXTMEM_ORIGIN as u32, MAX_MEM_SIZE as u32); - let guessed_size = unsafe { + let last_correctly_read = unsafe { let ptr = EXTMEM_ORIGIN as *mut u8; for i in (1023..MAX_MEM_SIZE).step_by(1024) { ptr.add(i).write_volatile(0x7f); @@ -82,21 +78,29 @@ pub(crate) fn map_psram(mut config: PsramConfig) -> Range { } } - last_correctly_read + 1 + last_correctly_read }; + if last_correctly_read == 0 { + warn!("No PSRAM found"); + return false; + } + let guessed_size = last_correctly_read + 1; info!("Assuming {} bytes of PSRAM", guessed_size); config.size = PsramSize::Size(guessed_size); } + true +} + +#[procmacros::ram] +pub(crate) fn map_psram(config: PsramConfig) -> Range { utils::s_mapping(EXTMEM_ORIGIN as u32, config.size.get() as u32); EXTMEM_ORIGIN..EXTMEM_ORIGIN + config.size.get() } pub(crate) mod utils { - use core::ptr::addr_of_mut; - use procmacros::ram; use super::*; @@ -170,10 +174,6 @@ pub(crate) mod utils { const PSRAM_HSPI_SPIWP_SD3_IO: u8 = 2; const PSRAM_HSPI_SPIHD_SD2_IO: u8 = 4; - const DR_REG_SPI1_BASE: u32 = 0x3ff42000; - const SPI1_USER_REG: u32 = DR_REG_SPI1_BASE + 0x1C; - const SPI1_W0_REG: u32 = DR_REG_SPI1_BASE + 0x80; - const fn psram_cs_hold_time_from_psram_speed(speed: PsramCacheSpeed) -> u32 { match speed { PsramCacheSpeed::PsramCacheF80mS40m => 0, @@ -466,7 +466,6 @@ pub(crate) mod utils { } // Update cs timing according to psram driving method. - psram_set_cs_timing_spi1(mode, clk_mode); psram_set_cs_timing_spi0(mode, clk_mode); // SPI_CACHE_PORT psram_enable_qio_mode_spi1(clk_mode, mode); @@ -504,11 +503,13 @@ pub(crate) mod utils { // 2+SRAM DIV4 } PsramCacheSpeed::PsramCacheF80mS40m => { - spi.clock().modify(|_, w| w.clk_equ_sysclk().clear_bit()); - spi.clock().modify(|_, w| w.clkdiv_pre().bits(0)); - spi.clock().modify(|_, w| w.clkcnt_n().bits(1)); - spi.clock().modify(|_, w| w.clkcnt_h().bits(0)); - spi.clock().modify(|_, w| w.clkcnt_l().bits(1)); + spi.clock().modify(|_, w| { + w.clk_equ_sysclk().clear_bit(); + w.clkdiv_pre().bits(0); + w.clkcnt_n().bits(1); + w.clkcnt_h().bits(0); + w.clkcnt_l().bits(1) + }); spi.date().modify(|r, w| { let current_bits = r.bits(); @@ -525,60 +526,44 @@ pub(crate) mod utils { } } - spi.cache_sctrl() - .modify(|_, w| w.usr_sram_dio().clear_bit()); // disable dio mode for cache command - spi.cache_sctrl().modify(|_, w| w.usr_sram_qio().set_bit()); // enable qio mode for cache command - spi.cache_sctrl() - .modify(|_, w| w.cache_sram_usr_rcmd().set_bit()); // enable cache read command - spi.cache_sctrl() - .modify(|_, w| w.cache_sram_usr_wcmd().set_bit()); // enable cache write command - spi.cache_sctrl() - .modify(|_, w| w.sram_addr_bitlen().bits(23)); // write address for cache command. - spi.cache_sctrl() - .modify(|_, w| w.usr_rd_sram_dummy().set_bit()); // enable cache read dummy - - // config sram cache r/w command - spi.sram_drd_cmd() - .modify(|_, w| w.cache_sram_usr_rd_cmd_bitlen().bits(7)); + // QIO cache command, 24-bit address, dummy. Dummy: 40 MHz +1, 80 MHz +2. + spi.cache_sctrl().modify(|_, w| { + w.usr_sram_dio().clear_bit(); + w.usr_sram_qio().set_bit(); + w.cache_sram_usr_rcmd().set_bit(); + w.cache_sram_usr_wcmd().set_bit(); + w.sram_addr_bitlen().bits(23); + w.usr_rd_sram_dummy().set_bit(); + w.sram_dummy_cyclelen() + .bits((PSRAM_FAST_READ_QUAD_DUMMY + extra_dummy) as u8) + }); + spi.sram_drd_cmd().modify(|_, w| { + w.cache_sram_usr_rd_cmd_bitlen().bits(7); w.cache_sram_usr_rd_cmd_value() .bits(PSRAM_FAST_READ_QUAD as u16) }); - spi.sram_dwr_cmd() - .modify(|_, w| w.cache_sram_usr_wr_cmd_bitlen().bits(7)); spi.sram_dwr_cmd().modify(|_, w| { + w.cache_sram_usr_wr_cmd_bitlen().bits(7); w.cache_sram_usr_wr_cmd_value() .bits(PSRAM_QUAD_WRITE as u16) }); - // dummy, psram cache : 40m--+1dummy; 80m--+2dummy - spi.cache_sctrl().modify(|_, w| { - w.sram_dummy_cyclelen() - .bits((PSRAM_FAST_READ_QUAD_DUMMY + extra_dummy) as u8) - }); - match psram_cache_mode { PsramCacheSpeed::PsramCacheF80mS80m => (), // in this mode , no delay is needed _ => { if clk_mode == PsramClkMode::PsramClkModeDclk { - spi.sram_drd_cmd() - .modify(|_, w| w.cache_sram_usr_rd_cmd_bitlen().bits(15)); // read command length, 2 bytes(1byte for delay),sending in qio mode in - // cache + // Extra command byte (0x00) delays the QIO command in DCLK mode. spi.sram_drd_cmd().modify(|_, w| { + w.cache_sram_usr_rd_cmd_bitlen().bits(15); w.cache_sram_usr_rd_cmd_value() .bits((PSRAM_FAST_READ_QUAD << 8) as u16) - }); // read command value,(0x00 for delay,0xeb for cmd) - - spi.sram_dwr_cmd() - .modify(|_, w| w.cache_sram_usr_wr_cmd_bitlen().bits(15)); // write command length,2 bytes(1byte for delay,send in qio mode in cache) + }); spi.sram_dwr_cmd().modify(|_, w| { + w.cache_sram_usr_wr_cmd_bitlen().bits(15); w.cache_sram_usr_wr_cmd_value() .bits((PSRAM_QUAD_WRITE << 8) as u16) - }); // write command value,(0x00 for delay) - spi.cache_sctrl().modify(|_, w| { - w.sram_dummy_cyclelen() - .bits((PSRAM_FAST_READ_QUAD_DUMMY + extra_dummy) as u8) - }); // dummy, psram cache : 40m--+1dummy; 80m--+2dummy + }); } } } @@ -609,27 +594,17 @@ pub(crate) mod utils { // use Dram1 to visit ext sram. cache page mode : 1 -->16k 4 -->2k // 0-->32k,(accord with the settings in cache_sram_mmu_set) + // Dram1 visits ext SRAM. Cache page mode 0 = 32 k (matches cache_sram_mmu_set). dport.pro_cache_ctrl1().modify(|_, w| { - w.pro_cache_mask_dram1() - .clear_bit() - .pro_cache_mask_opsdram() - .clear_bit() + w.pro_cache_mask_dram1().clear_bit(); + w.pro_cache_mask_opsdram().clear_bit(); + w.pro_cmmu_sram_page_mode().bits(0) }); - dport - .pro_cache_ctrl1() - .modify(|_, w| w.pro_cmmu_sram_page_mode().bits(0)); - - // use Dram1 to visit ext sram. cache page mode : 1 -->16k 4 -->2k - // 0-->32k,(accord with the settings in cache_sram_mmu_set) dport.app_cache_ctrl1().modify(|_, w| { - w.app_cache_mask_dram1() - .clear_bit() - .app_cache_mask_opsdram() - .clear_bit() + w.app_cache_mask_dram1().clear_bit(); + w.app_cache_mask_opsdram().clear_bit(); + w.app_cmmu_sram_page_mode().bits(0) }); - dport - .app_cache_ctrl1() - .modify(|_, w| w.app_cmmu_sram_page_mode().bits(0)); // ENABLE SPI0 CS1 TO PSRAM(CS0--FLASH; CS1--SRAM) spi.pin().modify(|_, w| w.cs1_dis().clear_bit()); @@ -643,84 +618,72 @@ pub(crate) mod utils { mode: PsramCacheSpeed, clk_mode: PsramClkMode, ) { - unsafe { - let spi = SPI1::regs(); - // We need to clear last bit of INT_EN field here. - spi.slave().modify(|_, w| w.trans_inten().clear_bit()); - // SPI_CPOL & SPI_CPHA - spi.pin().modify(|_, w| w.ck_idle_edge().clear_bit()); - spi.user().modify(|_, w| w.ck_out_edge().clear_bit()); - // SPI bit order - spi.ctrl().modify(|_, w| w.wr_bit_order().clear_bit()); - spi.ctrl().modify(|_, w| w.rd_bit_order().clear_bit()); - // SPI bit order - spi.user().modify(|_, w| w.doutdin().clear_bit()); - // May be not must to do. - spi.user1().modify(|_, w| w.bits(0)); - // SPI mode type - spi.slave().modify(|_, w| w.mode().clear_bit()); - - let ptr = SPI1_W0_REG as *mut u32; - for i in 0..16 { - ptr.offset(i).write_volatile(0); - } + SPI1::regs().slave().modify(|_, w| { + w.trans_inten().clear_bit(); + w.mode().clear_bit() + }); + SPI1::regs() + .pin() + .modify(|_, w| w.ck_idle_edge().clear_bit()); + SPI1::regs().user().modify(|_, w| { + w.ck_out_edge().clear_bit(); + w.doutdin().clear_bit() + }); + SPI1::regs().ctrl().modify(|_, w| { + w.wr_bit_order().clear_bit(); + w.rd_bit_order().clear_bit() + }); + SPI1::regs().user1().modify(|_, w| unsafe { w.bits(0) }); - psram_set_cs_timing_spi1(mode, clk_mode); - } + SPI1::regs().w_iter().for_each(|w| { + w.write(|w| unsafe { w.bits(0) }); + }); + + psram_set_cs_timing_spi1(mode, clk_mode); } fn psram_set_cs_timing_spi1(psram_cache_mode: PsramCacheSpeed, clk_mode: PsramClkMode) { - unsafe { - let spi = SPI1::regs(); - if clk_mode == PsramClkMode::PsramClkModeNorm { - spi.user().modify(|_, w| w.cs_hold().set_bit()); - spi.user().modify(|_, w| w.cs_setup().set_bit()); - - spi.ctrl2().modify(|_, w| { - w.hold_time() - .bits(psram_cs_hold_time_from_psram_speed(psram_cache_mode) as u8) - }); - - // Set cs time. - spi.ctrl2().modify(|_, w| w.setup_time().bits(0)); - } else { - spi.user().modify(|_, w| w.cs_hold().clear_bit()); - spi.user().modify(|_, w| w.cs_setup().clear_bit()); - } + let spi = SPI1::regs(); + let normal_mode = clk_mode == PsramClkMode::PsramClkModeNorm; + spi.user().modify(|_, w| { + w.cs_hold().bit(normal_mode); + w.cs_setup().bit(normal_mode) + }); + if normal_mode { + spi.ctrl2().modify(|_, w| unsafe { + w.hold_time() + .bits(psram_cs_hold_time_from_psram_speed(psram_cache_mode) as u8); + w.setup_time().bits(0) + }); } } fn psram_set_cs_timing_spi0(psram_cache_mode: PsramCacheSpeed, clk_mode: PsramClkMode) { - unsafe { - let spi = SPI0::regs(); - if clk_mode == PsramClkMode::PsramClkModeNorm { - spi.user().modify(|_, w| w.cs_hold().set_bit()); - spi.user().modify(|_, w| w.cs_setup().set_bit()); - - spi.ctrl2().modify(|_, w| { - w.hold_time() - .bits(psram_cs_hold_time_from_psram_speed(psram_cache_mode) as u8) - }); - - // Set cs time. - spi.ctrl2().modify(|_, w| w.setup_time().bits(0)); - } else { - spi.user().modify(|_, w| w.cs_hold().clear_bit()); - spi.user().modify(|_, w| w.cs_setup().clear_bit()); - } + let spi = SPI0::regs(); + let normal_mode = clk_mode == PsramClkMode::PsramClkModeNorm; + spi.user().modify(|_, w| { + w.cs_hold().bit(normal_mode); + w.cs_setup().bit(normal_mode) + }); + if normal_mode { + spi.ctrl2().modify(|_, w| unsafe { + w.hold_time() + .bits(psram_cs_hold_time_from_psram_speed(psram_cache_mode) as u8); + w.setup_time().bits(0) + }); } } - #[derive(Default, Debug, Copy, Clone, PartialEq)] - struct PsramCmd { - cmd: u16, // Command value - cmd_bit_len: u16, // Command byte length - addr: u32, // Address value - addr_bit_len: u16, // Address byte length - tx_data: *const u32, // Point to send data buffer - tx_data_bit_len: u16, // Send data byte length. - rx_data: *mut u32, // Point to recevie data buffer - rx_data_bit_len: u16, // Recevie Data byte length. + #[derive(Default, Debug, PartialEq)] + struct PsramCmd<'a> { + cmd: u16, // Command value + cmd_bit_len: u16, // Command byte length + addr: u32, // Address value + addr_bit_len: u16, // Address byte length + tx_data: &'a [u32], // Point to send data buffer + tx_data_bit_len: u16, + rx_data: &'a mut [u32], // Point to receive data buffer + rx_data_bit_len: u16, dummy_bit_len: u32, } @@ -729,211 +692,182 @@ pub(crate) mod utils { // enter QPI mode #[ram] fn psram_enable_qio_mode_spi1(clk_mode: PsramClkMode, psram_mode: PsramCacheSpeed) { - let mut ps_cmd: PsramCmd = PsramCmd::default(); - let addr: u32 = PSRAM_ENTER_QMODE << 24; + let ps_cmd = PsramCmd { + cmd_bit_len: if clk_mode == PsramClkMode::PsramClkModeDclk + && psram_mode != PsramCacheSpeed::PsramCacheF80mS80m + { + 2 + } else { + 0 + }, + cmd: 0, + addr: PSRAM_ENTER_QMODE << 24, + addr_bit_len: 8, + tx_data: &[], + tx_data_bit_len: 0, + rx_data: &mut [], + rx_data_bit_len: 0, + dummy_bit_len: 0, + }; - ps_cmd.cmd_bit_len = 0; - if clk_mode == PsramClkMode::PsramClkModeDclk { - match psram_mode { - PsramCacheSpeed::PsramCacheF80mS80m => (), - _ => { - ps_cmd.cmd_bit_len = 2; - } - } - } - ps_cmd.cmd = 0; - ps_cmd.addr = addr; - ps_cmd.addr_bit_len = 8; - ps_cmd.tx_data = core::ptr::null(); - ps_cmd.tx_data_bit_len = 0; - ps_cmd.rx_data = core::ptr::null_mut(); - ps_cmd.rx_data_bit_len = 0; - ps_cmd.dummy_bit_len = 0; let (backup_usr, backup_usr1, backup_usr2) = psram_cmd_config_spi1(&ps_cmd); - psram_cmd_recv_start_spi1(core::ptr::null_mut(), 0, PsramCmdMode::PsramCmdQpi); + psram_cmd_recv_start_spi1(&mut [], PsramCmdMode::PsramCmdQpi); psram_cmd_end_spi1(backup_usr, backup_usr1, backup_usr2); } #[ram] fn psram_cmd_end_spi1(backup_usr: u32, backup_usr1: u32, backup_usr2: u32) { + while SPI1::regs().cmd().read().usr().bit_is_set() {} unsafe { - let spi = SPI1::regs(); - while spi.cmd().read().usr().bit_is_set() {} - - spi.user().write(|w| w.bits(backup_usr)); - spi.user1().write(|w| w.bits(backup_usr1)); - spi.user2().write(|w| w.bits(backup_usr2)); + SPI1::regs().user().write(|w| w.bits(backup_usr)); + SPI1::regs().user1().write(|w| w.bits(backup_usr1)); + SPI1::regs().user2().write(|w| w.bits(backup_usr2)); } } // setup spi command/addr/data/dummy in user mode #[ram] - fn psram_cmd_config_spi1(p_in_data: &PsramCmd) -> (u32, u32, u32) { - unsafe { - let spi = SPI1::regs(); - while spi.cmd().read().usr().bit_is_set() {} - - let backup_usr = spi.user().read().bits(); - let backup_usr1 = spi.user1().read().bits(); - let backup_usr2 = spi.user2().read().bits(); - - // Set command by user. - if p_in_data.cmd_bit_len != 0 { - // Max command length 16 bits. - spi.user2().modify(|_, w| { - w.usr_command_bitlen() - .bits((p_in_data.cmd_bit_len - 1) as u8) - }); - // Enable command - spi.user().modify(|_, w| w.usr_command().set_bit()); - // Load command,bit15-0 is cmd value. - spi.user2() - .modify(|_, w| w.usr_command_value().bits(p_in_data.cmd)); - } else { - spi.user().modify(|_, w| w.usr_command().clear_bit()); - spi.user2().modify(|_, w| w.usr_command_bitlen().bits(0)); - } - // Set Address by user. - if p_in_data.addr_bit_len != 0 { - spi.user1() - .modify(|_, w| w.usr_addr_bitlen().bits((p_in_data.addr_bit_len - 1) as u8)); - // Enable address - spi.user().modify(|_, w| w.usr_addr().set_bit()); - // Set address - spi.addr().modify(|_, w| w.bits(p_in_data.addr)); - } else { - spi.user().modify(|_, w| w.usr_addr().clear_bit()); - spi.user1().modify(|_, w| w.usr_addr_bitlen().bits(0)); - } - // Set data by user. - let p_tx_val = p_in_data.tx_data; - if p_in_data.tx_data_bit_len != 0 { - // Enable MOSI - spi.user().modify(|_, w| w.usr_mosi().set_bit()); - // Load send buffer - let len = p_in_data.tx_data_bit_len.div_ceil(32); - if !p_tx_val.is_null() { - for i in 0..len { - spi.w(i as usize) - .write(|w| w.bits(p_tx_val.offset(i as isize).read_volatile())); - } - } - // Set data send buffer length.Max data length 64 bytes. - spi.mosi_dlen().modify(|_, w| { - w.usr_mosi_dbitlen() - .bits((p_in_data.tx_data_bit_len - 1) as u32) - }); - } else { - spi.user().modify(|_, w| w.usr_mosi().clear_bit()); - spi.mosi_dlen().modify(|_, w| w.usr_mosi_dbitlen().bits(0)); - } - // Set rx data by user. - if p_in_data.rx_data_bit_len != 0 { - // Enable MISO - spi.user().modify(|_, w| w.usr_miso().set_bit()); - // Set data send buffer length.Max data length 64 bytes. - spi.miso_dlen().modify(|_, w| { - w.usr_miso_dbitlen() - .bits((p_in_data.rx_data_bit_len - 1) as u32) - }); - } else { - spi.user().modify(|_, w| w.usr_miso().clear_bit()); - spi.miso_dlen().modify(|_, w| w.usr_miso_dbitlen().bits(0)); - } - if p_in_data.dummy_bit_len != 0 { - spi.user().modify(|_, w| w.usr_dummy().set_bit()); // dummy en - spi.user1().modify(|_, w| { - w.usr_dummy_cyclelen() - .bits((p_in_data.dummy_bit_len - 1) as u8) - }); // DUMMY - } else { - spi.user().modify(|_, w| w.usr_dummy().clear_bit()); // dummy dis - spi.user1().modify(|_, w| w.usr_dummy_cyclelen().bits(0)); // DUMMY - } + fn psram_cmd_config_spi1(cmd: &PsramCmd<'_>) -> (u32, u32, u32) { + debug_assert_eq!(cmd.tx_data.len(), cmd.tx_data_bit_len.div_ceil(32) as usize); + debug_assert_eq!(cmd.rx_data.len(), cmd.rx_data_bit_len.div_ceil(32) as usize); + debug_assert!(cmd.tx_data_bit_len <= 64); + debug_assert!(cmd.rx_data_bit_len <= 64); - (backup_usr, backup_usr1, backup_usr2) + while SPI1::regs().cmd().read().usr().bit_is_set() {} + + let backup_usr = SPI1::regs().user().read().bits(); + let backup_usr1 = SPI1::regs().user1().read().bits(); + let backup_usr2 = SPI1::regs().user2().read().bits(); + + // Set command by user. + // + SPI1::regs().user().modify(|_, w| { + w.usr_command().bit(cmd.cmd_bit_len != 0); + w.usr_addr().bit(cmd.addr_bit_len != 0); + w.usr_mosi().bit(cmd.tx_data_bit_len != 0); + w.usr_miso().bit(cmd.rx_data_bit_len != 0); + w.usr_dummy().bit(cmd.dummy_bit_len != 0) + }); + SPI1::regs().user1().modify(|_, w| unsafe { + w.usr_addr_bitlen() + .bits(cmd.addr_bit_len.saturating_sub(1) as u8); + w.usr_dummy_cyclelen() + .bits(cmd.dummy_bit_len.saturating_sub(1) as u8) + }); + SPI1::regs().user2().modify(|_, w| unsafe { + w.usr_command_value().bits(cmd.cmd); + w.usr_command_bitlen() + .bits(cmd.cmd_bit_len.saturating_sub(1) as u8) + }); + + // Set data send buffer length. Max data length 64 bytes. + SPI1::regs().mosi_dlen().write(|w| unsafe { + w.usr_mosi_dbitlen() + .bits(cmd.tx_data_bit_len.saturating_sub(1) as u32) + }); + + // Set data send buffer length. Max data length 64 bytes. + SPI1::regs().miso_dlen().write(|w| unsafe { + w.usr_miso_dbitlen() + .bits(cmd.rx_data_bit_len.saturating_sub(1) as u32) + }); + + // Set address. + if cmd.addr_bit_len != 0 { + SPI1::regs().addr().write(|w| unsafe { w.bits(cmd.addr) }); } + + // Load TX data. + for (i, tx) in cmd.tx_data.iter().enumerate() { + SPI1::regs().w(i).write(|w| unsafe { w.bits(*tx) }); + } + + (backup_usr, backup_usr1, backup_usr2) } #[derive(Debug, Clone, Copy, PartialEq)] enum PsramCmdMode { PsramCmdQpi, + #[expect(unused)] PsramCmdSpi, } // start sending cmd/addr and optionally, receiving data #[ram] - fn psram_cmd_recv_start_spi1( - p_rx_data: *mut u32, - rx_data_len_words: usize, - cmd_mode: PsramCmdMode, - ) { - unsafe { - let spi = SPI1::regs(); - // get cs1 - spi.pin().modify(|_, w| w.cs1_dis().clear_bit()); - spi.pin().modify(|_, w| w.cs0_dis().set_bit()); + fn psram_cmd_recv_start_spi1(rx_data: &mut [u32], cmd_mode: PsramCmdMode) { + // get cs1 + SPI1::regs().pin().modify(|_, w| { + w.cs1_dis().clear_bit(); + w.cs0_dis().set_bit() + }); - let mode_backup: u32 = (spi.user().read().bits() >> SPI_FWRITE_DUAL_S) & 0xf; - let rd_mode_backup: u32 = spi.ctrl().read().bits() - & (SPI_FREAD_DIO_M | SPI_FREAD_DUAL_M | SPI_FREAD_QUAD_M | SPI_FREAD_QIO_M); + let mode_backup: u32 = (SPI1::regs().user().read().bits() >> SPI_FWRITE_DUAL_S) & 0xf; + let rd_mode_backup: u32 = SPI1::regs().ctrl().read().bits() + & (SPI_FREAD_DIO_M | SPI_FREAD_DUAL_M | SPI_FREAD_QUAD_M | SPI_FREAD_QIO_M); - if cmd_mode == PsramCmdMode::PsramCmdSpi { + match cmd_mode { + PsramCmdMode::PsramCmdSpi => { psram_set_basic_write_mode_spi1(); psram_set_basic_read_mode_spi1(); - } else if cmd_mode == PsramCmdMode::PsramCmdQpi { + } + PsramCmdMode::PsramCmdQpi => { psram_set_qio_write_mode_spi1(); psram_set_qio_read_mode_spi1(); } + } - // Wait for SPI0 to idle - while SPI1::regs().ext2().read().bits() != 0 {} - - // DPORT_SET_PERI_REG_MASK(DPORT_HOST_INF_SEL_REG, 1 << 14); - DPORT::regs() - .host_inf_sel() - .modify(|r, w| w.bits(r.bits() | (1 << 14))); - - // Start send data - spi.cmd().modify(|_, w| w.usr().set_bit()); - while spi.cmd().read().usr().bit_is_set() {} - - // DPORT_CLEAR_PERI_REG_MASK(DPORT_HOST_INF_SEL_REG, 1 << 14); - DPORT::regs() - .host_inf_sel() - .modify(|r, w| w.bits(r.bits() & !(1 << 14))); - - // recover spi mode - // TODO: get back to this, why writing on `0xf` address? - set_peri_reg_bits( - SPI1_USER_REG, - if !p_rx_data.is_null() { - SPI_FWRITE_DUAL_M - } else { - 0xf - }, - mode_backup, - SPI_FWRITE_DUAL_S, - ); + // Wait for **SPI0** to idle + while SPI0::regs().ext2().read().bits() != 0 {} - spi.ctrl().modify(|_, w| { - w.fread_dio().clear_bit(); - w.fread_dual().clear_bit(); - w.fread_quad().clear_bit(); - w.fread_qio().clear_bit() - }); - spi.ctrl().modify(|r, w| w.bits(r.bits() | rd_mode_backup)); + // DPORT_SET_PERI_REG_MASK(DPORT_HOST_INF_SEL_REG, 1 << 14); + DPORT::regs() + .host_inf_sel() + .modify(|r, w| unsafe { w.bits(r.bits() | (1 << 14)) }); - // return cs to cs0 - spi.pin().modify(|_, w| w.cs1_dis().set_bit()); - spi.pin().modify(|_, w| w.cs0_dis().clear_bit()); + // Start send data + SPI1::regs().cmd().modify(|_, w| w.usr().set_bit()); + while SPI1::regs().cmd().read().usr().bit_is_set() {} - if !p_rx_data.is_null() { - // Read data out - for i in 0..rx_data_len_words { - p_rx_data.add(i).write_volatile(spi.w(i).read().bits()); - } - } + // DPORT_CLEAR_PERI_REG_MASK(DPORT_HOST_INF_SEL_REG, 1 << 14); + DPORT::regs() + .host_inf_sel() + .modify(|r, w| unsafe { w.bits(r.bits() & !(1 << 14)) }); + + // recover spi mode + SPI1::regs().user().modify(|r, w| unsafe { + let bits = r.bits(); + + // TODO: mirrors esp-idf, but looks like a bug + let bit_map = if !rx_data.is_empty() { + SPI_FWRITE_DUAL_M + } else { + 0xf + }; + let shift = SPI_FWRITE_DUAL_S; + + w.bits((bits & (!bit_map << shift)) | (mode_backup & bit_map) << shift) + }); + + SPI1::regs().ctrl().modify(|_, w| { + w.fread_dio().clear_bit(); + w.fread_dual().clear_bit(); + w.fread_quad().clear_bit(); + w.fread_qio().clear_bit() + }); + + SPI1::regs() + .ctrl() + .modify(|r, w| unsafe { w.bits(r.bits() | rd_mode_backup) }); + + // return cs to cs0 + SPI1::regs().pin().modify(|_, w| { + w.cs1_dis().set_bit(); + w.cs0_dis().clear_bit() + }); + + // Read data out + for (i, rx) in rx_data.iter_mut().enumerate() { + *rx = SPI1::regs().w(i).read().bits(); } } @@ -980,8 +914,7 @@ pub(crate) mod utils { // psram gpio init , different working frequency we have different solutions fn psram_gpio_config(psram_io: &PsramIo, mode: PsramCacheSpeed) -> u32 { unsafe { - let spi = SPI0::regs(); - let g_rom_spiflash_dummy_len_plus_ptr = addr_of_mut!(g_rom_spiflash_dummy_len_plus); + let g_rom_spiflash_dummy_len_plus_ptr = &raw mut g_rom_spiflash_dummy_len_plus; #[derive(Debug, Clone, Copy)] enum Field { @@ -1006,17 +939,17 @@ pub(crate) mod utils { } } - let spi_cache_dummy; - let rd_mode_reg = spi.ctrl().read().bits(); - if (rd_mode_reg & SPI_FREAD_QIO_M) != 0 { - spi_cache_dummy = SPI0_R_QIO_DUMMY_CYCLELEN; - } else if (rd_mode_reg & SPI_FREAD_DIO_M) != 0 { - spi_cache_dummy = SPI0_R_DIO_DUMMY_CYCLELEN; - spi.user1() + let rd_mode_reg = SPI0::regs().ctrl().read(); + let spi_cache_dummy = if rd_mode_reg.fread_qio().bit_is_set() { + SPI0_R_QIO_DUMMY_CYCLELEN + } else if rd_mode_reg.fread_dio().bit_is_set() { + SPI0::regs() + .user1() .modify(|_, w| w.usr_addr_bitlen().bits(SPI0_R_DIO_ADDR_BITSLEN as u8)); + SPI0_R_DIO_DUMMY_CYCLELEN } else { - spi_cache_dummy = SPI0_R_FAST_DUMMY_CYCLELEN; - } + SPI0_R_FAST_DUMMY_CYCLELEN + }; let extra_dummy; @@ -1031,7 +964,7 @@ pub(crate) mod utils { .offset(_SPI_FLASH_PORT as isize) .write_volatile(PSRAM_IO_MATRIX_DUMMY_40M); - spi.user1().modify(|_, w| { + SPI0::regs().user1().modify(|_, w| { w.usr_dummy_cyclelen() .bits(spi_cache_dummy as u8 + PSRAM_IO_MATRIX_DUMMY_80M) }); // DUMMY @@ -1053,7 +986,7 @@ pub(crate) mod utils { .offset(_SPI_FLASH_PORT as isize) .write_volatile(PSRAM_IO_MATRIX_DUMMY_80M); - spi.user1().modify(|_, w| { + SPI0::regs().user1().modify(|_, w| { w.usr_dummy_cyclelen() .bits(spi_cache_dummy as u8 + PSRAM_IO_MATRIX_DUMMY_80M) }); // DUMMY @@ -1075,7 +1008,7 @@ pub(crate) mod utils { .offset(_SPI_FLASH_PORT as isize) .write_volatile(PSRAM_IO_MATRIX_DUMMY_40M); - spi.user1().modify(|_, w| { + SPI0::regs().user1().modify(|_, w| { w.usr_dummy_cyclelen() .bits(spi_cache_dummy as u8 + PSRAM_IO_MATRIX_DUMMY_40M) }); // DUMMY @@ -1089,7 +1022,7 @@ pub(crate) mod utils { } } - spi.user().modify(|_, w| w.usr_dummy().set_bit()); // dummy enable + SPI0::regs().user().modify(|_, w| w.usr_dummy().set_bit()); // dummy enable // In bootloader, all the signals are already configured, // We keep the following code in case the bootloader is some older version. @@ -1192,13 +1125,4 @@ pub(crate) mod utils { extra_dummy as u32 } } - - fn set_peri_reg_bits(reg: u32, bitmap: u32, value: u32, shift: u32) { - unsafe { - (reg as *mut u32).write_volatile( - ((reg as *mut u32).read_volatile() & !(bitmap << shift)) - | ((value & bitmap) << shift), - ); - } - } } diff --git a/esp-hal/src/psram/esp32c5_c61.rs b/esp-hal/src/psram/esp32c5_c61.rs index 43adca7e6d1..d8f5a8be251 100644 --- a/esp-hal/src/psram/esp32c5_c61.rs +++ b/esp-hal/src/psram/esp32c5_c61.rs @@ -61,9 +61,9 @@ impl FlashFreq { #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum SpiRamFreq { /// PSRAM frequency 40 MHz - #[default] Freq40m = 40, - /// PSRAM frequency 80 MHz + /// PSRAM frequency 80 MHz. Default. + #[default] Freq80m = 80, } @@ -121,6 +121,7 @@ impl Default for PsramConfig { extra_dummy_len: 2, }, ram_frequency: Default::default(), + // IDF default 80 MHz STR tuning point ram_tuning: MspiTimingTuningParam { spi_din_mode: 3, spi_din_num: 1, @@ -130,7 +131,7 @@ impl Default for PsramConfig { } } -/// Initialize PSRAM to be used for data. +/// Initializes PSRAM to be used for data. #[procmacros::ram] pub(crate) fn init_psram(config: &mut PsramConfig) -> bool { quad::psram_init(config) @@ -238,7 +239,7 @@ mod ctrlr_ll { }); } - /// Set PSRAM write cmd + /// Sets PSRAM write cmd. #[inline(always)] pub(crate) fn psram_ctrlr_ll_set_wr_cmd(_mspi_id: u32, cmd_bitlen: u32, cmd_val: u32) { assert!(cmd_bitlen > 0); @@ -253,7 +254,7 @@ mod ctrlr_ll { }); } - /// Set PSRAM read cmd + /// Sets PSRAM read cmd. #[inline(always)] pub(crate) fn psram_ctrlr_ll_set_rd_cmd(_mspi_id: u32, cmd_bitlen: u32, cmd_val: u32) { assert!(cmd_bitlen > 0); @@ -269,7 +270,7 @@ mod ctrlr_ll { }); } - /// Set PSRAM addr bitlen + /// Sets PSRAM addr bitlen. #[inline(always)] pub(crate) fn psram_ctrlr_ll_set_addr_bitlen(_mspi_id: u32, addr_bitlen: u32) { assert!(addr_bitlen > 0); @@ -279,7 +280,7 @@ mod ctrlr_ll { .modify(|_, w| unsafe { w.sram_addr_bitlen().bits(addr_bitlen as u8 - 1) }); } - /// Set PSRAM read dummy + /// Sets PSRAM read dummy. #[inline(always)] pub(crate) fn psram_ctrlr_ll_set_rd_dummy(_mspi_id: u32, dummy_n: u32) { assert!(dummy_n > 0); @@ -291,7 +292,7 @@ mod ctrlr_ll { }); } - /// Select which pin to use for the psram + /// Selects which pin to use for the psram. #[inline(always)] pub(crate) fn psram_ctrlr_ll_set_cs_pin(_mspi_id: u32, cs_id: PsramLlCsIdT) { SPI1::regs().misc().modify(|_, w| { @@ -316,7 +317,7 @@ fn mspi_timing_config_set_flash_clock(flash_freq_mhz: u32, speed_mode: quad::Msp mspi_timing_ll_set_flash_clock(1, reg_val); } -/// Set MSPI_FAST_CLK's high-speed divider (valid when SOC_ROOT clock source is PLL) +/// Sets MSPI_FAST_CLK's high-speed divider (valid when SOC_ROOT clock source is PLL). #[inline(always)] pub(crate) fn mspi_timing_ll_set_core_clock(core_clk_mhz: u32) { let divider = match core_clk_mhz { @@ -329,7 +330,7 @@ pub(crate) fn mspi_timing_ll_set_core_clock(core_clk_mhz: u32) { .modify(|_, w| unsafe { w.mspi_fast_div_num().bits(divider - 1) }); } -/// Calculate spi_flash clock frequency division parameters for register. +/// Calculates spi_flash clock frequency division parameters for register. #[inline(always)] fn mspi_timing_ll_calculate_clock_reg(clkdiv: u32) -> u32 { if clkdiv == 1 { @@ -339,7 +340,7 @@ fn mspi_timing_ll_calculate_clock_reg(clkdiv: u32) -> u32 { } } -/// Set Flash clock +/// Sets Flash clock. #[inline(always)] fn mspi_timing_ll_set_flash_clock(mspi_id: u32, clock_conf: u32) { if mspi_id == 0 { @@ -368,7 +369,7 @@ fn mspi_timing_config_set_psram_clock(psram_freq_mhz: u32, speed_mode: quad::Msp mspi_timing_ll_set_psram_clock(reg_val); } -/// Set PSRAM clock +/// Sets PSRAM clock. #[inline(always)] fn mspi_timing_ll_set_psram_clock(clock_conf: u32) { SPI0::regs() @@ -376,7 +377,7 @@ fn mspi_timing_ll_set_psram_clock(clock_conf: u32) { .write(|w| unsafe { w.bits(clock_conf) }); } -/// Set MSPI Flash din mode +/// Sets MSPI Flash din mode. #[inline(always)] pub(crate) fn mspi_timing_ll_set_flash_din_mode(mspi_id: u8, din_mode: u8) { assert!(mspi_id == 0); @@ -403,7 +404,7 @@ pub(crate) fn mspi_timing_ll_set_flash_din_mode(mspi_id: u8, din_mode: u8) { .modify(|_, w| w.update().set_bit()); } -/// Set MSPI Flash din num +/// Sets MSPI Flash din num. #[inline(always)] pub(crate) fn mspi_timing_ll_set_flash_din_num(mspi_id: u8, din_num: u8) { assert!(mspi_id == 0); @@ -430,7 +431,7 @@ pub(crate) fn mspi_timing_ll_set_flash_din_num(mspi_id: u8, din_num: u8) { .modify(|_, w| w.update().set_bit()); } -/// Set MSPI Flash extra dummy +/// Sets MSPI Flash extra dummy. #[inline(always)] pub(crate) fn mspi_timing_ll_set_flash_extra_dummy(mspi_id: u8, extra_dummy: u8) { if mspi_id == 0 { @@ -452,7 +453,7 @@ pub(crate) fn mspi_timing_ll_set_flash_extra_dummy(mspi_id: u8, extra_dummy: u8) .modify(|_, w| w.update().set_bit()); } -/// Set MSPI PSRAM din mode +/// Sets MSPI PSRAM din mode. #[inline(always)] pub(crate) fn mspi_timing_ll_set_psram_din_mode(mspi_id: u8, din_mode: u8) { assert!(mspi_id == 0); @@ -479,7 +480,7 @@ pub(crate) fn mspi_timing_ll_set_psram_din_mode(mspi_id: u8, din_mode: u8) { .modify(|_, w| w.update().set_bit()); } -/// Set MSPI PSRAM din num +/// Sets MSPI PSRAM din num. #[inline(always)] pub(crate) fn mspi_timing_ll_set_psram_din_num(mspi_id: u8, din_num: u8) { assert!(mspi_id == 0); @@ -506,7 +507,7 @@ pub(crate) fn mspi_timing_ll_set_psram_din_num(mspi_id: u8, din_num: u8) { .modify(|_, w| w.update().set_bit()); } -/// Set MSPI PSRAM extra dummy +/// Sets MSPI PSRAM extra dummy. #[inline(always)] pub(crate) fn mspi_timing_ll_set_psram_extra_dummy(mspi_id: u8, extra_dummy: u8) { assert!(mspi_id == 0); @@ -522,7 +523,7 @@ pub(crate) fn mspi_timing_ll_set_psram_extra_dummy(mspi_id: u8, extra_dummy: u8) .modify(|_, w| w.update().set_bit()); } -/// Get MSPI flash dummy info +/// Returns the MSPI flash dummy info. #[inline(always)] pub(crate) fn mspi_timing_ll_get_flash_dummy(mspi_id: u8) -> (u8, u8) { assert!(mspi_id <= 1); @@ -546,7 +547,7 @@ pub(crate) fn mspi_timing_ll_get_flash_dummy(mspi_id: u8) -> (u8, u8) { } } -/// Get MSPI PSRAM dummy info +/// Returns the MSPI PSRAM dummy info. #[inline(always)] pub(crate) fn mspi_timing_ll_get_psram_dummy(mspi_id: u8) -> (u8, u8) { assert!(mspi_id == 0); diff --git a/esp-hal/src/psram/esp32p4.rs b/esp-hal/src/psram/esp32p4.rs index d4d5331f10a..f4d08fd6df4 100644 --- a/esp-hal/src/psram/esp32p4.rs +++ b/esp-hal/src/psram/esp32p4.rs @@ -14,14 +14,12 @@ mod oct_hex; #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[instability::unstable] pub enum PsramMode { - /// 16-line DDR, AP HEX PSRAM with MR8.x16 = 1. Default. + /// 16-line DDR. Default. #[default] Hex, - // TODO; selecting `Oct` - // requires the cache-side controller config (`mem_sdin_hex` / - // `mem_sdout_hex` bits) and chip MR8.x16 to flip together. Wire that - // path before exposing. - // Oct, + + /// 8-line DDR. + Oct, } /// PSRAM configuration. @@ -61,12 +59,12 @@ pub struct PsramTimingParams { /// MR4.wr_latency field value. pub mr4_wl: u8, - /// Read dummy length in bits for sync data reads (cache path). + /// Reads dummy length in bits for sync data reads (cache path). /// /// For `N` dummy bits, configure `reg_dummy_bits` to `N - 1`. pub rd_dummy_bits: u8, - /// Write dummy length in bits for sync data writes (cache path). + /// Writes dummy length in bits for sync data writes (cache path). /// /// For `N` dummy bits, configure `reg_dummy_bits` to `N - 1`. pub wr_dummy_bits: u8, @@ -138,7 +136,7 @@ impl PsramTimingParams { }; } -/// Initialize PSRAM. +/// Initializes PSRAM. #[crate::ram] pub(crate) fn init_psram(config: &mut PsramConfig) -> bool { psram_phy_ldo_init(); @@ -189,7 +187,7 @@ pub(crate) fn map_psram(config: PsramConfig) -> core::ops::Range { start..start + config.size.get() } -/// Program the PMU external LDO regulators for the MSPI PHY +/// Programs the PMU external LDO regulators for the MSPI PHY. fn psram_phy_ldo_init() { PMU::regs() .ext_ldo_p0_0p1a() diff --git a/esp-hal/src/psram/esp32s2.rs b/esp-hal/src/psram/esp32s2.rs index 9e8f988b8c4..fb8fdc120ea 100644 --- a/esp-hal/src/psram/esp32s2.rs +++ b/esp-hal/src/psram/esp32s2.rs @@ -1,35 +1,54 @@ use core::ops::Range; use super::{EXTMEM_ORIGIN, PsramSize}; -use crate::peripherals::{EXTMEM, SPI0, SPI1}; +use crate::peripherals::EXTMEM; -// Cache Speed -#[derive(PartialEq, Eq, Debug, Copy, Clone, Default)] +/// Frequency of PSRAM memory +#[derive(Copy, Clone, Debug, Default, PartialEq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] -#[allow(missing_docs)] -pub enum PsramCacheSpeed { - PsramCacheS80m = 1, - PsramCacheS40m, - PsramCacheS26m, - PsramCacheS20m, +pub enum SpiRamFreq { + /// PSRAM frequency 20 MHz + Freq20m = 20, + /// PSRAM frequency 26 MHz + Freq26m = 26, + /// PSRAM frequency 40 MHz + Freq40m = 40, + /// PSRAM frequency 80 MHz. Default for Espressif modules. #[default] - PsramCacheMax, + Freq80m = 80, +} + +impl SpiRamFreq { + fn divider(self) -> u32 { + match self { + Self::Freq80m => 1, + Self::Freq40m => 2, + Self::Freq26m => 3, + Self::Freq20m => 4, + } + } } /// PSRAM configuration -#[derive(Copy, Clone, Debug, Default)] +#[derive(Copy, Clone, Debug, Default, PartialEq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub struct PsramConfig { /// PSRAM size pub size: PsramSize, - /// Cache Speed - pub speed: PsramCacheSpeed, + /// Frequency of PSRAM memory + pub ram_frequency: SpiRamFreq, } -/// Initialize PSRAM to be used for data. +/// Initializes PSRAM to be used for data. #[procmacros::ram] pub(crate) fn init_psram(config: &mut PsramConfig) -> bool { - utils::psram_init(config) + let success = quad_spi_impl::psram_init(config); + if !success { + warn!( + "Failed to configure PSRAM. This may indicate a missing/inoperable PSRAM chip, or an incorrect PSRAM configuration. Check if the PSRAM chip is present and the configuration is correct." + ); + } + success } #[procmacros::ram] @@ -37,7 +56,7 @@ pub(crate) fn map_psram(config: PsramConfig) -> Range { const MMU_ACCESS_SPIRAM: u32 = 1 << 16; unsafe extern "C" { - /// Set DCache mmu mapping. + /// Sets DCache mmu mapping. /// /// [`ext_ram`]: u32 DPORT_MMU_ACCESS_FLASH for flash, DPORT_MMU_ACCESS_SPIRAM for spiram, DPORT_MMU_INVALID for invalid. /// [`vaddr`]: u32 Virtual address in CPU address space. @@ -63,7 +82,7 @@ pub(crate) fn map_psram(config: PsramConfig) -> Range { EXTMEM_ORIGIN as u32, START_PAGE << 16, 64, - config.size.get() as u32 / 1024 / 64, // number of pages to map + config.size.get() as u32 / 1024 / 64, 0, ) }; @@ -81,314 +100,40 @@ pub(crate) fn map_psram(config: PsramConfig) -> Range { EXTMEM_ORIGIN..EXTMEM_ORIGIN + config.size.get() } -pub(crate) mod utils { - use super::*; - - const PSRAM_RESET_EN: u16 = 0x66; - const PSRAM_RESET: u16 = 0x99; - const PSRAM_DEVICE_ID: u16 = 0x9F; - const CS_PSRAM_SEL: u8 = 1 << 1; +pub(crate) mod quad_spi_impl { + use procmacros::ram; - /// PS-RAM addressing mode - #[derive(PartialEq, Eq, Debug, Copy, Clone, Default)] - #[cfg_attr(feature = "defmt", derive(defmt::Format))] - #[allow(unused)] - pub enum PsramVaddrMode { - /// App and pro CPU use their own flash cache for external RAM access - #[default] - Normal = 0, - /// App and pro CPU share external RAM caches: pro CPU has low2M, app - /// CPU has high 2M - Lowhigh, - /// App and pro CPU share external RAM caches: pro CPU does even 32yte - /// ranges, app does odd ones. - Evenodd, - } + use super::*; + use crate::psram::quad_xtensa; - // Function initializes the PSRAM by configuring GPIO pins, resetting the PSRAM, - // and enabling Quad I/O (QIO) mode. It also calls the psram_cache_init - // function to configure cache parameters and read/write commands. + #[ram] pub(crate) fn psram_init(config: &mut PsramConfig) -> bool { psram_gpio_config(); if config.size.is_auto() { - psram_disable_qio_mode(); - - // read chip id - let mut dev_id = 0u32; - psram_exec_cmd( - CommandMode::PsramCmdSpi, - PSRAM_DEVICE_ID, - 8, // command and command bit len - 0, - 24, // address and address bit len - 0, // dummy bit len - core::ptr::null(), - 0, // tx data and tx bit len - &mut dev_id as *mut _ as *mut u8, - 24, // rx data and rx bit len - CS_PSRAM_SEL, // cs bit mask - false, - ); - - if dev_id == 0xffffff { - debug!( - "Unknown PSRAM chip ID: {:x}. PSRAM chip not found or not supported.", - dev_id - ); + let Some(size) = quad_xtensa::detect_quad_size() else { return false; - } - - info!("chip id = {:x}", dev_id); - - const PSRAM_ID_EID_S: u32 = 16; - const PSRAM_ID_EID_M: u32 = 0xff; - const PSRAM_EID_SIZE_M: u32 = 0x07; - const PSRAM_EID_SIZE_S: u32 = 5; - - let size_id = (((dev_id >> PSRAM_ID_EID_S) & PSRAM_ID_EID_M) >> PSRAM_EID_SIZE_S) - & PSRAM_EID_SIZE_M; - - const PSRAM_EID_SIZE_32MBITS: u32 = 1; - const PSRAM_EID_SIZE_64MBITS: u32 = 2; - - let size = match size_id { - PSRAM_EID_SIZE_64MBITS => 8 * 1024 * 1024, - PSRAM_EID_SIZE_32MBITS => 4 * 1024 * 1024, - _ => 2 * 1024 * 1024, }; - - info!("size is {}", size); - config.size = PsramSize::Size(size); } - psram_reset_mode(); - psram_enable_qio_mode(); - - psram_cache_init(config.speed, PsramVaddrMode::Normal); + quad_xtensa::psram_reset_mode_spi1(); + quad_xtensa::psram_enable_qio_mode_spi1(); + quad_xtensa::config_psram_spi_phases(); + mspi_timing_enter_high_speed_mode(config); + info!("PSRAM initialized successfully in Quad SPI mode"); true } - // send reset command to psram, in spi mode - fn psram_reset_mode() { - psram_exec_cmd( - CommandMode::PsramCmdSpi, - PSRAM_RESET_EN, - 8, // command and command bit len - 0, - 0, // address and address bit len - 0, // dummy bit len - core::ptr::null(), - 0, // tx data and tx bit len - core::ptr::null_mut(), - 0, // rx data and rx bit len - CS_PSRAM_SEL, // cs bit mask - false, - ); // whether is program/erase operation - - psram_exec_cmd( - CommandMode::PsramCmdSpi, - PSRAM_RESET, - 8, // command and command bit len - 0, - 0, // address and address bit len - 0, // dummy bit len - core::ptr::null(), - 0, // tx data and tx bit len - core::ptr::null_mut(), - 0, // rx data and rx bit len - CS_PSRAM_SEL, // cs bit mask - false, - ); // whether is program/erase operation - } - - /// Enter QPI mode - fn psram_enable_qio_mode() { - const PSRAM_ENTER_QMODE: u16 = 0x35; - const CS_PSRAM_SEL: u8 = 1 << 1; - - psram_exec_cmd( - CommandMode::PsramCmdSpi, - PSRAM_ENTER_QMODE, - 8, // command and command bit len - 0, - 0, // address and address bit len - 0, // dummy bit len - core::ptr::null(), - 0, // tx data and tx bit len - core::ptr::null_mut(), - 0, // rx data and rx bit len - CS_PSRAM_SEL, // cs bit mask - false, // whether is program/erase operation - ); - } - - /// Exit QPI mode - fn psram_disable_qio_mode() { - const PSRAM_EXIT_QMODE: u16 = 0xF5; - const CS_PSRAM_SEL: u8 = 1 << 1; - - psram_exec_cmd( - CommandMode::PsramCmdQpi, - PSRAM_EXIT_QMODE, - 8, // command and command bit len - 0, - 0, // address and address bit len - 0, // dummy bit len - core::ptr::null(), - 0, // tx data and tx bit len - core::ptr::null_mut(), - 0, // rx data and rx bit len - CS_PSRAM_SEL, // cs bit mask - false, // whether is program/erase operation + #[ram] + fn mspi_timing_enter_high_speed_mode(config: &PsramConfig) { + let psram_div = config.ram_frequency.divider(); + info!( + "PSRAM {} MHz, psram_div = {}", + config.ram_frequency as u32, psram_div ); - } - - #[derive(PartialEq)] - #[allow(unused)] - enum CommandMode { - PsramCmdQpi = 0, - PsramCmdSpi = 1, - } - - #[expect(clippy::too_many_arguments)] - #[inline(always)] - fn psram_exec_cmd( - mode: CommandMode, - cmd: u16, - cmd_bit_len: u16, - addr: u32, - addr_bit_len: u32, - dummy_bits: u32, - mosi_data: *const u8, - mosi_bit_len: u32, - miso_data: *mut u8, - miso_bit_len: u32, - cs_mask: u8, - is_write_erase_operation: bool, - ) { - unsafe extern "C" { - /// Start a spi user command sequence - /// [`spi_num`] spi port - /// [`rx_buf`] buffer pointer to receive data - /// [`rx_len`] receive data length in byte - /// [`cs_en_mask`] decide which cs to use, 0 for cs0, 1 for cs1 - /// [`is_write_erase`] to indicate whether this is a write or erase - /// operation, since the CPU would check permission - fn esp_rom_spi_cmd_start( - spi_num: u32, - rx_buf: *const u8, - rx_len: u16, - cs_en_mask: u8, - is_write_erase: bool, - ); - } - - unsafe { - let spi1 = SPI1::regs(); - let backup_usr = spi1.user().read().bits(); - let backup_usr1 = spi1.user1().read().bits(); - let backup_usr2 = spi1.user2().read().bits(); - let backup_ctrl = spi1.ctrl().read().bits(); - psram_set_op_mode(mode); - _psram_exec_cmd( - cmd, - cmd_bit_len, - &addr, - addr_bit_len, - dummy_bits, - mosi_data, - mosi_bit_len, - miso_data, - miso_bit_len, - ); - esp_rom_spi_cmd_start( - 1, - miso_data, - (miso_bit_len / 8) as u16, - cs_mask, - is_write_erase_operation, - ); - - spi1.user().write(|w| w.bits(backup_usr)); - spi1.user1().write(|w| w.bits(backup_usr1)); - spi1.user2().write(|w| w.bits(backup_usr2)); - spi1.ctrl().write(|w| w.bits(backup_ctrl)); - } - } - - #[expect(clippy::too_many_arguments)] - #[inline(always)] - fn _psram_exec_cmd( - cmd: u16, - cmd_bit_len: u16, - addr: *const u32, - addr_bit_len: u32, - dummy_bits: u32, - mosi_data: *const u8, - mosi_bit_len: u32, - miso_data: *mut u8, - miso_bit_len: u32, - ) { - #[repr(C)] - #[allow(non_camel_case_types)] - struct esp_rom_spi_cmd_t { - cmd: u16, // Command value - cmd_bit_len: u16, // Command byte length - addr: *const u32, // Point to address value - addr_bit_len: u32, // Address byte length - tx_data: *const u32, // Point to send data buffer - tx_data_bit_len: u32, // Send data byte length. - rx_data: *mut u32, // Point to recevie data buffer - rx_data_bit_len: u32, // Recevie Data byte length. - dummy_bit_len: u32, - } - - unsafe extern "C" { - /// Config the spi user command - /// [`spi_num`] spi port - /// [`pcmd`] pointer to accept the spi command struct - fn esp_rom_spi_cmd_config(spi_num: u32, pcmd: *const esp_rom_spi_cmd_t); - } - - let conf = esp_rom_spi_cmd_t { - cmd, - cmd_bit_len, - addr, - addr_bit_len, - tx_data: mosi_data as *const u32, - tx_data_bit_len: mosi_bit_len, - rx_data: miso_data as *mut u32, - rx_data_bit_len: miso_bit_len, - dummy_bit_len: dummy_bits, - }; - - unsafe { - esp_rom_spi_cmd_config(1, &conf); - } - } - - fn psram_set_op_mode(mode: CommandMode) { - unsafe extern "C" { - fn esp_rom_spi_set_op_mode(spi: u32, mode: u32); - } - - const ESP_ROM_SPIFLASH_QIO_MODE: u32 = 0; - const ESP_ROM_SPIFLASH_SLOWRD_MODE: u32 = 5; - - unsafe { - match mode { - CommandMode::PsramCmdQpi => { - esp_rom_spi_set_op_mode(1, ESP_ROM_SPIFLASH_QIO_MODE); - SPI1::regs().ctrl().modify(|_, w| w.fcmd_quad().set_bit()); - } - CommandMode::PsramCmdSpi => { - esp_rom_spi_set_op_mode(1, ESP_ROM_SPIFLASH_SLOWRD_MODE); - } - } - } + quad_xtensa::spi0_timing_config_set_psram_clock(psram_div); } #[repr(C)] @@ -403,11 +148,12 @@ pub(crate) mod utils { psram_spihd_sd2_io: u8, } + #[ram] fn psram_gpio_config() { unsafe extern "C" { fn esp_rom_efuse_get_flash_gpio_info() -> u32; - /// Enable Quad I/O pin functions + /// Enables Quad I/O pin functions. /// /// Sets the HD & WP pin functions for Quad I/O modes, based on the /// efuse SPI pin configuration. @@ -420,8 +166,8 @@ pub(crate) mod utils { /// ignored. /// - For other values, this parameter encodes the HD pin number and also the CLK pin /// number. CLK pin selection is used to determine if HSPI or SPI peripheral will be - /// used (use HSPI if CLK pin is the HSPI clock pin, otherwise use SPI). - // Both HD & WP pins are configured via GPIO matrix to map to the selected peripheral. + /// used (use HSPI if CLK pin is the HSPI clock pin, otherwise use SPI). Both HD & WP + /// pins are configured via GPIO matrix to map to the selected peripheral. fn esp_rom_spiflash_select_qio_pins(wp_gpio_num: u8, spiconfig: u32); } @@ -444,130 +190,11 @@ pub(crate) mod utils { // FLASH pins(except wp / hd) are all configured via IO_MUX in // rom. } else { - // this case is currently not yet supported panic!( "Unsupported for now! The case 'FLASH pins are all configured via GPIO matrix in ROM.' is not yet supported." ); - - // FLASH pins are all configured via GPIO matrix in ROM. - // psram_io.flash_clk_io = - // EFUSE_SPICONFIG_RET_SPICLK(spiconfig); - // psram_io.flash_cs_io = EFUSE_SPICONFIG_RET_SPICS0(spiconfig); - // psram_io.psram_spiq_sd0_io = - // EFUSE_SPICONFIG_RET_SPIQ(spiconfig); - // psram_io.psram_spid_sd1_io = - // EFUSE_SPICONFIG_RET_SPID(spiconfig); - // psram_io.psram_spihd_sd2_io = - // EFUSE_SPICONFIG_RET_SPIHD(spiconfig); - // psram_io.psram_spiwp_sd3_io = - // esp_rom_efuse_get_flash_wp_gpio(); } esp_rom_spiflash_select_qio_pins(psram_io.psram_spiwp_sd3_io, spiconfig); - // s_psram_cs_io = psram_io.psram_cs_io; - } - } - - const PSRAM_IO_MATRIX_DUMMY_20M: u32 = 0; - const PSRAM_IO_MATRIX_DUMMY_40M: u32 = 0; - const PSRAM_IO_MATRIX_DUMMY_80M: u32 = 0; - - /// Register initialization for sram cache params and r/w commands - fn psram_cache_init(psram_cache_mode: PsramCacheSpeed, _vaddrmode: PsramVaddrMode) { - let mut extra_dummy = 0; - match psram_cache_mode { - PsramCacheSpeed::PsramCacheS80m => { - psram_clock_set(1); - extra_dummy = PSRAM_IO_MATRIX_DUMMY_80M; - } - PsramCacheSpeed::PsramCacheS40m => { - psram_clock_set(2); - extra_dummy = PSRAM_IO_MATRIX_DUMMY_40M; - } - PsramCacheSpeed::PsramCacheS26m => { - psram_clock_set(3); - extra_dummy = PSRAM_IO_MATRIX_DUMMY_20M; - } - PsramCacheSpeed::PsramCacheS20m => { - psram_clock_set(4); - extra_dummy = PSRAM_IO_MATRIX_DUMMY_20M; - } - _ => { - psram_clock_set(2); - } - } - - const PSRAM_QUAD_WRITE: u32 = 0x38; - const PSRAM_FAST_READ_QUAD: u32 = 0xEB; - const PSRAM_FAST_READ_QUAD_DUMMY: u32 = 0x5; - - unsafe { - let spi = SPI0::regs(); - - spi.cache_sctrl() - .modify(|_, w| w.usr_sram_dio().clear_bit()); // disable dio mode for cache command - - spi.cache_sctrl().modify(|_, w| w.usr_sram_qio().set_bit()); // enable qio mode for cache command - - spi.cache_sctrl() - .modify(|_, w| w.cache_sram_usr_rcmd().set_bit()); // enable cache read command - - spi.cache_sctrl() - .modify(|_, w| w.cache_sram_usr_wcmd().set_bit()); // enable cache write command - - // write address for cache command. - spi.cache_sctrl() - .modify(|_, w| w.sram_addr_bitlen().bits(23)); - - spi.cache_sctrl() - .modify(|_, w| w.usr_rd_sram_dummy().set_bit()); // enable cache read dummy - - // config sram cache r/w command - spi.sram_dwr_cmd() - .modify(|_, w| w.cache_sram_usr_wr_cmd_bitlen().bits(7)); - - spi.sram_dwr_cmd().modify(|_, w| { - w.cache_sram_usr_wr_cmd_value() - .bits(PSRAM_QUAD_WRITE as u16) - }); - - spi.sram_drd_cmd() - .modify(|_, w| w.cache_sram_usr_rd_cmd_bitlen().bits(7)); - - spi.sram_drd_cmd().modify(|_, w| { - w.cache_sram_usr_rd_cmd_value() - .bits(PSRAM_FAST_READ_QUAD as u16) - }); - - // dummy, psram cache : 40m--+1dummy,80m--+2dummy - spi.cache_sctrl().modify(|_, w| { - w.sram_rdummy_cyclelen() - .bits((PSRAM_FAST_READ_QUAD_DUMMY + extra_dummy) as u8) - }); - - // ESP-IDF has some code here to deal with `!CONFIG_FREERTOS_UNICORE` - not - // needed for ESP32-S2 - - // ENABLE SPI0 CS1 TO PSRAM(CS0--FLASH; CS1--SRAM) - spi.misc().modify(|_, w| w.cs1_dis().clear_bit()); - } - } - - fn psram_clock_set(freqdiv: i8) { - const SPI_MEM_SCLKCNT_N_S: u32 = 16; - const SPI_MEM_SCLKCNT_H_S: u32 = 8; - const SPI_MEM_SCLKCNT_L_S: u32 = 0; - - if 1 >= freqdiv { - SPI0::regs() - .sram_clk() - .modify(|_, w| w.sclk_equ_sysclk().set_bit()); - } else { - let freqbits: u32 = (((freqdiv - 1) as u32) << SPI_MEM_SCLKCNT_N_S) - | (((freqdiv / 2 - 1) as u32) << SPI_MEM_SCLKCNT_H_S) - | (((freqdiv - 1) as u32) << SPI_MEM_SCLKCNT_L_S); - unsafe { - SPI0::regs().sram_clk().modify(|_, w| w.bits(freqbits)); - } } } } diff --git a/esp-hal/src/psram/esp32s3.rs b/esp-hal/src/psram/esp32s3.rs index 2145fb9e4cb..47a6fbfec4b 100644 --- a/esp-hal/src/psram/esp32s3.rs +++ b/esp-hal/src/psram/esp32s3.rs @@ -1,5 +1,7 @@ use core::ops::Range; +use procmacros::ram; + use super::{EXTMEM_ORIGIN, PsramSize}; use crate::peripherals::{EXTMEM, IO_MUX, MMU_TABLE, SPI0, SPI1}; @@ -7,7 +9,7 @@ use crate::peripherals::{EXTMEM, IO_MUX, MMU_TABLE, SPI0, SPI1}; #[derive(Copy, Clone, Debug, Default, PartialEq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum PsramMode { - /// Try to detect the PSRAM mode. While convenient, not entirely reliable. + /// Tries to detect the PSRAM mode. While convenient, not entirely reliable. #[default] Auto, @@ -39,9 +41,9 @@ pub enum FlashFreq { #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum SpiRamFreq { /// PSRAM frequency 40 MHz - #[default] Freq40m = 40, - /// PSRAM frequency 80 MHz + /// PSRAM frequency 80 MHz. Default. + #[default] Freq80m = 80, /// PSRAM frequency 120 MHz /// This is not recommended, see @@ -79,7 +81,7 @@ pub struct PsramConfig { pub ram_frequency: SpiRamFreq, } -/// Initialize PSRAM to be used for data. +/// Initializes PSRAM to be used for data. #[procmacros::ram] pub(crate) fn init_psram(config: &mut PsramConfig) -> bool { let success = match config.mode { @@ -111,11 +113,11 @@ pub(crate) fn map_psram(config: PsramConfig) -> Range { const START_PAGE: u32 = 0; unsafe extern "C" { - fn Cache_Suspend_DCache(); + fn Cache_Suspend_DCache() -> u32; fn Cache_Resume_DCache(param: u32); - /// Set DCache mmu mapping. + /// Sets DCache mmu mapping. /// /// [`ext_ram`]: u32 DPORT_MMU_ACCESS_FLASH for flash, DPORT_MMU_ACCESS_SPIRAM for spiram, DPORT_MMU_INVALID for invalid. /// [`vaddr`]: u32 Virtual address in CPU address space. @@ -190,14 +192,16 @@ pub(crate) fn map_psram(config: PsramConfig) -> Range { } pub(crate) mod quad_spi_impl { - use procmacros::ram; - use super::*; + use crate::psram::quad_xtensa; - const PSRAM_RESET_EN: u16 = 0x66; - const PSRAM_RESET: u16 = 0x99; - const PSRAM_DEVICE_ID: u16 = 0x9F; - const CS_PSRAM_SEL: u8 = 1 << 1; + const PSRAM_CS_IO: u8 = 26; + const SPI_CS1_GPIO_NUM: u8 = 26; + const FUNC_SPICS1_SPICS1: u8 = 0; + const PIN_FUNC_GPIO: u8 = 2; + const PSRAM_SPIWP_SD3_IO: u8 = 10; + const ESP_ROM_EFUSE_FLASH_DEFAULT_SPI: u32 = 0; + const SPICS1_OUT_IDX: u8 = 6; #[ram] pub(crate) fn psram_init(config: &mut PsramConfig) -> bool { @@ -205,53 +209,9 @@ pub(crate) mod quad_spi_impl { psram_set_cs_timing(); if config.size.is_auto() { - psram_disable_qio_mode_spi1(); - - // read chip id - let mut dev_id = 0u32; - psram_exec_cmd( - CommandMode::PsramCmdSpi, - PSRAM_DEVICE_ID, - 8, // command and command bit len - 0, - 24, // address and address bit len - 0, // dummy bit len - core::ptr::null(), - 0, // tx data and tx bit len - &mut dev_id as *mut _ as *mut u8, - 24, // rx data and rx bit len - CS_PSRAM_SEL, // cs bit mask - false, - ); - if dev_id == 0xffffff { - debug!( - "Unknown PSRAM chip ID: {:x}. PSRAM chip not found or not supported. Check if the interface mode is configured correctly.", - dev_id - ); + let Some(size) = quad_xtensa::detect_quad_size() else { return false; - } - - info!("chip id = {:x}", dev_id); - - const PSRAM_ID_EID_S: u32 = 16; - const PSRAM_ID_EID_M: u32 = 0xff; - const PSRAM_EID_SIZE_M: u32 = 0x07; - const PSRAM_EID_SIZE_S: u32 = 5; - - let size_id = ((((dev_id) >> PSRAM_ID_EID_S) & PSRAM_ID_EID_M) >> PSRAM_EID_SIZE_S) - & PSRAM_EID_SIZE_M; - - const PSRAM_EID_SIZE_32MBITS: u32 = 1; - const PSRAM_EID_SIZE_64MBITS: u32 = 2; - - let size = match size_id { - PSRAM_EID_SIZE_64MBITS => 64 / 8 * 1024 * 1024, - PSRAM_EID_SIZE_32MBITS => 32 / 8 * 1024 * 1024, - _ => 16 / 8 * 1024 * 1024, }; - - info!("size is {}", size); - config.size = PsramSize::Size(size); } @@ -263,43 +223,20 @@ pub(crate) mod quad_spi_impl { }); } - // SPI1: send psram reset command - psram_reset_mode_spi1(); - // SPI1: send QPI enable command - psram_enable_qio_mode_spi1(); + quad_xtensa::psram_reset_mode_spi1(); + quad_xtensa::psram_enable_qio_mode_spi1(); - // Do PSRAM timing tuning, we use SPI1 to do the tuning, and set the SPI0 PSRAM - // timing related registers accordingly + // Timing tuning is not implemented. Quad 80 MHz does not require it. + // See IDF `mspi_timing_psram_tuning`. mspi_timing_psram_tuning(); - // Configure SPI0 PSRAM related SPI Phases - config_psram_spi_phases(); - // Back to the high speed mode. Flash/PSRAM clocks are set to the clock that - // user selected. SPI0/1 registers are all set correctly + quad_xtensa::config_psram_spi_phases(); mspi_timing_enter_high_speed_mode(true, config); info!("PSRAM initialized successfully in Quad SPI mode"); true } - const PSRAM_CS_IO: u8 = 26; - const SPI_CS1_GPIO_NUM: u8 = 26; - const FUNC_SPICS1_SPICS1: u8 = 0; - const PIN_FUNC_GPIO: u8 = 2; - const PSRAM_SPIWP_SD3_IO: u8 = 10; - const ESP_ROM_EFUSE_FLASH_DEFAULT_SPI: u32 = 0; - const SPICS1_OUT_IDX: u8 = 6; - - const PSRAM_QUAD_WRITE: u32 = 0x38; - const PSRAM_FAST_READ_QUAD: u32 = 0xEB; - const PSRAM_FAST_READ_QUAD_DUMMY: u32 = 6; - const SPI_MEM_CLKCNT_N_S: u32 = 16; - const SPI_MEM_SCLKCNT_N_S: u32 = 16; - const SPI_MEM_CLKCNT_H_S: u32 = 8; - const SPI_MEM_SCLKCNT_H_S: u32 = 8; - const SPI_MEM_CLKCNT_L_S: u32 = 0; - const SPI_MEM_SCLKCNT_L_S: u32 = 0; - unsafe extern "C" { fn esp_rom_efuse_get_flash_gpio_info() -> u32; @@ -312,7 +249,7 @@ pub(crate) mod quad_spi_impl { oen_inv: bool, ); - /// Enable Quad I/O pin functions + /// Enables Quad I/O pin functions. /// /// Sets the HD & WP pin functions for Quad I/O modes, based on the /// efuse SPI pin configuration. @@ -330,75 +267,20 @@ pub(crate) mod quad_spi_impl { fn esp_rom_spiflash_select_qio_pins(wp_gpio_num: u8, spiconfig: u32); } - // Configure PSRAM SPI0 phase related registers here according to the PSRAM chip - // requirement - #[ram] - fn config_psram_spi_phases() { - unsafe { - let spi = SPI0::regs(); - // Config CMD phase - spi.cache_sctrl() - .modify(|_, w| w.usr_sram_dio().clear_bit()); // disable dio mode for cache command - - spi.cache_sctrl().modify(|_, w| w.usr_sram_qio().set_bit()); // enable qio mode for cache command - - spi.cache_sctrl() - .modify(|_, w| w.cache_sram_usr_rcmd().set_bit()); // enable cache read command - - spi.cache_sctrl() - .modify(|_, w| w.cache_sram_usr_wcmd().set_bit()); // enable cache write command - - spi.sram_dwr_cmd() - .modify(|_, w| w.cache_sram_usr_wr_cmd_bitlen().bits(7)); - - spi.sram_dwr_cmd().modify(|_, w| { - w.cache_sram_usr_wr_cmd_value() - .bits(PSRAM_QUAD_WRITE as u16) - }); - - spi.sram_drd_cmd() - .modify(|_, w| w.cache_sram_usr_rd_cmd_bitlen().bits(7)); - - spi.sram_drd_cmd().modify(|_, w| { - w.cache_sram_usr_rd_cmd_value() - .bits(PSRAM_FAST_READ_QUAD as u16) - }); - - // Config ADDR phase - spi.cache_sctrl() - .modify(|_, w| w.sram_addr_bitlen().bits(23)); - - // Dummy - // We set the PSRAM chip required dummy here. If timing tuning is - // needed, the dummy length will be updated in - // `mspi_timing_enter_high_speed_mode()` - spi.cache_sctrl() - .modify(|_, w| w.usr_rd_sram_dummy().set_bit()); // enable cache read dummy - - spi.cache_sctrl().modify(|_, w| { - w.sram_rdummy_cyclelen() - .bits((PSRAM_FAST_READ_QUAD_DUMMY - 1) as u8) - }); - - // ENABLE SPI0 CS1 TO PSRAM(CS0--FLASH; CS1--SRAM) - spi.misc().modify(|_, w| w.cs1_dis().clear_bit()); - } - } - #[ram] fn mspi_timing_psram_tuning() { // currently we only support !SPI_TIMING_PSRAM_NEEDS_TUNING // see https://github.com/espressif/esp-idf/blob/4e24516ee2731eb55687182d4e061b5b93a9e33f/components/esp_hw_support/mspi_timing_tuning.c#L391-L415 } - /// Set SPI0 FLASH and PSRAM module clock, din_num, din_mode and extra + /// Sets SPI0 FLASH and PSRAM module clock, din_num, din_mode and extra /// dummy, according to the configuration got from timing tuning /// function (`calculate_best_flash_tuning_config`). iF control_spi1 == /// 1, will also update SPI1 timing registers. Should only be set to 1 when /// do tuning. /// - /// This function should always be called after `mspi_timing_flash_tuning` - /// or `calculate_best_flash_tuning_config` + /// Must always be called after `mspi_timing_flash_tuning` or + /// `calculate_best_flash_tuning_config` #[ram] fn mspi_timing_enter_high_speed_mode(control_spi1: bool, config: &PsramConfig) { let core_clock: SpiTimingConfigCoreClock = mspi_core_clock(config); @@ -406,8 +288,12 @@ pub(crate) mod quad_spi_impl { let psram_div: u32 = psram_clock_divider(config); info!( - "PSRAM core_clock {:?}, flash_div = {}, psram_div = {}", - core_clock, flash_div, psram_div + "PSRAM {} MHz, flash {} MHz, core_clock {:?}, flash_div = {}, psram_div = {}", + config.ram_frequency as u32, + config.flash_frequency as u32, + core_clock, + flash_div, + psram_div ); // Set SPI01 core clock @@ -419,12 +305,7 @@ pub(crate) mod quad_spi_impl { if control_spi1 { spi1_timing_config_set_flash_clock(flash_div); } - // Set PSRAM module clock - spi0_timing_config_set_psram_clock(psram_div); - - // #if SPI_TIMING_FLASH_NEEDS_TUNING || SPI_TIMING_PSRAM_NEEDS_TUNING - // set_timing_tuning_regs_as_required(true); - // #endif + quad_xtensa::spi0_timing_config_set_psram_clock(psram_div); } #[ram] @@ -441,54 +322,6 @@ pub(crate) mod quad_spi_impl { } } - #[ram] - fn spi0_timing_config_set_flash_clock(freqdiv: u32) { - if freqdiv == 1 { - SPI0::regs() - .clock() - .modify(|_, w| w.clk_equ_sysclk().set_bit()); - } else { - let freqbits: u32 = ((freqdiv - 1) << SPI_MEM_CLKCNT_N_S) - | ((freqdiv / 2 - 1) << SPI_MEM_CLKCNT_H_S) - | ((freqdiv - 1) << SPI_MEM_CLKCNT_L_S); - unsafe { - SPI0::regs().clock().modify(|_, w| w.bits(freqbits)); - } - } - } - - #[ram] - fn spi1_timing_config_set_flash_clock(freqdiv: u32) { - if freqdiv == 1 { - SPI1::regs() - .clock() - .modify(|_, w| w.clk_equ_sysclk().set_bit()); - } else { - let freqbits: u32 = ((freqdiv - 1) << SPI_MEM_CLKCNT_N_S) - | ((freqdiv / 2 - 1) << SPI_MEM_CLKCNT_H_S) - | ((freqdiv - 1) << SPI_MEM_CLKCNT_L_S); - unsafe { - SPI1::regs().clock().modify(|_, w| w.bits(freqbits)); - } - } - } - - #[ram] - fn spi0_timing_config_set_psram_clock(freqdiv: u32) { - if freqdiv == 1 { - SPI0::regs() - .sram_clk() - .modify(|_, w| w.sclk_equ_sysclk().set_bit()); - } else { - let freqbits: u32 = ((freqdiv - 1) << SPI_MEM_SCLKCNT_N_S) - | ((freqdiv / 2 - 1) << SPI_MEM_SCLKCNT_H_S) - | ((freqdiv - 1) << SPI_MEM_SCLKCNT_L_S); - unsafe { - SPI0::regs().sram_clk().modify(|_, w| w.bits(freqbits)); - } - } - } - #[ram] fn mspi_core_clock(config: &PsramConfig) -> SpiTimingConfigCoreClock { config.core_clock.unwrap_or_default() @@ -504,268 +337,34 @@ pub(crate) mod quad_spi_impl { config.core_clock.unwrap_or_default() as u32 / config.ram_frequency as u32 } - // send reset command to psram, in spi mode - #[ram] - fn psram_reset_mode_spi1() { - psram_exec_cmd( - CommandMode::PsramCmdSpi, - PSRAM_RESET_EN, - 8, // command and command bit len - 0, - 0, // address and address bit len - 0, // dummy bit len - core::ptr::null(), - 0, // tx data and tx bit len - core::ptr::null_mut(), - 0, // rx data and rx bit len - CS_PSRAM_SEL, // cs bit mask - false, - ); // whether is program/erase operation - - psram_exec_cmd( - CommandMode::PsramCmdSpi, - PSRAM_RESET, - 8, // command and command bit len - 0, - 0, // address and address bit len - 0, // dummy bit len - core::ptr::null(), - 0, // tx data and tx bit len - core::ptr::null_mut(), - 0, // rx data and rx bit len - CS_PSRAM_SEL, // cs bit mask - false, - ); // whether is program/erase operation - } - - #[derive(PartialEq)] - #[allow(unused)] - enum CommandMode { - PsramCmdQpi = 0, - PsramCmdSpi = 1, - } - - #[expect(clippy::too_many_arguments)] - #[ram] - fn psram_exec_cmd( - mode: CommandMode, - cmd: u16, - cmd_bit_len: u16, - addr: u32, - addr_bit_len: u32, - dummy_bits: u32, - mosi_data: *const u8, - mosi_bit_len: u32, - miso_data: *mut u8, - miso_bit_len: u32, - cs_mask: u8, - is_write_erase_operation: bool, - ) { - unsafe extern "C" { - /// Start a spi user command sequence - /// [`spi_num`] spi port - /// [`rx_buf`] buffer pointer to receive data - /// [`rx_len`] receive data length in byte - /// [`cs_en_mask`] decide which cs to use, 0 for cs0, 1 for cs1 - /// [`is_write_erase`] to indicate whether this is a write or erase - /// operation, since the CPU would check permission - fn esp_rom_spi_cmd_start( - spi_num: u32, - rx_buf: *const u8, - rx_len: u16, - cs_en_mask: u8, - is_write_erase: bool, - ); - } - - unsafe { - let spi1 = SPI1::regs(); - let backup_usr = spi1.user().read().bits(); - let backup_usr1 = spi1.user1().read().bits(); - let backup_usr2 = spi1.user2().read().bits(); - let backup_ctrl = spi1.ctrl().read().bits(); - psram_set_op_mode(mode); - _psram_exec_cmd( - cmd, - cmd_bit_len, - addr, - addr_bit_len, - dummy_bits, - mosi_data, - mosi_bit_len, - miso_data, - miso_bit_len, - ); - esp_rom_spi_cmd_start( - 1, - miso_data, - (miso_bit_len / 8) as u16, - cs_mask, - is_write_erase_operation, - ); - - spi1.user().write(|w| w.bits(backup_usr)); - spi1.user1().write(|w| w.bits(backup_usr1)); - spi1.user2().write(|w| w.bits(backup_usr2)); - spi1.ctrl().write(|w| w.bits(backup_ctrl)); - } - } - - #[expect(clippy::too_many_arguments)] - #[ram] - fn _psram_exec_cmd( - cmd: u16, - cmd_bit_len: u16, - addr: u32, - addr_bit_len: u32, - dummy_bits: u32, - mosi_data: *const u8, - mosi_bit_len: u32, - miso_data: *mut u8, - miso_bit_len: u32, - ) { - #[repr(C)] - struct esp_rom_spi_cmd_t { - cmd: u16, // Command value - cmd_bit_len: u16, // Command byte length - addr: *const u32, // Point to address value - addr_bit_len: u32, // Address byte length - tx_data: *const u32, // Point to send data buffer - tx_data_bit_len: u32, // Send data byte length. - rx_data: *mut u32, // Point to recevie data buffer - rx_data_bit_len: u32, // Recevie Data byte length. - dummy_bit_len: u32, - } - - unsafe extern "C" { - /// Config the spi user command - /// [`spi_num`] spi port - /// [`pcmd`] pointer to accept the spi command struct - fn esp_rom_spi_cmd_config(spi_num: u32, pcmd: *const esp_rom_spi_cmd_t); - } - - let conf = esp_rom_spi_cmd_t { - cmd, - cmd_bit_len, - addr: &addr, - addr_bit_len, - tx_data: mosi_data as *const u32, - tx_data_bit_len: mosi_bit_len, - rx_data: miso_data as *mut u32, - rx_data_bit_len: miso_bit_len, - dummy_bit_len: dummy_bits, - }; - - unsafe { - esp_rom_spi_cmd_config(1, &conf); - } - } - - #[ram] - fn psram_set_op_mode(mode: CommandMode) { - unsafe extern "C" { - fn esp_rom_spi_set_op_mode(spi: u32, mode: u32); - } - - const ESP_ROM_SPIFLASH_QIO_MODE: u32 = 0; - const ESP_ROM_SPIFLASH_SLOWRD_MODE: u32 = 5; - - unsafe { - match mode { - CommandMode::PsramCmdQpi => { - esp_rom_spi_set_op_mode(1, ESP_ROM_SPIFLASH_QIO_MODE); - SPI1::regs().ctrl().modify(|_, w| w.fcmd_quad().set_bit()); - } - CommandMode::PsramCmdSpi => { - esp_rom_spi_set_op_mode(1, ESP_ROM_SPIFLASH_SLOWRD_MODE); - } - } - } - } - - /// Exit QPI mode - #[ram] - fn psram_disable_qio_mode_spi1() { - const PSRAM_EXIT_QMODE: u16 = 0xF5; - const CS_PSRAM_SEL: u8 = 1 << 1; - - psram_exec_cmd( - CommandMode::PsramCmdQpi, - PSRAM_EXIT_QMODE, - 8, // command and command bit len - 0, - 0, // address and address bit len - 0, // dummy bit len - core::ptr::null(), - 0, // tx data and tx bit len - core::ptr::null_mut(), - 0, // rx data and rx bit len - CS_PSRAM_SEL, // cs bit mask - false, // whether is program/erase operation - ); - } - - /// Enter QPI mode - #[ram] - fn psram_enable_qio_mode_spi1() { - const PSRAM_ENTER_QMODE: u16 = 0x35; - const CS_PSRAM_SEL: u8 = 1 << 1; - - psram_exec_cmd( - CommandMode::PsramCmdSpi, - PSRAM_ENTER_QMODE, - 8, // command and command bit len - 0, - 0, // address and address bit len - 0, // dummy bit len - core::ptr::null(), - 0, // tx data and tx bit len - core::ptr::null_mut(), - 0, // rx data and rx bit len - CS_PSRAM_SEL, // cs bit mask - false, // whether is program/erase operation - ); - } - #[ram] fn psram_set_cs_timing() { - unsafe { - // SPI0/1 share the cs_hold / cs_setup, cd_hold_time / cd_setup_time registers - // for PSRAM, so we only need to set SPI0 related registers here - SPI0::regs() - .spi_smem_ac() - .modify(|_, w| w.spi_smem_cs_hold_time().bits(0)); - SPI0::regs() - .spi_smem_ac() - .modify(|_, w| w.spi_smem_cs_setup_time().bits(0)); - SPI0::regs() - .spi_smem_ac() - .modify(|_, w| w.spi_smem_cs_hold().set_bit()); - SPI0::regs() - .spi_smem_ac() - .modify(|_, w| w.spi_smem_cs_setup().set_bit()); - } + // SPI0/1 share the cs_hold / cs_setup, cd_hold_time / cd_setup_time registers + // for PSRAM, so we only need to set SPI0 related registers here + SPI0::regs().spi_smem_ac().modify(|_, w| unsafe { + w.spi_smem_cs_hold_time().bits(0); + w.spi_smem_cs_setup_time().bits(0); + w.spi_smem_cs_hold().set_bit(); + w.spi_smem_cs_setup().set_bit() + }); } #[ram] fn psram_gpio_config() { // CS1 let cs1_io: u8 = PSRAM_CS_IO; - if cs1_io == SPI_CS1_GPIO_NUM { - unsafe { - IO_MUX::regs() - .gpio(cs1_io as usize) - .modify(|_, w| w.mcu_sel().bits(FUNC_SPICS1_SPICS1)); - } + let mcu_sel = if cs1_io == SPI_CS1_GPIO_NUM { + FUNC_SPICS1_SPICS1 } else { unsafe { esp_rom_gpio_connect_out_signal(cs1_io, SPICS1_OUT_IDX, false, false); - - IO_MUX::regs() - .gpio(cs1_io as usize) - .modify(|_, w| w.mcu_sel().bits(PIN_FUNC_GPIO)); + PIN_FUNC_GPIO } - } + }; + + IO_MUX::regs() + .gpio(cs1_io as usize) + .modify(|_, w| unsafe { w.mcu_sel().bits(mcu_sel) }); // WP HD let mut wp_io: u8 = PSRAM_SPIWP_SD3_IO; @@ -786,9 +385,8 @@ pub(crate) mod quad_spi_impl { } pub(crate) mod octal_spi_impl { - use procmacros::ram; - use super::*; + use crate::psram::quad_xtensa; const OPI_PSRAM_SYNC_READ: u16 = 0x0000; const OPI_PSRAM_SYNC_WRITE: u16 = 0x8080; @@ -806,21 +404,9 @@ pub(crate) mod octal_spi_impl { const OCT_PSRAM_CS_HOLD_TIME: u8 = 3; const OCT_PSRAM_CS_HOLD_DELAY: u8 = 2; - const PSRAM_SIZE_2MB: usize = 2 * 1024 * 1024; - const PSRAM_SIZE_4MB: usize = 4 * 1024 * 1024; - const PSRAM_SIZE_8MB: usize = 8 * 1024 * 1024; - const PSRAM_SIZE_16MB: usize = 16 * 1024 * 1024; - const PSRAM_SIZE_32MB: usize = 32 * 1024 * 1024; - const SPI_CS1_GPIO_NUM: u8 = 26; const FUNC_SPICS1_SPICS1: u8 = 0; - const SPI_MEM_CLKCNT_N_S: u32 = 16; - const SPI_MEM_SCLKCNT_N_S: u32 = 16; - const SPI_MEM_CLKCNT_H_S: u32 = 8; - const SPI_MEM_SCLKCNT_H_S: u32 = 8; - const SPI_MEM_CLKCNT_L_S: u32 = 0; - const SPI_MEM_SCLKCNT_L_S: u32 = 0; const ESP_ROM_SPIFLASH_OPI_DTR_MODE: u8 = 7; unsafe extern "C" { @@ -1077,7 +663,6 @@ pub(crate) mod octal_spi_impl { #[ram] pub(crate) fn psram_init(config: &mut PsramConfig) -> bool { mspi_pin_init(); - init_psram_pins(); set_psram_cs_timing(); // for now we don't support ECC @@ -1117,11 +702,11 @@ pub(crate) mod octal_spi_impl { } let psram_size = match mode_reg.density() { - 0x0 => PSRAM_SIZE_2MB, - 0x1 => PSRAM_SIZE_4MB, - 0x3 => PSRAM_SIZE_8MB, - 0x5 => PSRAM_SIZE_16MB, - 0x7 => PSRAM_SIZE_32MB, + 0x0 => 2 * 1024 * 1024, + 0x1 => 4 * 1024 * 1024, + 0x3 => 8 * 1024 * 1024, + 0x5 => 16 * 1024 * 1024, + 0x7 => 32 * 1024 * 1024, _ => 0, }; info!("{} bytes of PSRAM", psram_size); @@ -1165,60 +750,51 @@ pub(crate) mod octal_spi_impl { // Configure PSRAM SPI0 phase related registers here according to the PSRAM chip // requirement fn config_psram_spi_phases() { - unsafe { - let spi = SPI0::regs(); - // Config Write CMD phase for SPI0 to access PSRAM - spi.cache_sctrl() - .modify(|_, w| w.cache_sram_usr_wcmd().set_bit()); - - spi.sram_dwr_cmd().modify(|_, w| { - w.cache_sram_usr_wr_cmd_bitlen() - .bits(OCT_PSRAM_WR_CMD_BITLEN - 1) - }); - spi.sram_dwr_cmd() - .modify(|_, w| w.cache_sram_usr_wr_cmd_value().bits(OPI_PSRAM_SYNC_WRITE)); + SPI0::regs().cache_sctrl().modify(|_, w| unsafe { + w.sram_oct().set_bit(); - // Config Read CMD phase for SPI0 to access PSRAM - spi.cache_sctrl() - .modify(|_, w| w.cache_sram_usr_rcmd().set_bit()); - - spi.sram_drd_cmd().modify(|_, w| { - w.cache_sram_usr_rd_cmd_bitlen() - .bits(OCT_PSRAM_RD_CMD_BITLEN - 1) - }); - spi.sram_drd_cmd() - .modify(|_, w| w.cache_sram_usr_rd_cmd_value().bits(OPI_PSRAM_SYNC_READ)); + w.cache_sram_usr_rcmd().set_bit(); + w.cache_sram_usr_wcmd().set_bit(); // Config ADDR phase - spi.cache_sctrl() - .modify(|_, w| w.sram_addr_bitlen().bits(OCT_PSRAM_ADDR_BITLEN - 1)); - spi.cache_sctrl() - .modify(|_, w| w.cache_usr_scmd_4byte().set_bit()); + w.sram_addr_bitlen().bits(OCT_PSRAM_ADDR_BITLEN - 1); + w.cache_usr_scmd_4byte().set_bit(); // Config RD/WR Dummy phase - spi.cache_sctrl() - .modify(|_, w| w.usr_rd_sram_dummy().set_bit()); - spi.cache_sctrl() - .modify(|_, w| w.usr_wr_sram_dummy().set_bit()); - spi.cache_sctrl() - .modify(|_, w| w.sram_rdummy_cyclelen().bits(OCT_PSRAM_RD_DUMMY_BITLEN - 1)); - spi.spi_smem_ddr() - .modify(|_, w| w.spi_smem_var_dummy().set_bit()); - spi.cache_sctrl() - .modify(|_, w| w.sram_wdummy_cyclelen().bits(OCT_PSRAM_WR_DUMMY_BITLEN - 1)); - - spi.spi_smem_ddr().modify(|_, w| w.wdat_swp().clear_bit()); - spi.spi_smem_ddr().modify(|_, w| w.rdat_swp().clear_bit()); - spi.spi_smem_ddr().modify(|_, w| w.en().set_bit()); - - spi.sram_cmd().modify(|_, w| w.sdummy_out().set_bit()); - spi.sram_cmd().modify(|_, w| w.scmd_oct().set_bit()); - spi.sram_cmd().modify(|_, w| w.saddr_oct().set_bit()); - spi.sram_cmd().modify(|_, w| w.sdout_oct().set_bit()); - spi.sram_cmd().modify(|_, w| w.sdin_oct().set_bit()); - - spi.cache_sctrl().modify(|_, w| w.sram_oct().set_bit()); - } + w.usr_rd_sram_dummy().set_bit(); + w.usr_wr_sram_dummy().set_bit(); + w.sram_rdummy_cyclelen().bits(OCT_PSRAM_RD_DUMMY_BITLEN - 1); + w.sram_wdummy_cyclelen().bits(OCT_PSRAM_WR_DUMMY_BITLEN - 1) + }); + + // Config Write CMD phase for SPI0 to access PSRAM + SPI0::regs().sram_dwr_cmd().modify(|_, w| unsafe { + w.cache_sram_usr_wr_cmd_value().bits(OPI_PSRAM_SYNC_WRITE); + w.cache_sram_usr_wr_cmd_bitlen() + .bits(OCT_PSRAM_WR_CMD_BITLEN - 1) + }); + + // Config Read CMD phase for SPI0 to access PSRAM + SPI0::regs().sram_drd_cmd().modify(|_, w| unsafe { + w.cache_sram_usr_rd_cmd_bitlen() + .bits(OCT_PSRAM_RD_CMD_BITLEN - 1); + w.cache_sram_usr_rd_cmd_value().bits(OPI_PSRAM_SYNC_READ) + }); + + SPI0::regs().spi_smem_ddr().modify(|_, w| { + w.spi_smem_var_dummy().set_bit(); + w.wdat_swp().clear_bit(); + w.rdat_swp().clear_bit(); + w.en().set_bit() + }); + + SPI0::regs().sram_cmd().modify(|_, w| { + w.sdummy_out().set_bit(); + w.scmd_oct().set_bit(); + w.saddr_oct().set_bit(); + w.sdout_oct().set_bit(); + w.sdin_oct().set_bit() + }); } #[ram] @@ -1237,31 +813,38 @@ pub(crate) mod octal_spi_impl { #[ram] fn mspi_pin_init() { unsafe { esp_rom_opiflash_pin_config() }; - spi_timing_set_pin_drive_strength(); // Set F4R4 board pin drive strength. TODO: IDF-3663 - } - #[ram] - fn spi_timing_set_pin_drive_strength() { // For now, set them all to 3. Need to check after QVL test results are out. // TODO: IDF-3663 Set default clk - unsafe { - SPI0::regs() - .date() - .modify(|_, w| w.spi_spiclk_pad_drv_ctl_en().set_bit()); - SPI0::regs() - .date() - .modify(|_, w| w.spi_smem_spiclk_fun_drv().bits(3)); - SPI0::regs() - .date() - .modify(|_, w| w.spi_fmem_spiclk_fun_drv().bits(3)); - - // Set default mspi d0 ~ d7, dqs pin drive strength - let pins = [27usize, 28, 31, 32, 33, 34, 35, 36, 37]; - for pin in pins { - IO_MUX::regs().gpio(pin).modify(|_, w| w.fun_drv().bits(3)); - } + SPI0::regs().date().modify(|_, w| unsafe { + w.spi_spiclk_pad_drv_ctl_en().set_bit(); + w.spi_smem_spiclk_fun_drv().bits(3); + w.spi_fmem_spiclk_fun_drv().bits(3) + }); + + // Set default mspi d0 ~ d7, dqs pin drive strength + let pins = [ + OCT_PSRAM_CS1_IO as usize, + 27, + 28, + 31, + 32, + 33, + 34, + 35, + 36, + 37, + ]; + for pin in pins { + IO_MUX::regs() + .gpio(pin) + .modify(|_, w| unsafe { w.fun_drv().bits(3) }); } + + IO_MUX::regs() + .gpio(OCT_PSRAM_CS1_IO as usize) + .modify(|_, w| unsafe { w.mcu_sel().bits(FUNC_SPICS1_SPICS1) }); } fn spi_timing_enter_mspi_low_speed_mode(control_spi1: bool) { @@ -1284,7 +867,7 @@ pub(crate) mod octal_spi_impl { } // Set PSRAM module clock - spi0_timing_config_set_psram_clock(4); + quad_xtensa::spi0_timing_config_set_psram_clock(4); // for now we don't support tuning the timing // "clear_timing_tuning_regs(control_spi1);" @@ -1309,56 +892,26 @@ pub(crate) mod octal_spi_impl { spi1_timing_config_set_flash_clock(flash_div); } // Set PSRAM module clock - spi0_timing_config_set_psram_clock(psram_div); + quad_xtensa::spi0_timing_config_set_psram_clock(psram_div); // for now we don't support tuning the timing // "set_timing_tuning_regs_as_required(true);" } fn set_psram_cs_timing() { - unsafe { - let spi = SPI0::regs(); - // SPI0/1 share the cs_hold / cs_setup, cd_hold_time / cd_setup_time, - // cs_hold_delay registers for PSRAM, so we only need to set SPI0 related - // registers here - spi.spi_smem_ac() - .modify(|_, w| w.spi_smem_cs_hold().set_bit()); - spi.spi_smem_ac() - .modify(|_, w| w.spi_smem_cs_setup().set_bit()); - - spi.spi_smem_ac() - .modify(|_, w| w.spi_smem_cs_hold_time().bits(OCT_PSRAM_CS_HOLD_TIME)); - spi.spi_smem_ac() - .modify(|_, w| w.spi_smem_cs_setup_time().bits(OCT_PSRAM_CS_SETUP_TIME)); + // SPI0/1 share the cs_hold / cs_setup, cd_hold_time / cd_setup_time, + // cs_hold_delay registers for PSRAM, so we only need to set SPI0 related + // registers here + SPI0::regs().spi_smem_ac().modify(|_, w| unsafe { + w.spi_smem_cs_hold().set_bit(); + w.spi_smem_cs_setup().set_bit(); + w.spi_smem_cs_hold_time().bits(OCT_PSRAM_CS_HOLD_TIME); + w.spi_smem_cs_setup_time().bits(OCT_PSRAM_CS_SETUP_TIME); // CONFIG_SPIRAM_ECC_ENABLE unsupported for now // CS1 high time - spi.spi_smem_ac() - .modify(|_, w| w.spi_smem_cs_hold_delay().bits(OCT_PSRAM_CS_HOLD_DELAY)); - } - } - - fn init_psram_pins() { - // Set cs1 pin function - unsafe { - IO_MUX::regs() - .gpio(OCT_PSRAM_CS1_IO as usize) - .modify(|_, w| w.mcu_sel().bits(FUNC_SPICS1_SPICS1)); - } - - // Set mspi cs1 drive strength - unsafe { - IO_MUX::regs() - .gpio(OCT_PSRAM_CS1_IO as usize) - .modify(|_, w| w.fun_drv().bits(3)); - } - - // Set psram clock pin drive strength - unsafe { - SPI0::regs() - .date() - .modify(|_, w| w.spi_smem_spiclk_fun_drv().bits(3)); - } + w.spi_smem_cs_hold_delay().bits(OCT_PSRAM_CS_HOLD_DELAY) + }); } fn psram_mode_reg(spi_num: u32, out_reg: &mut OpiPsramModeReg) { @@ -1608,54 +1161,6 @@ pub(crate) mod octal_spi_impl { } } - #[ram] - fn spi0_timing_config_set_flash_clock(freqdiv: u32) { - if freqdiv == 1 { - SPI0::regs() - .clock() - .modify(|_, w| w.clk_equ_sysclk().set_bit()); - } else { - let freqbits: u32 = ((freqdiv - 1) << SPI_MEM_CLKCNT_N_S) - | ((freqdiv / 2 - 1) << SPI_MEM_CLKCNT_H_S) - | ((freqdiv - 1) << SPI_MEM_CLKCNT_L_S); - unsafe { - SPI0::regs().clock().modify(|_, w| w.bits(freqbits)); - } - } - } - - #[ram] - fn spi1_timing_config_set_flash_clock(freqdiv: u32) { - if freqdiv == 1 { - SPI1::regs() - .clock() - .modify(|_, w| w.clk_equ_sysclk().set_bit()); - } else { - let freqbits: u32 = ((freqdiv - 1) << SPI_MEM_CLKCNT_N_S) - | ((freqdiv / 2 - 1) << SPI_MEM_CLKCNT_H_S) - | ((freqdiv - 1) << SPI_MEM_CLKCNT_L_S); - unsafe { - SPI1::regs().clock().modify(|_, w| w.bits(freqbits)); - } - } - } - - #[ram] - fn spi0_timing_config_set_psram_clock(freqdiv: u32) { - if freqdiv == 1 { - SPI0::regs() - .sram_clk() - .modify(|_, w| w.sclk_equ_sysclk().set_bit()); - } else { - let freqbits: u32 = ((freqdiv - 1) << SPI_MEM_SCLKCNT_N_S) - | ((freqdiv / 2 - 1) << SPI_MEM_SCLKCNT_H_S) - | ((freqdiv - 1) << SPI_MEM_SCLKCNT_L_S); - unsafe { - SPI0::regs().sram_clk().modify(|_, w| w.bits(freqbits)); - } - } - } - #[ram] fn flash_clock_divider(config: &PsramConfig) -> u32 { config.core_clock.unwrap_or_default() as u32 / config.flash_frequency as u32 @@ -1666,3 +1171,41 @@ pub(crate) mod octal_spi_impl { config.core_clock.unwrap_or_default() as u32 / config.ram_frequency as u32 } } + +#[ram] +fn spi0_timing_config_set_flash_clock(freqdiv: u32) { + if freqdiv == 1 { + SPI0::regs().clock().write(|w| unsafe { + w.clk_equ_sysclk().set_bit(); + w.clkcnt_h().bits(0); + w.clkcnt_n().bits(0); + w.clkcnt_l().bits(0) + }); + } else { + SPI0::regs().clock().write(|w| unsafe { + w.clk_equ_sysclk().clear_bit(); + w.clkcnt_h().bits((freqdiv / 2 - 1) as u8); + w.clkcnt_n().bits((freqdiv - 1) as u8); + w.clkcnt_l().bits((freqdiv - 1) as u8) + }); + } +} + +#[ram] +fn spi1_timing_config_set_flash_clock(freqdiv: u32) { + if freqdiv == 1 { + SPI1::regs().clock().write(|w| unsafe { + w.clk_equ_sysclk().set_bit(); + w.clkcnt_h().bits(0); + w.clkcnt_n().bits(0); + w.clkcnt_l().bits(0) + }); + } else { + SPI1::regs().clock().write(|w| unsafe { + w.clk_equ_sysclk().clear_bit(); + w.clkcnt_h().bits((freqdiv / 2 - 1) as u8); + w.clkcnt_n().bits((freqdiv - 1) as u8); + w.clkcnt_l().bits((freqdiv - 1) as u8) + }); + } +} diff --git a/esp-hal/src/psram/esp32s31.rs b/esp-hal/src/psram/esp32s31.rs index 0e66bb42d8f..1a262ec25fd 100644 --- a/esp-hal/src/psram/esp32s31.rs +++ b/esp-hal/src/psram/esp32s31.rs @@ -16,7 +16,7 @@ pub struct PsramConfig { /// Size of PSRAM to map. Default: `AutoDetect` via MR2 density. pub size: PsramSize, - /// PSRAM timing parameters. Default: 250 MHz. + /// PSRAM timing parameters. Default: 200 MHz. 250 MHz needs the MPLL at 500 MHz. pub timing: PsramTimingParams, // TODO: ECC enable. // The MSPI0 controller has a ECC engine. @@ -42,12 +42,12 @@ pub struct PsramTimingParams { /// MR4.wr_latency field value. pub mr4_wl: u8, - /// Read dummy length in bits for sync data reads (cache path). + /// Reads dummy length in bits for sync data reads (cache path). /// /// For `N` dummy bits, configure `reg_dummy_bits` to `N - 1`. pub rd_dummy_bits: u8, - /// Write dummy length in bits for sync data writes (cache path). + /// Writes dummy length in bits for sync data writes (cache path). /// /// For `N` dummy bits, configure `reg_dummy_bits` to `N - 1`. pub wr_dummy_bits: u8, @@ -58,7 +58,7 @@ pub struct PsramTimingParams { impl Default for PsramTimingParams { fn default() -> Self { - Self::MHZ_250 + Self::MHZ_200 } } @@ -119,7 +119,7 @@ impl PsramTimingParams { }; } -/// Initialize PSRAM. +/// Initializes PSRAM. #[crate::ram] pub(crate) fn init_psram(config: &mut PsramConfig) -> bool { // Module clock + clock source diff --git a/esp-hal/src/psram/mod.rs b/esp-hal/src/psram/mod.rs index be5c883dc96..f8c4cb9a1fb 100644 --- a/esp-hal/src/psram/mod.rs +++ b/esp-hal/src/psram/mod.rs @@ -43,6 +43,9 @@ use core::ops::Range; +#[cfg(any(esp32s2, esp32s3))] +mod quad_xtensa; + #[cfg_attr(esp32, path = "esp32.rs")] #[cfg_attr(esp32s2, path = "esp32s2.rs")] #[cfg_attr(esp32s3, path = "esp32s3.rs")] @@ -56,9 +59,9 @@ use portable_atomic::{AtomicUsize, Ordering}; use crate::peripherals::PSRAM; -/// Size of PSRAM +/// Size of PSRAM. /// -/// [PsramSize::AutoDetect] will try to detect the size of PSRAM +/// [`PsramSize::AutoDetect`] tries to detect the size of PSRAM. #[derive(Copy, Clone, Debug, Default, PartialEq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[instability::unstable] @@ -66,7 +69,7 @@ pub enum PsramSize { /// Detect PSRAM size #[default] AutoDetect, - /// A fixed PSRAM size + /// A fixed PSRAM size. Size(usize), } @@ -96,7 +99,7 @@ pub(crate) fn psram_range() -> Range { /// # Safety /// -/// This function must only be called once. +/// Must only be called once. unsafe fn set_psram_range(range: Range) { MAPPED_PSRAM_START.store(range.start, Ordering::Relaxed); MAPPED_PSRAM_END.store(range.end, Ordering::Release); diff --git a/esp-hal/src/psram/oct_hex.rs b/esp-hal/src/psram/oct_hex.rs index c3434b62919..ffbe500e82f 100644 --- a/esp-hal/src/psram/oct_hex.rs +++ b/esp-hal/src/psram/oct_hex.rs @@ -29,11 +29,11 @@ pub(super) fn write_psram_mmu_entry(entry_id: u32, page: u16) { MEMSPI2::regs().mmu_item_content().write(|w| unsafe { w.paddr().bits(page); w.access_spiram().set_bit(); - w.spiram_valid().set_bit() + w.valid().set_bit() }); } -/// Map PSRAM physical pages into the virtual address space via MMU. +/// Maps PSRAM physical pages into the virtual address space via MMU. /// /// ESP32-P4 has TWO independent MMUs: /// - Flash MMU (id 0): registers in `SPI_MEM_C` (FLASH_SPI0) @@ -63,7 +63,7 @@ pub(super) fn mmu_map_psram(size: usize) { unsafe { crate::soc::cache_invalidate_addr(EXTMEM_ORIGIN as u32, size as u32) }; } -/// Configure PSRAM_MSPI0 (AXI cache) for (OCT or HEX)/DDR access. +/// Configures PSRAM_MSPI0 (AXI cache) for (OCT or HEX)/DDR access. /// /// Faithful port of IDF `s_config_mspi_for_psram` from /// `esp_psram_impl_ap_oct.c`. Each register field is named after its @@ -130,7 +130,7 @@ pub(super) fn configure_psram_mspi(timing: &PsramTimingParams, is_hex: bool) { }); } -/// Set bus-clock divider for both PSRAM_MSPI0 and PSRAM_MSPI1. +/// Sets bus-clock divider for both PSRAM_MSPI0 and PSRAM_MSPI1. pub(super) fn set_bus_clock(clock: u32) -> bool { let source_mhz = PsramInstance::Psram.function_clock_frequency() / 1_000_000; if !source_mhz.is_multiple_of(clock) { @@ -172,7 +172,7 @@ pub(super) fn set_bus_clock(clock: u32) -> bool { true } -/// Enable DLL timing calibration for both controllers. +/// Enables DLL timing calibration for both controllers. pub(super) fn enable_dll() { MEMSPI2::regs() .timing_cali() @@ -182,7 +182,7 @@ pub(super) fn enable_dll() { .modify(|_, w| w.dll_timing_cali().set_bit()); } -/// Configure PSRAM PHY pads. +/// Configures PSRAM PHY pads. /// /// Mirrors IDF `mspi_timing_ll_pin_drv_set(2)` + /// `mspi_timing_ll_enable_dqs(true)`. @@ -230,7 +230,7 @@ pub(super) fn psram_pad_init(_is_hex: bool) { } } -/// Set PSRAM CS timing on the AXI controller's SMEM_AC register. +/// Sets PSRAM CS timing on the AXI controller's SMEM_AC register. /// SMEM_CS_SETUP=1, SMEM_CS_HOLD=1, setup_time=N-1, /// hold_time=N-1, hold_delay=N-1, split_trans_en=1. pub(super) fn set_cs_timing() { @@ -265,7 +265,7 @@ const MR_ADDR_MR6_MR7: u32 = 0x6; /// MR8 only used in current state, MR9 is unused or reserved. const MR_ADDR_MR8_MR9: u32 = 0x8; -/// Read an 8-bit mode-register pair from the AP OCT PSRAM chip. +/// Reads an 8-bit mode-register pair from the AP OCT PSRAM chip. /// /// Returns `(low, high)` where: /// - `low` = the MR at `mr_addr` @@ -275,7 +275,7 @@ fn psram_mr_read(timing: &PsramTimingParams, mr_addr: u32) -> (u8, u8) { ((pair & 0xFF) as u8, ((pair >> 8) & 0xFF) as u8) } -/// Write an 8-bit mode-register pair to the AP OCT PSRAM chip. +/// Writes an 8-bit mode-register pair to the AP OCT PSRAM chip. /// /// `low` goes to the MR at `mr_addr`, `high` goes to the MR at /// `mr_addr + 1`. For pair addresses whose high slot is reserved, pass @@ -285,11 +285,11 @@ fn psram_mr_write(mr_addr: u32, low: u8, high: u8) { mspi1_reg_write16(mr_addr, pair) } -/// Initialize AP OCT PSRAM mode registers via PSRAM_MSPI1 OPI DTR +/// Initializes AP OCT PSRAM mode registers via PSRAM_MSPI1 OPI DTR /// referenced IDF `oct_psram_mode_reg_t`). /// MR0: drive_str[1:0], read_latency[4:2], lt[5] /// MR4: wr_latency[7:5] -/// MR8: bl[1:0], bt[2], rbx[3], x16[6] +/// MR8: bl[1:0], bt[2], rbx[3], x16[6]. pub(super) fn init_mr_registers(timing: &PsramTimingParams, is_hex: bool) { // Read+modify+write MR0 (preserve MR1 high byte). let (mut mr0, mr1) = psram_mr_read(timing, MR_ADDR_MR0_MR1); @@ -339,17 +339,17 @@ const ESP_ROM_SPIFLASH_OPI_DTR_MODE: u32 = 7; const ROM_SPI_PSRAM_CMD_NUM: i32 = 3; unsafe extern "C" { - /// Set the controller's read mode (e.g. OPI-DTR). Configures cmd/addr/ + /// Sets the controller's read mode (e.g. OPI-DTR). Configures cmd/addr/ /// data line counts (8-line for OPI) and DDR mode bits in one call. /// Linked from `esp32s31.rom.ld`: `esp_rom_spi_set_op_mode = 0x4fc00110`. fn esp_rom_spi_set_op_mode(spi_num: i32, mode: u32); - /// Configure command/addr/dummy/data phases for next transaction. + /// Configures command/addr/dummy/data phases for next transaction. /// Writes USR / USER1 / USER2 / ADDR / MOSI_DLEN / MISO_DLEN / W0.. /// Linked from `esp32s31.rom.ld`: `esp_rom_spi_cmd_config = 0x4fc00108`. fn esp_rom_spi_cmd_config(spi_num: i32, pcmd: *mut EspRomSpiCmd); } -/// Kick the controller (set `SPI_USR` bit 18 in CMD_REG) and poll +/// Kicks the controller (sets `SPI_USR` bit 18 in CMD_REG) and polls /// bounded for completion. Replacement for ROM `esp_rom_spi_cmd_start`, /// which polls forever; a hang there gives no diagnostic, while the /// bounded variant surfaces a real failure as a returned error. After diff --git a/esp-hal/src/psram/quad.rs b/esp-hal/src/psram/quad.rs index 105aabc9143..f0db9951f9f 100644 --- a/esp-hal/src/psram/quad.rs +++ b/esp-hal/src/psram/quad.rs @@ -36,7 +36,7 @@ pub(super) enum MspiTimingSpeedMode { /// /// As a tradeoff, the performance of the MSPI (devices) are switched to a very low speed MspiTimingSpeedModeLowPerf, - /// Normal performance speed mode, MSPI speed is the same as you configured + /// Normal performance speed mode. MSPI speed matches the configured speed. MspiTimingSpeedModeNormalPerf, } @@ -121,7 +121,7 @@ pub(crate) fn psram_init(config: &mut super::PsramConfig) -> bool { unsafe extern "C" { fn esp_rom_gpio_connect_out_signal(gpio_num: u8, signal_idx: u8, out_inv: bool, oen_inv: bool); - /// Enable Quad I/O pin functions + /// Enables Quad I/O pin functions. /// /// Sets the HD & WP pin functions for Quad I/O modes, based on the /// efuse SPI pin configuration. @@ -167,16 +167,22 @@ fn mspi_timing_psram_tuning() { // for now we just use the user provided setting (which might be default settings) } -/// Set SPI0 FLASH and PSRAM module clock, din_num, din_mode and extra +/// Sets SPI0 FLASH and PSRAM module clock, din_num, din_mode and extra /// dummy, according to the configuration got from timing tuning /// function (`calculate_best_flash_tuning_config`). iF control_spi1 == /// 1, will also update SPI1 timing registers. Should only be set to 1 when /// do tuning. /// -/// This function should always be called after `mspi_timing_flash_tuning` -/// or `calculate_best_flash_tuning_config` +/// Must always be called after `mspi_timing_flash_tuning` or +/// `calculate_best_flash_tuning_config` #[ram] fn mspi_timing_enter_high_speed_mode(config: &PsramConfig) { + info!( + "PSRAM clock {} MHz, flash clock {} MHz", + config.ram_frequency.mhz(), + config.flash_frequency.mhz() + ); + super::mspi_timing_config_set_flash_clock( config.flash_frequency.mhz(), MspiTimingSpeedMode::MspiTimingSpeedModeNormalPerf, @@ -243,13 +249,13 @@ fn psram_exec_cmd( is_write_erase_operation: bool, ) { unsafe extern "C" { - /// Start a spi user command sequence + /// Starts a SPI user command sequence. /// [`spi_num`] spi port /// [`rx_buf`] buffer pointer to receive data /// [`rx_len`] receive data length in byte /// [`cs_en_mask`] decide which cs to use, 0 for cs0, 1 for cs1 /// [`is_write_erase`] to indicate whether this is a write or erase - /// operation, since the CPU would check permission + /// operation, since the CPU would check permission. fn esp_rom_spi_cmd_start( spi_num: u32, rx_buf: *const u8, @@ -313,7 +319,7 @@ fn psram_config_cmd( addr_bit_len: u32, // Address byte length tx_data: *const u32, // Point to send data buffer tx_data_bit_len: u32, // Send data byte length. - rx_data: *mut u32, // Point to recevie data buffer + rx_data: *mut u32, // Point to receive data buffer rx_data_bit_len: u32, // Recevie Data byte length. dummy_bit_len: u32, } @@ -364,7 +370,7 @@ fn psram_set_op_mode(mode: CommandMode) { } } -/// Exit QPI mode +/// Exits QPI mode. #[ram] fn psram_disable_qio_mode_spi1() { const PSRAM_EXIT_QMODE: u16 = 0xF5; @@ -386,7 +392,7 @@ fn psram_disable_qio_mode_spi1() { ); } -/// Enter QPI mode +/// Enters QPI mode. #[ram] fn psram_enable_qio_mode_spi1() { const PSRAM_ENTER_QMODE: u16 = 0x35; diff --git a/esp-hal/src/psram/quad_xtensa.rs b/esp-hal/src/psram/quad_xtensa.rs new file mode 100644 index 00000000000..e043fb38fdd --- /dev/null +++ b/esp-hal/src/psram/quad_xtensa.rs @@ -0,0 +1,326 @@ +//! Shared Quad PSRAM helpers for ESP32-S2 and ESP32-S3. +//! +//! Command sequences, SPI1 ROM access, SPI0 cache phases, and the PSRAM module +//! clock register are the same on both chips. Pin mux, MSPI core clock, and MMU +//! mapping stay chip-specific. + +use procmacros::ram; + +use crate::peripherals::{SPI0, SPI1}; + +const CS_PSRAM_SEL: u8 = 1 << 1; + +const PSRAM_RESET_EN: u16 = 0x66; +const PSRAM_RESET: u16 = 0x99; +const PSRAM_DEVICE_ID: u16 = 0x9F; +const PSRAM_ENTER_QMODE: u16 = 0x35; +const PSRAM_EXIT_QMODE: u16 = 0xF5; + +const PSRAM_QUAD_WRITE: u32 = 0x38; +const PSRAM_FAST_READ_QUAD: u32 = 0xEB; +const PSRAM_FAST_READ_QUAD_DUMMY: u32 = 6; + +#[derive(PartialEq)] +enum CommandMode { + PsramCmdQpi = 0, + PsramCmdSpi = 1, +} + +/// Reads the AP-memory device ID and converts density to a byte size. +#[ram] +pub(crate) fn detect_quad_size() -> Option { + psram_disable_qio_mode_spi1(); + + let mut dev_id = 0u32; + psram_exec_cmd( + CommandMode::PsramCmdSpi, + PSRAM_DEVICE_ID, + 8, + 0, + 24, + 0, + core::ptr::null(), + 0, + &mut dev_id as *mut _ as *mut u8, + 24, + CS_PSRAM_SEL, + false, + ); + + if dev_id == 0xffffff { + debug!( + "Unknown PSRAM chip ID: {:x}. PSRAM chip not found or not supported. Check if the interface mode is configured correctly.", + dev_id + ); + return None; + } + + info!("chip id = {:x}", dev_id); + + const PSRAM_ID_EID_S: u32 = 16; + const PSRAM_ID_EID_M: u32 = 0xff; + const PSRAM_EID_SIZE_M: u32 = 0x07; + const PSRAM_EID_SIZE_S: u32 = 5; + const PSRAM_EID_SIZE_32MBITS: u32 = 1; + const PSRAM_EID_SIZE_64MBITS: u32 = 2; + + let size_id = + (((dev_id >> PSRAM_ID_EID_S) & PSRAM_ID_EID_M) >> PSRAM_EID_SIZE_S) & PSRAM_EID_SIZE_M; + + let size = match size_id { + PSRAM_EID_SIZE_64MBITS => 8 * 1024 * 1024, + PSRAM_EID_SIZE_32MBITS => 4 * 1024 * 1024, + _ => 2 * 1024 * 1024, + }; + + info!("size is {}", size); + Some(size) +} + +/// Configures SPI0 cache command/address/dummy phases for Quad PSRAM. +#[ram] +pub(crate) fn config_psram_spi_phases() { + SPI0::regs().cache_sctrl().modify(|_, w| unsafe { + w.usr_sram_dio().clear_bit(); + w.usr_sram_qio().set_bit(); + w.cache_sram_usr_rcmd().set_bit(); + w.cache_sram_usr_wcmd().set_bit(); + + w.sram_addr_bitlen().bits(23); + w.usr_rd_sram_dummy().set_bit(); + + w.sram_rdummy_cyclelen() + .bits((PSRAM_FAST_READ_QUAD_DUMMY - 1) as u8) + }); + + SPI0::regs().sram_dwr_cmd().modify(|_, w| unsafe { + w.cache_sram_usr_wr_cmd_bitlen().bits(7); + w.cache_sram_usr_wr_cmd_value() + .bits(PSRAM_QUAD_WRITE as u16) + }); + + SPI0::regs().sram_drd_cmd().modify(|_, w| unsafe { + w.cache_sram_usr_rd_cmd_bitlen().bits(7); + w.cache_sram_usr_rd_cmd_value() + .bits(PSRAM_FAST_READ_QUAD as u16) + }); + + // CS0 is flash, CS1 is PSRAM. + SPI0::regs().misc().modify(|_, w| w.cs1_dis().clear_bit()); +} + +/// Programs the SPI0 PSRAM module clock divider. +#[ram] +pub(crate) fn spi0_timing_config_set_psram_clock(freqdiv: u32) { + if freqdiv == 1 { + SPI0::regs().sram_clk().write(|w| unsafe { + w.sclk_equ_sysclk().set_bit(); + w.sclkcnt_h().bits(0); + w.sclkcnt_n().bits(0); + w.sclkcnt_l().bits(0) + }); + } else { + SPI0::regs().sram_clk().write(|w| unsafe { + w.sclk_equ_sysclk().clear_bit(); + w.sclkcnt_h().bits((freqdiv / 2 - 1) as u8); + w.sclkcnt_n().bits((freqdiv - 1) as u8); + w.sclkcnt_l().bits((freqdiv - 1) as u8) + }); + } +} + +#[ram] +pub(crate) fn psram_reset_mode_spi1() { + psram_exec_cmd( + CommandMode::PsramCmdSpi, + PSRAM_RESET_EN, + 8, + 0, + 0, + 0, + core::ptr::null(), + 0, + core::ptr::null_mut(), + 0, + CS_PSRAM_SEL, + false, + ); + psram_exec_cmd( + CommandMode::PsramCmdSpi, + PSRAM_RESET, + 8, + 0, + 0, + 0, + core::ptr::null(), + 0, + core::ptr::null_mut(), + 0, + CS_PSRAM_SEL, + false, + ); +} + +#[ram] +pub(crate) fn psram_enable_qio_mode_spi1() { + psram_exec_cmd( + CommandMode::PsramCmdSpi, + PSRAM_ENTER_QMODE, + 8, + 0, + 0, + 0, + core::ptr::null(), + 0, + core::ptr::null_mut(), + 0, + CS_PSRAM_SEL, + false, + ); +} + +#[ram] +fn psram_disable_qio_mode_spi1() { + psram_exec_cmd( + CommandMode::PsramCmdQpi, + PSRAM_EXIT_QMODE, + 8, + 0, + 0, + 0, + core::ptr::null(), + 0, + core::ptr::null_mut(), + 0, + CS_PSRAM_SEL, + false, + ); +} + +#[expect(clippy::too_many_arguments)] +#[ram] +fn psram_exec_cmd( + mode: CommandMode, + cmd: u16, + cmd_bit_len: u16, + addr: u32, + addr_bit_len: u32, + dummy_bits: u32, + mosi_data: *const u8, + mosi_bit_len: u32, + miso_data: *mut u8, + miso_bit_len: u32, + cs_mask: u8, + is_write_erase_operation: bool, +) { + unsafe extern "C" { + fn esp_rom_spi_cmd_start( + spi_num: u32, + rx_buf: *const u8, + rx_len: u16, + cs_en_mask: u8, + is_write_erase: bool, + ); + } + + unsafe { + let spi1 = SPI1::regs(); + let backup_usr = spi1.user().read().bits(); + let backup_usr1 = spi1.user1().read().bits(); + let backup_usr2 = spi1.user2().read().bits(); + let backup_ctrl = spi1.ctrl().read().bits(); + psram_set_op_mode(mode); + psram_config_cmd( + cmd, + cmd_bit_len, + addr, + addr_bit_len, + dummy_bits, + mosi_data, + mosi_bit_len, + miso_data, + miso_bit_len, + ); + esp_rom_spi_cmd_start( + 1, + miso_data, + (miso_bit_len / 8) as u16, + cs_mask, + is_write_erase_operation, + ); + + spi1.user().write(|w| w.bits(backup_usr)); + spi1.user1().write(|w| w.bits(backup_usr1)); + spi1.user2().write(|w| w.bits(backup_usr2)); + spi1.ctrl().write(|w| w.bits(backup_ctrl)); + } +} + +#[expect(clippy::too_many_arguments)] +#[ram] +fn psram_config_cmd( + cmd: u16, + cmd_bit_len: u16, + addr: u32, + addr_bit_len: u32, + dummy_bits: u32, + mosi_data: *const u8, + mosi_bit_len: u32, + miso_data: *mut u8, + miso_bit_len: u32, +) { + #[repr(C)] + struct EspRomSpiCmd { + cmd: u16, + cmd_bit_len: u16, + addr: *const u32, + addr_bit_len: u32, + tx_data: *const u32, + tx_data_bit_len: u32, + rx_data: *mut u32, + rx_data_bit_len: u32, + dummy_bit_len: u32, + } + + unsafe extern "C" { + fn esp_rom_spi_cmd_config(spi_num: u32, pcmd: *const EspRomSpiCmd); + } + + let conf = EspRomSpiCmd { + cmd, + cmd_bit_len, + addr: &addr, + addr_bit_len, + tx_data: mosi_data as *const u32, + tx_data_bit_len: mosi_bit_len, + rx_data: miso_data as *mut u32, + rx_data_bit_len: miso_bit_len, + dummy_bit_len: dummy_bits, + }; + + unsafe { + esp_rom_spi_cmd_config(1, &conf); + } +} + +#[ram] +fn psram_set_op_mode(mode: CommandMode) { + unsafe extern "C" { + fn esp_rom_spi_set_op_mode(spi: u32, mode: u32); + } + + const ESP_ROM_SPIFLASH_QIO_MODE: u32 = 0; + const ESP_ROM_SPIFLASH_SLOWRD_MODE: u32 = 5; + + unsafe { + match mode { + CommandMode::PsramCmdQpi => { + esp_rom_spi_set_op_mode(1, ESP_ROM_SPIFLASH_QIO_MODE); + SPI1::regs().ctrl().modify(|_, w| w.fcmd_quad().set_bit()); + } + CommandMode::PsramCmdSpi => { + esp_rom_spi_set_op_mode(1, ESP_ROM_SPIFLASH_SLOWRD_MODE); + } + } + } +} diff --git a/esp-hal/src/rmt.rs b/esp-hal/src/rmt.rs index 3258a230651..28ebf1cfb32 100644 --- a/esp-hal/src/rmt.rs +++ b/esp-hal/src/rmt.rs @@ -236,18 +236,18 @@ use reader::{ReaderState, RmtReader}; mod writer; use writer::{RmtWriter, WriterState}; -/// A configuration error +/// A configuration error. #[derive(Debug, Clone, Copy, PartialEq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[non_exhaustive] pub enum ConfigError { - /// The desired frequency is impossible to reach + /// The desired frequency is impossible to reach. UnreachableTargetFrequency, - /// The idle threshold exceeds [`MAX_RX_IDLE_THRESHOLD`] + /// The idle threshold exceeds [`MAX_RX_IDLE_THRESHOLD`]. IdleThresholdOutOfRange, - /// The memsize is 0 or larger than what the channel can support + /// The memsize is 0 or larger than what the channel can support. MemsizeOutOfRange, - /// (Part of) the requested channel memory is in use by another channel + /// (Part of) the requested channel memory is in use by another channel. MemoryBlockNotAvailable, } @@ -274,17 +274,17 @@ impl core::fmt::Display for ConfigError { #[allow(clippy::enum_variant_names, reason = "peripheral is unstable")] #[non_exhaustive] pub enum Error { - /// The amount of pulses exceeds the size of the FIFO + /// The amount of pulses exceeds the size of the FIFO. Overflow, - /// An argument is invalid + /// An argument is invalid. InvalidArgument, - /// An error occurred during transmission + /// An error occurred during transmission. TransmissionError, - /// No transmission end marker found + /// No transmission end marker found. EndMarkerMissing, - /// The data length is invalid + /// The data length is invalid. InvalidDataLength, - /// Receiver error most likely RMT memory overflow + /// Receiver error most likely RMT memory overflow. ReceiverError, } @@ -338,7 +338,7 @@ impl PulseCode { /// Maximum value for the `length1` and `length2` fields. pub const MAX_LEN: u16 = 0x7FFF; - /// Create a new instance. + /// Creates a new instance. /// /// Panics if `length1` or `length2` exceed the maximum representable range. #[inline] @@ -353,7 +353,7 @@ impl PulseCode { unsafe { Self::new_unchecked(level1, length1, level2, length2) } } - /// Create a new instance. + /// Creates a new instance. /// /// If `length1` or `length2` exceed the maximum representable range, they /// will be clamped to `Self::MAX_LEN`. @@ -376,7 +376,7 @@ impl PulseCode { unsafe { Self::new_unchecked(level1, length1, level2, length2) } } - /// Create a new instance, attempting to convert lengths to `u16` first. + /// Creates a new instance, attempting to convert lengths to `u16` first. /// /// This is slightly more convenient when passing in longer integers (e.g. `u32`) resulting from /// a preceding calculation. @@ -402,7 +402,7 @@ impl PulseCode { Some(unsafe { Self::new_unchecked(level1, length1, level2, length2) }) } - /// Create a new instance without checking that code lengths are in range. + /// Creates a new instance without checking that code lengths are in range. /// /// # Safety /// @@ -422,7 +422,7 @@ impl PulseCode { ) } - /// Create a new instance that is an end marker with `Level::Low`. + /// Creates a new instance that is an end marker with `Level::Low`. /// /// This corresponds to the all-zero [`PulseCode`], i.e. with both level and /// length fields set to zero, equivalent to (but more semantic than) @@ -435,7 +435,7 @@ impl PulseCode { Self(0) } - /// Set all levels and lengths to 0. + /// Sets all levels and lengths to 0. /// /// In other words, assigns the value of [`PulseCode::end_marker()`] to `self`. #[inline] @@ -469,7 +469,7 @@ impl PulseCode { ((self.0 >> LENGTH2_SHIFT) & LENGTH_MASK) as u16 } - /// Set `level1` and return the modified [`PulseCode`]. + /// Sets `level1` and returns the modified [`PulseCode`]. #[inline] pub const fn with_level1(mut self, level: Level) -> Self { self.0 &= !LEVEL1_MASK; @@ -477,7 +477,7 @@ impl PulseCode { self } - /// Set `level2` and return the modified [`PulseCode`]. + /// Sets `level2` and returns the modified [`PulseCode`]. #[inline] pub const fn with_level2(mut self, level: Level) -> Self { self.0 &= !LEVEL2_MASK; @@ -485,7 +485,7 @@ impl PulseCode { self } - /// Set `length1` and return the modified [`PulseCode`]. + /// Sets `length1` and returns the modified [`PulseCode`]. /// /// Returns `None` if `length` exceeds the representable range. #[inline] @@ -499,7 +499,7 @@ impl PulseCode { Some(self) } - /// Set `length2` and return the modified [`PulseCode`]. + /// Sets `length2` and returns the modified [`PulseCode`]. /// /// Returns `None` if `length` exceeds the representable range. #[inline] @@ -513,7 +513,7 @@ impl PulseCode { Some(self) } - /// Return whether this pulse code contains an end marker. + /// Returns whether this pulse code contains an end marker. /// /// Equivalent to `self.length1() == 0 || self.length2() == 0`. #[inline] @@ -583,31 +583,31 @@ impl From for u32 { struct MemSize(u8); impl MemSize { - /// Create from the given number of RMT RAM blocks. + /// Creates from the given number of RMT RAM blocks. #[inline] const fn from_blocks(blocks: u8) -> Self { Self(blocks) } - /// Return the number of RMT RAM blocks specified by this `MemSize`. + /// Returns the number of RMT RAM blocks specified by this `MemSize`. #[inline] const fn blocks(self) -> u8 { self.0 } - /// Return the number of RMT pulse codes specified by this `MemSize`. + /// Returns the number of RMT pulse codes specified by this `MemSize`. #[inline] const fn codes(self) -> usize { self.0 as usize * property!("rmt.channel_ram_size") } } -/// Marker for a channel capable of/configured for transmit operations +/// Marker for a channel capable of or configured for transmit operations. #[derive(Clone, Copy, Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub struct Tx; -/// Marker for a channel capable of/configured for receive operations +/// Marker for a channel capable of or configured for receive operations. #[derive(Clone, Copy, Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub struct Rx; @@ -655,11 +655,11 @@ impl DynChannelAccess { pub struct TxChannelConfig { /// Channel's clock divider clk_divider: u8, - /// Whether the idle output level is low/high + /// Whether the idle output level is low/high. idle_output_level: Level, - /// Whether idle output is enabled + /// Whether idle output is enabled. idle_output: bool, - /// Whether carrier modulation is enabled + /// Whether carrier modulation is enabled. carrier_modulation: bool, /// Carrier high phase in ticks carrier_high: u16, @@ -667,7 +667,7 @@ pub struct TxChannelConfig { carrier_low: u16, /// Level of the carrier carrier_level: Level, - /// The amount of memory blocks allocated to this channel + /// The amount of memory blocks allocated to this channel. memsize: u8, } @@ -692,7 +692,7 @@ impl Default for TxChannelConfig { pub struct RxChannelConfig { /// Channel's clock divider clk_divider: u8, - /// Whether carrier demodulation is enabled + /// Whether carrier demodulation is enabled. carrier_modulation: bool, /// Carrier high phase in ticks carrier_high: u16, @@ -702,9 +702,9 @@ pub struct RxChannelConfig { carrier_level: Level, /// Filter threshold in ticks filter_threshold: u8, - /// Idle threshold in ticks, must not exceed [`MAX_RX_IDLE_THRESHOLD`] + /// Idle threshold in ticks, must not exceed [`MAX_RX_IDLE_THRESHOLD`]. idle_threshold: u16, - /// The amount of memory blocks allocted to this channel + /// The amount of memory blocks allocated to this channel. memsize: u8, } @@ -914,17 +914,16 @@ impl ChannelIndex { } impl<'rmt> Rmt<'rmt, Blocking> { - /// Create a new RMT instance. + /// Creates a new RMT instance. /// /// The `frequency` parameter configures the global RMT counter clock. Use /// [`Rmt::frequency`] to retrieve the actual configured frequency when /// converting real-time pulse durations to [`PulseCode`] lengths; this is /// not necessarily the APB clock frequency. /// - /// ## Errors + /// # Errors /// - /// This function can return - /// - [`ConfigError::UnreachableTargetFrequency`]. + /// [`ConfigError::UnreachableTargetFrequency`] when the target frequency cannot be reached. pub fn new(peripheral: RMT<'rmt>, frequency: Rate) -> Result { let clk_src = ClockSource::default(); let (div, counter_frequency) = self::chip_specific::validate_clock(clk_src, frequency)?; @@ -933,14 +932,13 @@ impl<'rmt> Rmt<'rmt, Blocking> { // contains lots of code to drop them again on error. let this = Rmt::create(peripheral, counter_frequency); - self::chip_specific::configure_clock(clk_src, div); + self::chip_specific::configure_clock(clk_src, div, counter_frequency); Ok(this) } /// Registers an interrupt handler for the RMT peripheral. /// - /// Note that this will replace any previously registered interrupt - /// handlers. + /// Replaces any previously registered interrupt handlers. #[instability::unstable] pub fn set_interrupt_handler(&mut self, handler: crate::interrupt::InterruptHandler) { for core in crate::system::Cpu::other() { @@ -1049,7 +1047,7 @@ mod state { } impl RmtState { - /// Check whether this state corresponds to a rx, tx, or other configuration. + /// Returns whether this state corresponds to a rx, tx, or other configuration. #[allow(unused)] #[inline] pub(super) fn is_tx(&self) -> Option { @@ -1060,20 +1058,20 @@ mod state { } } - /// Convert a `u8` to `Self` without checking that it has a valid value for the enum. + /// Converts a `u8` to `Self` without checking that it has a valid value for the enum. /// /// # Safety /// - /// - Must only be called with valid values of the RmtState discrimiant + /// - Must only be called with valid values of the RmtState discriminant #[allow(unused)] #[inline] unsafe fn from_u8_unchecked(value: u8) -> Self { unsafe { core::mem::transmute::<_, Self>(value) } } - /// Load channel state from the global `STATE` by channel index. + /// Loads channel state from the global `STATE` by channel index. /// - /// # Safety: + /// # Safety /// /// - the `channel` number must be in 0..NUM_CHANNELS #[allow(unused)] @@ -1082,7 +1080,7 @@ mod state { unsafe { Self::from_u8_unchecked(STATE[channel as usize].load(ordering)) } } - /// Store the given state to all channel states for an index range in reverse order. + /// Stores the given state to all channel states for an index range in reverse order. #[inline] pub(super) fn store_range_rev(self, range: Range, ordering: Ordering) { for ch_num in range.rev() { @@ -1090,14 +1088,14 @@ mod state { } } - /// Store channel state to the global `STATE` given a `DynChannelAccess`. + /// Stores channel state to the global `STATE` given a `DynChannelAccess`. #[allow(unused)] #[inline] pub(super) fn store(self, raw: DynChannelAccess, ordering: Ordering) { STATE[raw.channel() as usize].store(self as u8, ordering); } - /// Load channel state from the global `STATE` given a `DynChannelAccess`. + /// Loads channel state from the global `STATE` given a `DynChannelAccess`. #[allow(unused)] #[inline] pub(super) fn load(raw: DynChannelAccess, ordering: Ordering) -> Self { @@ -1106,7 +1104,7 @@ mod state { unsafe { Self::load_by_channel_number(raw.channel(), ordering) } } - /// Perform a compare_exchange on the global `STATE` by channel index. + /// Performs a compare_exchange on the global `STATE` by channel index. #[inline] pub(super) fn compare_exchange( ch_num: u8, @@ -1167,7 +1165,7 @@ impl ChannelGuards { } } -/// RMT Channel +/// RMT Channel. #[derive(Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[non_exhaustive] @@ -1295,7 +1293,7 @@ where Dm: crate::DriverMode, Dir: Direction, { - /// Reborrow this channel for a shorter lifetime `'a`. + /// Reborrows this channel for a shorter lifetime `'a`. pub fn reborrow<'a>(&'a mut self) -> Channel<'a, Dm, Dir> { Channel { raw: self.raw, @@ -1312,7 +1310,7 @@ impl<'ch, Dm> Channel<'ch, Dm, Tx> where Dm: crate::DriverMode, { - /// Connect a pin to the channel's output signal. + /// Connects a pin to the channel's output signal. /// /// This will replace previous pin assignments for this signal. pub fn with_pin(mut self, pin: impl PeripheralOutput<'ch>) -> Self { @@ -1329,13 +1327,11 @@ where self } - /// Change the configuration. + /// Changes the configuration. /// - /// ## Errors + /// # Errors /// - /// This function can return - /// - [`ConfigError::MemoryBlockNotAvailable`], - /// - [`ConfigError::MemsizeOutOfRange`]. + /// [`ConfigError::MemoryBlockNotAvailable`] or [`ConfigError::MemsizeOutOfRange`]. pub fn apply_config(&mut self, config: &TxChannelConfig) -> Result<(), ConfigError> { apply_tx_config(self.raw, config, true) } @@ -1345,7 +1341,7 @@ impl<'ch, Dm> Channel<'ch, Dm, Rx> where Dm: crate::DriverMode, { - /// Connect a pin to the channel's input signal. + /// Connects a pin to the channel's input signal. /// /// This will replace previous pin assignments for this signal. pub fn with_pin(self, pin: impl PeripheralInput<'ch>) -> Self { @@ -1358,44 +1354,45 @@ where self } - /// Change the configuration. + /// Changes the configuration. /// - /// ## Errors + /// # Errors /// - /// This function can return - /// - [`ConfigError::MemoryBlockNotAvailable`], - /// - [`ConfigError::MemsizeOutOfRange`], - /// - [`ConfigError::IdleThresholdOutOfRange`]. + /// [`ConfigError::MemoryBlockNotAvailable`], [`ConfigError::MemsizeOutOfRange`], or + /// [`ConfigError::IdleThresholdOutOfRange`]. pub fn apply_config(&mut self, config: &RxChannelConfig) -> Result<(), ConfigError> { apply_rx_config(self.raw, config, true) } } -/// Creates a TX channel +/// TX channel creator for the RMT peripheral. pub trait TxChannelCreator<'ch, Dm> where Dm: crate::DriverMode, { - /// Configure the TX channel + /// Configures the TX channel. /// - /// ## Errors + /// # Errors /// - /// Returns errors under the same conditions as [`Channel::apply_config`]. + /// [`ConfigError::MemoryBlockNotAvailable`] or [`ConfigError::MemsizeOutOfRange`] under the + /// same conditions as [`Channel::apply_config`]. fn configure_tx(self, config: &TxChannelConfig) -> Result, ConfigError> where Self: Sized; } -/// Creates a RX channel +/// RX channel creator for the RMT peripheral. pub trait RxChannelCreator<'ch, Dm> where Dm: crate::DriverMode, { - /// Configure the RX channel + /// Configures the RX channel. /// - /// ## Errors + /// # Errors /// - /// Returns errors under the same conditions as [`Channel::apply_config`]. + /// [`ConfigError::MemoryBlockNotAvailable`], [`ConfigError::MemsizeOutOfRange`], or + /// [`ConfigError::IdleThresholdOutOfRange`] under the same conditions as + /// [`Channel::apply_config`]. fn configure_rx(self, config: &RxChannelConfig) -> Result, ConfigError> where Self: Sized; @@ -1416,7 +1413,7 @@ impl TxGuard { Self { raw: None } } - /// Indicate that the transaction has completed (or was never started) and does not require + /// Indicates that the transaction has completed (or was never started) and does not require /// explicit stopping on drop. fn set_completed(&mut self) { self.raw = None; @@ -1459,7 +1456,7 @@ impl RxGuard { Self { raw: None } } - /// Indicate that the transaction has completed (or was never started) and does not require + /// Indicates that the transaction has completed (or was never started) and does not require /// explicit stopping on drop. fn set_completed(&mut self) { self.raw = None; @@ -1515,7 +1512,7 @@ impl<'ch> TxTransaction<'ch, '_> { status } - /// Check transmission status and write new data to the hardware if + /// Checks transmission status and writes new data to the hardware if /// necessary. /// /// Returns whether transmission has ended (whether successfully or with an @@ -1525,7 +1522,7 @@ impl<'ch> TxTransaction<'ch, '_> { matches!(self.poll_internal(), Some(Event::Error | Event::End)) } - /// Wait for the transaction to complete + /// Waits for the transaction to complete. #[cfg_attr(place_rmt_driver_in_ram, inline(always))] pub fn wait( mut self, @@ -1549,7 +1546,7 @@ impl<'ch> TxTransaction<'ch, '_> { } } -/// An in-progress continuous TX transaction +/// An in-progress continuous TX transaction. #[must_use = "transactions will be aborted when dropped"] #[derive(Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] @@ -1564,7 +1561,7 @@ pub struct ContinuousTxTransaction<'ch> { impl<'ch> ContinuousTxTransaction<'ch> { // FIXME: This interface isn't great, since one cannot use the waiting time until tx is stopped // for other things! Implement a poll-like interface similar to TxTransaction! - /// Stop transaction when the current iteration ends. + /// Stops transaction when the current iteration ends. #[cfg_attr(place_rmt_driver_in_ram, inline(always))] pub fn stop_next( self, @@ -1572,7 +1569,7 @@ impl<'ch> ContinuousTxTransaction<'ch> { self.stop_impl(false) } - /// Stop transaction as soon as possible. + /// Stops transaction as soon as possible. #[cfg_attr(place_rmt_driver_in_ram, inline(always))] pub fn stop(self) -> Result, (Error, Channel<'ch, Blocking, Tx>)> { self.stop_impl(true) @@ -1619,7 +1616,7 @@ impl<'ch> ContinuousTxTransaction<'ch> { } } - /// Check if the `loopcount` interrupt bit is set. + /// Returns whether the `loopcount` interrupt bit is set. /// /// Whether this implies that the transmission has stopped depends on the [`LoopMode`] value /// provided when starting it. @@ -1629,7 +1626,7 @@ impl<'ch> ContinuousTxTransaction<'ch> { } } -/// RMT Channel Creator +/// RMT Channel Creator. #[derive(Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub struct ChannelCreator<'ch, Dm, const CHANNEL: u8> @@ -1637,7 +1634,7 @@ where Dm: crate::DriverMode, { // Conceptually, this retains a reference to the main driver struct, even when the - // `ChannelCreator` is taken out of it and the `Rmt` dropped. This prevents re-inititalizing + // `ChannelCreator` is taken out of it and the `Rmt` dropped. This prevents re-initializing // the `Rmt` and obtaining a duplicate `ChannelCreator`. _rmt: PhantomData>, @@ -1676,7 +1673,7 @@ where } } - /// Reborrow this channel creator for a shorter lifetime `'a`. + /// Reborrows this channel creator for a shorter lifetime `'a`. pub fn reborrow<'a>(&'a mut self) -> ChannelCreator<'a, Dm, CHANNEL> { Self { _rmt: PhantomData, @@ -1700,26 +1697,26 @@ where } } -/// Loop mode for continuous transmission +/// Loop mode for continuous transmission. /// /// Depending on hardware support, the `loopcount` interrupt and automatic stopping of the /// transmission upon reaching a specified loop count may not be available. #[derive(Copy, Clone, Debug, PartialEq, Eq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum LoopMode { - /// Repeat until explicitly stopped. + /// Repeats until explicitly stopped. Infinite, // FIXME: Does continuous tx trigger the End interrupt on each repetition such that it could // be used to emulate the LoopCount interrupt on devices that lack it? - /// Repeat until explicitly stopped, and assert the loop count interrupt upon completing the + /// Repeats until explicitly stopped, and asserts the loop count interrupt upon completing the /// given number of iterations. /// /// Loop counts larger than [`MAX_TX_LOOPCOUNT`] will result in an error. #[cfg(rmt_has_tx_loop_count)] InfiniteWithInterrupt(u16), - /// Repeat for the given number of iterations, and also set the loop count interrupt flag upon + /// Repeats for the given number of iterations, and also sets the loop count interrupt flag upon /// completion. /// /// If the iteration count is 0, the transaction will complete immediately without @@ -1743,12 +1740,11 @@ impl LoopMode { } } -/// Channel in TX mode +/// Channel in TX mode. impl<'ch> Channel<'ch, Blocking, Tx> { - /// Start transmitting the given pulse code sequence. - /// This returns a [`TxTransaction`] which can be used to wait for - /// the transaction to complete and get back the channel for further - /// use. + /// Starts transmitting the given pulse code sequence. + /// Returns a [`TxTransaction`] that can be used to wait for the transaction to + /// complete and get back the channel for further use. #[cfg_attr(place_rmt_driver_in_ram, ram)] pub fn transmit<'data>( self, @@ -1775,10 +1771,10 @@ impl<'ch> Channel<'ch, Blocking, Tx> { }) } - /// Start transmitting the given pulse code continuously. + /// Starts transmitting the given pulse code continuously. /// - /// This returns a [`ContinuousTxTransaction`] which can be used to stop the - /// ongoing transmission and get back the channel for further use. + /// Returns a [`ContinuousTxTransaction`] that can be used to stop the ongoing + /// transmission and get back the channel for further use. /// /// The `mode` argument determines whether transmission will continue until explicitly stopped /// or for a fixed number of iterations; see [`LoopMode`] for more details. @@ -1828,7 +1824,7 @@ impl<'ch> Channel<'ch, Blocking, Tx> { } } -/// RX transaction instance +/// RX transaction instance. #[must_use = "transactions need to be `poll()`ed / `wait()`ed for to ensure progress"] #[derive(Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] @@ -1856,10 +1852,11 @@ impl<'ch> RxTransaction<'ch, '_> { Some(Event::End | Event::Error) => { // Do not clear the interrupt flags here: Subsequent calls of wait() must // be able to observe them if this is currently called via poll() - // Rx is stopped already, but we do need to clear the rx enable flag! - // Otherwise the next `raw.update` call will start it even though that - // might not be desired. + // Rx is stopped already, but we do need to clear the rx enable flag and + // apply that right away! Otherwise the next `raw.update` call would do so + // while starting the next transaction, which breaks it when SCLK is slow. raw.stop_rx(false); + raw.update(); // `RmtReader::read()` is safe to call even if `poll_internal` is called repeatedly // after the receiver finished since it returns immediately if already done. @@ -1881,7 +1878,7 @@ impl<'ch> RxTransaction<'ch, '_> { status } - /// Check receive status + /// Checks receive status. /// /// Returns whether reception has ended (whether successfully or with an /// error). In that case, a subsequent call to `wait()` returns immediately. @@ -1890,7 +1887,7 @@ impl<'ch> RxTransaction<'ch, '_> { matches!(self.poll_internal(), Some(Event::Error | Event::End)) } - /// Wait for the transaction to complete + /// Waits for the transaction to complete. #[cfg_attr(place_rmt_driver_in_ram, inline(always))] // The return type isn't nice, but the blocking API needs a broader redesign anyway. #[allow(clippy::type_complexity)] @@ -1914,7 +1911,7 @@ impl<'ch> RxTransaction<'ch, '_> { } } -/// Channel is RX mode +/// Channel is RX mode. impl<'ch> Channel<'ch, Blocking, Rx> { #[procmacros::doc_replace( "rx_size_limit" => { @@ -1922,9 +1919,9 @@ impl<'ch> Channel<'ch, Blocking, Rx> { _ => "" } )] - /// Start receiving pulse codes into the given buffer. - /// This returns a [RxTransaction] which can be used to wait for receive to - /// complete and get back the channel for further use. + /// Starts receiving pulse codes into the given buffer. + /// Returns a [`RxTransaction`] that can be used to wait for receive to complete + /// and get back the channel for further use. /// /// # {rx_size_limit} #[cfg_attr(place_rmt_driver_in_ram, ram)] @@ -2007,9 +2004,9 @@ impl core::future::Future for TxFuture<'_> { } } -/// TX channel in async mode +/// TX channel in async mode. impl Channel<'_, Async, Tx> { - /// Start transmitting the given pulse code sequence. + /// Starts transmitting the given pulse code sequence. #[cfg_attr(place_rmt_driver_in_ram, ram)] pub fn transmit(&mut self, mut data: &[PulseCode]) -> impl Future> { let raw = self.raw; @@ -2074,10 +2071,11 @@ impl core::future::Future for RxFuture<'_> { let result = match raw.get_rx_status() { // Read all available data also on error Some(ev @ (Event::End | Event::Error)) => { - // Rx is stopped already, but we do need to clear the rx enable flag! - // Otherwise the next `raw.update` call will start it even though that - // might not be desired. + // Rx is stopped already, but we do need to clear the rx enable flag and + // apply that right away! Otherwise the next `raw.update` call would do so + // while starting the next transaction, which breaks it when SCLK is slow. raw.stop_rx(false); + raw.update(); if !this.reader.read(&mut this.data, raw, true) { Err(Error::ReceiverError) @@ -2109,7 +2107,7 @@ impl core::future::Future for RxFuture<'_> { } } -/// RX channel in async mode +/// RX channel in async mode. impl Channel<'_, Async, Rx> { #[procmacros::doc_replace( "rx_size_limit" => { @@ -2117,7 +2115,7 @@ impl Channel<'_, Async, Rx> { _ => "" } )] - /// Start receiving a pulse code sequence. + /// Starts receiving a pulse code sequence. /// /// # {rx_size_limit} #[cfg_attr(place_rmt_driver_in_ram, ram)] @@ -2256,6 +2254,7 @@ macro_rules! max_from_register_spec { #[cfg(not(any(esp32, esp32s2)))] mod chip_specific { use enumset::EnumSet; + use portable_atomic::{AtomicU32, Ordering}; #[cfg(place_rmt_driver_in_ram)] use procmacros::ram; @@ -2276,6 +2275,9 @@ mod chip_specific { }; use crate::{peripherals::RMT, soc::clocks, time::Rate}; + // Time to wait after a `conf_update`, see `DynChannelAccess::update`. + static CONF_UPDATE_DELAY_US: AtomicU32 = AtomicU32::new(0); + pub(super) fn validate_clock( source: ClockSource, frequency: Rate, @@ -2297,7 +2299,17 @@ mod chip_specific { Ok((div, actual_frequency)) } - pub(super) fn configure_clock(source: ClockSource, div: u8) { + pub(super) fn configure_clock(source: ClockSource, div: u8, frequency: Rate) { + // Synchronizing a `conf_update` into the SCLK domain takes about one SCLK cycle, wait for + // two to leave some margin. For a fast SCLK, this is shorter than the register accesses + // following the update, so don't delay at all. + let delay_us = if frequency < Rate::from_mhz(10) { + 2_000_000u32.div_ceil(frequency.as_hz()) + } else { + 0 + }; + CONF_UPDATE_DELAY_US.store(delay_us, Ordering::Relaxed); + clocks::ClockTree::with(|clocks| { clocks::RmtInstance::Rmt.configure_sclk(clocks, source); }); @@ -2397,6 +2409,14 @@ mod chip_specific { rmt.ch_rx_conf1(ch_idx) .modify(|_, w| w.conf_update().set_bit()); } + + // The update needs to be synchronized into the SCLK domain before it takes effect. + // Register writes or another update during that time may be lost, which breaks + // transactions in unexpected ways when SCLK is slow. + let delay_us = CONF_UPDATE_DELAY_US.load(Ordering::Relaxed); + if delay_us > 0 { + crate::rom::ets_delay_us(delay_us); + } } pub fn set_divider(self, divider: u8) { @@ -2454,17 +2474,8 @@ mod chip_specific { // documented in re-export below #[allow(missing_docs)] - pub const MAX_TX_LOOPCOUNT: u16 = { - // TODO: unify naming in PAC - cfg_select! { - any(esp32p4, esp32s31) => { - max_from_register_spec!(u16, ch_tx_lim, CH_TX_LIM_SPEC, TX_LOOP_NUM_CH_W) - } - _ => { - max_from_register_spec!(u16, ch_tx_lim, CH_TX_LIM_SPEC, TX_LOOP_NUM_W) - } - } - }; + pub const MAX_TX_LOOPCOUNT: u16 = + max_from_register_spec!(u16, ch_tx_lim, CH_TX_LIM_SPEC, TX_LOOP_NUM_W); impl DynChannelAccess { #[inline(always)] @@ -2859,7 +2870,7 @@ mod chip_specific { Ok((1, frequency)) } - pub(super) fn configure_clock(source: ClockSource, _div: u8) { + pub(super) fn configure_clock(source: ClockSource, _div: u8, _frequency: Rate) { let rmt = RMT::regs(); clocks::ClockTree::with(|clocks| { diff --git a/esp-hal/src/rng/mod.rs b/esp-hal/src/rng/mod.rs index d004970b9a2..0664905431e 100644 --- a/esp-hal/src/rng/mod.rs +++ b/esp-hal/src/rng/mod.rs @@ -6,9 +6,9 @@ //! ## Overview //! //! The Random Number Generator (RNG) module provides an interface to generate -//! random numbers using the RNG peripheral on ESP chips. This driver allows you -//! to generate random numbers that can be used for various cryptographic, -//! security, or general-purpose applications. +//! random numbers using the RNG peripheral on ESP chips. The driver generates +//! random numbers that can be used for various cryptographic, security, or +//! general-purpose applications. //! //! There are certain pre-conditions which must be met in order for the RNG to //! produce *true* random numbers. @@ -82,7 +82,7 @@ pub use trng::*; /// (Pseudo-)Random Number Generator. /// -/// To generate pseudo-random numbers, you can create [`Rng`] at any time. +/// [`Rng`] can be created at any time to generate pseudo-random numbers #[cfg_attr( rng_trng_supported, doc = r"To generate true random numbers, see [`Trng`]." @@ -102,7 +102,7 @@ impl Rng { #[procmacros::doc_replace] /// Reads currently available `u32` integer from `RNG`. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -123,7 +123,7 @@ impl Rng { /// Reads enough bytes from hardware random number generator to fill /// `buffer`. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} diff --git a/esp-hal/src/rng/trng.rs b/esp-hal/src/rng/trng.rs index 084ba02c4dc..90aed6f6637 100644 --- a/esp-hal/src/rng/trng.rs +++ b/esp-hal/src/rng/trng.rs @@ -29,11 +29,11 @@ impl<'d> TrngSource<'d> { /// /// # Panics /// - /// This function panics if the internal counter overflows. + /// Panics if the internal counter overflows. /// /// # Safety /// - /// This function must only be called after a new entropy source has been enabled. + /// Must only be called after a new entropy source has been enabled. #[instability::unstable] pub unsafe fn increase_entropy_source_counter() { if TRNG_ENABLED.fetch_add(1, Ordering::Relaxed) == usize::MAX { @@ -43,16 +43,16 @@ impl<'d> TrngSource<'d> { /// Decreases the internal entropy source counter. /// - /// This function should only be called **before** disabling an entropy source (such as the + /// Should only be called **before** disabling an entropy source (such as the /// radio). /// - /// This function should only be called as many times as + /// Should only be called as many times as /// [`TrngSource::increase_entropy_source_counter`] was called. /// /// # Panics /// - /// This function panics if the internal counter underflows. Dropping the `TrngSource` will - /// panic if this function is called more times than + /// Panics if the internal counter underflows. Dropping the `TrngSource` panics + /// if this method is called more times than /// [`TrngSource::increase_entropy_source_counter`]. #[instability::unstable] pub fn decrease_entropy_source_counter(_private: crate::private::Internal) { @@ -70,7 +70,7 @@ impl<'d> TrngSource<'d> { /// Returns whether the TRNG is currently enabled. /// - /// Note that entropy sources can be disabled at any time. + /// Entropy sources can be disabled at any time. #[instability::unstable] pub fn is_enabled() -> bool { TRNG_ENABLED.load(Ordering::Relaxed) > 0 @@ -78,12 +78,14 @@ impl<'d> TrngSource<'d> { /// Attempts to disable the TRNG. /// - /// This function returns `Err(TrngSource)` if there are TRNG users. - /// /// # Panics /// - /// This function panics if the TRNG is not enabled (i.e. it has been disabled by calling + /// Panics if the TRNG is not enabled (i.e. it has been disabled by calling /// [`TrngSource::decrease_entropy_source_counter`] incorrectly). + /// + /// # Errors + /// + /// [`TrngSource`] when there are TRNG users. #[instability::unstable] pub fn try_disable(self) -> Result<(), Self> { if TRNG_ENABLED @@ -121,26 +123,25 @@ impl Drop for TrngSource<'_> { pub enum TrngError { /// The [`TrngSource`] is not enabled. /// - /// This error is returned by [`Trng::try_new`] when the RNG is not configured - /// to generate true random numbers. + /// Returned by [`Trng::try_new`] when the RNG is not configured to generate + /// true random numbers. TrngSourceNotEnabled, } #[cfg_attr(docsrs, procmacros::doc_replace( - "analog_pin" => gpio_for_signal!(ADC1_CH4), + "analog_pin" => gpio_for_signal!(ADC1_CH3), ))] /// True Random Number Generator (TRNG) /// -/// The `Trng` struct represents a true random number generator that combines -/// the randomness from the hardware RNG and an ADC. This struct provides -/// methods to generate random numbers and fill buffers with random bytes. -/// Due to pulling the entropy source from the ADC, it uses the associated -/// registers, so to use TRNG we need to "occupy" the ADC peripheral. +/// The `Trng` struct represents a true random number generator that combines randomness from the +/// hardware RNG and an ADC. Provides methods to generate random numbers and fill buffers with +/// random bytes. Because entropy is sourced from the ADC, the associated registers are used and +/// the ADC peripheral must be occupied. /// -/// To generate true random numbers, an instance of [`TrngSource`] is required. Once created, you -/// can create [`Trng`] instances at any time, as long as the [`TrngSource`] is alive. +/// To generate true random numbers, an instance of [`TrngSource`] is required. Once created, +/// [`Trng`] instances can be created at any time, as long as the [`TrngSource`] is alive /// -/// ## Example +/// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -168,7 +169,7 @@ pub enum TrngError { /// /// let mut adc1_config = AdcConfig::new(); /// let mut adc1_pin = adc1_config.enable_pin(peripherals.__analog_pin__, Attenuation::_11dB); -/// let mut adc1 = Adc::new(peripherals.ADC1, adc1_config); +/// let mut adc1 = Adc::new(peripherals.ADC1, adc1_config)?; /// let pin_value = adc1.read_oneshot(&mut adc1_pin)?; /// /// // Now we can only generate pseudo-random numbers... @@ -196,10 +197,11 @@ impl Clone for Trng { } impl Trng { - /// Attempts to create a new True Random Number Generator (TRNG) instance. + /// Creates a new True Random Number Generator (TRNG) instance. + /// + /// # Errors /// - /// This function returns a new `Trng` instance on success, or an error if the - /// [`TrngSource`] is not active. + /// [`TrngError::TrngSourceNotEnabled`] when the [`TrngSource`] is not active. #[inline] #[instability::unstable] pub fn try_new() -> Result { diff --git a/esp-hal/src/rom/regi2c.rs b/esp-hal/src/rom/regi2c.rs index 56d849f61da..72e76d8950c 100644 --- a/esp-hal/src/rom/regi2c.rs +++ b/esp-hal/src/rom/regi2c.rs @@ -57,25 +57,29 @@ pub(crate) struct RawRegI2cField { impl RawRegI2cField { #[allow(unused)] pub const fn new(register: RegI2cRegister, msb: u8, lsb: u8) -> Self { - ::core::assert!(msb < 8 + lsb); + ::core::assert!(lsb <= msb && msb < 8); Self { register, msb, lsb } } + const fn mask(&self) -> u8 { + const fn lower_n_bits(bits: u8) -> u8 { + !((u32::MAX << bits) as u8) + } + + lower_n_bits(self.msb - self.lsb + 1) + } + #[allow(unused)] pub fn read(&self) -> u8 { - let reg_raw = self.register.read(); - (reg_raw >> self.lsb) & !(u8::MAX << (self.msb - self.lsb + 1)) + (self.register.read() >> self.lsb) & self.mask() } #[allow(unused)] pub fn write_field(&self, data: u8) { + let mask = self.mask() << self.lsb; let bits = self.register.read(); - - let unwritten_bits = (!(u32::MAX << self.lsb) | (u32::MAX << (self.msb + 1))) as u8; - let data_mask = !(u32::MAX << (self.msb - self.lsb + 1)) as u8; - let data_bits = (data & data_mask) << self.lsb; - - self.register.write_reg((bits & unwritten_bits) | data_bits); + self.register + .write_reg((bits & !mask) | ((data << self.lsb) & mask)); } } diff --git a/esp-hal/src/rsa/mod.rs b/esp-hal/src/rsa/mod.rs index 4f1ebf01236..ca286d93156 100644 --- a/esp-hal/src/rsa/mod.rs +++ b/esp-hal/src/rsa/mod.rs @@ -33,7 +33,7 @@ use crate::{ pac, peripherals::RSA, rtc_cntl::WakeLock, - system::{GenericPeripheralGuard, Peripheral as PeripheralEnable}, + system::{CryptoClockGuard, GenericPeripheralGuard, Peripheral as PeripheralEnable}, trm_markdown_link, work_queue::{self, Status, VTable, WorkQueue, WorkQueueDriver, WorkQueueFrontend}, }; @@ -45,6 +45,53 @@ pub struct Rsa<'d, Dm: DriverMode> { _guard: RsaGuard, } +/// RSA accelerator configuration. +/// +/// The default is the most secure: constant time on and search acceleration off. The ESP32 has +/// neither option, so its `Config` is empty. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, procmacros::BuilderLite)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[non_exhaustive] +pub struct Config { + /// Constant time operation for modular exponentiation. + /// + /// Turning it off makes modular exponentiation faster for an exponent with many 0 bits, + /// and exposes the exponent to timing-based side-channel attacks. Turn it off only for a + /// public exponent, such as when verifying a signature. + /// + /// Default value: `true`. + #[cfg(not(rsa_version = "1"))] + constant_time: bool, + + /// Search acceleration for modular exponentiation. + /// + /// Turning it on makes modular exponentiation faster by skipping the exponent's bits above + /// its most significant set bit, and exposes the exponent's length. Turn it on only for a + /// public exponent, such as when verifying a signature. + /// + /// Default value: `false`. + #[cfg(not(rsa_version = "1"))] + search_acceleration: bool, +} + +#[cfg_attr(rsa_version = "1", expect(clippy::derivable_impls))] +impl Default for Config { + fn default() -> Self { + Self { + #[cfg(not(rsa_version = "1"))] + constant_time: true, + #[cfg(not(rsa_version = "1"))] + search_acceleration: false, + } + } +} + +/// RSA configuration error. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[non_exhaustive] +pub enum ConfigError {} + // There are two distinct peripheral versions: ESP32, and all else. There is a naming split in the // later devices, and they use different (memory size, operand size increment) parameters, but they // are largely the same. @@ -57,10 +104,12 @@ const WORDS_PER_INCREMENT: u32 = property!("rsa.size_increment") / 32; struct RsaGuard { _guard: GenericPeripheralGuard<{ PeripheralEnable::Rsa as u8 }>, + _clock_guard: CryptoClockGuard, } impl RsaGuard { fn new() -> Self { + let _clock_guard = CryptoClockGuard::new(); let _guard = GenericPeripheralGuard::new(); cfg_select! { rsa_version = "1" => {} @@ -76,7 +125,10 @@ impl RsaGuard { } } - Self { _guard } + Self { + _guard, + _clock_guard, + } } } @@ -107,11 +159,11 @@ impl Drop for RsaGuard { } impl<'d> Rsa<'d, Blocking> { - /// Create a new instance in [Blocking] mode. + /// Creates a new instance in [Blocking] mode, with the given configuration. /// /// Optionally an interrupt handler can be bound. - pub fn new(rsa: RSA<'d>) -> Self { - let this = Self { + pub fn new(rsa: RSA<'d>, config: Config) -> Result { + let mut this = Self { rsa, phantom: PhantomData, _guard: RsaGuard::new(), @@ -119,7 +171,8 @@ impl<'d> Rsa<'d, Blocking> { while !this.ready() {} - this + this.apply_config(&config)?; + Ok(this) } /// Reconfigures the RSA driver to operate in asynchronous mode. @@ -134,7 +187,7 @@ impl<'d> Rsa<'d, Blocking> { } } - /// Enables/disables rsa interrupt. + /// Enables or disables the RSA interrupt. /// /// When enabled rsa peripheral would generate an interrupt when a operation /// is finished. @@ -144,8 +197,7 @@ impl<'d> Rsa<'d, Blocking> { /// Registers an interrupt handler for the RSA peripheral. /// - /// Note that this will replace any previously registered interrupt - /// handlers. + /// Replaces any previously registered interrupt handlers. #[instability::unstable] pub fn set_interrupt_handler(&mut self, handler: InterruptHandler) { self.rsa.disable_peri_interrupt_on_all_cores(); @@ -163,7 +215,7 @@ impl crate::interrupt::InterruptConfigurable for Rsa<'_, Blocking> { } impl<'d> Rsa<'d, Async> { - /// Create a new instance in [crate::Blocking] mode. + /// Reconfigures the RSA driver to operate in [`Blocking`] mode. pub fn into_blocking(self) -> Rsa<'d, Blocking> { self.internal_enable_disable_interrupt(false); self.rsa.disable_peri_interrupt_on_all_cores(); @@ -185,10 +237,7 @@ impl<'d, Dm: DriverMode> Rsa<'d, Dm> { self.rsa.register_block() } - /// After the RSA accelerator is released from reset, the memory blocks - /// needs to be initialized, only after that peripheral should be used. - /// This function would return without an error if the memory is - /// initialized. + /// Returns whether RSA memory blocks are initialized after reset. fn ready(&self) -> bool { low_level::ready(self.regs()) } @@ -213,7 +262,7 @@ impl<'d, Dm: DriverMode> Rsa<'d, Dm> { low_level::clear_interrupt(self.regs()); } - /// Checks if the RSA peripheral is idle. + /// Returns whether the RSA peripheral is idle. fn is_idle(&self) -> bool { low_level::is_idle(self.regs()) } @@ -303,42 +352,28 @@ impl<'d, Dm: DriverMode> Rsa<'d, Dm> { self.read_out(outbuf); } - /// Enables/disables constant time operation. - /// - /// Disabling constant time operation increases the performance of modular - /// exponentiation by simplifying the calculation concerning the 0 bits - /// of the exponent. I.e. the less the Hamming weight, the greater the - /// performance. + /// Applies a new configuration. /// - /// Note: this compromises security by enabling timing-based side-channel attacks. - /// - /// For more information refer to the + /// For more information on the options, refer to the #[doc = trm_markdown_link!("rsa")] - #[cfg(not(rsa_version = "1"))] - pub fn disable_constant_time(&mut self, disable: bool) { - self.regs() - .constant_time() - .write(|w| w.constant_time().bit(disable)); + pub fn apply_config(&mut self, config: &Config) -> Result<(), ConfigError> { + self.write_config(config); + Ok(()) } - /// Enables/disables search acceleration. - /// - /// When enabled it would increase the performance of modular - /// exponentiation by discarding the exponent's bits before the most - /// significant set bit. - /// - /// Note: this compromises security by effectively decreasing the key length. - /// - /// For more information refer to the - #[doc = trm_markdown_link!("rsa")] - #[cfg(not(rsa_version = "1"))] - pub fn search_acceleration(&mut self, enable: bool) { - self.regs() - .search_enable() - .write(|w| w.search_enable().bit(enable)); + fn write_config(&mut self, _config: &Config) { + #[cfg(not(rsa_version = "1"))] + { + self.regs() + .constant_time() + .write(|w| w.constant_time().bit(_config.constant_time)); + self.regs() + .search_enable() + .write(|w| w.search_enable().bit(_config.search_acceleration)); + } } - /// Checks if the search functionality is enabled in the RSA hardware. + /// Returns whether the search functionality is enabled in the RSA hardware. #[cfg(not(rsa_version = "1"))] fn is_search_enabled(&mut self) -> bool { self.regs() @@ -394,10 +429,10 @@ pub mod operand_sizes { ); } -/// Support for RSA peripheral's modular exponentiation feature that could be +/// Support for the RSA peripheral's modular exponentiation feature that could be /// used to find the `(base ^ exponent) mod modulus`. /// -/// Each operand is a little endian byte array of the same size +/// Each operand is a little endian byte array of the same size. pub struct RsaModularExponentiation<'a, 'd, T: RsaMode, Dm: DriverMode> { rsa: &'a mut Rsa<'d, Dm>, phantom: PhantomData, @@ -478,10 +513,10 @@ where } } -/// Support for RSA peripheral's modular multiplication feature that could be +/// Support for the RSA peripheral's modular multiplication feature that could be /// used to find the `(operand a * operand b) mod modulus`. /// -/// Each operand is a little endian byte array of the same size +/// Each operand is a little endian byte array of the same size. pub struct RsaModularMultiplication<'a, 'd, T, Dm> where T: RsaMode, @@ -553,10 +588,10 @@ where } } -/// Support for RSA peripheral's large number multiplication feature that could +/// Support for the RSA peripheral's large number multiplication feature that could /// be used to find the `operand a * operand b`. /// -/// Each operand is a little endian byte array of the same size +/// Each operand is a little endian byte array of the same size. pub struct RsaMultiplication<'a, 'd, T, Dm> where T: RsaMode + Multi, @@ -776,12 +811,12 @@ enum RsaBackendState<'d> { /// RSA processing backend. /// /// The backend processes work items placed in the RSA work queue. The backend needs to be created -/// and started for operations to be processed. This allows you to perform operations on the RSA -/// accelerator without carrying around the peripheral singleton, or the driver. +/// and started for operations to be processed. Operations can be performed on the RSA accelerator +/// without carrying around the peripheral singleton, or the driver. /// /// The [`RsaContext`] struct can enqueue work items that this backend will process. /// -/// ## Example +/// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -811,7 +846,7 @@ impl<'d> RsaBackend<'d> { #[procmacros::doc_replace] /// Creates a new RSA backend. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -832,7 +867,7 @@ impl<'d> RsaBackend<'d> { /// /// The driver stops operating when the returned object is dropped. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -879,11 +914,7 @@ impl<'d> RsaBackend<'d> { work_queue::Poll::Pending(true) } RsaBackendState::Ready(mut rsa) => { - #[cfg(not(rsa_version = "1"))] - { - rsa.disable_constant_time(!item.constant_time); - rsa.search_acceleration(item.search_acceleration); - } + rsa.write_config(&item.config); match item.operation { RsaOperation::Multiplication { x, y } => { @@ -945,7 +976,7 @@ impl<'d> RsaBackend<'d> { rsa.write_r(unsafe { r_inv.as_ref() }); #[cfg(not(rsa_version = "1"))] - if item.search_acceleration { + if item.config.search_acceleration { fn find_search_pos(exponent: &[u32]) -> u32 { for (i, byte) in exponent.iter().rev().enumerate() { if *byte == 0 { @@ -1031,11 +1062,7 @@ impl<'t, 'd> RsaWorkQueueDriver<'t, 'd> { #[derive(Clone)] struct RsaWorkItem { - // Acceleration options - #[cfg(not(rsa_version = "1"))] - search_acceleration: bool, - #[cfg(not(rsa_version = "1"))] - constant_time: bool, + config: Config, // The operation to execute. operation: RsaOperation, @@ -1109,10 +1136,7 @@ impl RsaContext { pub fn new() -> Self { Self { frontend: WorkQueueFrontend::new(RsaWorkItem { - #[cfg(not(rsa_version = "1"))] - search_acceleration: false, - #[cfg(not(rsa_version = "1"))] - constant_time: true, + config: Config::default(), operation: RsaOperation::Multiplication { x: NonNull::from(&[]), y: NonNull::from(&[]), @@ -1129,12 +1153,12 @@ impl RsaContext { /// exponentiation by discarding the exponent's bits before the most /// significant set bit. /// - /// > ⚠️ Note: this compromises security by effectively decreasing the key length. + /// Compromises security by effectively decreasing the key length. /// /// For more information refer to the #[doc = trm_markdown_link!("rsa")] pub fn enable_search_acceleration(&mut self) { - self.frontend.data_mut().search_acceleration = true; + self.frontend.data_mut().config.search_acceleration = true; } #[cfg(not(rsa_version = "1"))] @@ -1145,12 +1169,12 @@ impl RsaContext { /// of the exponent. I.e. the less the Hamming weight, the greater the /// performance. /// - /// > ⚠️ Note: this compromises security by enabling timing-based side-channel attacks. + /// Compromises security by enabling timing-based side-channel attacks. /// /// For more information refer to the #[doc = trm_markdown_link!("rsa")] pub fn enable_acceleration(&mut self) { - self.frontend.data_mut().constant_time = false; + self.frontend.data_mut().config.constant_time = false; } fn post(&mut self) -> RsaHandle<'_> { @@ -1220,11 +1244,11 @@ impl RsaContext { /// # {after_snippet} /// ``` /// - /// The calculation is done asynchronously. This function returns an [`RsaHandle`] that can be - /// used to poll the status of the calculation, to wait for it to finish, or to cancel the - /// operation (by dropping the handle). + /// Returns an [`RsaHandle`] for the asynchronous calculation that can be used to poll the + /// status of the calculation, to wait for it to finish, or to cancel the operation (by + /// dropping the handle). /// - /// When the operation is completed, the result will be stored in `result`. + /// When the operation is completed, the result is stored in `result` pub fn modular_exponentiate<'t, OP>( &'t mut self, x: &'t OP::InputType, @@ -1258,11 +1282,11 @@ impl RsaContext { /// For an example how these values can be calculated and used, see /// [Self::modular_exponentiate]. /// - /// The calculation is done asynchronously. This function returns an [`RsaHandle`] that can be - /// used to poll the status of the calculation, to wait for it to finish, or to cancel the - /// operation (by dropping the handle). + /// Returns an [`RsaHandle`] for the asynchronous calculation that can be used to poll the + /// status of the calculation, to wait for it to finish, or to cancel the operation (by + /// dropping the handle). /// - /// When the operation is completed, the result will be stored in `result`. + /// When the operation is completed, the result is stored in `result` pub fn modular_multiply<'t, OP>( &'t mut self, x: &'t OP::InputType, @@ -1289,14 +1313,14 @@ impl RsaContext { #[procmacros::doc_replace] /// Starts a multiplication operation, performing `Z = X * Y`. /// - /// The calculation is done asynchronously. This function returns an [`RsaHandle`] that can be - /// used to poll the status of the calculation, to wait for it to finish, or to cancel the - /// operation (by dropping the handle). + /// Returns an [`RsaHandle`] for the asynchronous calculation that can be used to poll the + /// status of the calculation, to wait for it to finish, or to cancel the operation (by + /// dropping the handle). /// - /// When the operation is completed, the result will be stored in `result`. The `result` is - /// twice as wide as the inputs. + /// When the operation is completed, the result is stored in `result`. The `result` is twice as + /// wide as the inputs. /// - /// ## Example + /// # Examples /// /// ```rust,no_run /// # {before_snippet} diff --git a/esp-hal/src/rtc_cntl/cpu_retention/memory.rs b/esp-hal/src/rtc_cntl/cpu_retention/memory.rs new file mode 100644 index 00000000000..de1ef3baa94 --- /dev/null +++ b/esp-hal/src/rtc_cntl/cpu_retention/memory.rs @@ -0,0 +1,176 @@ +//! Shared CPU retention buffer types and the one-shot install API. + +use core::{ + cell::UnsafeCell, + mem::MaybeUninit, + ptr::{self, NonNull}, +}; + +use portable_atomic::{AtomicPtr, Ordering}; +use static_cell::ConstStaticCell; + +use crate::rtc_cntl::sleep::LowPower; + +cfg_select! { + cpu_retention = "software" => { + pub(crate) use super::software::BUFFER_SIZE; + } + _ => { + pub(crate) const BUFFER_SIZE: usize = property!("sleep.cpu_retention_mem_size"); + + /// `repr(align)` takes a literal, so the buffer takes the strictest alignment of every + /// chip. The alignment then needs no check at run time. + const _: () = ::core::assert!(property!("sleep.cpu_retention_mem_align") <= 16); + + const MEM_START: usize = property!("sleep.cpu_retention_mem_start"); + const MEM_END: usize = property!("sleep.cpu_retention_mem_end"); + } +} + +static INSTALLED: AtomicPtr = AtomicPtr::new(ptr::null_mut()); + +/// Memory that light sleep uses to retain the CPU domain. +/// +/// This storage must be placed to `#[ram(reclaimed, unstable(zeroed))]`, then +/// a static mutable reference to [`CpuRetentionMemory`] can be taken out of it. +#[instability::unstable] +pub struct CpuRetentionStorage { + inner: ConstStaticCell, +} + +impl CpuRetentionStorage { + /// Creates storage for the retention memory. + #[instability::unstable] + pub const fn new() -> Self { + Self { + inner: ConstStaticCell::new(CpuRetentionMemory { + storage: UnsafeCell::new(MaybeUninit::uninit()), + }), + } + } + + /// Takes the reference to the retention memory. + /// + /// Can only be called once. + #[instability::unstable] + pub fn take(&'static self) -> &'static mut CpuRetentionMemory { + self.inner.take() + } +} + +#[instability::unstable] +impl Default for CpuRetentionStorage { + fn default() -> Self { + Self::new() + } +} + +// SAFETY: ConstStaticCell is a `MaybeUninit` buffer, and an AtomicBool strapped together, +// both are safe to be zero-initialized. +unsafe impl bytemuck::Zeroable for CpuRetentionStorage {} + +/// Memory that light sleep uses to retain the CPU domain. +/// +/// The sleep path writes this memory while the CPU domain has no power, so the buffer gives no way +/// to read or write its contents through safe Rust. +/// +/// Install the buffer with [`LowPower::install_cpu_retention_memory`]. The buffer must live in +/// internal RAM that stays powered across light sleep. The [`#[ram(reclaimed)]`][crate::ram] +/// attribute places a static inside the reachable range on chips that use the retention DMA. +#[repr(align(16))] +#[instability::unstable] +pub struct CpuRetentionMemory { + storage: UnsafeCell>, +} + +impl CpuRetentionMemory { + pub(crate) fn as_mut_ptr(&self) -> *mut u8 { + self.storage.get().cast() + } +} + +/// The reason why [`LowPower::install_cpu_retention_memory`] refused a buffer. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[instability::unstable] +#[non_exhaustive] +pub enum CpuRetentionMemoryError { + /// The buffer is not inside the range that retention needs. + #[cfg(not(cpu_retention = "software"))] + OutOfRange, + /// The driver holds a retention buffer already. + AlreadyInstalled, +} + +#[instability::unstable] +impl core::error::Error for CpuRetentionMemoryError {} + +#[instability::unstable] +impl core::fmt::Display for CpuRetentionMemoryError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + #[cfg(not(cpu_retention = "software"))] + Self::OutOfRange => write!( + f, + "the buffer is outside the retention memory range (0x{MEM_START:X}..0x{MEM_END:X})" + ), + Self::AlreadyInstalled => write!(f, "a retention buffer is installed already"), + } + } +} + +impl LowPower<'_> { + #[procmacros::doc_replace] + /// Gives light sleep the memory that it uses to retain the CPU domain. + /// + /// Light sleep powers the CPU domain down only after it has this memory. The memory stays with + /// the driver for the life of the program, and a second call is an error, because the sleep + /// path can hold one buffer only. + /// + /// # Errors + /// + /// Returns [`CpuRetentionMemoryError`] if the driver holds a buffer already, or if the buffer + /// is not inside the range that retention needs. The + /// [`#[ram(reclaimed, unstable(zeroed))]`][crate::ram] attribute places a static inside that + /// range on DMA chips. + /// + /// # Examples + /// + /// ```rust, no_run + /// # {before_snippet} + /// use esp_hal::rtc_cntl::{CpuRetentionStorage, sleep::LowPower}; + /// + /// // #[esp_hal::ram(reclaimed, unstable(zeroed))] + /// static RETENTION: CpuRetentionStorage = CpuRetentionStorage::new(); + /// + /// let mut lpwr = LowPower::new(peripherals.LPWR); + /// lpwr.install_cpu_retention_memory(RETENTION.take())?; + /// # {after_snippet} + /// ``` + #[instability::unstable] + pub fn install_cpu_retention_memory( + &mut self, + memory: &'static mut CpuRetentionMemory, + ) -> Result<(), CpuRetentionMemoryError> { + let memory = memory.as_mut_ptr(); + + #[cfg(not(cpu_retention = "software"))] + { + let start = memory as usize; + if start < MEM_START || start + BUFFER_SIZE > MEM_END { + return Err(CpuRetentionMemoryError::OutOfRange); + } + } + + INSTALLED + .compare_exchange(ptr::null_mut(), memory, Ordering::AcqRel, Ordering::Acquire) + .map(|_| ()) + .map_err(|_| CpuRetentionMemoryError::AlreadyInstalled) + } +} + +pub(crate) fn installed_buffer_ptr() -> Option> { + let memory = INSTALLED.load(Ordering::Acquire); + + NonNull::new(memory.cast::()) +} diff --git a/esp-hal/src/rtc_cntl/cpu_retention/mod.rs b/esp-hal/src/rtc_cntl/cpu_retention/mod.rs new file mode 100644 index 00000000000..5f81990131b --- /dev/null +++ b/esp-hal/src/rtc_cntl/cpu_retention/mod.rs @@ -0,0 +1,26 @@ +//! Retention of the CPU power domain across a light sleep. + +cfg_select! { + cpu_retention = "software" => { + mod software; + #[cfg(feature = "rt")] + pub(crate) use software::configure_cpu_retention; + #[cfg(all(multi_core, feature = "rt"))] + pub(crate) use software::rendezvous; + pub(crate) use software::{ + enter_sleep_with_retention, + finish_cpu_retention, + sleep_retained, + }; + } + + cpu_retention = "rtc_cntl" => { + mod rtc_cntl; + pub(crate) use rtc_cntl::*; + } + + _ => {} +} + +pub(crate) mod memory; +pub(crate) use memory::installed_buffer_ptr; diff --git a/esp-hal/src/rtc_cntl/cpu_retention/rtc_cntl/esp32c3.rs b/esp-hal/src/rtc_cntl/cpu_retention/rtc_cntl/esp32c3.rs new file mode 100644 index 00000000000..0ed4d510796 --- /dev/null +++ b/esp-hal/src/rtc_cntl/cpu_retention/rtc_cntl/esp32c3.rs @@ -0,0 +1,73 @@ +use core::ptr::NonNull; + +use crate::{ + peripherals::{APB_CTRL, LPWR}, + rtc_cntl::{cpu_retention, sleep::RtcSleepConfig}, +}; + +// The cache needs no maintenance around a retained sleep on this chip: the tag memory stays +// powered, so it survives the CPU power-down. This is why the chip has no tag memory retention +// feature, and why `rtc_cntl_hal_enable_cpu_retention` and its disable counterpart touch no cache. + +// `SOC_RTC_CNTL_CPU_PD_REG_FILE_NUM` (108) times `SOC_RTC_CNTL_CPU_PD_DMA_BLOCK_SIZE` (16). +const _: () = ::core::assert!(cpu_retention::payload_size() == 108 * 16); + +/// The last of the four configuration words that the CPU frames begin with. The S3 writes a +/// different value here, so the word belongs to the chip and not to the shared descriptor code. +const RETENTION_CONFIG_WORD3: u32 = 0xffff_ffff; + +/// Couples CPU power-down to the installed retention buffer, for a light sleep. +/// +/// The bit is written and not only set, so that a configuration from [`RtcSleepConfig::deep`] +/// cannot carry a power-down into a light sleep that has no retention memory. +pub(crate) fn configure_cpu_retention(config: &mut RtcSleepConfig, buffer: Option>) { + config.set_cpu_pd_en(buffer.is_some()); +} + +/// Prepares CPU retention for the upcoming sleep. +pub(crate) fn prepare_cpu_retention(buffer: Option>) { + let Some(buffer) = buffer else { + return; + }; + + unsafe { + cpu_retention::init_cpu_dma_link(buffer, RETENTION_CONFIG_WORD3); + } + + enable_cpu_retention(buffer.addr().get()); +} + +/// Finishes CPU retention after the sleep request returns. +pub(crate) fn finish_cpu_retention(_rejected: bool) { + // Disarm on every exit, including a rejected request that never slept. A stale descriptor + // would otherwise affect the next unretained sleep. + disable_cpu_retention(); +} + +fn enable_cpu_retention(link_addr: usize) { + // The field is 27 bits and the address needs 30, so the write drops the top three. The DMA + // reaches internal SRAM only, so the hardware supplies those bits; esp-idf truncates the same + // way through `REG_SET_FIELD`. `modify` keeps `nobypass_cpu_iso_rst`, which shares the + // register. + APB_CTRL::regs() + .retention_ctrl() + .modify(|_, w| unsafe { w.retention_link_addr().bits(link_addr as u32) }); + + // The retention timing fields keep their reset values of 20, 3 and 2 cycles. + // `rtc_cntl_hal_enable_cpu_retention` lengthens them to the maximum on the S3, which has five + // times as many register frames and the cache tag memory to move, and leaves them alone here. + + LPWR::regs() + .clk_conf() + .modify(|_, w| w.dig_clk8m_en().set_bit()); + + LPWR::regs() + .retention_ctrl() + .modify(|_, w| w.retention_en().set_bit()); +} + +fn disable_cpu_retention() { + LPWR::regs() + .retention_ctrl() + .modify(|_, w| w.retention_en().clear_bit()); +} diff --git a/esp-hal/src/rtc_cntl/cpu_retention/rtc_cntl/esp32s3.rs b/esp-hal/src/rtc_cntl/cpu_retention/rtc_cntl/esp32s3.rs new file mode 100644 index 00000000000..87c6ceaab67 --- /dev/null +++ b/esp-hal/src/rtc_cntl/cpu_retention/rtc_cntl/esp32s3.rs @@ -0,0 +1,191 @@ +use core::ptr::NonNull; + +use crate::{ + peripherals::{APB_CTRL, LPWR}, + rtc_cntl::{cpu_retention, sleep::RtcSleepConfig}, +}; + +// The cache tag memory powers down with the CPU, so a retained sleep must write the data cache back +// first and invalidate both caches after. Tag memory retention, which lets a program skip this +// work, comes later; until then the answer is always yes. + +// `SOC_RTC_CNTL_CPU_PD_REG_FILE_NUM` (549) times `SOC_RTC_CNTL_CPU_PD_DMA_BLOCK_SIZE` (16). +const _: () = ::core::assert!(cpu_retention::payload_size() == 549 * 16); + +const RETENTION_CONFIG_WORD3: u32 = 0xfffe_0000; +const RETENTION_WAIT_CYCLES: u8 = 0x7f; +const RETENTION_CLKOFF_WAIT_CYCLES: u8 = 0x0f; +const RETENTION_DONE_WAIT_CYCLES: u8 = 0x07; +// `RETENTION_TARGET` is a bit per target: the CPU is 1 and the cache tag memory is 2. +const RETENTION_TARGET_CPU: u8 = 1; +const RETENTION_TARGET_TAGMEM: u8 = 2; + +/// Whether the tag memory survives the sleep, which is what lets the cache work be skipped. +/// +/// Both caches are retained together, so one answer serves all three questions below. esp-idf +/// gates them separately because it retains only the tags that cover its mapped segments. +fn tag_memory_retained() -> bool { + crate::rtc_cntl::tagmem::installed_buffer_ptr().is_some() +} + +/// Whether a retained sleep must write the data cache back before the CPU domain powers down. +fn dcache_writeback_needed() -> bool { + !tag_memory_retained() +} + +/// Whether a retained sleep must invalidate the instruction cache after wake. +fn icache_invalidate_needed() -> bool { + !tag_memory_retained() +} + +/// Whether a retained sleep must invalidate the data cache after wake. +fn dcache_invalidate_needed() -> bool { + !tag_memory_retained() +} + +/// Couples CPU power-down to the installed retention buffer, for a light sleep. +/// +/// The bit is written and not only set, so that a configuration from [`RtcSleepConfig::deep`] +/// cannot carry a power-down into a light sleep that has no retention memory. +pub(crate) fn configure_cpu_retention(config: &mut RtcSleepConfig, buffer: Option>) { + config.set_cpu_pd_en(buffer.is_some()); +} + +/// Prepares CPU retention for the upcoming sleep. +pub(crate) fn prepare_cpu_retention(buffer: Option>) { + let Some(buffer) = buffer else { + return; + }; + + unsafe { + cpu_retention::init_cpu_dma_link(buffer, RETENTION_CONFIG_WORD3); + enable_cpu_retention(buffer.addr().get()); + + // The tags are lost only when the CPU domain powers down, so this is armed with the CPU + // and never on its own. + if let Some(tag_memory) = crate::rtc_cntl::tagmem::installed_buffer_ptr() { + init_tag_memory_dma_link(tag_memory); + enable_tag_memory_retention(tag_memory.addr().get()); + } + + // Only PSRAM data in the d-cache is at risk, and nothing writes to it between here and the + // sleep request, so a writeback now is enough. Follows + // `rtc_cntl_hal_enable_cpu_retention`. + if dcache_writeback_needed() { + crate::soc::cache_writeback_all(); + } + } +} + +/// Finishes CPU retention after the sleep request returns. +pub(crate) fn finish_cpu_retention(rejected: bool) { + // Disarm on every exit, including a rejected request that never slept. A stale descriptor + // would otherwise affect the next unretained sleep. + disable_cpu_retention(); + + if tag_memory_retained() { + disable_tag_memory_retention(); + } + + // A rejected request never slept, so it lost no cache contents. + if rejected { + return; + } + + // The tag memory powered down with the CPU, so every line is stale. Follows + // `rtc_cntl_hal_disable_cpu_retention`. + unsafe { + if icache_invalidate_needed() { + crate::soc::cache_invalidate_icache_all(); + } + if dcache_invalidate_needed() { + crate::soc::cache_invalidate_dcache_all(); + } + } +} + +fn enable_cpu_retention(link_addr: usize) { + // The field is 27 bits and the address needs 30, so the write drops the top three. The DMA + // reaches internal SRAM only, so the hardware supplies those bits; esp-idf truncates the same + // way through `REG_SET_FIELD`. `modify` keeps `nobypass_cpu_iso_rst`, which shares the + // register. + APB_CTRL::regs() + .retention_ctrl() + .modify(|_, w| unsafe { w.retention_cpu_link_addr().bits(link_addr as u32) }); + + LPWR::regs().retention_ctrl().modify(|_, w| unsafe { + w.retention_wait().bits(RETENTION_WAIT_CYCLES); + w.retention_clkoff_wait().bits(RETENTION_CLKOFF_WAIT_CYCLES); + w.retention_done_wait().bits(RETENTION_DONE_WAIT_CYCLES) + }); + + LPWR::regs() + .clk_conf() + .modify(|_, w| w.dig_clk8m_en().set_bit()); + + LPWR::regs().retention_ctrl().modify(|r, w| unsafe { + w.retention_target() + .bits(r.retention_target().bits() | RETENTION_TARGET_CPU); + w.retention_en().set_bit() + }); +} + +fn disable_cpu_retention() { + LPWR::regs() + .retention_ctrl() + .modify(|_, w| w.retention_en().clear_bit()); +} + +/// The tag memory needs no configuration header, unlike the CPU frames. +unsafe fn init_tag_memory_dma_link(buffer: NonNull) { + unsafe { + cpu_retention::init_link(buffer, crate::rtc_cntl::tagmem::payload_size()); + } +} + +fn enable_tag_memory_retention(link_addr: usize) { + let (icache_size, dcache_size) = crate::rtc_cntl::tagmem::size_fields(); + + APB_CTRL::regs() + .retention_ctrl1() + .modify(|_, w| unsafe { w.retention_tag_link_addr().bits(link_addr as u32) }); + + // Every set is retained, so the valid size is the whole size and the starting row does not + // matter. esp-idf narrows both to the rows its mapped code and data segments occupy, which + // saves DMA time but needs those segment addresses; retaining all of it needs nothing and + // cannot under-cover. The size field wraps, so the largest cache writes zero. + APB_CTRL::regs().retention_ctrl2().modify(|_, w| unsafe { + w.ret_icache_start_point().bits(0); + w.ret_icache_vld_size().bits(icache_size); + w.ret_icache_size().bits(icache_size); + w.ret_icache_enable().set_bit() + }); + + APB_CTRL::regs().retention_ctrl3().modify(|_, w| unsafe { + w.ret_dcache_start_point().bits(0); + w.ret_dcache_vld_size().bits(dcache_size); + w.ret_dcache_size().bits(dcache_size); + w.ret_dcache_enable().set_bit() + }); + + // The CPU shares this field, and it is armed first, so the bit is added rather than written. + LPWR::regs().retention_ctrl().modify(|r, w| unsafe { + w.retention_target() + .bits(r.retention_target().bits() | RETENTION_TARGET_TAGMEM) + }); +} + +fn disable_tag_memory_retention() { + LPWR::regs().retention_ctrl().modify(|r, w| unsafe { + w.retention_target() + .bits(r.retention_target().bits() & !RETENTION_TARGET_TAGMEM) + }); + + APB_CTRL::regs() + .retention_ctrl2() + .modify(|_, w| w.ret_icache_enable().clear_bit()); + + APB_CTRL::regs() + .retention_ctrl3() + .modify(|_, w| w.ret_dcache_enable().clear_bit()); +} diff --git a/esp-hal/src/rtc_cntl/cpu_retention/rtc_cntl/mod.rs b/esp-hal/src/rtc_cntl/cpu_retention/rtc_cntl/mod.rs new file mode 100644 index 00000000000..d9d47e5f21c --- /dev/null +++ b/esp-hal/src/rtc_cntl/cpu_retention/rtc_cntl/mod.rs @@ -0,0 +1,69 @@ +//! CPU retention through the RTC_CNTL retention DMA. + +use core::ptr::NonNull; + +use super::memory::BUFFER_SIZE; + +#[cfg_attr(esp32c3, path = "esp32c3.rs")] +#[cfg_attr(esp32s3, path = "esp32s3.rs")] +mod chip; +pub(crate) use chip::*; + +/// Bytes the DMA descriptor takes at the head of a retention buffer. +pub(crate) const DMA_LINK_SIZE: usize = 16; + +/// Bytes the DMA moves out of a CPU retention buffer, not counting the descriptor. +pub(crate) const fn payload_size() -> usize { + BUFFER_SIZE - DMA_LINK_SIZE +} + +/// RTC_CNTL retention DMA link node. Matches `lldesc_t` in `esp_rom_lldesc.h`. +#[repr(C)] +struct RtcCntlDmaLink { + word0: u32, + buf: *mut u8, + next: u32, +} + +/// Writes the descriptor at the head of the buffer and returns the payload that follows it. +/// +/// # Safety +/// +/// `buffer` must be valid for `DMA_LINK_SIZE + payload_size` bytes, and aligned as the DMA needs. +pub(crate) unsafe fn init_link(buffer: NonNull, payload_size: usize) -> *mut u8 { + let buffer = buffer.as_ptr(); + unsafe { + let link = buffer.cast::(); + let payload = buffer.add(DMA_LINK_SIZE); + let units = (payload_size >> 4) as u32; + + // `lldesc_t` first word, from `rom/lldesc.h`: size in bits 0..12, length in 12..24, `eof` + // at bit 30 for the only node in the list, `owner` at bit 31 for the DMA. Both counts are + // in 16-byte units, as `rtc_cntl_hal_dma_link_init` writes them. + let word0 = units | (units << 12) | (1 << 30) | (1 << 31); + + core::ptr::write_volatile(&raw mut (*link).word0, word0); + core::ptr::write_volatile(&raw mut (*link).buf, payload); + core::ptr::write_volatile(&raw mut (*link).next, 0); + + payload + } +} + +/// Writes the descriptor and the four configuration words that the CPU frames begin with. +/// +/// The chips agree on every word but the last, which `config_word3` supplies. +/// +/// # Safety +/// +/// `buffer` must be the installed CPU retention buffer. +pub(crate) unsafe fn init_cpu_dma_link(buffer: NonNull, config_word3: u32) { + unsafe { + let cfg = init_link(buffer, payload_size()).cast::(); + + core::ptr::write_volatile(cfg, 0); + core::ptr::write_volatile(cfg.add(1), 0); + core::ptr::write_volatile(cfg.add(2), 0); + core::ptr::write_volatile(cfg.add(3), config_word3); + } +} diff --git a/esp-hal/src/rtc_cntl/cpu_retention/software/device_regs.rs b/esp-hal/src/rtc_cntl/cpu_retention/software/device_regs.rs new file mode 100644 index 00000000000..8f622f19eb9 --- /dev/null +++ b/esp-hal/src/rtc_cntl/cpu_retention/software/device_regs.rs @@ -0,0 +1,56 @@ +//! Save and restore of the CPU-domain device registers. +//! +//! esp-idf moves these with plain register loops and not with the PAU regdma engine +//! (`esp32c6/sleep_cpu.c:237-258`). + +/// A run of device registers that the CPU power-down loses. +pub(crate) struct DeviceRegion { + start: *const u32, + words: usize, +} + +impl DeviceRegion { + pub(crate) const fn new(start: *const u32, words: usize) -> Self { + Self { start, words } + } +} + +/// Reads every region into `frame`, in the order of `regions`. +/// +/// # Panics +/// +/// Panics if `frame` is shorter than the regions need. +#[crate::ram] +pub(crate) fn save(regions: &[DeviceRegion], frame: &mut [u32]) { + let mut offset = 0; + for region in regions { + for word in 0..region.words { + // SAFETY: a chip module builds every region from a register block that the chip has. + frame[offset] = unsafe { region.start.add(word).read_volatile() }; + offset += 1; + } + } +} + +/// Writes `frame` back to every region, in the order of `regions`. +/// +/// # Panics +/// +/// Panics if `frame` is shorter than the regions need. +#[crate::ram] +pub(crate) fn restore(regions: &[DeviceRegion], frame: &[u32]) { + let mut offset = 0; + for region in regions { + for word in 0..region.words { + // SAFETY: a chip module builds every region from a register block that the chip has. + unsafe { + region + .start + .add(word) + .cast_mut() + .write_volatile(frame[offset]) + }; + offset += 1; + } + } +} diff --git a/esp-hal/src/rtc_cntl/cpu_retention/software/frames/c6_h2.rs b/esp-hal/src/rtc_cntl/cpu_retention/software/frames/c6_h2.rs new file mode 100644 index 00000000000..df8cbead5a5 --- /dev/null +++ b/esp-hal/src/rtc_cntl/cpu_retention/software/frames/c6_h2.rs @@ -0,0 +1,95 @@ +//! Sleep frames of the ESP32-C6 and the ESP32-H2. +//! +//! The two chips have byte-identical `rvsleep-frames.h`, so they share one layout. + +pub(crate) use super::{CRITICAL_FRAME_SIZE, CriticalSleepFrame}; +use crate::macros::{read_csr, write_csr}; + +/// Low two bits of `CriticalSleepFrame::pmufunc`: the CPU is about to sleep. +pub(crate) const PMUFUNC_GOING_TO_SLEEP: u32 = 1; +/// Low two bits of `CriticalSleepFrame::pmufunc`: the CPU has just woken. +pub(crate) const PMUFUNC_JUST_WOKE: u32 = 3; + +const _: () = ::core::assert!(size_of::() == 39 * 4); + +// The custom numbers come from `esp32c6/sleep_cpu.c:39-52`, and the PMA numbers from +// `components/riscv/include/riscv/csr_pma.h`. +super::non_critical_frame! { + mscratch = 0x340, + mideleg = 0x303, + misa = 0x301, + tselect = 0x7a0, + tdata1 = 0x7a1, + tdata2 = 0x7a2, + tcontrol = 0x7a5, + pmpaddr0 = 0x3b0, + pmpaddr1 = 0x3b1, + pmpaddr2 = 0x3b2, + pmpaddr3 = 0x3b3, + pmpaddr4 = 0x3b4, + pmpaddr5 = 0x3b5, + pmpaddr6 = 0x3b6, + pmpaddr7 = 0x3b7, + pmpaddr8 = 0x3b8, + pmpaddr9 = 0x3b9, + pmpaddr10 = 0x3ba, + pmpaddr11 = 0x3bb, + pmpaddr12 = 0x3bc, + pmpaddr13 = 0x3bd, + pmpaddr14 = 0x3be, + pmpaddr15 = 0x3bf, + pmpcfg0 = 0x3a0, + pmpcfg1 = 0x3a1, + pmpcfg2 = 0x3a2, + pmpcfg3 = 0x3a3, + pmaaddr0 = 0xbd0, + pmaaddr1 = 0xbd1, + pmaaddr2 = 0xbd2, + pmaaddr3 = 0xbd3, + pmaaddr4 = 0xbd4, + pmaaddr5 = 0xbd5, + pmaaddr6 = 0xbd6, + pmaaddr7 = 0xbd7, + pmaaddr8 = 0xbd8, + pmaaddr9 = 0xbd9, + pmaaddr10 = 0xbda, + pmaaddr11 = 0xbdb, + pmaaddr12 = 0xbdc, + pmaaddr13 = 0xbdd, + pmaaddr14 = 0xbde, + pmaaddr15 = 0xbdf, + pmacfg0 = 0xbc0, + pmacfg1 = 0xbc1, + pmacfg2 = 0xbc2, + pmacfg3 = 0xbc3, + pmacfg4 = 0xbc4, + pmacfg5 = 0xbc5, + pmacfg6 = 0xbc6, + pmacfg7 = 0xbc7, + pmacfg8 = 0xbc8, + pmacfg9 = 0xbc9, + pmacfg10 = 0xbca, + pmacfg11 = 0xbcb, + pmacfg12 = 0xbcc, + pmacfg13 = 0xbcd, + pmacfg14 = 0xbce, + pmacfg15 = 0xbcf, + utvec = 0x005, + ustatus = 0x000, + uepc = 0x041, + ucause = 0x042, + mpcer = 0x7e0, + mpcmr = 0x7e1, + mpccr = 0x7e2, + cpu_testbus_ctrl = 0x7e3, + upcer = 0x800, + upcmr = 0x801, + upccr = 0x802, + ugpio_oen = 0x803, + ugpio_in = 0x804, + ugpio_out = 0x805, +} + +const _: () = ::core::assert!(size_of::() == 73 * 4); + +pub(crate) const NON_CRITICAL_FRAME_SIZE: usize = size_of::(); diff --git a/esp-hal/src/rtc_cntl/cpu_retention/software/frames/clic.rs b/esp-hal/src/rtc_cntl/cpu_retention/software/frames/clic.rs new file mode 100644 index 00000000000..0f2dbb994ac --- /dev/null +++ b/esp-hal/src/rtc_cntl/cpu_retention/software/frames/clic.rs @@ -0,0 +1,87 @@ +//! Sleep frames of CLIC RISC-V cores. +//! +//! The ESP32-C5 and the ESP32-C61 have byte-identical `rvsleep-frames.h`, so they share one layout. + +pub(crate) use super::{CRITICAL_FRAME_SIZE, CriticalSleepFrame}; +use crate::macros::{read_csr, write_csr}; + +/// Low two bits of `CriticalSleepFrame::pmufunc`: the CPU is about to sleep. +pub(crate) const PMUFUNC_GOING_TO_SLEEP: u32 = 1; +/// Low two bits of `CriticalSleepFrame::pmufunc`: the CPU has just woken. +pub(crate) const PMUFUNC_JUST_WOKE: u32 = 3; + +const _: () = ::core::assert!(size_of::() == 40 * 4); + +// The custom numbers come from `esp32c5/sleep_cpu.c:43-49`, and the PMA numbers from +// `components/riscv/include/riscv/csr.h`. +super::non_critical_frame! { + mscratch = 0x340, + misa = 0x301, + tselect = 0x7a0, + tdata1 = 0x7a1, + tdata2 = 0x7a2, + tcontrol = 0x7a5, + pmpaddr0 = 0x3b0, + pmpaddr1 = 0x3b1, + pmpaddr2 = 0x3b2, + pmpaddr3 = 0x3b3, + pmpaddr4 = 0x3b4, + pmpaddr5 = 0x3b5, + pmpaddr6 = 0x3b6, + pmpaddr7 = 0x3b7, + pmpaddr8 = 0x3b8, + pmpaddr9 = 0x3b9, + pmpaddr10 = 0x3ba, + pmpaddr11 = 0x3bb, + pmpaddr12 = 0x3bc, + pmpaddr13 = 0x3bd, + pmpaddr14 = 0x3be, + pmpaddr15 = 0x3bf, + pmpcfg0 = 0x3a0, + pmpcfg1 = 0x3a1, + pmpcfg2 = 0x3a2, + pmpcfg3 = 0x3a3, + pmaaddr0 = 0xbd0, + pmaaddr1 = 0xbd1, + pmaaddr2 = 0xbd2, + pmaaddr3 = 0xbd3, + pmaaddr4 = 0xbd4, + pmaaddr5 = 0xbd5, + pmaaddr6 = 0xbd6, + pmaaddr7 = 0xbd7, + pmaaddr8 = 0xbd8, + pmaaddr9 = 0xbd9, + pmaaddr10 = 0xbda, + pmaaddr11 = 0xbdb, + pmaaddr12 = 0xbdc, + pmaaddr13 = 0xbdd, + pmaaddr14 = 0xbde, + pmaaddr15 = 0xbdf, + pmacfg0 = 0xbc0, + pmacfg1 = 0xbc1, + pmacfg2 = 0xbc2, + pmacfg3 = 0xbc3, + pmacfg4 = 0xbc4, + pmacfg5 = 0xbc5, + pmacfg6 = 0xbc6, + pmacfg7 = 0xbc7, + pmacfg8 = 0xbc8, + pmacfg9 = 0xbc9, + pmacfg10 = 0xbca, + pmacfg11 = 0xbcb, + pmacfg12 = 0xbcc, + pmacfg13 = 0xbcd, + pmacfg14 = 0xbce, + pmacfg15 = 0xbcf, + mcycle = 0xb00, + mtvt = 0x307, + mxstatus = 0x7c0, + mhcr = 0x7c1, + mhint = 0x7c5, + mexstatus = 0x7e1, + jvt = 0x017, +} + +const _: () = ::core::assert!(size_of::() == 65 * 4); + +pub(crate) const NON_CRITICAL_FRAME_SIZE: usize = size_of::(); diff --git a/esp-hal/src/rtc_cntl/cpu_retention/software/frames/mod.rs b/esp-hal/src/rtc_cntl/cpu_retention/software/frames/mod.rs new file mode 100644 index 00000000000..ca66bb07450 --- /dev/null +++ b/esp-hal/src/rtc_cntl/cpu_retention/software/frames/mod.rs @@ -0,0 +1,113 @@ +//! Sleep frame layouts. +//! +//! The chips fall into three groups, and the groups do not share a layout. See +//! `components/esp_hw_support/lowpower/port//rvsleep-frames.h`. + +/// Declares the critical frame and the matched pair that moves it. +/// +/// One list drives the struct, the save and the restore, so the three cannot drift apart. +macro_rules! critical_frame { + ( + { // fields in the group - each inherits the cfg + $($field:ident),* $(,)? + } + $(, // conditional groups + #[$cfg:meta] + { // fields in the group - each inherits the cfg + $($cfg_field:ident),* $(,)? + } + )+ + ) => { + /// Registers that the assembly saves, because the CPU has no valid state at that point. + #[repr(C)] + pub(crate) struct CriticalSleepFrame { + $( + pub $field: u32, + )* + $( + $( #[$cfg] pub $cfg_field: u32, )* + )* + } + }; +} + +critical_frame! { + { + mepc, + ra, + sp, + gp, + tp, + t0, t1, t2, t3, t4, t5, t6, + s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, + a0, a1, a2, a3, a4, a5, a6, a7, + mstatus, + mtvec, + mcause, + mtval, + mie, + mip, + pmufunc, + }, + #[cfg(any(esp32p4))] + { + mtvt, + }, + #[cfg(any(cpu_retention_frame = "clic", esp32p4, esp32s31))] + { + mintthresh, + }, + #[cfg(any(esp32p4, esp32s31))] + { + fpu_ft0, fpu_ft1, fpu_ft2, fpu_ft3, fpu_ft4, fpu_ft5, fpu_ft6, fpu_ft7, + fpu_ft8, fpu_ft9, fpu_ft10, fpu_ft11, + fpu_fs0, fpu_fs1, fpu_fs2, fpu_fs3, fpu_fs4, fpu_fs5, fpu_fs6, fpu_fs7, + fpu_fs8, fpu_fs9, fpu_fs10, fpu_fs11, + fpu_fa0, fpu_fa1, fpu_fa2, fpu_fa3, fpu_fa4, fpu_fa5, fpu_fa6, fpu_fa7, + fpu_fcsr, + } +} + +/// `RV_SLEEP_CTX_FRMSZ`: the critical frame size, rounded up to 16 bytes. +pub(crate) const CRITICAL_FRAME_SIZE: usize = size_of::().next_multiple_of(16); + +/// Declares the non-critical frame and the matched pair that moves it. +/// +/// One list drives the struct, the save and the restore, so the three cannot drift apart. +macro_rules! non_critical_frame { + ($($field:ident = $csr:expr),* $(,)?) => { + /// Registers that Rust saves, because the CPU is usable while they move. + #[repr(C)] + pub(crate) struct NonCriticalSleepFrame { + $($field: u32,)* + } + + impl NonCriticalSleepFrame { + /// Reads every CSR of the frame. + /// + /// # Safety + /// + /// The caller must own the CPU state that the frame describes. + pub(crate) unsafe fn save(&mut self) { + $(self.$field = unsafe { read_csr!($csr) };)* + } + + /// Writes every CSR of the frame back. + /// + /// # Safety + /// + /// The frame must hold a state that [`Self::save`] read from this core. + pub(crate) unsafe fn restore(&self) { + $(unsafe { write_csr!($csr, self.$field) };)* + } + } + }; +} + +pub(crate) use non_critical_frame; + +#[cfg_attr(cpu_retention_frame = "c6_h2", path = "c6_h2.rs")] +#[cfg_attr(cpu_retention_frame = "clic", path = "clic.rs")] +#[cfg_attr(cpu_retention_frame = "p4", path = "p4.rs")] +#[cfg_attr(cpu_retention_frame = "s31", path = "s31.rs")] +pub(crate) mod chip; diff --git a/esp-hal/src/rtc_cntl/cpu_retention/software/frames/p4.rs b/esp-hal/src/rtc_cntl/cpu_retention/software/frames/p4.rs new file mode 100644 index 00000000000..47bc47c8207 --- /dev/null +++ b/esp-hal/src/rtc_cntl/cpu_retention/software/frames/p4.rs @@ -0,0 +1,80 @@ +//! Sleep frames of the ESP32-P4 RISC-V core. + +pub(crate) use super::{CRITICAL_FRAME_SIZE, CriticalSleepFrame}; +use crate::macros::{read_csr, write_csr}; + +/// Low two bits of `CriticalSleepFrame::pmufunc`: the CPU is about to sleep. +pub(crate) const PMUFUNC_GOING_TO_SLEEP: u32 = 1; +/// Low two bits of `CriticalSleepFrame::pmufunc`: the CPU has just woken. +pub(crate) const PMUFUNC_JUST_WOKE: u32 = 3; + +const _: () = ::core::assert!(size_of::() == 74 * 4); + +// The custom numbers come from `esp32p4/sleep_cpu.c:79-85`, and the PMA numbers from +// `components/riscv/include/riscv/csr.h`. +super::non_critical_frame! { + mscratch = 0x340, + misa = 0x301, + mhcr = 0x7c1, + tselect = 0x7a0, + tdata1 = 0x7a1, + tdata2 = 0x7a2, + tcontrol = 0x7a5, + pmpaddr0 = 0x3b0, + pmpaddr1 = 0x3b1, + pmpaddr2 = 0x3b2, + pmpaddr3 = 0x3b3, + pmpaddr4 = 0x3b4, + pmpaddr5 = 0x3b5, + pmpaddr6 = 0x3b6, + pmpaddr7 = 0x3b7, + pmpaddr8 = 0x3b8, + pmpaddr9 = 0x3b9, + pmpaddr10 = 0x3ba, + pmpaddr11 = 0x3bb, + pmpaddr12 = 0x3bc, + pmpaddr13 = 0x3bd, + pmpaddr14 = 0x3be, + pmpaddr15 = 0x3bf, + pmpcfg0 = 0x3a0, + pmpcfg1 = 0x3a1, + pmpcfg2 = 0x3a2, + pmpcfg3 = 0x3a3, + pmaaddr0 = 0xbd0, + pmaaddr1 = 0xbd1, + pmaaddr2 = 0xbd2, + pmaaddr3 = 0xbd3, + pmaaddr4 = 0xbd4, + pmaaddr5 = 0xbd5, + pmaaddr6 = 0xbd6, + pmaaddr7 = 0xbd7, + pmaaddr8 = 0xbd8, + pmaaddr9 = 0xbd9, + pmaaddr10 = 0xbda, + pmaaddr11 = 0xbdb, + pmaaddr12 = 0xbdc, + pmaaddr13 = 0xbdd, + pmaaddr14 = 0xbde, + pmaaddr15 = 0xbdf, + pmacfg0 = 0xbc0, + pmacfg1 = 0xbc1, + pmacfg2 = 0xbc2, + pmacfg3 = 0xbc3, + pmacfg4 = 0xbc4, + pmacfg5 = 0xbc5, + pmacfg6 = 0xbc6, + pmacfg7 = 0xbc7, + pmacfg8 = 0xbc8, + pmacfg9 = 0xbc9, + pmacfg10 = 0xbca, + pmacfg11 = 0xbcb, + pmacfg12 = 0xbcc, + pmacfg13 = 0xbcd, + pmacfg14 = 0xbce, + pmacfg15 = 0xbcf, + mcycle = 0xb00, +} + +const _: () = ::core::assert!(size_of::() == 60 * 4); + +pub(crate) const NON_CRITICAL_FRAME_SIZE: usize = size_of::(); diff --git a/esp-hal/src/rtc_cntl/cpu_retention/software/frames/s31.rs b/esp-hal/src/rtc_cntl/cpu_retention/software/frames/s31.rs new file mode 100644 index 00000000000..cccea1e1e16 --- /dev/null +++ b/esp-hal/src/rtc_cntl/cpu_retention/software/frames/s31.rs @@ -0,0 +1,90 @@ +//! Sleep frames of the ESP32-S31 RISC-V core. + +pub(crate) use super::{CRITICAL_FRAME_SIZE, CriticalSleepFrame}; +use crate::macros::{read_csr, write_csr}; + +/// Low two bits of `CriticalSleepFrame::pmufunc`: the CPU is about to sleep. +pub(crate) const PMUFUNC_GOING_TO_SLEEP: u32 = 1; +/// Low two bits of `CriticalSleepFrame::pmufunc`: the CPU has just woken. +pub(crate) const PMUFUNC_JUST_WOKE: u32 = 3; + +const _: () = ::core::assert!(size_of::() == 73 * 4); + +// The custom numbers come from `esp32s31/sleep_cpu.c:65-75`, and the PMA numbers from +// `components/riscv/include/riscv/csr.h`. +super::non_critical_frame! { + mscratch = 0x340, + misa = 0x301, + mtvt = 0x307, + mscratchcsw = 0x348, + mscratchcswl = 0x349, + mxstatus = 0x7c0, + mhcr = 0x7c1, + mhint = 0x7c5, + mraddr = 0x7e0, + mexstatus = 0x7e1, + jvt = 0x017, + medeleg = 0x302, + tselect = 0x7a0, + tdata1 = 0x7a1, + tdata2 = 0x7a2, + tcontrol = 0x7a5, + pmpaddr0 = 0x3b0, + pmpaddr1 = 0x3b1, + pmpaddr2 = 0x3b2, + pmpaddr3 = 0x3b3, + pmpaddr4 = 0x3b4, + pmpaddr5 = 0x3b5, + pmpaddr6 = 0x3b6, + pmpaddr7 = 0x3b7, + pmpaddr8 = 0x3b8, + pmpaddr9 = 0x3b9, + pmpaddr10 = 0x3ba, + pmpaddr11 = 0x3bb, + pmpaddr12 = 0x3bc, + pmpaddr13 = 0x3bd, + pmpaddr14 = 0x3be, + pmpaddr15 = 0x3bf, + pmpcfg0 = 0x3a0, + pmpcfg1 = 0x3a1, + pmpcfg2 = 0x3a2, + pmpcfg3 = 0x3a3, + pmaaddr0 = 0xbd0, + pmaaddr1 = 0xbd1, + pmaaddr2 = 0xbd2, + pmaaddr3 = 0xbd3, + pmaaddr4 = 0xbd4, + pmaaddr5 = 0xbd5, + pmaaddr6 = 0xbd6, + pmaaddr7 = 0xbd7, + pmaaddr8 = 0xbd8, + pmaaddr9 = 0xbd9, + pmaaddr10 = 0xbda, + pmaaddr11 = 0xbdb, + pmaaddr12 = 0xbdc, + pmaaddr13 = 0xbdd, + pmaaddr14 = 0xbde, + pmaaddr15 = 0xbdf, + pmacfg0 = 0xbc0, + pmacfg1 = 0xbc1, + pmacfg2 = 0xbc2, + pmacfg3 = 0xbc3, + pmacfg4 = 0xbc4, + pmacfg5 = 0xbc5, + pmacfg6 = 0xbc6, + pmacfg7 = 0xbc7, + pmacfg8 = 0xbc8, + pmacfg9 = 0xbc9, + pmacfg10 = 0xbca, + pmacfg11 = 0xbcb, + pmacfg12 = 0xbcc, + pmacfg13 = 0xbcd, + pmacfg14 = 0xbce, + pmacfg15 = 0xbcf, + mcycle = 0xb00, + mcycleh = 0xb80, +} + +const _: () = ::core::assert!(size_of::() == 70 * 4); + +pub(crate) const NON_CRITICAL_FRAME_SIZE: usize = size_of::(); diff --git a/esp-hal/src/rtc_cntl/cpu_retention/software/mod.rs b/esp-hal/src/rtc_cntl/cpu_retention/software/mod.rs new file mode 100644 index 00000000000..8e8ac546a12 --- /dev/null +++ b/esp-hal/src/rtc_cntl/cpu_retention/software/mod.rs @@ -0,0 +1,689 @@ +//! Software CPU retention across a light sleep. +//! +//! esp-idf saves the CPU-domain device registers with plain loops, not with the PAU regdma engine +//! (`esp32c6/sleep_cpu.c:237-341`). + +use core::{mem::offset_of, ptr, ptr::NonNull, slice}; + +use portable_atomic::{AtomicPtr, Ordering}; + +use crate::{ + rtc_cntl::{ + cpu_retention, + sleep::{self, RtcSleepConfig}, + }, + system::{self, Cpu}, +}; + +mod device_regs; +use device_regs::DeviceRegion; + +mod frames; +use frames::chip::{ + CRITICAL_FRAME_SIZE, + CriticalSleepFrame, + NON_CRITICAL_FRAME_SIZE, + NonCriticalSleepFrame, + PMUFUNC_GOING_TO_SLEEP, + PMUFUNC_JUST_WOKE, +}; + +// The rendezvous needs the IPC path, which `interrupt::ipc` gives to a +// multi-core chip with the `rt` and the `unstable` features. +#[cfg(all(multi_core, feature = "rt"))] +pub(crate) mod rendezvous; + +// The wake stub is an `extern "C" fn()` with no argument, so the critical frame address of each +// core lives here. Every core of a chip returns through the one wake stub register, so the restore +// assembly picks its entry by hart id. +static CRITICAL_FRAME_PTR: [AtomicPtr; Cpu::COUNT] = + [const { AtomicPtr::new(ptr::null_mut()) }; Cpu::COUNT]; + +/// Emits `critical_regs_save` and `critical_regs_restore` for one frame shape. +/// +/// The two shapes differ by the registers that only one of them holds. `save_extra` runs after the +/// save wrote `mepc`, and `restore_extra` before the restore reads it back, which is where +/// `/sleep_cpu_asm.S` puts them. +macro_rules! critical_regs_asm { + // A frame shape that holds the FPU registers. Every such chip moves the same registers, so + // this block lives here once, and it runs after the extras of the caller. esp-idf moves the + // FPU only when the FreeRTOS port marks the context dirty; esp-hal tracks no such state, so + // this code moves it every time. + // + // Both halves set `mstatus.FS` before they touch an FPU register, as `sleep_fpu_asm.S` does, + // because an access traps while the unit is off. The bit needs no undo: `mstatus` is in the + // frame, and the restore writes it back after the FPU registers. A core that had the unit off + // saves and restores register values that no later code can read. + // + // `.option arch, +f` only affects the assembler; `mstatus.FS` enables the unit. + ( + fpu, + save_extra: [$($save_extra:literal),* $(,)?], + restore_extra: [$($restore_extra:literal),* $(,)?] + $(, $operand:ident = const $value:expr)* $(,)? + ) => { + critical_regs_asm!( + save_extra: [ + $($save_extra,)* + "li t2, {fpu_enable}", + "csrs mstatus, t2", + ".option push", + ".option arch, +f", + "fsw ft0, {fpu_ft0}(t0)", + "fsw ft1, {fpu_ft1}(t0)", + "fsw ft2, {fpu_ft2}(t0)", + "fsw ft3, {fpu_ft3}(t0)", + "fsw ft4, {fpu_ft4}(t0)", + "fsw ft5, {fpu_ft5}(t0)", + "fsw ft6, {fpu_ft6}(t0)", + "fsw ft7, {fpu_ft7}(t0)", + "fsw fs0, {fpu_fs0}(t0)", + "fsw fs1, {fpu_fs1}(t0)", + "fsw fa0, {fpu_fa0}(t0)", + "fsw fa1, {fpu_fa1}(t0)", + "fsw fa2, {fpu_fa2}(t0)", + "fsw fa3, {fpu_fa3}(t0)", + "fsw fa4, {fpu_fa4}(t0)", + "fsw fa5, {fpu_fa5}(t0)", + "fsw fa6, {fpu_fa6}(t0)", + "fsw fa7, {fpu_fa7}(t0)", + "fsw fs2, {fpu_fs2}(t0)", + "fsw fs3, {fpu_fs3}(t0)", + "fsw fs4, {fpu_fs4}(t0)", + "fsw fs5, {fpu_fs5}(t0)", + "fsw fs6, {fpu_fs6}(t0)", + "fsw fs7, {fpu_fs7}(t0)", + "fsw fs8, {fpu_fs8}(t0)", + "fsw fs9, {fpu_fs9}(t0)", + "fsw fs10, {fpu_fs10}(t0)", + "fsw fs11, {fpu_fs11}(t0)", + "fsw ft8, {fpu_ft8}(t0)", + "fsw ft9, {fpu_ft9}(t0)", + "fsw ft10, {fpu_ft10}(t0)", + "fsw ft11, {fpu_ft11}(t0)", + "csrr t2, fcsr", + "sw t2, {fpu_fcsr}(t0)", + ".option pop", + ], + restore_extra: [ + $($restore_extra,)* + "li t2, {fpu_enable}", + "csrs mstatus, t2", + ".option push", + ".option arch, +f", + "flw ft0, {fpu_ft0}(t0)", + "flw ft1, {fpu_ft1}(t0)", + "flw ft2, {fpu_ft2}(t0)", + "flw ft3, {fpu_ft3}(t0)", + "flw ft4, {fpu_ft4}(t0)", + "flw ft5, {fpu_ft5}(t0)", + "flw ft6, {fpu_ft6}(t0)", + "flw ft7, {fpu_ft7}(t0)", + "flw fs0, {fpu_fs0}(t0)", + "flw fs1, {fpu_fs1}(t0)", + "flw fa0, {fpu_fa0}(t0)", + "flw fa1, {fpu_fa1}(t0)", + "flw fa2, {fpu_fa2}(t0)", + "flw fa3, {fpu_fa3}(t0)", + "flw fa4, {fpu_fa4}(t0)", + "flw fa5, {fpu_fa5}(t0)", + "flw fa6, {fpu_fa6}(t0)", + "flw fa7, {fpu_fa7}(t0)", + "flw fs2, {fpu_fs2}(t0)", + "flw fs3, {fpu_fs3}(t0)", + "flw fs4, {fpu_fs4}(t0)", + "flw fs5, {fpu_fs5}(t0)", + "flw fs6, {fpu_fs6}(t0)", + "flw fs7, {fpu_fs7}(t0)", + "flw fs8, {fpu_fs8}(t0)", + "flw fs9, {fpu_fs9}(t0)", + "flw fs10, {fpu_fs10}(t0)", + "flw fs11, {fpu_fs11}(t0)", + "flw ft8, {fpu_ft8}(t0)", + "flw ft9, {fpu_ft9}(t0)", + "flw ft10, {fpu_ft10}(t0)", + "flw ft11, {fpu_ft11}(t0)", + "lw t2, {fpu_fcsr}(t0)", + "csrw fcsr, t2", + ".option pop", + ], + $($operand = const $value,)* + fpu_enable = const 1 << 13, + fpu_ft0 = const offset_of!(CriticalSleepFrame, fpu_ft0), + fpu_ft1 = const offset_of!(CriticalSleepFrame, fpu_ft1), + fpu_ft2 = const offset_of!(CriticalSleepFrame, fpu_ft2), + fpu_ft3 = const offset_of!(CriticalSleepFrame, fpu_ft3), + fpu_ft4 = const offset_of!(CriticalSleepFrame, fpu_ft4), + fpu_ft5 = const offset_of!(CriticalSleepFrame, fpu_ft5), + fpu_ft6 = const offset_of!(CriticalSleepFrame, fpu_ft6), + fpu_ft7 = const offset_of!(CriticalSleepFrame, fpu_ft7), + fpu_fs0 = const offset_of!(CriticalSleepFrame, fpu_fs0), + fpu_fs1 = const offset_of!(CriticalSleepFrame, fpu_fs1), + fpu_fa0 = const offset_of!(CriticalSleepFrame, fpu_fa0), + fpu_fa1 = const offset_of!(CriticalSleepFrame, fpu_fa1), + fpu_fa2 = const offset_of!(CriticalSleepFrame, fpu_fa2), + fpu_fa3 = const offset_of!(CriticalSleepFrame, fpu_fa3), + fpu_fa4 = const offset_of!(CriticalSleepFrame, fpu_fa4), + fpu_fa5 = const offset_of!(CriticalSleepFrame, fpu_fa5), + fpu_fa6 = const offset_of!(CriticalSleepFrame, fpu_fa6), + fpu_fa7 = const offset_of!(CriticalSleepFrame, fpu_fa7), + fpu_fs2 = const offset_of!(CriticalSleepFrame, fpu_fs2), + fpu_fs3 = const offset_of!(CriticalSleepFrame, fpu_fs3), + fpu_fs4 = const offset_of!(CriticalSleepFrame, fpu_fs4), + fpu_fs5 = const offset_of!(CriticalSleepFrame, fpu_fs5), + fpu_fs6 = const offset_of!(CriticalSleepFrame, fpu_fs6), + fpu_fs7 = const offset_of!(CriticalSleepFrame, fpu_fs7), + fpu_fs8 = const offset_of!(CriticalSleepFrame, fpu_fs8), + fpu_fs9 = const offset_of!(CriticalSleepFrame, fpu_fs9), + fpu_fs10 = const offset_of!(CriticalSleepFrame, fpu_fs10), + fpu_fs11 = const offset_of!(CriticalSleepFrame, fpu_fs11), + fpu_ft8 = const offset_of!(CriticalSleepFrame, fpu_ft8), + fpu_ft9 = const offset_of!(CriticalSleepFrame, fpu_ft9), + fpu_ft10 = const offset_of!(CriticalSleepFrame, fpu_ft10), + fpu_ft11 = const offset_of!(CriticalSleepFrame, fpu_ft11), + fpu_fcsr = const offset_of!(CriticalSleepFrame, fpu_fcsr), + ); + }; + + ( + save_extra: [$($save_extra:literal),* $(,)?], + restore_extra: [$($restore_extra:literal),* $(,)?] + $(, $operand:ident = const $value:expr)* $(,)? + ) => { + critical_regs_asm!( + @functions + save_extra: [$($save_extra),*], + restore_extra: [$($restore_extra),*], + common: { + ra = const offset_of!(CriticalSleepFrame, ra), + sp = const offset_of!(CriticalSleepFrame, sp), + gp = const offset_of!(CriticalSleepFrame, gp), + tp = const offset_of!(CriticalSleepFrame, tp), + t1 = const offset_of!(CriticalSleepFrame, t1), + t2 = const offset_of!(CriticalSleepFrame, t2), + s0 = const offset_of!(CriticalSleepFrame, s0), + s1 = const offset_of!(CriticalSleepFrame, s1), + a0 = const offset_of!(CriticalSleepFrame, a0), + a1 = const offset_of!(CriticalSleepFrame, a1), + a2 = const offset_of!(CriticalSleepFrame, a2), + a3 = const offset_of!(CriticalSleepFrame, a3), + a4 = const offset_of!(CriticalSleepFrame, a4), + a5 = const offset_of!(CriticalSleepFrame, a5), + a6 = const offset_of!(CriticalSleepFrame, a6), + a7 = const offset_of!(CriticalSleepFrame, a7), + s2 = const offset_of!(CriticalSleepFrame, s2), + s3 = const offset_of!(CriticalSleepFrame, s3), + s4 = const offset_of!(CriticalSleepFrame, s4), + s5 = const offset_of!(CriticalSleepFrame, s5), + s6 = const offset_of!(CriticalSleepFrame, s6), + s7 = const offset_of!(CriticalSleepFrame, s7), + s8 = const offset_of!(CriticalSleepFrame, s8), + s9 = const offset_of!(CriticalSleepFrame, s9), + s10 = const offset_of!(CriticalSleepFrame, s10), + s11 = const offset_of!(CriticalSleepFrame, s11), + t3 = const offset_of!(CriticalSleepFrame, t3), + t4 = const offset_of!(CriticalSleepFrame, t4), + t5 = const offset_of!(CriticalSleepFrame, t5), + t6 = const offset_of!(CriticalSleepFrame, t6), + mstatus = const offset_of!(CriticalSleepFrame, mstatus), + mtvec = const offset_of!(CriticalSleepFrame, mtvec), + mcause = const offset_of!(CriticalSleepFrame, mcause), + mtval = const offset_of!(CriticalSleepFrame, mtval), + mie = const offset_of!(CriticalSleepFrame, mie), + mip = const offset_of!(CriticalSleepFrame, mip), + mepc = const offset_of!(CriticalSleepFrame, mepc), + pmufunc = const offset_of!(CriticalSleepFrame, pmufunc), + $($operand = const $value,)* + } + ); + }; + + // `naked_asm!` rejects unused operands, so the operands that both functions use are passed to + // each of them, and the rest are listed per function. + ( + @functions + save_extra: [$($save_extra:literal),*], + restore_extra: [$($restore_extra:literal),*], + common: { $($common:tt)* } + ) => { + #[unsafe(link_section = ".rwtext")] + #[unsafe(naked)] + unsafe extern "C" fn critical_regs_save( + _frame: *mut CriticalSleepFrame, + ) -> *mut CriticalSleepFrame { + core::arch::naked_asm!( + "csrw mscratch, t0", + "mv t0, a0", + "sw ra, {ra}(t0)", + "sw sp, {sp}(t0)", + "sw gp, {gp}(t0)", + "sw tp, {tp}(t0)", + "sw t1, {t1}(t0)", + "sw t2, {t2}(t0)", + "sw s0, {s0}(t0)", + "sw s1, {s1}(t0)", + "mv a0, t0", + "sw a0, {a0}(t0)", + "sw a1, {a1}(t0)", + "sw a2, {a2}(t0)", + "sw a3, {a3}(t0)", + "sw a4, {a4}(t0)", + "sw a5, {a5}(t0)", + "sw a6, {a6}(t0)", + "sw a7, {a7}(t0)", + "sw s2, {s2}(t0)", + "sw s3, {s3}(t0)", + "sw s4, {s4}(t0)", + "sw s5, {s5}(t0)", + "sw s6, {s6}(t0)", + "sw s7, {s7}(t0)", + "sw s8, {s8}(t0)", + "sw s9, {s9}(t0)", + "sw s10, {s10}(t0)", + "sw s11, {s11}(t0)", + "sw t3, {t3}(t0)", + "sw t4, {t4}(t0)", + "sw t5, {t5}(t0)", + "sw t6, {t6}(t0)", + "csrr t1, mstatus", + "sw t1, {mstatus}(t0)", + "csrr t2, mtvec", + "sw t2, {mtvec}(t0)", + "csrr t3, mcause", + "sw t3, {mcause}(t0)", + "csrr t1, mtval", + "sw t1, {mtval}(t0)", + "csrr t2, mie", + "sw t2, {mie}(t0)", + "csrr t3, mip", + "sw t3, {mip}(t0)", + "csrr t1, mepc", + "sw t1, {mepc}(t0)", + $($save_extra,)* + "li t1, ~0x3", + "lw t2, {pmufunc}(t0)", + "and t2, t1, t2", + "ori t2, t2, {going_to_sleep}", + "sw t2, {pmufunc}(t0)", + "mv t3, t0", + "csrr t0, mscratch", + "lw t1, {t1}(t3)", + "lw t2, {t2}(t3)", + "lw t3, {t3}(t3)", + "ret", + going_to_sleep = const PMUFUNC_GOING_TO_SLEEP, + $($common)* + ); + } + + #[unsafe(link_section = ".rwtext")] + #[unsafe(naked)] + unsafe extern "C" fn critical_regs_restore() { + core::arch::naked_asm!( + "la t1, {critical_frame_ptr}", + // The mask keeps a single-core chip on entry 0 without a second copy of this block. + // No general register is live here, so `t1` and `t2` are free. + "csrr t2, mhartid", + "andi t2, t2, {core_mask}", + "slli t2, t2, 2", + "add t1, t1, t2", + "lw t0, 0(t1)", + "beqz t0, 2f", + "lw t1, {pmufunc}(t0)", + "ori t1, t1, {just_woke}", + "sw t1, {pmufunc}(t0)", + $($restore_extra,)* + "lw t2, {mepc}(t0)", + "csrw mepc, t2", + "lw t3, {mip}(t0)", + "csrw mip, t3", + "lw t1, {mie}(t0)", + "csrw mie, t1", + "lw t2, {mstatus}(t0)", + "csrw mstatus, t2", + "lw t3, {mtvec}(t0)", + "csrw mtvec, t3", + "lw t1, {mcause}(t0)", + "csrw mcause, t1", + "lw t2, {mtval}(t0)", + "csrw mtval, t2", + "lw t6, {t6}(t0)", + "lw t5, {t5}(t0)", + "lw t4, {t4}(t0)", + "lw t3, {t3}(t0)", + "lw s11, {s11}(t0)", + "lw s10, {s10}(t0)", + "lw s9, {s9}(t0)", + "lw s8, {s8}(t0)", + "lw s7, {s7}(t0)", + "lw s6, {s6}(t0)", + "lw s5, {s5}(t0)", + "lw s4, {s4}(t0)", + "lw s3, {s3}(t0)", + "lw s2, {s2}(t0)", + "lw a7, {a7}(t0)", + "lw a6, {a6}(t0)", + "lw a5, {a5}(t0)", + "lw a4, {a4}(t0)", + "lw a3, {a3}(t0)", + "lw a2, {a2}(t0)", + "lw a1, {a1}(t0)", + "lw a0, {a0}(t0)", + "lw s1, {s1}(t0)", + "lw s0, {s0}(t0)", + "lw t2, {t2}(t0)", + "lw t1, {t1}(t0)", + "lw tp, {tp}(t0)", + "lw gp, {gp}(t0)", + "lw sp, {sp}(t0)", + "lw ra, {ra}(t0)", + "lw t0, {t0}(t0)", + "2:", + "ret", + t0 = const offset_of!(CriticalSleepFrame, t0), + just_woke = const PMUFUNC_JUST_WOKE, + critical_frame_ptr = sym CRITICAL_FRAME_PTR, + core_mask = const Cpu::COUNT - 1, + $($common)* + ); + } + }; +} + +#[cfg(cpu_retention_frame = "c6_h2")] +critical_regs_asm!(save_extra: [], restore_extra: []); + +// A CLIC part also holds the interrupt threshold. `MINTTHRESH_CSR` comes from +// `components/riscv/include/riscv/csr_clic.h`. +#[cfg(cpu_retention_frame = "clic")] +critical_regs_asm!( + save_extra: ["csrr t2, {mintthresh_csr}", "sw t2, {mintthresh}(t0)"], + restore_extra: ["lw t2, {mintthresh}(t0)", "csrw {mintthresh_csr}, t2"], + mintthresh = const offset_of!(CriticalSleepFrame, mintthresh), + mintthresh_csr = const 0x347, +); + +// The S31 critical frame also holds the interrupt threshold and the FPU. +#[cfg(cpu_retention_frame = "s31")] +critical_regs_asm!( + fpu, + save_extra: ["csrr t2, {mintthresh_csr}", "sw t2, {mintthresh}(t0)"], + restore_extra: ["lw t2, {mintthresh}(t0)", "csrw {mintthresh_csr}, t2"], + mintthresh = const offset_of!(CriticalSleepFrame, mintthresh), + mintthresh_csr = const 0x347, +); + +// The P4 critical frame also holds the trap-vector table base, the interrupt threshold and the +// FPU. `MTVT_CSR` comes from `components/riscv/include/riscv/csr_clic.h`. +#[cfg(cpu_retention_frame = "p4")] +critical_regs_asm!( + fpu, + save_extra: [ + "csrr t2, {mtvt_csr}", + "sw t2, {mtvt}(t0)", + "csrr t2, {mintthresh_csr}", + "sw t2, {mintthresh}(t0)", + ], + restore_extra: [ + "lw t2, {mtvt}(t0)", + "csrw {mtvt_csr}, t2", + "lw t2, {mintthresh}(t0)", + "csrw {mintthresh_csr}, t2", + ], + mtvt = const offset_of!(CriticalSleepFrame, mtvt), + mtvt_csr = const 0x307, + mintthresh = const offset_of!(CriticalSleepFrame, mintthresh), + mintthresh_csr = const 0x347, +); + +/// Per-core retention buffer layout for one save or restore pass. +pub(crate) struct CoreRetentionContext { + pub(crate) buffer: *mut u8, + pub(crate) core: usize, +} + +impl CoreRetentionContext { + #[crate::ram] + pub(crate) fn new(buffer: *mut u8, core: usize) -> Self { + // SAFETY: `install_cpu_retention_memory` checked the buffer against the size of every + // block. + let buffer = unsafe { buffer.add(core * BLOCK_SIZE) }; + Self { buffer, core } + } + + #[crate::ram] + pub(crate) fn device_frame(&mut self) -> &mut [u32] { + // SAFETY: the buffer is installed and sized for this chip. + unsafe { + slice::from_raw_parts_mut( + self.buffer.add(DEVICE_REGIONS_OFFSET) as *mut u32, + DEVICE_REGION_WORDS, + ) + } + } + + #[crate::ram] + pub(crate) fn non_critical(&self) -> *mut NonCriticalSleepFrame { + // SAFETY: the buffer is installed and sized for this chip. + unsafe { self.buffer.add(NON_CRITICAL_FRAME_OFFSET) as *mut NonCriticalSleepFrame } + } + + #[crate::ram] + pub(crate) fn critical(&self) -> *mut CriticalSleepFrame { + // SAFETY: the buffer is installed and sized for this chip. + unsafe { self.buffer.add(CRITICAL_FRAME_OFFSET) as *mut CriticalSleepFrame } + } +} + +/// Saves the device registers and the non-critical frame. +#[crate::ram] +pub(crate) fn save_pre_critical(ctx: &mut CoreRetentionContext) { + device_regs::save(®ions(), ctx.device_frame()); + // SAFETY: the buffer is installed and sized for this chip. + unsafe { ctx.non_critical().as_mut().unwrap().save() }; +} + +/// Saves the critical frame and returns its pointer. +#[crate::ram] +pub(crate) fn save_critical_frame(ctx: &CoreRetentionContext) -> *mut CriticalSleepFrame { + let critical = ctx.critical(); + CRITICAL_FRAME_PTR[ctx.core].store(critical, Ordering::Release); + // This call returns twice. It returns here after it saved the frame, and again from the wake + // stub, with every register of the frame back in place. + unsafe { critical_regs_save(critical) } +} + +/// Saves and restores the CPU domain around a light sleep request. +/// +/// The caller must run with interrupts disabled on this core. [`LowPower::sleep_light`] holds that +/// state for the whole sleep path. +/// +/// `enter_sleep` requests the sleep. `wait` blocks until the hardware reports the result. +/// +/// esp-idf does not write back or invalidate the cache on this chip. It saves and restores the +/// cache configuration registers in the device-region frame instead +/// (`esp32c6/sleep_cpu.c:317-341`). +#[crate::ram] +pub(crate) fn sleep_retained(buffer: *mut u8, enter_sleep: fn() -> bool) -> bool { + let core = system::raw_core(); + let mut ctx = CoreRetentionContext::new(buffer, core); + save_pre_critical(&mut ctx); + let frame = save_critical_frame(&ctx); + + // The wake stub writes this word while the compiler believes that nothing did. + // SAFETY: `save_critical_frame` returns the frame pointer that it was given. + let pmufunc = unsafe { ptr::read_volatile(&raw const (*frame).pmufunc) }; + let rejected = if pmufunc & 3 == PMUFUNC_GOING_TO_SLEEP { + arm_wake_stub(); + enter_sleep() + } else { + // The wake holds the APP CPU in reset. A core that waits in the rendezvous comes back + // through the wake stub once it runs again. + #[cfg(all(multi_core, feature = "rt"))] + if rendezvous::helper_saved() { + crate::soc::cpu_control::restart_core1_after_wake(); + } + false + }; + + // A rejected request never powered the domain down, so the registers still hold what the save + // read. Writing them back would repeat side effects such as a PLIC interrupt claim. + // `esp_sleep_cpu_retention` restores on a wake only, for the same reason + // (`esp32c6/sleep_cpu.c:331-341`). + if !rejected { + // SAFETY: the frame was filled on this path before the sleep. + unsafe { ctx.non_critical().as_mut().unwrap().restore() }; + device_regs::restore(®ions(), &*ctx.device_frame()); + } + + rejected +} + +/// Clears the wake stub address that [`arm_wake_stub`] wrote. +#[inline(always)] +pub(crate) fn disarm_wake_stub() { + // SAFETY: the register is the retention word of this chip, and it holds no other state. + unsafe { wake_stub_reg().write_volatile(0) }; +} + +#[inline(always)] +pub(crate) fn arm_wake_stub() { + let stub = critical_regs_restore as *const () as usize as u32; + // SAFETY: the register is the retention word of this chip, and it holds no other state. + unsafe { wake_stub_reg().write_volatile(stub) }; +} + +/// `RTC_SLEEP_WAKE_STUB_ADDR_REG`: the word that holds the wake stub address across the sleep. +#[inline(always)] +pub(crate) fn wake_stub_reg() -> *mut u32 { + cfg_select! { + esp32s31 => crate::peripherals::LP_SYS::regs().lp_store(8).as_ptr(), + esp32p4 => crate::peripherals::LP_AON::regs().lp_store8().as_ptr(), + _ => crate::peripherals::LP_AON::regs().store8().as_ptr(), + } +} + +/// Runtime absolute address (as `u32`) of a named PAC register. +macro_rules! reg { + ($peri:ident, [$($path:tt)+]) => { + unsafe { &*crate::pac::$peri::PTR }.$($path)+.as_ptr() as *const u32 + }; +} + +macro_rules! saved_region_map { + ($( + $( #[cfg($cfg:tt)] )? { + $peri:ident, $start:tt, $count:expr + }, + )*) => { + const REGION_COUNT: usize = 0 $(+ { + 1 $( * cfg!($cfg) as usize )? + })*; + + pub(crate) const DEVICE_REGION_WORDS: usize = 0 $(+ { + ($count) $( * cfg!($cfg) as usize )? + })*; + + #[inline(always)] + pub(crate) fn regions() -> [DeviceRegion; REGION_COUNT] { + [ + $( + $(#[cfg($cfg)])? + DeviceRegion::new(reg!($peri, $start), $count), + )* + ] + } + }; +} + +#[cfg(any(esp32h2, esp32c6))] +saved_region_map! { + { INTPRI, [cpu_int_enable()], 45 }, + { INTPRI, [rnd_eco_high()], 1 }, + #[cfg(esp32c6)] // H2 onward this is read-only, no need to save + { EXTMEM, [l1_cache_ctrl()], 1 }, + { EXTMEM, [l1_cache_wrap_around_ctrl()], 1 }, + { PLIC_MX, [mxint_enable()], 38 }, + { PLIC_MX, [mxint_conf()], 1 }, + { PLIC_UX, [uxint_enable()], 38 }, + { PLIC_UX, [uxint_conf()], 1 }, + { CLINT, [msip()], 6 }, + { CLINT, [usip()], 6 }, +} + +#[cfg(any(esp32c5, esp32c61))] +saved_region_map! { + { CACHE, [cache_autoload_ctrl()], 5 }, + { CLIC, [int_config()], 3 }, + { CLIC, [int_ip(0)], 48 }, + { CLINT, [msip()], 1 }, + { CLINT, [mtimecmp()], 2 }, + { CLINT, [mtimectl()], 1 }, + { CLINT, [mtime()], 2 }, +} + +#[cfg(esp32p4)] +saved_region_map! { + { CLIC, [int_config()], 3 }, + { CLIC, [int_ip(0)], 48 }, + { CLINT, [msip()], 1 }, +} + +// FIXME: find out why this isn't equivalent to P4 +#[cfg(esp32s31)] +saved_region_map! { + { CLIC, [int_config()], 1 }, + { CLIC, [int_thresh()], 1 }, + { CLIC, [int_ip(0)], 48 }, + { CLINT, [msip()], 1 }, +} + +pub(crate) const CRITICAL_FRAME_OFFSET: usize = 0; +pub(crate) const NON_CRITICAL_FRAME_OFFSET: usize = CRITICAL_FRAME_OFFSET + CRITICAL_FRAME_SIZE; +pub(crate) const DEVICE_REGIONS_OFFSET: usize = NON_CRITICAL_FRAME_OFFSET + NON_CRITICAL_FRAME_SIZE; + +/// Bytes one core's frames need, rounded up to the alignment of the buffer. +pub(crate) const BLOCK_SIZE: usize = + (DEVICE_REGIONS_OFFSET + DEVICE_REGION_WORDS * 4).next_multiple_of(16); + +/// Bytes every core's frames need. +pub(crate) const BUFFER_SIZE: usize = BLOCK_SIZE * Cpu::COUNT; + +/// Couples CPU power-down to the installed retention buffer, for a light sleep. +/// +/// The bit is written and not only set, so that a configuration from [`RtcSleepConfig::deep`] +/// cannot carry a power-down into a light sleep that has no retention memory. +/// +/// A second running core must save itself, so the power-down also needs the rendezvous. The sleep +/// path engages it before this call, and does not get here if the other core stays out. +#[cfg(feature = "rt")] +pub(crate) fn configure_cpu_retention(config: &mut RtcSleepConfig, buffer: Option>) { + config.pd_flags.set_pd_cpu(buffer.is_some()); +} + +/// Requests the sleep, and retains the CPU across it if the sleep powers the CPU domain down. +/// +/// The retained path returns twice, so it owns the request and the wait. A sleep that keeps the +/// domain powered needs no frames, and it must not write them back: the registers still hold what +/// a save would have read, and a restore repeats side effects such as an interrupt claim. +#[crate::ram] +pub(crate) fn enter_sleep_with_retention( + config: &RtcSleepConfig, + buffer: Option>, +) -> bool { + match buffer.filter(|_| config.pd_flags.pd_cpu()) { + Some(buffer) => { + cpu_retention::sleep_retained(buffer.as_ptr(), sleep::pmu_common::request_sleep) + } + None => config.enter_sleep(), + } +} + +/// Finishes CPU retention after the sleep request returns. +/// +/// The disarm is unconditional, because the tail of the sleep runs on a wake and on a rejected +/// request. A stale stub address would otherwise outlive the sleep that armed it. +#[inline(always)] +pub(crate) fn finish_cpu_retention(_rejected: bool) { + disarm_wake_stub(); +} diff --git a/esp-hal/src/rtc_cntl/cpu_retention/software/rendezvous.rs b/esp-hal/src/rtc_cntl/cpu_retention/software/rendezvous.rs new file mode 100644 index 00000000000..3022ceb3d17 --- /dev/null +++ b/esp-hal/src/rtc_cntl/cpu_retention/software/rendezvous.rs @@ -0,0 +1,337 @@ +//! The rendezvous that lets both cores retain themselves across a light sleep. +//! +//! Software retention means that each core saves itself, so a stalled core comes back with +//! garbage. The PRO CPU requests every light sleep, and the APP CPU saves itself in the same window +//! and then waits for the sleep to end. A light sleep that the APP CPU asks for starts on the PRO +//! CPU too: the APP CPU kicks the PRO CPU, which requests the sleep from its IPC handler, and the +//! APP CPU takes its part of the handshake from its own call. +//! +//! The handshake is one shared [`Phase`]. Every transition has one writer, except the ways out of +//! [`Phase::Wanted`] and [`Phase::Requested`], which both cores take with a compare-and-swap. + +use core::{cell::UnsafeCell, mem::MaybeUninit, ptr}; + +use esp_sync::raw::{RawLock, SingleCoreInterruptLock}; +use portable_atomic::{AtomicU8, Ordering}; + +use super::{ + CoreRetentionContext, + device_regs, + frames::chip::PMUFUNC_GOING_TO_SLEEP, + save_critical_frame, + save_pre_critical, +}; +use crate::{ + interrupt::ipc::Ipc, + peripherals::{IPC, LPWR}, + rtc_cntl::sleep::{LowPower, RtcSleepConfig, SleepKind}, + soc::cpu_control, + system::Cpu, + time::implem as raw_time, +}; + +/// How long a core waits for the other core to answer. +/// +/// esp-idf waits without a bound, because it delivers the helper routine in a high-priority +/// interrupt that a critical section cannot mask. esp-hal has no such path: the IPC interrupt runs +/// at the lowest priority, so a core that holds a critical section of its own cannot answer it. A +/// request without an answer refuses the sleep. +const ANSWER_TIMEOUT_US: u64 = 1_000; + +/// The step that the rendezvous has reached. +#[repr(u8)] +#[derive(Clone, Copy, PartialEq, Eq)] +enum Phase { + /// No sleep uses the rendezvous. + Idle, + + /// The APP CPU asks for a sleep, and waits for the PRO CPU to take the request. + Wanted, + + /// The PRO CPU took the request of the APP CPU, and prepares the sleep. + Taken, + + /// The PRO CPU asks the APP CPU to save itself. + Requested, + + /// The APP CPU refused the sleep. + Refused, + + /// The APP CPU took the request, and saves itself. + Joined, + + /// The APP CPU saved itself, and waits for the sleep to end. + Saved, + + /// The sleep is over, or it never started. The APP CPU restores itself if it lost power. + Resume, + + /// The APP CPU is back, and waits for the PRO CPU to finish the sleep. + Done, +} + +static PHASE: AtomicU8 = AtomicU8::new(Phase::Idle as u8); + +/// The configuration of the sleep that the APP CPU asks for. +struct SleepConfig(UnsafeCell>); + +// SAFETY: the APP CPU writes the configuration before it moves the phase to `Wanted`, and the PRO +// CPU reads it only after it moved the phase from `Wanted` to `Taken`. +unsafe impl Sync for SleepConfig {} + +static SLEEP_CONFIG: SleepConfig = SleepConfig(UnsafeCell::new(MaybeUninit::uninit())); + +/// Takes a sleep that the APP CPU asks for, so that the light sleep that the PRO CPU starts +/// answers it. +/// +/// Runs on the PRO CPU, before a light sleep. +#[inline(always)] +pub(crate) fn take_request() { + swap_phase(Phase::Wanted, Phase::Taken); +} + +/// Lets the APP CPU return from a light sleep, which the PRO CPU has finished. +/// +/// This answers the request that [`take_request`] took, and releases the APP CPU from the +/// rendezvous. Runs on the PRO CPU, after a light sleep. +#[inline(always)] +pub(crate) fn release_app_cpu() { + // No compare-and-swap needed: the APP CPU never writes the phase while it is `Taken` or `Done`. + if matches!(phase(), Phase::Taken | Phase::Done) { + PHASE.store(Phase::Idle as u8, Ordering::Release); + } +} + +/// Brings the APP CPU into the rendezvous, and returns whether the PRO CPU sleeps. +/// +/// Runs on the PRO CPU, with interrupts disabled. A `false` return means that the APP CPU refused +/// the sleep, or that it did not answer in time. Nothing needs an undo then. A `true` return needs +/// [`finish`], whether the sleep happens or not. +#[crate::ram] +pub(crate) fn engage() -> bool { + if !cpu_control::is_running(Cpu::AppCpu) { + // A core that never started, or that the program stalled, holds nothing to save. The + // caller then sleeps as a single-core chip does. + return true; + } + + // The APP CPU can move the phase between `Idle` and `Wanted` meanwhile, so the swap retries. + let app_cpu_waits = loop { + let current = phase(); + debug_assert!(matches!( + current, + Phase::Idle | Phase::Wanted | Phase::Taken + )); + if swap_phase(current, Phase::Requested) { + break current != Phase::Idle; + } + }; + + // An APP CPU that asked for a sleep waits for it with interrupts disabled, and reads the phase + // itself. It could not take the doorbell anyway. + if !app_cpu_waits { + // Only this function posts to the APP CPU, so the post merges with a pending doorbell + // instead of waiting for it. + Ipc::new(unsafe { IPC::steal() }).call_function(Cpu::AppCpu, helper_entry); + } + + let deadline = raw_time::raw_counter() + raw_time::us_to_ticks(ANSWER_TIMEOUT_US); + loop { + match phase() { + Phase::Saved => return true, + Phase::Refused => { + PHASE.store(Phase::Idle as u8, Ordering::Release); + return false; + } + // Once the APP CPU took the request, it saves itself without a further answer, so + // the timeout covers the request only. + Phase::Requested if raw_time::raw_counter() >= deadline => { + if swap_phase(Phase::Requested, Phase::Idle) { + return false; + } + } + _ => core::hint::spin_loop(), + } + } +} + +/// Returns whether the APP CPU saved itself and waits for the sleep to end. +#[inline(always)] +pub(crate) fn helper_saved() -> bool { + phase() == Phase::Saved +} + +/// Lets the APP CPU restore itself, and waits until it is back. +/// +/// Runs on the PRO CPU after [`engage`] returned `true`, and does nothing if the APP CPU is not in +/// the rendezvous. After a power-down wake the APP CPU passes the wake stub, so the stub must stay +/// armed until this function returns. The APP CPU returns only after [`release_app_cpu`], once the +/// PRO CPU has restored the time base and recorded the wakeup cause. +#[crate::ram] +pub(crate) fn finish() { + if !helper_saved() { + return; + } + + PHASE.store(Phase::Resume as u8, Ordering::Release); + while phase() != Phase::Done { + core::hint::spin_loop(); + } +} + +/// Asks the PRO CPU for a light sleep, and takes the part of the APP CPU in it. +/// +/// Runs on the APP CPU, with interrupts disabled. Returns when the sleep is over, when the PRO CPU +/// refused it, or when the PRO CPU did not take the request in time. +#[crate::ram] +pub(crate) fn sleep_from_app_cpu(config: RtcSleepConfig) { + let mut deadline = None; + loop { + match phase() { + Phase::Idle => match deadline { + // The PRO CPU answered the request without the rendezvous, or refused it. + Some(_) => return, + None => { + // SAFETY: the phase is not `Wanted`, so the PRO CPU does not read the + // configuration. + unsafe { (*SLEEP_CONFIG.0.get()).write(config) }; + if swap_phase(Phase::Idle, Phase::Wanted) { + // Only this function posts to the PRO CPU, so the post never waits. + Ipc::new(unsafe { IPC::steal() }).call_function(Cpu::ProCpu, kick_entry); + deadline = Some( + raw_time::raw_counter() + raw_time::us_to_ticks(ANSWER_TIMEOUT_US), + ); + } + } + }, + // Every sleep that the PRO CPU requests needs this core, the one it requests for this + // call and one it requests on its own. + Phase::Requested => { + if swap_phase(Phase::Requested, Phase::Joined) { + run_helper(); + return; + } + } + Phase::Wanted => { + if deadline.is_some_and(|deadline| raw_time::raw_counter() >= deadline) + && swap_phase(Phase::Wanted, Phase::Idle) + { + return; + } + } + _ => core::hint::spin_loop(), + } + } +} + +/// Takes the request of the APP CPU, and requests the sleep for it. +#[crate::ram] +fn kick_entry() { + // The answer of `can_sleep` holds for the whole sleep, so nothing may give this core work + // between the two. + let irq_token = unsafe { SingleCoreInterruptLock.enter() }; + + // A kick of a request that the APP CPU withdrew, or that an earlier sleep answered, finds the + // phase moved on. + if swap_phase(Phase::Wanted, Phase::Taken) { + if can_sleep() { + // SAFETY: the APP CPU wrote the configuration before it set `Wanted`. + let config = unsafe { (*SLEEP_CONFIG.0.get()).assume_init() }; + LowPower::new(unsafe { LPWR::steal() }).sleep(config, SleepKind::Light, true); + } else { + PHASE.store(Phase::Idle as u8, Ordering::Release); + } + } + + unsafe { SingleCoreInterruptLock.exit(irq_token) }; +} + +/// Takes the doorbell of the PRO CPU. +#[crate::ram] +fn helper_entry() { + // The answer of `can_sleep` holds for the whole sleep, so nothing may give this core work + // between the two. + let irq_token = unsafe { SingleCoreInterruptLock.enter() }; + + // A doorbell of a request that the PRO CPU withdrew finds the phase moved on. + if phase() == Phase::Requested { + let join = can_sleep(); + let next = if join { Phase::Joined } else { Phase::Refused }; + if swap_phase(Phase::Requested, next) && join { + run_helper(); + } + } + + unsafe { SingleCoreInterruptLock.exit(irq_token) }; +} + +/// Saves the APP CPU, waits for the sleep to end, then restores the APP CPU if it lost power. +/// +/// The caller holds interrupts disabled, so that no handler runs between the two frames, and it +/// moved the phase to [`Phase::Joined`]. +/// +/// The branch predictor starts cache requests of its own, so it must be off while the CPU domain +/// has no power. esp-idf turns it off for this routine only, and not for the single-core path. +#[crate::ram] +fn run_helper() { + let _predictor = crate::soc::branch_predictor::DisabledBranchPredictor::new(); + + // SAFETY: the PRO CPU starts the rendezvous for a sleep that retains the CPU only, so the + // memory of the frames is installed. + let buffer = unsafe { crate::rtc_cntl::installed_buffer_ptr().unwrap_unchecked() }; + let mut ctx = CoreRetentionContext::new(buffer.as_ptr(), Cpu::AppCpu as usize); + save_pre_critical(&mut ctx); + let frame = save_critical_frame(&ctx); + + // The wake stub writes this word while the compiler believes that nothing did. + // SAFETY: `save_critical_frame` returns the frame pointer that it was given. + let pmufunc = unsafe { ptr::read_volatile(&raw const (*frame).pmufunc) }; + if pmufunc & 3 == PMUFUNC_GOING_TO_SLEEP { + // The CPU domain can lose power from here on. This core then comes back through the wake + // stub, after the PRO CPU released it from reset. This core does not arm the wake stub: + // the PRO CPU arms it for both cores. + PHASE.store(Phase::Saved as u8, Ordering::Release); + } else { + // The wake stub restored the critical frame already. + // SAFETY: the frame holds what this core saved before the sleep. + unsafe { ctx.non_critical().as_ref().unwrap().restore() }; + device_regs::restore(&super::regions(), ctx.device_frame()); + } + + while phase() != Phase::Resume { + core::hint::spin_loop(); + } + PHASE.store(Phase::Done as u8, Ordering::Release); + + // The PRO CPU can start the next sleep right after it releases this core, so this core waits + // for the phase to leave `Done`, and not for a particular phase. + while phase() == Phase::Done { + core::hint::spin_loop(); + } +} + +/// Returns whether the core that runs this function agrees to a light sleep. +#[inline(always)] +fn can_sleep() -> bool { + let handler = crate::rtc_cntl::sleep::CAN_SLEEP_HANDLER.load(Ordering::Acquire); + // SAFETY: `set_can_sleep_handler` takes a `fn() -> bool`, and this is that pointer. + handler.is_null() || unsafe { core::mem::transmute::<*mut (), fn() -> bool>(handler)() } +} + +#[inline(always)] +fn phase() -> Phase { + // SAFETY: every write to `PHASE` writes a `Phase`. + unsafe { core::mem::transmute::(PHASE.load(Ordering::Acquire)) } +} + +#[inline(always)] +fn swap_phase(current: Phase, new: Phase) -> bool { + PHASE + .compare_exchange( + current as u8, + new as u8, + Ordering::AcqRel, + Ordering::Acquire, + ) + .is_ok() +} diff --git a/esp-hal/src/rtc_cntl/cpu_retention/tagmem.rs b/esp-hal/src/rtc_cntl/cpu_retention/tagmem.rs new file mode 100644 index 00000000000..896e4f701a2 --- /dev/null +++ b/esp-hal/src/rtc_cntl/cpu_retention/tagmem.rs @@ -0,0 +1,242 @@ +//! Cache tag memory retention through the RTC_CNTL retention DMA. + +use core::{ + cell::UnsafeCell, + mem::MaybeUninit, + ptr::{self, NonNull}, +}; + +use portable_atomic::{AtomicPtr, Ordering}; +use static_cell::ConstStaticCell; + +use crate::{ + rtc_cntl::{cpu_retention::DMA_LINK_SIZE, sleep::LowPower}, + soc::{ + CONFIG_DATA_CACHE_LINE_SIZE, + CONFIG_DATA_CACHE_SIZE, + CONFIG_DCACHE_ASSOCIATED_WAYS, + CONFIG_ICACHE_ASSOCIATED_WAYS, + CONFIG_INSTRUCTION_CACHE_LINE_SIZE, + CONFIG_INSTRUCTION_CACHE_SIZE, + }, +}; + +const MEM_START: usize = property!("sleep.cpu_retention_mem_start"); +const MEM_END: usize = property!("sleep.cpu_retention_mem_end"); + +/// Tag block groups the retention hardware moves for one cache. +/// +/// esp-idf reads the geometry at run time with `Cache_Get_Mode`, because a bootloader applies it. +/// esp-hal has it as constants and passes them to the ROM itself, so the count is known when the +/// program is built. +const fn tag_block_groups(size: usize, ways: usize, line_size: usize) -> usize { + let sets = size / ways / line_size; + sets * (ways >> 2) +} + +const ICACHE_GROUPS: usize = tag_block_groups( + CONFIG_INSTRUCTION_CACHE_SIZE, + CONFIG_ICACHE_ASSOCIATED_WAYS, + CONFIG_INSTRUCTION_CACHE_LINE_SIZE, +); +const DCACHE_GROUPS: usize = tag_block_groups( + CONFIG_DATA_CACHE_SIZE, + CONFIG_DCACHE_ASSOCIATED_WAYS, + CONFIG_DATA_CACHE_LINE_SIZE, +); + +/// The group count as `RET_ICACHE_SIZE` and `RET_DCACHE_SIZE` take it. +/// +/// The largest cache of this chip needs 256 instruction and 512 data groups, one more than the +/// 8-bit and 9-bit fields hold, so the count wraps: zero means the full count, and every other +/// value means itself. esp-idf masks the same way (`sleep_cpu.c:73,93`). +/// +/// No document states this encoding, because the technical reference manual omits these registers +/// and the SVD carries no description of them, so it was measured instead. With the default cache +/// both fields read zero, and a light sleep still overwrote every payload byte of a buffer painted +/// beforehand: 9216 bytes, which is the full 768 groups. Zero therefore means the full count. +const ICACHE_SIZE_FIELD: u8 = (ICACHE_GROUPS & 0xff) as u8; +const DCACHE_SIZE_FIELD: u16 = (DCACHE_GROUPS & 0x1ff) as u16; + +/// A tag block is 92 bits for the instruction cache and 88 for the data cache, and the DMA aligns +/// both to 96. Three transfers of the 128-bit bus therefore move four blocks. +/// +/// This sizes from the true group counts, not from the wrapped register values, because the DMA +/// moves a full cache when the field reads zero. esp-idf reaches the same size through the +/// fallback in `blk_gs` (`sleep_cpu.c:79,103`). +const PAYLOAD_SIZE: usize = + ((ICACHE_GROUPS.next_multiple_of(4) + DCACHE_GROUPS.next_multiple_of(4)) << 2) * 3; + +const BUFFER_SIZE: usize = PAYLOAD_SIZE + DMA_LINK_SIZE; + +static INSTALLED: AtomicPtr = AtomicPtr::new(ptr::null_mut()); + +/// Memory that light sleep uses to retain the cache tag memory. +/// +/// This storage must be placed to `#[ram(reclaimed, unstable(zeroed))]`, then +/// a static mutable reference to [`CacheTagRetentionMemory`] can be taken out of it. +#[instability::unstable] +pub struct CacheTagRetentionStorage { + inner: ConstStaticCell, +} + +impl CacheTagRetentionStorage { + /// Creates storage for the retention memory. + #[instability::unstable] + pub const fn new() -> Self { + Self { + inner: ConstStaticCell::new(CacheTagRetentionMemory { + storage: UnsafeCell::new(MaybeUninit::uninit()), + }), + } + } + + /// Takes the reference to the retention memory. + /// + /// Can only be called once. + #[instability::unstable] + pub fn take(&'static self) -> &'static mut CacheTagRetentionMemory { + self.inner.take() + } +} + +#[instability::unstable] +impl Default for CacheTagRetentionStorage { + fn default() -> Self { + Self::new() + } +} + +// SAFETY: ConstStaticCell is a `MaybeUninit` buffer, and an AtomicBool strapped together, +// both are safe to be zero-initialized. +unsafe impl bytemuck::Zeroable for CacheTagRetentionStorage {} + +/// Memory that light sleep uses to retain the cache tag memory. +/// +/// Retaining the tags lets the wake path skip the cache invalidate, and the misses that follow it. +/// This trades memory for wake latency, and it is not needed for correctness. +/// +/// The size follows the cache geometry that the program is built with, so a program that +/// configures a smaller cache needs less memory. +/// +/// The retention DMA writes this memory while the CPU is powered down, so the buffer gives no way +/// to read or write its contents. +/// +/// Install the buffer with [`LowPower::install_cache_tag_retention_memory`], in addition to the +/// memory that [`LowPower::install_cpu_retention_memory`][install] takes. Retaining the tags alone +/// does nothing: the tags are lost only when the CPU domain powers down. +/// +/// [install]: LowPower::install_cpu_retention_memory +#[repr(align(16))] +#[instability::unstable] +pub struct CacheTagRetentionMemory { + storage: UnsafeCell>, +} + +impl CacheTagRetentionMemory { + fn as_mut_ptr(&self) -> *mut u8 { + self.storage.get().cast() + } +} + +/// The reason why [`LowPower::install_cache_tag_retention_memory`] refused a buffer. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[instability::unstable] +#[non_exhaustive] +pub enum CacheTagRetentionMemoryError { + /// The buffer is not inside the range that the retention DMA reaches. + OutOfRange, + /// The driver holds a tag memory buffer already. + AlreadyInstalled, +} + +#[instability::unstable] +impl core::error::Error for CacheTagRetentionMemoryError {} + +#[instability::unstable] +impl core::fmt::Display for CacheTagRetentionMemoryError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::OutOfRange => write!( + f, + "the buffer is outside the retention memory range (0x{MEM_START:X}..0x{MEM_END:X})" + ), + Self::AlreadyInstalled => write!(f, "a tag memory buffer is installed already"), + } + } +} + +impl LowPower<'_> { + #[procmacros::doc_replace] + /// Gives light sleep the memory that it uses to retain the cache tag memory. + /// + /// This is an optimisation, and it is separate from + /// [`install_cpu_retention_memory`][install] because it costs memory and buys wake latency + /// rather than correctness. Without it, a retained sleep invalidates both caches on the wake + /// path, which is correct but slower. + /// + /// The memory stays with the driver for the life of the program, and a second call is an + /// error, because the sleep path can hold one buffer only. + /// + /// # Errors + /// + /// Returns [`CacheTagRetentionMemoryError`] if the driver holds a buffer already, or if the + /// buffer is not inside the range that the retention DMA reaches. The + /// [`#[ram(reclaimed, unstable(zeroed))]`][crate::ram] attribute places a static inside that + /// range. + /// + /// # Examples + /// + /// ```rust, no_run + /// # {before_snippet} + /// use esp_hal::rtc_cntl::{CacheTagRetentionStorage, CpuRetentionStorage, sleep::LowPower}; + /// + /// // #[esp_hal::ram(reclaimed, unstable(zeroed))] + /// static RETENTION: CpuRetentionStorage = CpuRetentionStorage::new(); + /// + /// // #[esp_hal::ram(reclaimed, unstable(zeroed))] + /// static TAG_MEMORY: CacheTagRetentionStorage = CacheTagRetentionStorage::new(); + /// + /// let mut lpwr = LowPower::new(peripherals.LPWR); + /// lpwr.install_cpu_retention_memory(RETENTION.take())?; + /// lpwr.install_cache_tag_retention_memory(TAG_MEMORY.take())?; + /// # {after_snippet} + /// ``` + /// + /// [install]: LowPower::install_cpu_retention_memory + #[instability::unstable] + pub fn install_cache_tag_retention_memory( + &mut self, + memory: &'static mut CacheTagRetentionMemory, + ) -> Result<(), CacheTagRetentionMemoryError> { + let memory = memory.as_mut_ptr(); + let start = memory as usize; + + if start < MEM_START || start + BUFFER_SIZE > MEM_END { + return Err(CacheTagRetentionMemoryError::OutOfRange); + } + + INSTALLED + .compare_exchange(ptr::null_mut(), memory, Ordering::AcqRel, Ordering::Acquire) + .map(|_| ()) + .map_err(|_| CacheTagRetentionMemoryError::AlreadyInstalled) + } +} + +/// The installed buffer, and the payload size the DMA descriptor needs. +pub(crate) fn installed_buffer_ptr() -> Option> { + let memory = INSTALLED.load(Ordering::Acquire); + + NonNull::new(memory) +} + +/// Bytes the DMA moves, not counting the descriptor. +pub(crate) const fn payload_size() -> usize { + PAYLOAD_SIZE +} + +/// The values that `RET_ICACHE_SIZE` and `RET_DCACHE_SIZE` take for this cache. +pub(crate) const fn size_fields() -> (u8, u16) { + (ICACHE_SIZE_FIELD, DCACHE_SIZE_FIELD) +} diff --git a/esp-hal/src/rtc_cntl/mod.rs b/esp-hal/src/rtc_cntl/mod.rs index 5442854c406..83717f523a2 100644 --- a/esp-hal/src/rtc_cntl/mod.rs +++ b/esp-hal/src/rtc_cntl/mod.rs @@ -118,9 +118,40 @@ use crate::{ peripherals::Interrupt, }; use crate::{peripherals::RTC_TIMER, system::Cpu, time::Duration}; -// only include sleep where it's been implemented -#[cfg(sleep_driver_supported)] -pub mod sleep; + +unstable_module! { + // only include sleep where it's been implemented + #[cfg(sleep_driver_supported)] + pub mod sleep; +} + +cfg_select! { + supports_cpu_power_down => { + mod cpu_retention; + pub(crate) use cpu_retention::installed_buffer_ptr; + #[instability::unstable] + pub use cpu_retention::memory::{ + CpuRetentionMemory, + CpuRetentionMemoryError, + CpuRetentionStorage, + }; + } + _ => {} +} + +cfg_select! { + supports_tagmem_power_down => { + #[path = "cpu_retention/tagmem.rs"] + mod tagmem; + #[instability::unstable] + pub use tagmem::{ + CacheTagRetentionMemory, + CacheTagRetentionMemoryError, + CacheTagRetentionStorage, + }; + } + _ => {} +} #[cfg_attr(esp32, path = "rtc/esp32.rs")] #[cfg_attr(esp32c2, path = "rtc/esp32c2.rs")] @@ -129,12 +160,32 @@ pub mod sleep; #[cfg_attr(esp32c6, path = "rtc/esp32c6.rs")] #[cfg_attr(esp32c61, path = "rtc/esp32c61.rs")] #[cfg_attr(esp32h2, path = "rtc/esp32h2.rs")] +#[cfg_attr(esp32h4, path = "rtc/esp32h4.rs")] #[cfg_attr(esp32p4, path = "rtc/esp32p4.rs")] #[cfg_attr(esp32s2, path = "rtc/esp32s2.rs")] #[cfg_attr(esp32s3, path = "rtc/esp32s3.rs")] #[cfg_attr(esp32s31, path = "rtc/esp32s31.rs")] pub(crate) mod rtc; +// Trims the RTC bandgap using eFuse calibration data. +// +// The trim only needs to be applied on power-on; the analog domain retains it +// across other resets, so the eFuses are not read again on those paths. +// +// `ocode` returns the trim value to apply, or `None` if the eFuses hold no +// usable calibration data. +#[cfg(any(esp32c2, esp32c3, esp32c5, esp32c6, esp32c61, esp32s2, esp32s3))] +pub(crate) fn calibrate_ocode(ocode: impl FnOnce() -> Option) { + if crate::system::reset_reason() != Some(SocResetReason::ChipPowerOn) { + return; + } + + if let Some(ocode) = ocode() { + crate::soc::regi2c::I2C_ULP_EXT_CODE.write_reg(ocode); + crate::soc::regi2c::I2C_ULP_IR_FORCE_CODE.write_field(1); + } +} + cfg_select! { esp32s31 => { use crate::peripherals::{LP_SYS as LP_AON, LP_WDT}; @@ -177,12 +228,12 @@ for_each_wakeup_source! { (all $( ($variant:ident, $bit:literal) ),*) => { /// A source that can wake the chip from sleep. /// - /// Each variant models a single bit in the wakeup registers. This enum is the internal - /// representation shared by [`WakeTriggers`][crate::rtc_cntl::sleep::WakeTriggers] (the - /// sources configured to end a sleep) and [`WakeupReason`] (the source(s) that caused the - /// most recent wakeup, see [`wakeup_cause`]). + /// Each variant models a single bit in the wakeup registers. Internal representation shared + /// by [`WakeTriggers`][crate::rtc_cntl::sleep::WakeTriggers] (the sources configured to + /// end a sleep) and [`WakeupReason`] (the source(s) that caused the most recent wakeup, + /// see [`wakeup_cause`]) /// - /// Note that the available variants depend on the target chip. + /// The available variants depend on the target chip. #[derive(Debug, enumset::EnumSetType)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum WakeupSource { @@ -199,7 +250,7 @@ for_each_wakeup_source! { /// Returned by [`wakeup_cause`]. This is a thin wrapper around the set of [`WakeupSource`]s that /// were reported by the hardware. The set is empty if the chip was not woken from sleep. /// -/// Note that the available sources depend on the target chip. +/// The available sources depend on the target chip. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[cfg(sleep_driver_supported)] @@ -207,12 +258,12 @@ pub struct WakeupReason(enumset::EnumSet); #[cfg(sleep_driver_supported)] impl WakeupReason { - /// Returns `true` if the chip was not woken from sleep by any source. + /// Returns whether the chip was not woken from sleep by any source. pub fn is_empty(&self) -> bool { self.0.is_empty() } - /// Returns `true` if the given source caused the most recent wakeup. + /// Returns whether the given source caused the most recent wakeup. pub fn contains(&self, source: WakeupSource) -> bool { self.0.contains(source) } @@ -228,7 +279,7 @@ pub struct Rtc<'d> { // This field holds the peripheral, which prevents a second `Rtc`. The code uses // `RTC_TIMER::regs()` for the registers, because the sleep alarm needs them without an `Rtc`. _rtc_timer: RTC_TIMER<'d>, - /// Reset Watchdog Timer. + /// Resets Watchdog Timer. pub rwdt: Rwdt, /// Super Watchdog #[cfg(soc_has_swd_watchdog)] @@ -236,7 +287,7 @@ pub struct Rtc<'d> { } impl<'d> Rtc<'d> { - /// Create a new instance in [crate::Blocking] mode. + /// Creates a new instance in [crate::Blocking] mode. /// /// Optionally an interrupt handler can be bound. pub fn new(rtc_timer: RTC_TIMER<'d>) -> Self { @@ -248,31 +299,30 @@ impl<'d> Rtc<'d> { } } - /// Get the time since boot in the raw register units. + /// Returns the time since boot in the raw register units. #[cfg(lp_timer_driver_supported)] fn time_since_boot_raw(&self) -> u64 { time_since_boot_raw() } - /// Get the time elapsed since the last power-on reset. + /// Returns the time elapsed since the last power-on reset. /// - /// It should be noted that any reset or sleep, other than a power-up reset, will not stop or + /// Any reset or sleep, other than a power-up reset, will not stop or /// reset the RTC timer. #[cfg(lp_timer_driver_supported)] pub fn time_since_power_up(&self) -> Duration { Duration::from_micros(crate::clock::rtc_ticks_to_us(self.time_since_boot_raw())) } - /// Read the current value of the boot time registers in microseconds. + /// Reads the current value of the boot time registers in microseconds. #[cfg(lp_timer_driver_supported)] fn boot_time_us(&self) -> u64 { // For more info on about how RTC setting works and what it has to do with boot time, see https://github.com/esp-rs/esp-hal/pull/1883 - let (low_reg, high_reg) = - cfg_select! { - esp32s31 => (LP_AON::regs().lp_store(2), LP_AON::regs().lp_store(3)), - esp32p4 => (LP_AON::regs().lp_store2(), LP_AON::regs().lp_store3()), - _ => (LP_AON::regs().store2(), LP_AON::regs().store3()), - }; + let (low_reg, high_reg) = cfg_select! { + esp32s31 => (LP_AON::regs().lp_store(2), LP_AON::regs().lp_store(3)), + esp32p4 => (LP_AON::regs().lp_store2(), LP_AON::regs().lp_store3()), + _ => (LP_AON::regs().store2(), LP_AON::regs().store3()), + }; let l = low_reg.read().bits() as u64; let h = high_reg.read().bits() as u64; @@ -281,18 +331,17 @@ impl<'d> Rtc<'d> { l + (h << 32) } - /// Set the current value of the boot time registers in microseconds. + /// Sets the current value of the boot time registers in microseconds. #[cfg(lp_timer_driver_supported)] fn set_boot_time_us(&self, boot_time_us: u64) { // Please see `boot_time_us` for documentation on registers and peripherals // used for certain SOCs. - let (low_reg, high_reg) = - cfg_select! { - esp32s31 => (LP_AON::regs().lp_store(2), LP_AON::regs().lp_store(3)), - esp32p4 => (LP_AON::regs().lp_store2(), LP_AON::regs().lp_store3()), - _ => (LP_AON::regs().store2(), LP_AON::regs().store3()), - }; + let (low_reg, high_reg) = cfg_select! { + esp32s31 => (LP_AON::regs().lp_store(2), LP_AON::regs().lp_store(3)), + esp32p4 => (LP_AON::regs().lp_store2(), LP_AON::regs().lp_store3()), + _ => (LP_AON::regs().store2(), LP_AON::regs().store3()), + }; // https://github.com/espressif/esp-idf/blob/23e4823/components/newlib/port/esp_time_impl.c#L102-L103 @@ -303,9 +352,9 @@ impl<'d> Rtc<'d> { } #[procmacros::doc_replace] - /// Get the current time in microseconds. + /// Returns the current time in microseconds. /// - /// # Example + /// # Examples /// /// This example shows how to get the weekday of the current time in /// New York using the `jiff` crate. This example works in core-only @@ -344,7 +393,7 @@ impl<'d> Rtc<'d> { } } - /// Set the current time in microseconds. + /// Sets the current time in microseconds. #[cfg(lp_timer_driver_supported)] pub fn set_current_time_us(&self, current_time_us: u64) { // Current time is boot time + time since boot (rtc time) @@ -368,8 +417,7 @@ impl<'d> Rtc<'d> { /// Temporarily disable log messages of the ROM bootloader. /// - /// If you need to permanently disable the ROM bootloader messages, you'll - /// need to set the corresponding eFuse. + /// To permanently disable the ROM bootloader messages, set the corresponding eFuse. pub fn disable_rom_message_printing(&self) { // Corresponding documentation: // ESP32-S3: TRM v1.5 chapter 8.3 @@ -381,18 +429,15 @@ impl<'d> Rtc<'d> { _ => LP_AON::regs().store4(), }; let disable_mask = cfg_select! { - any(esp32p4, esp32s31) => { - Self::RTC_DISABLE_ROM_LOG | (Self::RTC_DISABLE_ROM_LOG << 16) - } + any(esp32p4, esp32s31) => Self::RTC_DISABLE_ROM_LOG | (Self::RTC_DISABLE_ROM_LOG << 16), _ => Self::RTC_DISABLE_ROM_LOG, }; reg.modify(|r, w| unsafe { w.bits(r.bits() | disable_mask) }); } - /// Register an interrupt handler for the RTC. + /// Registers an interrupt handler for the RTC. /// - /// Note that this will replace any previously registered interrupt - /// handlers. + /// Replaces any previously registered interrupt handlers. #[instability::unstable] #[cfg(lp_timer_driver_supported)] pub fn set_interrupt_handler(&mut self, handler: InterruptHandler) { @@ -424,14 +469,14 @@ impl crate::interrupt::InterruptConfigurable for Rtc<'_> { pub enum RwdtStageAction { /// No effect on the system. Off = 0, - /// Trigger an interrupt. + /// Triggers an interrupt. Interrupt = 1, - /// Reset the CPU core. + /// Resets the CPU core. ResetCpu = 2, - /// Reset the main system. + /// Resets the main system. /// The power management unit and RTC peripherals will not be reset. ResetCore = 3, - /// Reset the main system, power management unit and RTC peripherals. + /// Resets the main system, power management unit and RTC peripherals. ResetSystem = 4, } @@ -457,14 +502,14 @@ pub struct Rwdt; /// RTC Watchdog Timer driver. impl Rwdt { - /// Enable the watchdog timer instance. + /// Enables the watchdog timer instance. /// Watchdog starts with default settings (`stage 0` resets the system, the - /// others are deactivated) + /// others are deactivated). pub fn enable(&mut self) { self.set_enabled(true); } - /// Disable the watchdog timer instance. + /// Disables the watchdog timer instance. pub fn disable(&mut self) { self.set_enabled(false); } @@ -497,17 +542,17 @@ impl Rwdt { self.set_write_protection(true); } - /// Listen for interrupts on stage 0. + /// Listens for interrupts on stage 0. pub fn listen(&mut self) { self.set_listen(true); } - /// Stop listening for interrupts on stage 0. + /// Stops listening for interrupts on stage 0. pub fn unlisten(&mut self) { self.set_listen(false); } - /// Clear interrupt. + /// Clears interrupt. pub fn clear_interrupt(&mut self) { self.set_write_protection(false); @@ -521,7 +566,7 @@ impl Rwdt { self.set_write_protection(true); } - /// Check if the interrupt is set. + /// Returns whether the interrupt is set. pub fn is_interrupt_set(&self) -> bool { cfg_select! { esp32p4 => LP_WDT::regs().int_st().read().lp_wdt().bit_is_set(), @@ -529,7 +574,7 @@ impl Rwdt { } } - /// Feed the watchdog timer. + /// Feeds the watchdog timer. pub fn feed(&mut self) { self.set_write_protection(false); @@ -578,7 +623,7 @@ impl Rwdt { self.set_write_protection(true); } - /// Configure timeout value for the selected stage. + /// Configures timeout value for the selected stage. pub fn set_timeout(&mut self, stage: RwdtStage, timeout: Duration) { let timeout_raw = crate::clock::us_to_rtc_ticks(timeout.as_micros()) as u32; @@ -598,7 +643,7 @@ impl Rwdt { self.set_write_protection(true); } - /// Set the action for a specific stage. + /// Sets the action for a specific stage. pub fn set_stage_action(&mut self, stage: RwdtStage, action: RwdtStageAction) { self.set_write_protection(false); @@ -628,17 +673,17 @@ pub struct Swd; /// Super Watchdog driver #[cfg(soc_has_swd_watchdog)] impl Swd { - /// Enable the watchdog timer instance + /// Enables the watchdog timer instance. pub fn enable(&mut self) { self.set_enabled(true); } - /// Disable the watchdog timer instance + /// Disables the watchdog timer instance. pub fn disable(&mut self) { self.set_enabled(false); } - /// Enable/disable write protection for WDT registers + /// Enables or disables write protection for WDT registers. fn set_write_protection(&mut self, enable: bool) { let wkey = if enable { 0u32 @@ -722,7 +767,7 @@ pub(crate) fn time_since_boot_raw() -> u64 { }) } -/// Return reset reason. +/// Returns reset reason. pub fn reset_reason(cpu: Cpu) -> Option { let reason = crate::rom::rtc_get_reset_reason(cpu as u32); @@ -733,7 +778,7 @@ pub fn reset_reason(cpu: Cpu) -> Option { #[cfg(sleep_driver_supported)] static LIGHT_SLEEP_WAKEUP: portable_atomic::AtomicBool = portable_atomic::AtomicBool::new(false); -/// Return the cause(s) of the most recent wakeup. +/// Returns the cause(s) of the most recent wakeup. /// /// A sleep can be ended by more than one source simultaneously, so all matching sources are /// returned. The result is empty if the chip was not woken from sleep (for example on a cold boot, @@ -811,8 +856,7 @@ impl WakeLock { /// Releases a wake lock, allowing automatic light sleep when no wake locks are held. /// - /// Note that this function should only be called to release a wake lock acquired via - /// [`Self::acquire`]. + /// Must only be called to release a wake lock acquired via [`Self::acquire`] pub fn release() { #[cfg(sleep_light_sleep)] { @@ -821,7 +865,7 @@ impl WakeLock { } } - /// Returns `true` if at least one wake lock is currently held. + /// Returns whether at least one wake lock is currently held. #[instability::unstable] pub fn is_active() -> bool { cfg_select! { diff --git a/esp-hal/src/rtc_cntl/rtc/esp32.rs b/esp-hal/src/rtc_cntl/rtc/esp32.rs index 1ff65fbb528..50394af73e3 100644 --- a/esp-hal/src/rtc_cntl/rtc/esp32.rs +++ b/esp-hal/src/rtc_cntl/rtc/esp32.rs @@ -15,7 +15,7 @@ pub(crate) fn init(_config: &ClockConfig) {} #[derive(Debug, Clone, Copy, PartialEq, Eq, FromRepr)] /// SOC Reset Reason. pub enum SocResetReason { - /// Power on reset + /// Powers on reset. ChipPowerOn = 0x01, /// Software resets the digital core CoreSw = 0x03, @@ -46,7 +46,7 @@ pub enum SocResetReason { Cpu0RtcWdt = 0x0D, /// CPU0 resets CPU1 by DPORT_APPCPU_RESETTING Cpu1Cpu0 = 0x0E, - /// Reset when the VDD voltage is not stable + /// Resets when the VDD voltage is not stable. SysBrownOut = 0x0F, /// RTC watch dog resets digital core and rtc module SysRtcWdt = 0x10, diff --git a/esp-hal/src/rtc_cntl/rtc/esp32c2.rs b/esp-hal/src/rtc_cntl/rtc/esp32c2.rs index 1b87d3bf3eb..4752cff7887 100644 --- a/esp-hal/src/rtc_cntl/rtc/esp32c2.rs +++ b/esp-hal/src/rtc_cntl/rtc/esp32c2.rs @@ -36,11 +36,24 @@ pub(crate) fn init(_config: &ClockConfig) { regi2c::I2C_ULP_IR_FORCE_XPD_CK.write_field(0); } -fn calibrate_ocode() {} +// Trims the RTC bandgap using eFuse calibration data. +// +// See `set_ocode_by_efuse` in +// +fn calibrate_ocode() { + super::calibrate_ocode(|| { + (crate::efuse::block_version() != (0, 0)).then(|| { + (crate::efuse::sign_magnitude( + crate::efuse::read_field_le::(crate::efuse::OCODE).into(), + 6, + ) + 100) as u8 + }) + }); +} fn set_rtc_dig_dbias() {} -/// Perform clock control related initialization +/// Performs clock control related initialization. fn clock_control_init() { let extmem = EXTMEM::regs(); let spi_mem_0 = SPI0::regs(); @@ -61,7 +74,7 @@ fn clock_control_init() { spi_mem_1.clock_gate().modify(|_, w| w.clk_en().clear_bit()); } -/// Perform power control related initialization +/// Performs power control related initialization. fn power_control_init() { let rtc_cntl = LPWR::regs(); let system = SYSTEM::regs(); @@ -126,7 +139,7 @@ fn power_control_init() { }); } -/// Configure whether certain peripherals are powered down in deep sleep +/// Configures whether certain peripherals are powered down in deep sleep. fn rtc_sleep_pu() { LPWR::regs() .dig_pwc() @@ -154,7 +167,7 @@ fn rtc_sleep_pu() { #[derive(Debug, Clone, Copy, PartialEq, Eq, FromRepr)] /// SOC Reset Reason. pub enum SocResetReason { - /// Power on reset + /// Powers on reset. ChipPowerOn = 0x01, /// Software resets the digital core by RTC_CNTL_SW_SYS_RST CoreSw = 0x03, @@ -170,7 +183,7 @@ pub enum SocResetReason { Cpu0Sw = 0x0C, /// RTC watch dog resets CPU 0 Cpu0RtcWdt = 0x0D, - /// VDD voltage is not stable and resets the digital core + /// VDD voltage is not stable and resets the digital core. SysBrownOut = 0x0F, /// RTC watch dog resets digital core and rtc module SysRtcWdt = 0x10, diff --git a/esp-hal/src/rtc_cntl/rtc/esp32c3.rs b/esp-hal/src/rtc_cntl/rtc/esp32c3.rs index 83f4eb22e4c..291521d84c0 100644 --- a/esp-hal/src/rtc_cntl/rtc/esp32c3.rs +++ b/esp-hal/src/rtc_cntl/rtc/esp32c3.rs @@ -54,11 +54,20 @@ pub(crate) fn init(_config: &ClockConfig) { regi2c::I2C_ULP_IR_FORCE_XPD_CK.write_field(0); } -fn calibrate_ocode() {} +// Trims the RTC bandgap using eFuse calibration data. +// +// See `set_ocode_by_efuse` in +// +fn calibrate_ocode() { + super::calibrate_ocode(|| { + (crate::efuse::block_version().0 == 1) + .then(|| crate::efuse::read_field_le::(crate::efuse::OCODE)) + }); +} fn set_rtc_dig_dbias() {} -/// Perform clock control related initialization +/// Performs clock control related initialization. fn clock_control_init() { let extmem = EXTMEM::regs(); let spi_mem_0 = SPI0::regs(); @@ -79,7 +88,7 @@ fn clock_control_init() { spi_mem_1.clock_gate().modify(|_, w| w.clk_en().clear_bit()); } -/// Perform power control related initialization +/// Performs power control related initialization. fn power_control_init() { let rtc_cntl = LPWR::regs(); let system = SYSTEM::regs(); @@ -151,7 +160,7 @@ fn power_control_init() { }); } -/// Configure whether certain peripherals are powered down in deep sleep +/// Configures whether certain peripherals are powered down in deep sleep. fn rtc_sleep_pu() { let rtc_cntl = LPWR::regs(); let apb_ctrl = APB_CTRL::regs(); @@ -183,7 +192,7 @@ fn rtc_sleep_pu() { /// SOC Reset Reason. #[derive(Debug, Clone, Copy, PartialEq, Eq, FromRepr)] pub enum SocResetReason { - /// Power on reset + /// Powers on reset. /// /// In ESP-IDF this value (0x01) can *also* be `ChipBrownOut` or /// `ChipSuperWdt`, however that is not really compatible with Rust-style @@ -205,7 +214,7 @@ pub enum SocResetReason { Cpu0Sw = 0x0C, /// RTC watch dog resets CPU 0 Cpu0RtcWdt = 0x0D, - /// VDD voltage is not stable and resets the digital core + /// VDD voltage is not stable and resets the digital core. SysBrownOut = 0x0F, /// RTC watch dog resets digital core and rtc module SysRtcWdt = 0x10, diff --git a/esp-hal/src/rtc_cntl/rtc/esp32c5.rs b/esp-hal/src/rtc_cntl/rtc/esp32c5.rs index cdb322f8d29..f577a78dfd9 100644 --- a/esp-hal/src/rtc_cntl/rtc/esp32c5.rs +++ b/esp-hal/src/rtc_cntl/rtc/esp32c5.rs @@ -9,6 +9,22 @@ use crate::{ }, }; +// Trims the RTC bandgap using eFuse calibration data. +// +// See `esp_ocode_calib_init` in +// +fn calibrate_ocode() { + super::calibrate_ocode(|| { + let chip = crate::efuse::chip_revision().combined(); + let (major, minor) = crate::efuse::block_version(); + let blk = u16::from(major) * 100 + u16::from(minor); + + // v0.1 chips and v1.0+ chips got the ocode in different block versions. + ((chip == 1 && blk >= 1) || (chip >= 100 && blk >= 2)) + .then(|| crate::efuse::read_field_le::(crate::efuse::OCODE)) + }); +} + fn pmu_power_domain_force_default() { // for bypass reserved power domain @@ -114,6 +130,7 @@ impl From for ModemClockLpclkSource { fn from(src: LpSlowClkConfig) -> Self { match src { LpSlowClkConfig::RcSlow => Self::RcSlow, + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => Self::XTAL32K, LpSlowClkConfig::OscSlow => Self::EXT32K, } @@ -1001,6 +1018,8 @@ pub(crate) fn init(config: &ClockConfig) { pmu_power_domain_force_default(); + calibrate_ocode(); + // esp_perip_clk_init() modem_clock_domain_power_state_icg_map_init(); @@ -1086,7 +1105,7 @@ fn modem_clk_domain_active_state_icg_map_preinit() { /// SOC Reset Reason. #[derive(Debug, Clone, Copy, PartialEq, Eq, FromRepr)] pub enum SocResetReason { - /// Power on reset + /// Powers on reset. /// /// In ESP-IDF this value (0x01) can *also* be `ChipBrownOut` or /// `ChipSuperWdt`, however that is not really compatible with Rust-style @@ -1108,7 +1127,7 @@ pub enum SocResetReason { Cpu0Sw = 0x0C, /// RTC watch dog resets CPU 0 Cpu0RtcWdt = 0x0D, - /// VDD voltage is not stable and resets the digital core + /// VDD voltage is not stable and resets the digital core. SysBrownOut = 0x0F, /// RTC watch dog resets digital core and rtc module SysRtcWdt = 0x10, @@ -1124,7 +1143,7 @@ pub enum SocResetReason { CoreUsbJtag = 0x16, /// JTAG resets CPU Cpu0JtagCpu = 0x18, - /// Power glitch resets CPU + /// Powers glitch resets CPU. PowerGlitch = 0x19, /// CPU lockup reset CpuLockup = 0x1A, diff --git a/esp-hal/src/rtc_cntl/rtc/esp32c6.rs b/esp-hal/src/rtc_cntl/rtc/esp32c6.rs index f3b6240181a..78316a0386d 100644 --- a/esp-hal/src/rtc_cntl/rtc/esp32c6.rs +++ b/esp-hal/src/rtc_cntl/rtc/esp32c6.rs @@ -6,6 +6,17 @@ use crate::{ soc::{clocks::LpSlowClkConfig, regi2c, xtal32k}, }; +// Trims the RTC bandgap using eFuse calibration data. +// +// See `esp_ocode_calib_init` in +// +fn calibrate_ocode() { + super::calibrate_ocode(|| { + (crate::efuse::block_version() != (0, 0)) + .then(|| crate::efuse::read_field_le::(crate::efuse::OCODE)) + }); +} + fn pmu_power_domain_force_default() { // for bypass reserved power domain @@ -68,7 +79,6 @@ fn pmu_power_domain_force_default() { fn modem_clock_domain_power_state_icg_map_init() { // C6 has SOC_PM_SUPPORT_PMU_MODEM_STATE defined - // const ICG_NOGATING_SLEEP: u8 = 1 << 0; // unused const ICG_NOGATING_MODEM: u8 = 1 << 1; const ICG_NOGATING_ACTIVE: u8 = 1 << 2; @@ -111,6 +121,7 @@ impl From for ModemClockLpclkSource { fn from(src: LpSlowClkConfig) -> Self { match src { LpSlowClkConfig::RcSlow => Self::RcSlow, + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => Self::XTAL32K, LpSlowClkConfig::OscSlow => Self::EXT32K, } @@ -185,6 +196,8 @@ const ICG_MODEM_CODE_SLEEP: u8 = 0; const ICG_MODEM_CODE_MODEM: u8 = 1; const ICG_MODEM_CODE_ACTIVE: u8 = 2; +pub(crate) const ICG_NOGATING_SLEEP: u8 = 1 << ICG_MODEM_CODE_SLEEP; + const HP_SYSCLK_XTAL: u8 = 0; const HP_SYSCLK_PLL: u8 = 1; @@ -993,6 +1006,8 @@ pub(crate) fn init(config: &ClockConfig) { pmu_power_domain_force_default(); + calibrate_ocode(); + // esp_perip_clk_init() modem_clock_domain_power_state_icg_map_init(); @@ -1074,7 +1089,7 @@ fn modem_clk_domain_active_state_icg_map_preinit() { /// SOC Reset Reason. #[derive(Debug, Clone, Copy, PartialEq, Eq, FromRepr)] pub enum SocResetReason { - /// Power on reset + /// Powers on reset. /// /// In ESP-IDF this value (0x01) can *also* be `ChipBrownOut` or /// `ChipSuperWdt`, however that is not really compatible with Rust-style @@ -1098,7 +1113,7 @@ pub enum SocResetReason { Cpu0Sw = 0x0C, /// RTC watch dog resets CPU 0 Cpu0RtcWdt = 0x0D, - /// VDD voltage is not stable and resets the digital core + /// VDD voltage is not stable and resets the digital core. SysBrownOut = 0x0F, /// RTC watch dog resets digital core and rtc module SysRtcWdt = 0x10, diff --git a/esp-hal/src/rtc_cntl/rtc/esp32c61.rs b/esp-hal/src/rtc_cntl/rtc/esp32c61.rs index b45561576fc..131595e9b1b 100644 --- a/esp-hal/src/rtc_cntl/rtc/esp32c61.rs +++ b/esp-hal/src/rtc_cntl/rtc/esp32c61.rs @@ -9,6 +9,17 @@ use crate::{ }, }; +// Trims the RTC bandgap using eFuse calibration data. +// +// See `esp_ocode_calib_init` in +// +fn calibrate_ocode() { + super::calibrate_ocode(|| { + (crate::efuse::block_version() != (0, 0)) + .then(|| crate::efuse::read_field_le::(crate::efuse::OCODE)) + }); +} + fn pmu_power_domain_force_default() { // for bypass reserved power domain @@ -114,6 +125,7 @@ impl From for ModemClockLpclkSource { fn from(src: LpSlowClkConfig) -> Self { match src { LpSlowClkConfig::RcSlow => Self::RcSlow, + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => Self::XTAL32K, LpSlowClkConfig::OscSlow => Self::EXT32K, } @@ -1001,6 +1013,8 @@ pub(crate) fn init(config: &ClockConfig) { pmu_power_domain_force_default(); + calibrate_ocode(); + // esp_perip_clk_init() modem_clock_domain_power_state_icg_map_init(); @@ -1086,7 +1100,7 @@ fn modem_clk_domain_active_state_icg_map_preinit() { /// SOC Reset Reason. #[derive(Debug, Clone, Copy, PartialEq, Eq, FromRepr)] pub enum SocResetReason { - /// Power on reset + /// Powers on reset. /// /// In ESP-IDF this value (0x01) can *also* be `ChipBrownOut` or /// `ChipSuperWdt`, however that is not really compatible with Rust-style @@ -1108,7 +1122,7 @@ pub enum SocResetReason { Cpu0Sw = 0x0C, /// RTC watch dog resets CPU 0 Cpu0RtcWdt = 0x0D, - /// VDD voltage is not stable and resets the digital core + /// VDD voltage is not stable and resets the digital core. SysBrownOut = 0x0F, /// RTC watch dog resets digital core and rtc module SysRtcWdt = 0x10, @@ -1124,7 +1138,7 @@ pub enum SocResetReason { CoreUsbJtag = 0x16, /// JTAG resets CPU Cpu0JtagCpu = 0x18, - /// Power glitch resets CPU + /// Powers glitch resets CPU. PowerGlitch = 0x19, /// CPU lockup reset CpuLockup = 0x1A, diff --git a/esp-hal/src/rtc_cntl/rtc/esp32h2.rs b/esp-hal/src/rtc_cntl/rtc/esp32h2.rs index ddbedb06752..c28097af50c 100644 --- a/esp-hal/src/rtc_cntl/rtc/esp32h2.rs +++ b/esp-hal/src/rtc_cntl/rtc/esp32h2.rs @@ -76,7 +76,7 @@ pub(crate) fn init(_config: &ClockConfig) { /// SOC Reset Reason. #[derive(Debug, Clone, Copy, PartialEq, Eq, FromRepr)] pub enum SocResetReason { - /// Power on reset + /// Powers on reset. /// /// In ESP-IDF this value (0x01) can *also* be `ChipBrownOut` or /// `ChipSuperWdt`, however that is not really compatible with Rust-style @@ -98,7 +98,7 @@ pub enum SocResetReason { Cpu0Sw = 0x0C, /// RTC watch dog resets CPU 0 Cpu0RtcWdt = 0x0D, - /// VDD voltage is not stable and resets the digital core + /// VDD voltage is not stable and resets the digital core. SysBrownOut = 0x0F, /// RTC watch dog resets digital core and rtc module SysRtcWdt = 0x10, diff --git a/esp-hal/src/rtc_cntl/rtc/esp32h4.rs b/esp-hal/src/rtc_cntl/rtc/esp32h4.rs new file mode 100644 index 00000000000..f689e092ae0 --- /dev/null +++ b/esp-hal/src/rtc_cntl/rtc/esp32h4.rs @@ -0,0 +1,858 @@ +use strum::FromRepr; + +use crate::{ + peripherals::{LP_AON, LP_CLKRST, PMU}, + soc::{clocks::ClockConfig, regi2c, xtal32k}, +}; + +// IDF sourced values. +const CK8M_DFREQ: u16 = 100; +const SCK_DCAP: u16 = 28; +pub(crate) const HP_CALI_DRVB: u32 = 6; +pub(crate) const LP_CALI_DBIAS: u8 = 0; + +const ICG_MODEM_CODE_SLEEP: u8 = 0; +const ICG_MODEM_CODE_MODEM: u8 = 1; +const ICG_MODEM_CODE_ACTIVE: u8 = 2; + +// `PMU_CLK_SRC_VAL` of esp-idf `pmu_param.c`, used by `dig_sysclk_sel` and `backup_clk_sel`. +const PMU_CLK_SRC_XTAL: u8 = 0; +const PMU_CLK_SRC_XTAL_X2: u8 = 2; +const PMU_CLK_SRC_PLL: u8 = 3; + +// `PMU_ICG_FUNC_ENA_HPBUS` of esp-idf `pmu_icg_mapping.h`. +const ICG_FUNC_ENA_HPBUS: u32 = 1 << 15; + +const fn hp_retention_regdma_config(dir: u8, entry: u8) -> u8 { + (((dir) << 4) | (entry & 0xf)) & 0x1f +} + +/// Clears the force bits of the power domains. +fn pmu_power_domain_force_default() { + // PMU_HP_PD_TOP + PMU::regs().power_pd_top_cntl().modify(|_, w| { + w.force_top_reset().bit(false); // pmu_ll_hp_set_power_force_reset + w.force_top_iso().bit(false); // pmu_ll_hp_set_power_force_isolate + w.force_top_pu().bit(false); // pmu_ll_hp_set_power_force_power_up + w.force_top_no_reset().bit(false); // pmu_ll_hp_set_power_force_no_reset + w.force_top_no_iso().bit(false); // pmu_ll_hp_set_power_force_no_isolate + w.force_top_pd().bit(false) // pmu_ll_hp_set_power_force_power_down + }); + + // PMU_HP_PD_HP_AON + PMU::regs().power_pd_hpaon_cntl().modify(|_, w| { + w.force_hp_aon_reset().bit(false); + w.force_hp_aon_iso().bit(false); + w.force_hp_aon_pu().bit(false); + w.force_hp_aon_no_reset().bit(false); + w.force_hp_aon_no_iso().bit(false); + w.force_hp_aon_pd().bit(false) + }); + + // PMU_HP_PD_CPU + PMU::regs().power_pd_hpcpu_cntl().modify(|_, w| { + w.force_hp_cpu_reset().bit(false); + w.force_hp_cpu_iso().bit(false); + w.force_hp_cpu_pu().bit(false); + w.force_hp_cpu_no_reset().bit(false); + w.force_hp_cpu_no_iso().bit(false); + w.force_hp_cpu_pd().bit(false) + }); + + // PMU_HP_PD_BT_154 + PMU::regs().power_pd_hpwifi_cntl().modify(|_, w| { + w.force_hp_wifi_reset().bit(false); + w.force_hp_wifi_iso().bit(false); + w.force_hp_wifi_pu().bit(false); + w.force_hp_wifi_no_reset().bit(false); + w.force_hp_wifi_no_iso().bit(false); + w.force_hp_wifi_pd().bit(false) + }); + + PMU::regs().power_pd_mem_cntl().modify(|_, w| unsafe { + // Isolate all memory banks while sleeping, avoid memory leakage current + w.force_hp_mem_no_iso().bits(0); // pmu_ll_hp_set_memory_no_isolate + // Disable memory force pu for memory pd during deep sleep + w.force_hp_mem_pu().bits(0) // pmu_ll_hp_set_memory_power_up + }); + + // pmu_ll_hp_set_vdd_flash_tiel_enable + PMU::regs().power_vdd_flash().modify(|_, w| { + w.flash_ldo_tiel_en().set_bit(); + w.flash_ldo_tiel().set_bit() + }); + + PMU::regs().power_pd_lpperi_cntl().modify(|_, w| { + w.force_lp_peri_reset().bit(false); // pmu_ll_lp_set_power_force_reset + w.force_lp_peri_iso().bit(false); // pmu_ll_lp_set_power_force_isolate + w.force_lp_peri_pu().bit(false); // pmu_ll_lp_set_power_force_power_up + w.force_lp_peri_no_reset().bit(false); // pmu_ll_lp_set_power_force_no_reset + w.force_lp_peri_no_iso().bit(false); // pmu_ll_lp_set_power_force_no_isolate + w.force_lp_peri_pd().bit(false) // pmu_ll_lp_set_power_force_power_down + }); +} + +bitfield::bitfield! { + #[derive(Clone, Copy, Default)] + // pmu_hp_power_t.0 + pub struct HpDigPower(u32); + + pub u8, vdd_flash_mode, set_vdd_flash_mode: 21, 18; + pub bool, mem_dslp , set_mem_dslp : 22; + pub u8, mem_pd_en , set_mem_pd_en : 26, 23; + pub bool, wifi_pd_en , set_wifi_pd_en : 27; + pub bool, peri_pd_en , set_peri_pd_en : 28; + pub bool, cpu_pd_en , set_cpu_pd_en : 29; + pub bool, aon_pd_en , set_aon_pd_en : 30; + pub bool, top_pd_en , set_top_pd_en : 31; +} + +bitfield::bitfield! { + #[derive(Clone, Copy, Default)] + // pmu_hp_power_t.1 + pub struct HpClkPower(u32); + + pub bool, i2c_iso_en , set_i2c_iso_en : 26; + pub bool, i2c_retention, set_i2c_retention: 27; + pub bool, xpd_bb_i2c , set_xpd_bb_i2c : 28; + pub bool, xpd_bbpll_i2c, set_xpd_bbpll_i2c: 29; + pub bool, xpd_bbpll , set_xpd_bbpll : 30; +} + +bitfield::bitfield! { + #[derive(Clone, Copy, Default)] + // pmu_hp_power_t.2 + pub struct XtalPower(u32); + + pub bool, xpd_xtalx2, set_xpd_xtalx2: 30; + pub bool, xpd_xtal , set_xpd_xtal : 31; +} + +#[derive(Clone, Copy, Default)] +// pmu_sleep_power_config_t.hp_sys +pub struct HpSysPower { + pub dig_power: HpDigPower, + pub clk: HpClkPower, + pub xtal: XtalPower, +} + +bitfield::bitfield! { + #[derive(Clone, Copy, Default)] + // pmu_hp_sys_cntl_reg_t + pub struct HpSysCntlReg(u32); + + pub bool, uart_wakeup_en , set_uart_wakeup_en : 24; + pub bool, lp_pad_hold_all, set_lp_pad_hold_all: 25; + pub bool, hp_pad_hold_all, set_hp_pad_hold_all: 26; + pub bool, dig_pad_slp_sel, set_dig_pad_slp_sel: 27; + pub bool, dig_pause_wdt , set_dig_pause_wdt : 28; + pub bool, dig_cpu_stall , set_dig_cpu_stall : 29; +} + +bitfield::bitfield! { + #[derive(Clone, Copy, Default)] + // pmu_hp_sysclk_reg_t + pub struct HpSysclk(u32); + + pub bool, dig_sysclk_nodiv, set_dig_sysclk_nodiv: 26; + pub bool, icg_sysclk_en , set_icg_sysclk_en : 27; + pub bool, sysclk_slp_sel , set_sysclk_slp_sel : 28; + pub bool, icg_slp_sel , set_icg_slp_sel : 29; + pub u8, dig_sysclk_sel , set_dig_sysclk_sel : 31, 30; +} + +// pmu_hp_system_clock_param_t +#[derive(Clone, Copy, Default)] +struct SystemClockParam { + icg_func: u32, + icg_apb: u32, + icg_modem_code: u8, + sysclk: HpSysclk, +} + +bitfield::bitfield! { + #[derive(Clone, Copy, Default)] + // pmu_hp_analog_t.0, which is also pmu_lp_analog_t.0 without `xpd_trx` + pub struct AnalogBias(u32); + + pub bool, dcdc_ccm_enb , set_dcdc_ccm_enb : 9; + pub bool, dcdc_clear_rdy , set_dcdc_clear_rdy : 10; + pub u8, dig_reg_dpcur_bias, set_dig_reg_dpcur_bias: 12, 11; + pub u8, dig_reg_dsfmos , set_dig_reg_dsfmos : 16, 13; + pub u8, dcm_vset , set_dcm_vset : 21, 17; + pub u8, dcm_mode , set_dcm_mode : 23, 22; + pub bool, xpd_trx , set_xpd_trx : 24; + pub bool, xpd_bias , set_xpd_bias : 25; + pub bool, discnnt_dig_rtc , set_discnnt_dig_rtc : 29; + pub bool, pd_cur , set_pd_cur : 30; + pub bool, bias_sleep , set_bias_sleep : 31; +} + +bitfield::bitfield! { + #[derive(Clone, Copy, Default)] + // pmu_hp_analog_t.1 + pub struct HpAnalogRegulator0(u32); + + pub bool, power_det_bypass, set_power_det_bypass: 0; + // Only the HP_ACTIVE mode has these two fields. + pub bool, dbias_sel , set_dbias_sel : 14; + pub bool, dbias_init , set_dbias_init : 15; + pub bool, slp_mem_xpd , set_slp_mem_xpd : 16; + pub bool, slp_logic_xpd , set_slp_logic_xpd : 17; + pub bool, xpd , set_xpd : 18; + pub u8, slp_mem_dbias , set_slp_mem_dbias : 22, 19; + pub u8, slp_logic_dbias , set_slp_logic_dbias : 26, 23; + pub u8, dbias , set_dbias : 31, 27; +} + +bitfield::bitfield! { + #[derive(Clone, Copy, Default)] + // pmu_hp_analog_t.2 + pub struct HpAnalogRegulator1(u32); + + pub u32, drv_b, set_drv_b: 31, 8; +} + +#[derive(Clone, Copy, Default)] +// pmu_hp_analog_t +pub struct HpAnalog { + pub bias: AnalogBias, + pub regulator0: HpAnalogRegulator0, + pub regulator1: HpAnalogRegulator1, +} + +bitfield::bitfield! { + #[derive(Clone, Copy, Default)] + // pmu_hp_backup_reg_t/active + struct HpActiveBackup(u32); + + pub u8, hp_sleep2active_backup_modem_clk_code, set_hp_sleep2active_backup_modem_clk_code: 5, 4; + pub u8, hp_modem2active_backup_modem_clk_code, set_hp_modem2active_backup_modem_clk_code: 7, 6; + pub u8, hp_sleep2active_backup_clk_sel , set_hp_sleep2active_backup_clk_sel : 15, 14; + pub u8, hp_modem2active_backup_clk_sel , set_hp_modem2active_backup_clk_sel : 17, 16; + pub u8, hp_sleep2active_backup_mode , set_hp_sleep2active_backup_mode : 22, 18; + pub u8, hp_modem2active_backup_mode , set_hp_modem2active_backup_mode : 27, 23; + pub bool, hp_sleep2active_backup_en , set_hp_sleep2active_backup_en : 29; + pub bool, hp_modem2active_backup_en , set_hp_modem2active_backup_en : 30; +} + +bitfield::bitfield! { + #[derive(Clone, Copy, Default)] + // pmu_hp_backup_reg_t/modem + struct HpModemBackup(u32); + + pub u8, hp_sleep2modem_backup_modem_clk_code, set_hp_sleep2modem_backup_modem_clk_code: 5, 4; + pub u8, hp_sleep2modem_backup_clk_sel , set_hp_sleep2modem_backup_clk_sel : 15, 14; + pub u8, hp_sleep2modem_backup_mode , set_hp_sleep2modem_backup_mode : 24, 20; + pub bool, hp_sleep2modem_backup_en , set_hp_sleep2modem_backup_en : 29; +} + +bitfield::bitfield! { + #[derive(Clone, Copy, Default)] + // pmu_hp_backup_reg_t/sleep + struct HpSleepBackup(u32); + + pub u8, hp_modem2sleep_backup_modem_clk_code , set_hp_modem2sleep_backup_modem_clk_code : 7, 6; + pub u8, hp_active2sleep_backup_modem_clk_code, set_hp_active2sleep_backup_modem_clk_code: 9, 8; + pub u8, hp_modem2sleep_backup_clk_sel , set_hp_modem2sleep_backup_clk_sel : 17, 16; + pub u8, hp_active2sleep_backup_clk_sel , set_hp_active2sleep_backup_clk_sel : 19, 18; + pub u8, hp_modem2sleep_backup_mode , set_hp_modem2sleep_backup_mode : 24, 20; + pub u8, hp_active2sleep_backup_mode , set_hp_active2sleep_backup_mode : 29, 25; + pub bool, hp_modem2sleep_backup_en , set_hp_modem2sleep_backup_en : 30; + pub bool, hp_active2sleep_backup_en , set_hp_active2sleep_backup_en : 31; +} + +/// Writes the parts of `pmu_hp_system_init` that are the same in every HP mode. +macro_rules! hp_system_init { + ($state:ident => $s:ident) => { + paste::paste! { + unsafe { + PMU::regs().[<$state _dig_power >]().write(|w| w.bits($s.power.dig_power.0)); + PMU::regs().[<$state _xtal >]().modify(|_, w| w + .[<$state _xpd_xtal >]().bit($s.power.xtal.xpd_xtal()) + ); + + PMU::regs().[<$state _icg_hp_func >]().write(|w| w.bits($s.clock.icg_func)); + PMU::regs().[<$state _icg_hp_apb >]().write(|w| w.bits($s.clock.icg_apb)); + PMU::regs().[<$state _icg_modem >]().write(|w| w + .[<$state _dig_icg_modem_code >]().bits($s.clock.icg_modem_code) + ); + PMU::regs().[<$state _sysclk >]().modify(|_, w| w + .[<$state _dig_sys_clk_no_div >]().bit($s.clock.sysclk.dig_sysclk_nodiv()) + .[<$state _icg_sys_clock_en >]().bit($s.clock.sysclk.icg_sysclk_en()) + .[<$state _sys_clk_slp_sel >]().bit($s.clock.sysclk.sysclk_slp_sel()) + .[<$state _icg_slp_sel >]().bit($s.clock.sysclk.icg_slp_sel()) + .[<$state _dig_sys_clk_sel >]().bits($s.clock.sysclk.dig_sysclk_sel()) + ); + + PMU::regs().[<$state _hp_sys_cntl >]().modify(|_, w| w + .[<$state _uart_wakeup_en >]().bit($s.syscntl.uart_wakeup_en()) + .[<$state _lp_pad_hold_all >]().bit($s.syscntl.lp_pad_hold_all()) + .[<$state _hp_pad_hold_all >]().bit($s.syscntl.hp_pad_hold_all()) + .[<$state _dig_pad_slp_sel >]().bit($s.syscntl.dig_pad_slp_sel()) + .[<$state _dig_pause_wdt >]().bit($s.syscntl.dig_pause_wdt()) + .[<$state _dig_cpu_stall >]().bit($s.syscntl.dig_cpu_stall()) + ); + + PMU::regs().[<$state _bias >]().modify(|_, w| w + .[<$state _dcdc_ccm_enb >]().bit($s.anlg.bias.dcdc_ccm_enb()) + .[<$state _dcdc_clear_rdy >]().bit($s.anlg.bias.dcdc_clear_rdy()) + .[<$state _dig_pmu_dpcur_bias >]().bits($s.anlg.bias.dig_reg_dpcur_bias()) + .[<$state _dig_pmu_dsfmos >]().bits($s.anlg.bias.dig_reg_dsfmos()) + .[<$state _dcm_vset >]().bits($s.anlg.bias.dcm_vset()) + .[<$state _dcm_mode >]().bits($s.anlg.bias.dcm_mode()) + .[<$state _xpd_bias >]().bit($s.anlg.bias.xpd_bias()) + .[<$state _xpd_trx >]().bit($s.anlg.bias.xpd_trx()) + .[<$state _discnnt_dig_rtc >]().bit($s.anlg.bias.discnnt_dig_rtc()) + .[<$state _pd_cur >]().bit($s.anlg.bias.pd_cur()) + .sleep().bit($s.anlg.bias.bias_sleep()) + ); + + PMU::regs().[<$state _hp_regulator0 >]().modify(|_, w| w + .[<$state _hp_power_det_bypass >]().bit($s.anlg.regulator0.power_det_bypass()) + .[<$state _hp_regulator_slp_mem_xpd >]().bit($s.anlg.regulator0.slp_mem_xpd()) + .[<$state _hp_regulator_slp_logic_xpd >]().bit($s.anlg.regulator0.slp_logic_xpd()) + .[<$state _hp_regulator_xpd >]().bit($s.anlg.regulator0.xpd()) + .[<$state _hp_regulator_slp_mem_dbias >]().bits($s.anlg.regulator0.slp_mem_dbias()) + .[<$state _hp_regulator_slp_logic_dbias >]().bits($s.anlg.regulator0.slp_logic_dbias()) + .[<$state _hp_regulator_dbias >]().bits($s.anlg.regulator0.dbias()) + ); + + PMU::regs().[<$state _hp_regulator1 >]().modify(|_, w| w + .[<$state _hp_regulator_drv_b >]().bits($s.anlg.regulator1.drv_b()) + ); + + PMU::regs().[<$state _backup >]().write(|w| w.bits($s.retention)); + PMU::regs().[<$state _backup_clk >]().write(|w| w.bits($s.backup_clk)); + } + } + }; +} + +// pmu_hp_system_param_t +struct HpSystemInit { + power: HpSysPower, + clock: SystemClockParam, + syscntl: HpSysCntlReg, + anlg: HpAnalog, + retention: u32, + backup_clk: u32, +} + +impl HpSystemInit { + /// The active-mode analog configuration, which the modem mode shares. + /// + /// PMU_HP_ACTIVE_ANALOG_CONFIG_DEFAULT, PMU_HP_MODEM_ANALOG_CONFIG_DEFAULT + fn active_analog() -> HpAnalog { + let mut anlg = HpAnalog::default(); + anlg.bias.set_dcdc_ccm_enb(false); + anlg.bias.set_dcdc_clear_rdy(false); + anlg.bias.set_dig_reg_dpcur_bias(3); + anlg.bias.set_dig_reg_dsfmos(15); + anlg.bias.set_dcm_mode(3); + anlg.bias.set_dcm_vset(24); + anlg.bias.set_xpd_trx(true); + anlg.bias.set_xpd_bias(true); + anlg.bias.set_discnnt_dig_rtc(false); + anlg.bias.set_pd_cur(false); + anlg.bias.set_bias_sleep(false); + + anlg.regulator0.set_power_det_bypass(false); + anlg.regulator0.set_dbias_sel(true); + anlg.regulator0.set_dbias_init(true); + anlg.regulator0.set_slp_mem_xpd(false); + anlg.regulator0.set_slp_logic_xpd(false); + anlg.regulator0.set_xpd(true); + anlg.regulator0.set_slp_mem_dbias(0); + anlg.regulator0.set_slp_logic_dbias(0); + anlg.regulator0.set_dbias(0); + + // get_act_hp_drvb + anlg.regulator1.set_drv_b(HP_CALI_DRVB); + + anlg + } + + fn active() -> Self { + // PMU_HP_ACTIVE_POWER_CONFIG_DEFAULT + let mut power = HpSysPower::default(); + power.clk.set_i2c_iso_en(false); + power.clk.set_i2c_retention(false); + power.clk.set_xpd_bb_i2c(true); + power.xtal.set_xpd_xtal(true); + + // PMU_HP_ACTIVE_CLOCK_CONFIG_DEFAULT + let mut clock = SystemClockParam { + icg_func: 0xffff_ffff, + icg_apb: 0xffff_ffff, + icg_modem_code: ICG_MODEM_CODE_ACTIVE, + ..Default::default() + }; + clock.sysclk.set_icg_sysclk_en(true); + clock.sysclk.set_dig_sysclk_sel(PMU_CLK_SRC_XTAL); + + // PMU_HP_ACTIVE_DIGITAL_CONFIG_DEFAULT + let syscntl = HpSysCntlReg::default(); + + // PMU_HP_ACTIVE_RETENTION_CONFIG_DEFAULT + let mut retention = HpActiveBackup::default(); + retention.set_hp_sleep2active_backup_modem_clk_code(2); + retention.set_hp_modem2active_backup_modem_clk_code(2); + retention.set_hp_sleep2active_backup_clk_sel(PMU_CLK_SRC_XTAL_X2); + retention.set_hp_modem2active_backup_clk_sel(PMU_CLK_SRC_XTAL); + retention.set_hp_sleep2active_backup_mode(hp_retention_regdma_config(0, 0)); + retention.set_hp_modem2active_backup_mode(hp_retention_regdma_config(0, 2)); + retention.set_hp_sleep2active_backup_en(false); + retention.set_hp_modem2active_backup_en(false); + + Self { + power, + clock, + syscntl, + anlg: Self::active_analog(), + retention: retention.0, + backup_clk: 0xffff_ffff, + } + } + + fn modem() -> Self { + // PMU_HP_MODEM_POWER_CONFIG_DEFAULT + let mut power = HpSysPower::default(); + power.dig_power.set_cpu_pd_en(true); + power.clk.set_xpd_bb_i2c(true); + power.xtal.set_xpd_xtal(true); + + // PMU_HP_MODEM_CLOCK_CONFIG_DEFAULT + let mut clock = SystemClockParam { + icg_func: ICG_FUNC_ENA_HPBUS, + icg_apb: 0, + icg_modem_code: ICG_MODEM_CODE_MODEM, + ..Default::default() + }; + clock.sysclk.set_icg_sysclk_en(true); + clock.sysclk.set_sysclk_slp_sel(true); + clock.sysclk.set_icg_slp_sel(true); + clock.sysclk.set_dig_sysclk_sel(PMU_CLK_SRC_PLL); + + // PMU_HP_MODEM_DIGITAL_CONFIG_DEFAULT + let mut syscntl = HpSysCntlReg::default(); + syscntl.set_uart_wakeup_en(true); + syscntl.set_dig_pause_wdt(true); + syscntl.set_dig_cpu_stall(true); + + // PMU_HP_MODEM_RETENTION_CONFIG_DEFAULT + let mut retention = HpModemBackup::default(); + retention.set_hp_sleep2modem_backup_modem_clk_code(1); + retention.set_hp_sleep2modem_backup_clk_sel(PMU_CLK_SRC_XTAL); + retention.set_hp_sleep2modem_backup_mode(hp_retention_regdma_config(0, 1)); + retention.set_hp_sleep2modem_backup_en(false); + + Self { + power, + clock, + syscntl, + anlg: Self::active_analog(), + retention: retention.0, + backup_clk: 0xffff_ffff, + } + } + + fn sleep() -> Self { + // PMU_HP_SLEEP_POWER_CONFIG_DEFAULT + let mut power = HpSysPower::default(); + power.dig_power.set_vdd_flash_mode(3); + power.clk.set_i2c_iso_en(true); + power.clk.set_i2c_retention(true); + + // PMU_HP_SLEEP_CLOCK_CONFIG_DEFAULT + let mut clock = SystemClockParam { + icg_func: 0, + icg_apb: 0, + icg_modem_code: ICG_MODEM_CODE_SLEEP, + ..Default::default() + }; + clock.sysclk.set_sysclk_slp_sel(true); + clock.sysclk.set_icg_slp_sel(true); + clock.sysclk.set_dig_sysclk_sel(PMU_CLK_SRC_XTAL); + + // PMU_HP_SLEEP_DIGITAL_CONFIG_DEFAULT + let mut syscntl = HpSysCntlReg::default(); + syscntl.set_uart_wakeup_en(true); + syscntl.set_dig_pad_slp_sel(true); + syscntl.set_dig_pause_wdt(true); + syscntl.set_dig_cpu_stall(true); + + // PMU_HP_SLEEP_ANALOG_CONFIG_DEFAULT + let mut anlg = HpAnalog::default(); + anlg.bias.set_dcdc_ccm_enb(true); + anlg.bias.set_dcdc_clear_rdy(false); + anlg.bias.set_dig_reg_dpcur_bias(1); + anlg.bias.set_dig_reg_dsfmos(4); + anlg.bias.set_dcm_mode(3); + anlg.bias.set_dcm_vset(20); + anlg.bias.set_xpd_trx(false); + anlg.bias.set_xpd_bias(false); + anlg.bias.set_discnnt_dig_rtc(false); + anlg.bias.set_pd_cur(true); + anlg.bias.set_bias_sleep(true); + anlg.regulator0.set_xpd(true); + anlg.regulator0.set_dbias(0); + anlg.regulator1.set_drv_b(25); + + // PMU_HP_SLEEP_RETENTION_CONFIG_DEFAULT + let mut retention = HpSleepBackup::default(); + retention.set_hp_modem2sleep_backup_modem_clk_code(0); + retention.set_hp_active2sleep_backup_modem_clk_code(2); + retention.set_hp_modem2sleep_backup_clk_sel(PMU_CLK_SRC_XTAL); + retention.set_hp_active2sleep_backup_clk_sel(PMU_CLK_SRC_XTAL_X2); + retention.set_hp_modem2sleep_backup_mode(hp_retention_regdma_config(1, 1)); + retention.set_hp_active2sleep_backup_mode(hp_retention_regdma_config(1, 0)); + retention.set_hp_modem2sleep_backup_en(false); + retention.set_hp_active2sleep_backup_en(false); + + Self { + power, + clock, + syscntl, + anlg, + retention: retention.0, + backup_clk: 0xffff_ffff, + } + } + + fn init_default() { + let active = Self::active(); + let modem = Self::modem(); + let sleep = Self::sleep(); + + hp_system_init!(hp_active => active); + hp_system_init!(hp_modem => modem); + hp_system_init!(hp_sleep => sleep); + + // The clock tree owns the power of the root clock circuits (BBPLL, XTAL_X2) in the active + // mode, so only the analog I2C master is configured there. + PMU::regs().hp_active_hp_ck_power().modify(|_, w| { + w.hp_active_xpd_bb_i2c().bit(active.power.clk.xpd_bb_i2c()); + w.hp_active_i2c_iso_en().bit(active.power.clk.i2c_iso_en()); + w.hp_active_i2c_retention() + .bit(active.power.clk.i2c_retention()) + }); + PMU::regs() + .hp_modem_hp_ck_power() + .write(|w| unsafe { w.bits(modem.power.clk.0) }); + PMU::regs() + .hp_modem_xtal() + .modify(|_, w| w.hp_modem_xpd_xtalx2().bit(modem.power.xtal.xpd_xtalx2())); + PMU::regs() + .hp_sleep_hp_ck_power() + .write(|w| unsafe { w.bits(sleep.power.clk.0) }); + PMU::regs() + .hp_sleep_xtal() + .modify(|_, w| w.hp_sleep_xpd_xtalx2().bit(sleep.power.xtal.xpd_xtalx2())); + + // Only the HP_ACTIVE mode has the regulator select bits. + PMU::regs().hp_active_hp_regulator0().modify(|_, w| { + w.dig_regulator0_dbias_sel() + .bit(active.anlg.regulator0.dbias_sel()); + w.dig_dbias_init().bit(active.anlg.regulator0.dbias_init()) + }); + + // Some PMU initial parameter configuration + PMU::regs() + .imm_modem_icg() + .write(|w| w.update_dig_icg_modem_en().set_bit()); + PMU::regs() + .imm_sleep_sysclk() + .write(|w| w.update_dig_icg_switch().set_bit()); + + const PMU_SLEEP_PROTECT_HP_LP_SLEEP: u8 = 2; + PMU::regs() + .slp_wakeup_cntl3() + .modify(|_, w| unsafe { w.sleep_prt_sel().bits(PMU_SLEEP_PROTECT_HP_LP_SLEEP) }); + + // pmu_ll_set_dcdc_ccm_sw_en + PMU::regs() + .dcm_ctrl() + .modify(|_, w| w.dcdc_ccm_sw_en().set_bit()); + + // lp_aon_ll_set_ldo_sw: the DC-DC LDO mode for a VDD below about 2.6 V. + const DREG_LDO_HW: u32 = 1 << 5; + const DREG_LDO_SW_SHIFT: u32 = 11; + const DREG_LDO_SW_MASK: u32 = 0xf << DREG_LDO_SW_SHIFT; + LP_AON::regs().date().modify(|r, w| unsafe { + w.bits((r.bits() & !(DREG_LDO_HW | DREG_LDO_SW_MASK)) | (15 << DREG_LDO_SW_SHIFT)) + }); + + // The BLE bandgap uses the calibrated ocode. + let ulp_ocode = if regi2c::I2C_ULP_IR_FORCE_CODE.read() != 0 { + regi2c::I2C_ULP_EXT_CODE.read() + } else { + regi2c::I2C_ULP_OCODE.read() + }; + PMU::regs().ble_bandgap_ctrl().modify(|_, w| unsafe { + w.ext_ocode().bits(ulp_ocode); + w.ext_force_ocode().set_bit() + }); + } +} + +bitfield::bitfield! { + #[derive(Clone, Copy, Default)] + // pmu_lp_power_t.0 + pub struct LpDigPower(u32); + + pub u8, vdd_io_mode , set_vdd_io_mode : 26, 23; + pub bool, bod_source_sel, set_bod_source_sel: 27; + pub u8, vddbat_mode , set_vddbat_mode : 29, 28; + pub bool, mem_dslp , set_mem_dslp : 30; + pub bool, peri_pd_en , set_peri_pd_en : 31; +} + +bitfield::bitfield! { + #[derive(Clone, Copy, Default)] + // pmu_lp_power_t.1 + pub struct LpClkPower(u32); + + pub bool, xpd_lppll , set_xpd_lppll : 27; + pub bool, xpd_xtal32k, set_xpd_xtal32k: 28; + pub bool, xpd_rc32k , set_xpd_rc32k : 29; + pub bool, xpd_fosc , set_xpd_fosc : 30; + pub bool, pd_osc , set_pd_osc : 31; +} + +#[derive(Clone, Copy, Default)] +// pmu_sleep_power_config_t.lp_sys +pub struct LpSysPower { + pub dig_power: LpDigPower, + pub clk_power: LpClkPower, + // Only the LP_SLEEP mode has this register. + pub xtal: XtalPower, +} + +bitfield::bitfield! { + #[derive(Clone, Copy, Default)] + // pmu_lp_analog_t.1 + pub struct LpAnalogRegulator0(u32); + + pub bool, slp_xpd , set_slp_xpd : 21; + pub bool, xpd , set_xpd : 22; + pub u8, slp_dbias, set_slp_dbias: 26, 23; + pub u8, dbias , set_dbias : 31, 27; +} + +bitfield::bitfield! { + #[derive(Clone, Copy, Default)] + // pmu_lp_analog_t.2 + pub struct LpAnalogRegulator1(u32); + + pub u8, drv_b, set_drv_b: 31, 28; +} + +#[derive(Clone, Copy, Default)] +// pmu_lp_analog_t +pub struct LpAnalog { + // Only the LP_SLEEP mode has this register. + pub bias: AnalogBias, + pub regulator0: LpAnalogRegulator0, + pub regulator1: LpAnalogRegulator1, +} + +/// Writes the parts of `pmu_lp_system_init` that are the same in every LP mode. +macro_rules! lp_system_init { + ($state:ident => $s:ident) => { + paste::paste! { + unsafe { + PMU::regs().[< $state _dig_power >]().write(|w| w.bits($s.power.dig_power.0)); + PMU::regs().[< $state _ck_power >]().write(|w| w.bits($s.power.clk_power.0)); + + PMU::regs().[< $state _regulator0 >]().modify(|_, w| w + .[< $state _regulator_slp_xpd >]().bit($s.anlg.regulator0.slp_xpd()) + .[< $state _regulator_xpd >]().bit($s.anlg.regulator0.xpd()) + .[< $state _regulator_slp_dbias >]().bits($s.anlg.regulator0.slp_dbias()) + .[< $state _regulator_dbias >]().bits($s.anlg.regulator0.dbias()) + ); + + PMU::regs().[< $state _regulator1 >]().modify(|_, w| w + .[< $state _regulator_drv_b >]().bits($s.anlg.regulator1.drv_b()) + ); + } + } + }; +} + +// pmu_lp_system_param_t +struct LpSystemInit { + power: LpSysPower, + anlg: LpAnalog, +} + +impl LpSystemInit { + fn active() -> Self { + // PMU_LP_ACTIVE_POWER_CONFIG_DEFAULT + let mut power = LpSysPower::default(); + power.clk_power.set_xpd_xtal32k(xtal32k::use_xtal32k()); + power.clk_power.set_xpd_fosc(true); + + // PMU_LP_ACTIVE_ANALOG_CONFIG_DEFAULT + let mut anlg = LpAnalog::default(); + anlg.regulator0.set_xpd(true); + anlg.regulator0.set_dbias(LP_CALI_DBIAS); + + Self { power, anlg } + } + + fn sleep() -> Self { + // PMU_LP_SLEEP_POWER_CONFIG_DEFAULT + let power = LpSysPower::default(); + + // PMU_LP_SLEEP_ANALOG_CONFIG_DEFAULT + let mut anlg = LpAnalog::default(); + anlg.bias.set_dcdc_ccm_enb(true); + anlg.bias.set_dcdc_clear_rdy(false); + anlg.bias.set_dig_reg_dpcur_bias(1); + anlg.bias.set_dig_reg_dsfmos(4); + anlg.bias.set_dcm_mode(3); + anlg.bias.set_dcm_vset(20); + anlg.bias.set_xpd_bias(false); + anlg.bias.set_discnnt_dig_rtc(true); + anlg.bias.set_pd_cur(true); + anlg.bias.set_bias_sleep(true); + anlg.regulator0.set_xpd(true); + anlg.regulator0.set_dbias(3); + + Self { power, anlg } + } + + fn init_default() { + let active = Self::active(); + let sleep = Self::sleep(); + + // The LP_ACTIVE registers are the ones named after HP_SLEEP. + lp_system_init!(hp_sleep_lp => active); + lp_system_init!(lp_sleep_lp => sleep); + + PMU::regs().lp_sleep_xtal().modify(|_, w| { + w.lp_sleep_xpd_xtal().bit(sleep.power.xtal.xpd_xtal()); + w.lp_sleep_xpd_xtalx2().bit(sleep.power.xtal.xpd_xtalx2()) + }); + + let bias = sleep.anlg.bias; + PMU::regs().lp_sleep_bias().modify(|_, w| unsafe { + w.lp_sleep_dcdc_ccm_enb().bit(bias.dcdc_ccm_enb()); + w.lp_sleep_dcdc_clear_rdy().bit(bias.dcdc_clear_rdy()); + w.lp_sleep_dig_pmu_dpcur_bias() + .bits(bias.dig_reg_dpcur_bias()); + w.lp_sleep_dig_pmu_dsfmos().bits(bias.dig_reg_dsfmos()); + w.lp_sleep_dcm_vset().bits(bias.dcm_vset()); + w.lp_sleep_dcm_mode().bits(bias.dcm_mode()); + w.lp_sleep_xpd_bias().bit(bias.xpd_bias()); + w.lp_sleep_discnnt_dig_rtc().bit(bias.discnnt_dig_rtc()); + w.lp_sleep_pd_cur().bit(bias.pd_cur()); + w.sleep().bit(bias.bias_sleep()) + }); + } +} + +pub(crate) fn init(_config: &ClockConfig) { + // pmu_init() + + // Peripheral reg i2c power up + PMU::regs().rf_pwc().modify(|_, w| { + w.xpd_perif_i2c().set_bit(); + w.xpd_rftx_i2c().set_bit(); + w.xpd_rfrx_i2c().set_bit() + }); + + HpSystemInit::init_default(); + LpSystemInit::init_default(); + + pmu_power_domain_force_default(); + + // This is the part of esp-idf's `rtc_clk_init` that has to run before the CPU can be switched + // to the BBPLL. + + // Tuning of the internal oscillators. Unlike on the other chips, RC_SLOW is tuned through the + // RC32K register (see the comment in esp-idf's rtc_clk_init.c). + LP_CLKRST::regs() + .fosc_cntl() + .modify(|_, w| unsafe { w.fosc_dfreq().bits(CK8M_DFREQ) }); + LP_CLKRST::regs() + .rc32k_cntl() + .modify(|_, w| unsafe { w.rc32k_dfreq().bits(SCK_DCAP) }); + + // Switch the DC-DC converter to CCM mode and apply its defaults. + PMU::regs() + .dcm_ctrl() + .modify(|_, w| w.dcdc_ccm_sw_en().set_bit()); + PMU::regs() + .hp_active_bias() + .modify(|_, w| w.hp_active_dcdc_ccm_enb().clear_bit()); + + regi2c::I2C_DCDC_CCM_DREG0.write_field(24); + regi2c::I2C_DCDC_CCM_PCUR_LIMIT0.write_field(4); + regi2c::I2C_DCDC_VCM_DREG0.write_field(24); + regi2c::I2C_DCDC_VCM_PCUR_LIMIT0.write_field(2); + regi2c::I2C_DCDC_XPD_TRX.write_field(0); + + // Power down the RF PLL. + PMU::regs() + .date() + .modify(|r, w| unsafe { w.bits(r.bits() & !(1 << 25)) }); + + // Regulator settings for the active modes. + PMU::regs() + .hp_active_hp_regulator0() + .modify(|_, w| w.hp_active_hp_regulator_xpd().set_bit()); + PMU::regs() + .hp_active_hp_regulator1() + .modify(|_, w| unsafe { w.hp_active_hp_regulator_drv_b().bits(HP_CALI_DRVB) }); + // The LP active mode registers are the ones named after HP sleep. + PMU::regs() + .hp_sleep_lp_regulator0() + .modify(|_, w| unsafe { w.hp_sleep_lp_regulator_dbias().bits(LP_CALI_DBIAS) }); +} + +/// SOC Reset Reason. +#[derive(Debug, Clone, Copy, PartialEq, Eq, FromRepr)] +pub enum SocResetReason { + /// Powers on reset. + /// + /// In ESP-IDF this value (0x01) can *also* be `ChipBrownOut` + ChipPowerOn = 0x01, + /// Software resets the digital core by LP_AON_HPSYS_SW_RESET + CoreSw = 0x03, + /// Deep sleep reset the digital core + CoreDeepSleep = 0x05, + /// Main watch dog 0 resets digital core + CoreMwdt0 = 0x07, + /// Main watch dog 1 resets digital core + CoreMwdt1 = 0x08, + /// RTC watch dog resets digital core + CoreRtcWdt = 0x09, + /// Main watch dog 0 resets CPU 0 + Cpu0Mwdt0 = 0x0B, + /// Software resets CPU 0 by LP_AON_CPU_CORE0_SW_RESET + Cpu0Sw = 0x0C, + /// RTC watch dog resets CPU 0 + Cpu0RtcWdt = 0x0D, + /// VDD voltage is not stable and resets the digital core + SysBrownOut = 0x0F, + /// RTC watch dog resets digital core and rtc module + SysRtcWdt = 0x10, + /// Main watch dog 1 resets CPU 0 + Cpu0Mwdt1 = 0x11, + /// Super watch dog resets the digital core and rtc module + SysSuperWdt = 0x12, + /// Glitch on power resets the digital core and rtc module + CorePwrGlitch = 0x13, + /// eFuse CRC error resets the digital core + CoreEfuseCrc = 0x14, + /// USB UART resets the digital core + CoreUsbUart = 0x15, + /// USB JTAG resets the digital core + CoreUsbJtag = 0x16, + /// JTAG resets CPU 0 + Cpu0JtagCpu = 0x18, + /// CPU lockup reset + CpuLockup = 0x1A, +} diff --git a/esp-hal/src/rtc_cntl/rtc/esp32p4.rs b/esp-hal/src/rtc_cntl/rtc/esp32p4.rs index 225f92ce380..01fee7f27e9 100644 --- a/esp-hal/src/rtc_cntl/rtc/esp32p4.rs +++ b/esp-hal/src/rtc_cntl/rtc/esp32p4.rs @@ -13,7 +13,7 @@ const HP_SYSCLK_XTAL: u8 = 0; #[repr(usize)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum SocResetReason { - /// Power on reset + /// Powers on reset. ChipPowerOn = 0x01, /// Software resets the digital core CoreSw = 0x03, @@ -33,7 +33,7 @@ pub enum SocResetReason { Cpu0Sw = 0x0C, /// RTC watch dog resets CPU 0 Cpu0RtcWdt = 0x0D, - /// VDD voltage is not stable and resets the digital core + /// VDD voltage is not stable and resets the digital core. SysBrownOut = 0x0F, /// RTC watch dog resets digital core and rtc module SysRtcWdt = 0x10, @@ -51,13 +51,16 @@ pub enum SocResetReason { Cpu0JtagCpu = 0x18, } -/// Clear all force flags on PMU power domains to allow normal power management. +/// Clears all force flags on PMU power domains to allow normal power management. /// /// eco5 power domains (verified against PAC): /// - TOP: power_pd_top_cntl (system top-level) /// - CNNT: power_pd_cnnt_cntl (connectivity, eco5 new -- replaces hpaon/hpcpu/hpwifi) /// - HPMEM: power_pd_hpmem_cntl (HP memory) +/// - CPU: power_pd_hp_cpu_cntl (the CPU that a light sleep with retention powers down) /// - LPPERI: power_pd_lpperi_cntl (LP peripherals, eco5 new) +/// +/// esp-idf clears the same flags for TOP, CNNT, HPMEM and CPU (`esp32p4/pmu_init.c:142-160`). fn pmu_power_domain_force_default() { let pmu = PMU::regs(); @@ -91,6 +94,17 @@ fn pmu_power_domain_force_default() { w.force_hp_mem_pd().bit(false) }); + // PMU_HP_PD_CPU. A force flag here keeps the CPU domain powered through a sleep that asks for + // the power-down, so a light sleep with CPU retention needs this clear. + pmu.power_pd_hp_cpu_cntl().modify(|_, w| { + w.force_hp_cpu_reset().bit(false); + w.force_hp_cpu_iso().bit(false); + w.force_hp_cpu_pu().bit(false); + w.force_hp_cpu_no_reset().bit(false); + w.force_hp_cpu_no_iso().bit(false); + w.force_hp_cpu_pd().bit(false) + }); + // PMU_LP_PD_LPPERI (eco5 new) pmu.power_pd_lpperi_cntl().modify(|_, w| { w.force_lp_peri_reset().bit(false); diff --git a/esp-hal/src/rtc_cntl/rtc/esp32s2.rs b/esp-hal/src/rtc_cntl/rtc/esp32s2.rs index 82bd49ec9ca..ea333e714b9 100644 --- a/esp-hal/src/rtc_cntl/rtc/esp32s2.rs +++ b/esp-hal/src/rtc_cntl/rtc/esp32s2.rs @@ -2,7 +2,20 @@ use strum::FromRepr; use crate::soc::clocks::ClockConfig; -pub(crate) fn init(_config: &ClockConfig) {} +pub(crate) fn init(_config: &ClockConfig) { + calibrate_ocode(); +} + +// Trims the RTC bandgap using eFuse calibration data. +// +// See `set_ocode_by_efuse` in +// +fn calibrate_ocode() { + super::calibrate_ocode(|| { + (crate::efuse::read_field_le::(crate::efuse::BLK_VERSION_MINOR) == 2) + .then(|| (crate::efuse::sign_magnitude(crate::efuse::ocode().into(), 6) + 93) as u8) + }); +} // Terminology: // @@ -15,7 +28,7 @@ pub(crate) fn init(_config: &ClockConfig) {} /// SOC Reset Reason. #[derive(Debug, Clone, Copy, PartialEq, Eq, FromRepr)] pub enum SocResetReason { - /// Power on reset + /// Powers on reset. /// /// In ESP-IDF this value (0x01) can *also* be `ChipBrownOut` or /// `ChipSuperWdt`, however that is not really compatible with Rust-style @@ -37,7 +50,7 @@ pub enum SocResetReason { Cpu0Sw = 0x0C, /// RTC watch dog resets CPU 0 Cpu0RtcWdt = 0x0D, - /// VDD voltage is not stable and resets the digital core + /// VDD voltage is not stable and resets the digital core. SysBrownOut = 0x0F, /// RTC watch dog resets digital core and rtc module SysRtcWdt = 0x10, diff --git a/esp-hal/src/rtc_cntl/rtc/esp32s3.rs b/esp-hal/src/rtc_cntl/rtc/esp32s3.rs index 229cdfacc20..a1585436965 100644 --- a/esp-hal/src/rtc_cntl/rtc/esp32s3.rs +++ b/esp-hal/src/rtc_cntl/rtc/esp32s3.rs @@ -2,7 +2,20 @@ use strum::FromRepr; use crate::soc::clocks::ClockConfig; -pub(crate) fn init(_config: &ClockConfig) {} +pub(crate) fn init(_config: &ClockConfig) { + calibrate_ocode(); +} + +// Trims the RTC bandgap using eFuse calibration data. +// +// See `set_ocode_by_efuse` in +// +fn calibrate_ocode() { + super::calibrate_ocode(|| { + (crate::efuse::block_version().0 == 1) + .then(|| crate::efuse::read_field_le::(crate::efuse::OCODE)) + }); +} // Terminology: // @@ -15,7 +28,7 @@ pub(crate) fn init(_config: &ClockConfig) {} /// SOC Reset Reason. #[derive(Debug, Clone, Copy, PartialEq, Eq, FromRepr)] pub enum SocResetReason { - /// Power on reset + /// Powers on reset. /// /// In ESP-IDF this value (0x01) can *also* be `ChipBrownOut` or /// `ChipSuperWdt`, however that is not really compatible with Rust-style @@ -46,7 +59,7 @@ pub enum SocResetReason { /// In ESP-IDF there are `Cpu0RtcWdt` and `Cpu1RtcWdt`, however they have /// the same values. CpuRtcWdt = 0x0D, - /// VDD voltage is not stable and resets the digital core + /// VDD voltage is not stable and resets the digital core. SysBrownOut = 0x0F, /// RTC watch dog resets digital core and rtc module SysRtcWdt = 0x10, diff --git a/esp-hal/src/rtc_cntl/rtc/esp32s31.rs b/esp-hal/src/rtc_cntl/rtc/esp32s31.rs index 6a7386dcbec..de15e8fe334 100644 --- a/esp-hal/src/rtc_cntl/rtc/esp32s31.rs +++ b/esp-hal/src/rtc_cntl/rtc/esp32s31.rs @@ -124,6 +124,24 @@ bitfield::bitfield! { pub u32, drv_b, set_drv_b: 31, 8; } +/// Analog settings of the high-power system during sleep. +#[derive(Clone, Copy, Default)] +pub struct HpAnalog { + pub bias: AnalogBias, + pub regulator0: HpRegulator0, + pub regulator1: HpRegulator1, +} + +/// Power settings of the high-power system during sleep. +#[derive(Clone, Copy, Default)] +pub struct HpSysPower { + pub dig_power: HpDigPower, + pub clk: HpClkPower, + pub xtal: XtalPower, +} + +pub type HpSysCntlReg = HpSysCntl; + bitfield::bitfield! { #[derive(Clone, Copy, Default)] pub struct HpBackup(u32); @@ -209,10 +227,8 @@ impl HpSystemInit { power.clk_power.set_xpd_bb_i2c(true); power.clk_power.set_xpd_cpll_i2c(true); power.clk_power.set_xpd_bbpll_i2c(true); - power.clk_power.set_xpd_mpll_i2c(true); power.clk_power.set_xpd_cpll(true); power.clk_power.set_xpd_bbpll(true); - power.clk_power.set_xpd_mpll(true); power.xtal.set_xpd_xtal(true); let mut icg_modem = HpIcgModem::default(); @@ -453,6 +469,22 @@ bitfield::bitfield! { pub u8, drv_b, set_drv_b: 31, 28; } +/// Power settings of the low-power system during sleep. +#[derive(Clone, Copy, Default)] +pub struct LpSysPower { + pub dig_power: LpDigPower, + pub clk_power: LpClkPower, + pub xtal: XtalPower, +} + +/// Analog settings of the low-power system during sleep. +#[derive(Clone, Copy, Default)] +pub struct LpAnalog { + pub bias: AnalogBias, + pub regulator0: LpRegulator0, + pub regulator1: LpRegulator1, +} + #[derive(Clone, Copy, Default)] struct LpSystemPower { dig_power: LpDigPower, @@ -603,7 +635,7 @@ fn modem_clock_domain_power_state_icg_map_init() { }); } -/// Select the WiFi LP clock after `ClockConfig::configure` has applied and +/// Selects the WiFi LP clock after `ClockConfig::configure` has applied and /// acquired the configured LP clock source. pub(crate) fn configure_wifi_lp_clock(config: &ClockConfig) { let lpcon = MODEM_LPCON::regs(); @@ -616,10 +648,14 @@ pub(crate) fn configure_wifi_lp_clock(config: &ClockConfig) { w.clk_wifipwr_lp_sel_xtal32k().clear_bit(); match source { LpSlowClkConfig::RcSlow => w.clk_wifipwr_lp_sel_osc_slow().set_bit(), + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => w.clk_wifipwr_lp_sel_xtal32k().set_bit(), } }); - if source == LpSlowClkConfig::Xtal32k { + if cfg_select! { + use_xtal32k => source == LpSlowClkConfig::Xtal32k, + _ => false, + } { // The WiFi 32 kHz selector feeds from the shared modem 32 kHz mux. // MODEM_CLOCK_XTAL32K_CODE is 0 on S31. lpcon @@ -661,7 +697,7 @@ pub(crate) fn init(_config: &ClockConfig) { /// SOC Reset Reason. #[derive(Debug, Clone, Copy, PartialEq, Eq, FromRepr)] pub enum SocResetReason { - /// Power on reset + /// Powers on reset. /// /// In ESP-IDF this value (0x01) can *also* be `ChipBrownOut` or /// `ChipSuperWdt`, however that is not really compatible with Rust-style @@ -685,7 +721,7 @@ pub enum SocResetReason { CpuSw = 0x0C, /// RWDT resets digital core CpuRwdt = 0x0D, - /// VDD voltage is not stable and resets the digital core + /// VDD voltage is not stable and resets the digital core. SysBrownOut = 0x0F, /// RWDT system reset SysRwdt = 0x10, diff --git a/esp-hal/src/rtc_cntl/sleep/esp32.rs b/esp-hal/src/rtc_cntl/sleep/esp32.rs index f18960379cd..434e3658e1c 100644 --- a/esp-hal/src/rtc_cntl/sleep/esp32.rs +++ b/esp-hal/src/rtc_cntl/sleep/esp32.rs @@ -1,7 +1,9 @@ use super::SleepKind; use crate::{ peripherals::{BB, DPORT, I2S0, LPWR, NRX}, + private::DropGuard, rtc_cntl::{Rtc, WakeupSource}, + soc::clocks::{self, ClockTree, CpuClkConfig}, }; // Approximate mapping of voltages to RTC_CNTL_DBIAS_WAK, RTC_CNTL_DBIAS_SLP, @@ -29,13 +31,13 @@ pub const RTC_CNTL_DBIAS_1V25: u8 = 7; pub const RTC_CNTL_XTL_BUF_WAIT_SLP_US: u32 = 1000; /// Cycles to wait for PLL buffer stabilization. pub const RTC_CNTL_PLL_BUF_WAIT_SLP_CYCLES: u8 = 1; -/// Cycles to wait for the 8MHz clock to stabilize. +/// Cycles to wait for the 8 MHz clock to stabilize. pub const RTC_CNTL_CK8M_WAIT_SLP_CYCLES: u8 = 4; /// Delay in cycles for wakeup signal to be applied. pub const RTC_CNTL_WAKEUP_DELAY_CYCLES: u8 = 7; /// Power-up cycles for other blocks. pub const RTC_CNTL_OTHER_BLOCKS_POWERUP_CYCLES: u8 = 1; -/// Wait cycles for other blocks. +/// Waits cycles for other blocks. pub const RTC_CNTL_OTHER_BLOCKS_WAIT_CYCLES: u16 = 1; /// Minimum sleep value (in cycles). pub const RTC_CNTL_MIN_SLP_VAL_MIN: u8 = 128; @@ -44,28 +46,28 @@ pub const RTC_CNTL_DBG_ATTEN_DEFAULT: u8 = 3; /// Power-up cycles for RTC memory. pub const RTC_MEM_POWERUP_CYCLES: u8 = RTC_CNTL_OTHER_BLOCKS_POWERUP_CYCLES; -/// Wait cycles for RTC memory. +/// Waits cycles for RTC memory. pub const RTC_MEM_WAIT_CYCLES: u16 = RTC_CNTL_OTHER_BLOCKS_WAIT_CYCLES; /// Power-up cycles for ROM and RAM. pub const ROM_RAM_POWERUP_CYCLES: u8 = RTC_CNTL_OTHER_BLOCKS_POWERUP_CYCLES; -/// Wait cycles for ROM and RAM. +/// Waits cycles for ROM and RAM. pub const ROM_RAM_WAIT_CYCLES: u16 = RTC_CNTL_OTHER_BLOCKS_WAIT_CYCLES; /// Power-up cycles for Wi-Fi. pub const WIFI_POWERUP_CYCLES: u8 = RTC_CNTL_OTHER_BLOCKS_POWERUP_CYCLES; -/// Wait cycles for Wi-Fi. +/// Waits cycles for Wi-Fi. pub const WIFI_WAIT_CYCLES: u16 = RTC_CNTL_OTHER_BLOCKS_WAIT_CYCLES; /// Power-up cycles for RTC components. pub const RTC_POWERUP_CYCLES: u8 = RTC_CNTL_OTHER_BLOCKS_POWERUP_CYCLES; -/// Wait cycles for RTC components. +/// Waits cycles for RTC components. pub const RTC_WAIT_CYCLES: u16 = RTC_CNTL_OTHER_BLOCKS_WAIT_CYCLES; /// Power-up cycles for the digital wrap components. pub const DG_WRAP_POWERUP_CYCLES: u8 = RTC_CNTL_OTHER_BLOCKS_POWERUP_CYCLES; -/// Wait cycles for the digital wrap components. +/// Waits cycles for the digital wrap components. pub const DG_WRAP_WAIT_CYCLES: u16 = RTC_CNTL_OTHER_BLOCKS_WAIT_CYCLES; -/// Default wait cycles for the 8MHz clock. +/// Default wait cycles for the 8 MHz clock. pub const RTC_CNTL_CK8M_WAIT_DEFAULT: u8 = 20; -/// Default wait cycles to enable the 8MHz clock. +/// Default wait cycles to enable the 8 MHz clock. pub const RTC_CK8M_ENABLE_WAIT_DEFAULT: u8 = 5; bitfield::bitfield! { @@ -87,7 +89,7 @@ bitfield::bitfield! { pub rtc_peri_pd_en, set_rtc_peri_pd_en: 5; /// power down WiFi pub wifi_pd_en, set_wifi_pd_en: 6; - /// Power down Internal 8M oscillator + /// Powers down Internal 8M oscillator. pub int_8m_pd_en, set_int_8m_pd_en: 7; /// power down main RAM and ROM pub rom_mem_pd_en, set_rom_mem_pd_en: 8; @@ -160,90 +162,54 @@ impl RtcSleepConfig { let rtc_cntl = LPWR::regs(); rtc_cntl.options0().modify(|_, w| { - w.bias_core_force_pu() - .clear_bit() - .bias_core_folw_8m() - .set_bit() - .bias_i2c_force_pu() - .clear_bit() - .bias_i2c_folw_8m() - .set_bit() - .bias_force_nosleep() - .clear_bit() - .bias_sleep_folw_8m() - .set_bit() - .xtl_force_pu() - .clear_bit() + w.bias_core_force_pu().clear_bit(); + w.bias_core_folw_8m().set_bit(); + w.bias_i2c_force_pu().clear_bit(); + w.bias_i2c_folw_8m().set_bit(); + w.bias_force_nosleep().clear_bit(); + w.bias_sleep_folw_8m().set_bit(); + w.xtl_force_pu().clear_bit() }); rtc_cntl.reg().modify(|_, w| { - w.force_pu() - .clear_bit() - .dboost_force_pu() - .clear_bit() - .dboost_force_pd() - .set_bit() + w.force_pu().clear_bit(); + w.dboost_force_pu().clear_bit(); + w.dboost_force_pd().set_bit() }); rtc_cntl.pwc().modify(|_, w| { - w.slowmem_force_pu() - .clear_bit() - .fastmem_force_pu() - .clear_bit() - .force_noiso() - .clear_bit() - .slowmem_force_noiso() - .clear_bit() - .fastmem_force_noiso() - .clear_bit() + w.slowmem_force_pu().clear_bit(); + w.fastmem_force_pu().clear_bit(); + w.force_noiso().clear_bit(); + w.slowmem_force_noiso().clear_bit(); + w.fastmem_force_noiso().clear_bit() }); rtc_cntl.dig_pwc().modify(|_, w| { - w.dg_wrap_force_pu() - .clear_bit() - .wifi_force_pu() - .clear_bit() - .wifi_force_pd() - .set_bit() - .inter_ram4_force_pu() - .clear_bit() - .inter_ram3_force_pu() - .clear_bit() - .inter_ram2_force_pu() - .clear_bit() - .inter_ram1_force_pu() - .clear_bit() - .inter_ram0_force_pu() - .clear_bit() - .rom0_force_pu() - .clear_bit() - .lslp_mem_force_pu() - .clear_bit() + w.dg_wrap_force_pu().clear_bit(); + w.wifi_force_pu().clear_bit(); + w.wifi_force_pd().set_bit(); + w.inter_ram4_force_pu().clear_bit(); + w.inter_ram3_force_pu().clear_bit(); + w.inter_ram2_force_pu().clear_bit(); + w.inter_ram1_force_pu().clear_bit(); + w.inter_ram0_force_pu().clear_bit(); + w.rom0_force_pu().clear_bit(); + w.lslp_mem_force_pu().clear_bit() }); rtc_cntl.dig_iso().modify(|_, w| { - w.dg_wrap_force_noiso() - .clear_bit() - .wifi_force_noiso() - .clear_bit() - .wifi_force_iso() - .set_bit() - .inter_ram4_force_noiso() - .clear_bit() - .inter_ram3_force_noiso() - .clear_bit() - .inter_ram2_force_noiso() - .clear_bit() - .inter_ram1_force_noiso() - .clear_bit() - .inter_ram0_force_noiso() - .clear_bit() - .rom0_force_noiso() - .clear_bit() - .dg_pad_force_unhold() - .clear_bit() - .dg_pad_force_noiso() - .clear_bit() + w.dg_wrap_force_noiso().clear_bit(); + w.wifi_force_noiso().clear_bit(); + w.wifi_force_iso().set_bit(); + w.inter_ram4_force_noiso().clear_bit(); + w.inter_ram3_force_noiso().clear_bit(); + w.inter_ram2_force_noiso().clear_bit(); + w.inter_ram1_force_noiso().clear_bit(); + w.inter_ram0_force_noiso().clear_bit(); + w.rom0_force_noiso().clear_bit(); + w.dg_pad_force_unhold().clear_bit(); + w.dg_pad_force_noiso().clear_bit() }); rtc_cntl.int_ena().modify(|_, w| w.brown_out().set_bit()); @@ -255,41 +221,28 @@ impl RtcSleepConfig { let rtc_cntl = LPWR::regs(); rtc_cntl.timer5().modify(|_, w| { - w.min_slp_val() - .bits(RTC_CNTL_MIN_SLP_VAL_MIN) - // set rtc memory timer - .rtcmem_powerup_timer() - .bits(RTC_MEM_POWERUP_CYCLES) - .rtcmem_wait_timer() - .bits(RTC_MEM_WAIT_CYCLES) + w.min_slp_val().bits(RTC_CNTL_MIN_SLP_VAL_MIN); + // set rtc memory timer + w.rtcmem_powerup_timer().bits(RTC_MEM_POWERUP_CYCLES); + w.rtcmem_wait_timer().bits(RTC_MEM_WAIT_CYCLES) }); rtc_cntl.timer3().modify(|_, w| { - w - // set rom&ram timer - .rom_ram_powerup_timer() - .bits(ROM_RAM_POWERUP_CYCLES) - .rom_ram_wait_timer() - .bits(ROM_RAM_WAIT_CYCLES) - // set wifi timer - .wifi_powerup_timer() - .bits(WIFI_POWERUP_CYCLES) - .wifi_wait_timer() - .bits(WIFI_WAIT_CYCLES) + // set rom&ram timer + w.rom_ram_powerup_timer().bits(ROM_RAM_POWERUP_CYCLES); + w.rom_ram_wait_timer().bits(ROM_RAM_WAIT_CYCLES); + // set wifi timer + w.wifi_powerup_timer().bits(WIFI_POWERUP_CYCLES); + w.wifi_wait_timer().bits(WIFI_WAIT_CYCLES) }); rtc_cntl.timer4().modify(|_, w| { - w - // set rtc peri timer - .powerup_timer() - .bits(RTC_POWERUP_CYCLES) - .wait_timer() - .bits(RTC_WAIT_CYCLES) - // set digital wrap timer - .dg_wrap_powerup_timer() - .bits(DG_WRAP_POWERUP_CYCLES) - .dg_wrap_wait_timer() - .bits(DG_WRAP_WAIT_CYCLES) + // set rtc peri timer + w.powerup_timer().bits(RTC_POWERUP_CYCLES); + w.wait_timer().bits(RTC_WAIT_CYCLES); + // set digital wrap timer + w.dg_wrap_powerup_timer().bits(DG_WRAP_POWERUP_CYCLES); + w.dg_wrap_wait_timer().bits(DG_WRAP_WAIT_CYCLES) }); rtc_cntl @@ -303,10 +256,8 @@ impl RtcSleepConfig { .modify(|_, w| w.lslp_mem_force_pu().clear_bit()); rtc_cntl.pwc().modify(|_, w| { - w.slowmem_force_pu() - .clear_bit() - .fastmem_force_pu() - .clear_bit() + w.slowmem_force_pu().clear_bit(); + w.fastmem_force_pu().clear_bit() }); // esp-idf also clears these: @@ -324,12 +275,9 @@ impl RtcSleepConfig { .modify(|_, w| w.fft_force_pu().clear_bit().dc_est_force_pu().clear_bit()); NRX::regs().nrxpd_ctrl().modify(|_, w| { - w.rx_rot_force_pu() - .clear_bit() - .vit_force_pu() - .clear_bit() - .demap_force_pu() - .clear_bit() + w.rx_rot_force_pu().clear_bit(); + w.vit_force_pu().clear_bit(); + w.demap_force_pu().clear_bit() }); // (&*esp32::FE::ptr()).gen_ctrl.modify(|_, w| w // .iq_est_force_pu().clear_bit() @@ -365,41 +313,28 @@ impl RtcSleepConfig { if self.deep_slp() { rtc_cntl.dig_iso().modify(|_, w| { - w.dg_wrap_force_noiso() - .clear_bit() - .wifi_force_noiso() - .clear_bit() - .dg_pad_force_iso() - .clear_bit() - .dg_pad_force_noiso() - .clear_bit() + w.dg_wrap_force_noiso().clear_bit(); + w.wifi_force_noiso().clear_bit(); + w.dg_pad_force_iso().clear_bit(); + w.dg_pad_force_noiso().clear_bit() }); rtc_cntl.dig_pwc().modify(|_, w| { - w.dg_wrap_pd_en() - .set_bit() - .dg_wrap_force_pu() - .clear_bit() - .dg_wrap_force_pd() - .clear_bit() + w.dg_wrap_pd_en().set_bit(); + w.dg_wrap_force_pu().clear_bit(); + w.dg_wrap_force_pd().clear_bit() }); rtc_cntl.options0().modify(|_, w| { - w.bias_force_nosleep() - .clear_bit() - .bb_i2c_force_pu() - .clear_bit() + w.bias_force_nosleep().clear_bit(); + w.bb_i2c_force_pu().clear_bit() }); rtc_cntl.ana_conf().modify(|_, w| { - w.ckgen_i2c_pu() - .clear_bit() - .pll_i2c_pu() - .clear_bit() - .rfrx_pbus_pu() - .clear_bit() - .txrf_i2c_pu() - .clear_bit() + w.ckgen_i2c_pu().clear_bit(); + w.pll_i2c_pu().clear_bit(); + w.rfrx_pbus_pu().clear_bit(); + w.txrf_i2c_pu().clear_bit() }); } else { rtc_cntl @@ -420,36 +355,47 @@ impl RtcSleepConfig { // enable VDDSDIO control by state machine rtc_cntl.sdio_conf().modify(|_, w| { - w.sdio_force() - .clear_bit() - .sdio_pd_en() - .bit(self.vddsdio_pd_en()) + w.sdio_force().clear_bit(); + w.sdio_pd_en().bit(self.vddsdio_pd_en()) }); rtc_cntl.reg().modify(|_, w| { - w.dbias_slp() - .bits(self.rtc_dbias_slp()) - .dbias_wak() - .bits(self.rtc_dbias_wak()) - .dig_dbias_slp() - .bits(self.dig_dbias_slp()) - .dig_dbias_wak() - .bits(self.dig_dbias_wak()) + w.dbias_slp().bits(self.rtc_dbias_slp()); + w.dbias_wak().bits(self.rtc_dbias_wak()); + w.dig_dbias_slp().bits(self.dig_dbias_slp()); + w.dig_dbias_wak().bits(self.dig_dbias_wak()) }); rtc_cntl.slp_reject_conf().modify(|_, w| { - w.deep_slp_reject_en() - .bit(self.deep_slp_reject()) - .light_slp_reject_en() - .bit(self.light_slp_reject()) + w.deep_slp_reject_en().bit(self.deep_slp_reject()); + w.light_slp_reject_en().bit(self.light_slp_reject()) }); } } - /// Configures the wakeup options and requests the sleep. + /// Configures the wakeup and reject sources of the sleep. /// - /// The caller waits for the result of the request. - pub(crate) fn start_sleep(&self, wakeup_mask: u32, reject_mask: u32) { + /// [`Self::enter_sleep`] requests the sleep after this call. The return value is a guard that + /// restores what sleep entry changed for the sleep only, so the caller keeps it until the + /// sleep ends. + #[crate::ram] + pub(crate) fn start_sleep(&self, wakeup_mask: u32, reject_mask: u32) -> impl Sized { + let restore_clock_config = ClockTree::with(|clocks| { + let old_root = clocks.cpu_clk(); + + clocks::configure_cpu_clk(clocks, CpuClkConfig::Xtal); + + // Restore the old clock settings when we return + DropGuard::new((), move |_| { + ClockTree::with(|clocks| { + crate::soc::clocks::reconfigure_pll(clocks); + if let Some(old_root) = old_root { + clocks::configure_cpu_clk(clocks, old_root); + } + }); + }) + }); + LPWR::regs() .reset_state() .modify(|_, w| w.procpu_stat_vector_sel().set_bit()); @@ -467,16 +413,23 @@ impl RtcSleepConfig { w.sdio_reject_en().bit(rejects.contains(WakeupSource::Sdio)) }); + restore_clock_config + } + + /// Requests the sleep. + /// + /// The caller waits for the result of the request. + #[inline(always)] + pub(crate) fn enter_sleep(&self) -> bool { LPWR::regs().state0().modify(|_, w| w.sleep_en().set_bit()); + super::wait_for_sleep_result() } pub(crate) fn finish_sleep(&self) { // In deep sleep mode, we never get here LPWR::regs().int_clr().write(|w| { - w.slp_reject() - .clear_bit_by_one() - .slp_wakeup() - .clear_bit_by_one() + w.slp_reject().clear_bit_by_one(); + w.slp_wakeup().clear_bit_by_one() }); // restore DBG_ATTEN to the default value diff --git a/esp-hal/src/rtc_cntl/sleep/esp32c2.rs b/esp-hal/src/rtc_cntl/sleep/esp32c2.rs index 8f5d8a391e2..bcdb0cfb2a2 100644 --- a/esp-hal/src/rtc_cntl/sleep/esp32c2.rs +++ b/esp-hal/src/rtc_cntl/sleep/esp32c2.rs @@ -60,9 +60,9 @@ pub const RTC_CNTL_PD_CUR_MONITOR_DEFAULT: bool = false; pub const RTC_CNTL_PLL_BUF_WAIT_DEFAULT: u8 = 20; /// Default number of cycles to wait for the XTL buffer to stabilize. pub const RTC_CNTL_XTL_BUF_WAIT_DEFAULT: u8 = 100; -/// Default number of cycles to wait for the internal 8MHz clock to stabilize. +/// Default number of cycles to wait for the internal 8 MHz clock to stabilize. pub const RTC_CNTL_CK8M_WAIT_DEFAULT: u8 = 20; -/// Default number of cycles required to enable the internal 8MHz clock. +/// Default number of cycles required to enable the internal 8 MHz clock. pub const RTC_CK8M_ENABLE_WAIT_DEFAULT: u8 = 5; /// Minimum number of cycles for sleep duration. @@ -70,7 +70,7 @@ pub const RTC_CNTL_MIN_SLP_VAL_MIN: u8 = 2; /// Power-up cycles for other hardware blocks. pub const OTHER_BLOCKS_POWERUP: u8 = 1; -/// Wait cycles for other hardware blocks to stabilize. +/// Waits cycles for other hardware blocks to stabilize. pub const OTHER_BLOCKS_WAIT: u16 = 1; /// Disables GPIO interrupt. @@ -98,19 +98,19 @@ bitfield::bitfield! { pub u8, xtal_wait, set_xtal_wait: 15, 8; /// Number of rtc_fast_clk cycles to wait for PLL clock to be ready pub u8, pll_wait, set_pll_wait: 23, 16; - /// Perform clock control related initialization. + /// Performs clock control related initialization. pub clkctl_init, set_clkctl_init: 24; - /// Perform power control related initialization. + /// Performs power control related initialization. pub pwrctl_init, set_pwrctl_init: 25; - /// Force power down RTC_DBOOST + /// Forces power-down of RTC_DBOOST. pub rtc_dboost_fpd, set_rtc_dboost_fpd: 26; - /// Keep the XTAL oscillator powered up in sleep. + /// Keeps the XTAL oscillator powered up in sleep. pub xtal_fpu, set_xtal_fpu: 27; - /// Keep the BBPLL oscillator powered up in sleep. + /// Keeps the BBPLL oscillator powered up in sleep. pub bbpll_fpu, set_bbpll_fpu: 28; - /// Enable clock gating when the CPU is in wait-for-interrupt state. + /// Enables clock gating when the CPU is in wait-for-interrupt state. pub cpu_waiti_clk_gate, set_cpu_waiti_clk_gate: 29; - /// Calibrate Ocode to make bandgap voltage more precise. + /// Calibrates Ocode to make bandgap voltage more precise. pub cali_ocode, set_cali_ocode: 30; } @@ -192,9 +192,7 @@ bitfield::bitfield! { pub wifi_pd_en, set_wifi_pd_en: 5; /// power down BT pub bt_pd_en, set_bt_pd_en: 6; - /// power down CPU, but not restart when lightsleep. - pub cpu_pd_en, set_cpu_pd_en: 7; - /// Power down Internal 8M oscillator + /// Powers down Internal 8M oscillator. pub int_8m_pd_en, set_int_8m_pd_en: 8; /// power down digital peripherals pub dig_peri_pd_en, set_dig_peri_pd_en: 9; @@ -323,7 +321,6 @@ impl RtcSleepConfig { cfg.set_rtc_peri_pd_en(true); cfg.set_wifi_pd_en(true); cfg.set_bt_pd_en(true); - cfg.set_cpu_pd_en(true); cfg.set_int_8m_pd_en(true); cfg.set_dig_peri_pd_en(true); @@ -488,7 +485,18 @@ impl RtcSleepConfig { } unsafe { - assert!(!self.pd_cur_slp() || self.bias_sleep_slp()); + // Like `rtc_sleep_get_default_config`: a crystal that stays on through a light sleep + // needs the bias current and the voltage of the active mode. + let xtal_on = self.xtal_fpu() && !self.deep_slp(); + let bias_sleep_slp = self.bias_sleep_slp() && !xtal_on; + let pd_cur_slp = self.pd_cur_slp() && !xtal_on; + let dbg_atten_slp = if xtal_on { + RTC_CNTL_DBG_ATTEN_LIGHTSLEEP_NODROP + } else { + self.dbg_atten_slp() + }; + + assert!(!pd_cur_slp || bias_sleep_slp); regi2c::I2C_DIG_REG_EXT_RTC_DREG_SLEEP.write_field(self.rtc_dbias_slp()); regi2c::I2C_DIG_REG_EXT_DIG_DREG_SLEEP.write_field(self.dig_dbias_slp()); @@ -503,9 +511,9 @@ impl RtcSleepConfig { }); rtc_cntl.bias_conf().modify(|_, w| { - w.dbg_atten_deep_slp().bits(self.dbg_atten_slp()); - w.bias_sleep_deep_slp().bit(self.bias_sleep_slp()); - w.pd_cur_deep_slp().bit(self.pd_cur_slp()) + w.dbg_atten_deep_slp().bits(dbg_atten_slp); + w.bias_sleep_deep_slp().bit(bias_sleep_slp); + w.pd_cur_deep_slp().bit(pd_cur_slp) }); if self.deep_slp() { @@ -567,9 +575,9 @@ impl RtcSleepConfig { } } - /// Configures the wakeup options and requests the sleep. + /// Configures the wakeup and reject sources of the sleep. /// - /// The caller waits for the result of the request. + /// [`Self::enter_sleep`] requests the sleep after this call. pub(crate) fn start_sleep(&self, wakeup_mask: u32, reject_mask: u32) { // set bits for what can wake us up LPWR::regs() @@ -581,8 +589,15 @@ impl RtcSleepConfig { LPWR::regs() .slp_reject_conf() .modify(|_, w| unsafe { w.sleep_reject_ena().bits(reject_mask) }); + } + /// Requests the sleep. + /// + /// The caller waits for the result of the request. + #[inline(always)] + pub(crate) fn enter_sleep(&self) -> bool { LPWR::regs().state0().modify(|_, w| w.sleep_en().set_bit()); + super::wait_for_sleep_result() } pub(crate) fn finish_sleep(&self) { diff --git a/esp-hal/src/rtc_cntl/sleep/esp32c3.rs b/esp-hal/src/rtc_cntl/sleep/esp32c3.rs index 77154e59a79..edfb8d04a04 100644 --- a/esp-hal/src/rtc_cntl/sleep/esp32c3.rs +++ b/esp-hal/src/rtc_cntl/sleep/esp32c3.rs @@ -60,9 +60,9 @@ pub const RTC_CNTL_PD_CUR_MONITOR_DEFAULT: bool = false; pub const RTC_CNTL_PLL_BUF_WAIT_DEFAULT: u8 = 20; /// Default number of cycles to wait for the XTL buffer to stabilize. pub const RTC_CNTL_XTL_BUF_WAIT_DEFAULT: u8 = 100; -/// Default number of cycles to wait for the internal 8MHz clock to stabilize. +/// Default number of cycles to wait for the internal 8 MHz clock to stabilize. pub const RTC_CNTL_CK8M_WAIT_DEFAULT: u8 = 20; -/// Default number of cycles required to enable the internal 8MHz clock. +/// Default number of cycles required to enable the internal 8 MHz clock. pub const RTC_CK8M_ENABLE_WAIT_DEFAULT: u8 = 5; /// Minimum number of cycles for sleep duration. @@ -70,7 +70,7 @@ pub const RTC_CNTL_MIN_SLP_VAL_MIN: u8 = 2; /// Power-up cycles for other hardware blocks. pub const OTHER_BLOCKS_POWERUP: u8 = 1; -/// Wait cycles for other hardware blocks to stabilize. +/// Waits cycles for other hardware blocks to stabilize. pub const OTHER_BLOCKS_WAIT: u16 = 1; /// Disables GPIO interrupt. @@ -98,19 +98,19 @@ bitfield::bitfield! { pub u8, xtal_wait, set_xtal_wait: 15, 8; /// Number of rtc_fast_clk cycles to wait for PLL clock to be ready pub u8, pll_wait, set_pll_wait: 23, 16; - /// Perform clock control related initialization. + /// Performs clock control related initialization. pub clkctl_init, set_clkctl_init: 24; - /// Perform power control related initialization. + /// Performs power control related initialization. pub pwrctl_init, set_pwrctl_init: 25; - /// Force power down `RTC_DBOOST`. + /// Forces power-down of `RTC_DBOOST`. pub rtc_dboost_fpd, set_rtc_dboost_fpd: 26; - /// Keep the XTAL oscillator powered up in sleep. + /// Keeps the XTAL oscillator powered up in sleep. pub xtal_fpu, set_xtal_fpu: 27; - /// Keep the BBPLL oscillator powered up in sleep. + /// Keeps the BBPLL oscillator powered up in sleep. pub bbpll_fpu, set_bbpll_fpu: 28; - /// Enable clock gating when the CPU is in wait-for-interrupt state. + /// Enables clock gating when the CPU is in wait-for-interrupt state. pub cpu_waiti_clk_gate, set_cpu_waiti_clk_gate: 29; - /// Calibrate Ocode to make bandgap voltage more precise. + /// Calibrates Ocode to make bandgap voltage more precise. pub cali_ocode, set_cali_ocode: 30; } @@ -192,8 +192,11 @@ bitfield::bitfield! { /// power down BT pub bt_pd_en, set_bt_pd_en: 6; /// power down CPU, but not restart when lightsleep. - pub cpu_pd_en, set_cpu_pd_en: 7; - /// Power down Internal 8M oscillator + /// + /// Crate-private, because a light sleep derives this from the installed retention memory. A + /// CPU power-down without retention loses the CPU state. + pub(crate) cpu_pd_en, set_cpu_pd_en: 7; + /// Powers down Internal 8M oscillator. pub int_8m_pd_en, set_int_8m_pd_en: 8; /// power down digital peripherals pub dig_peri_pd_en, set_dig_peri_pd_en: 9; @@ -278,8 +281,8 @@ fn rtc_sleep_pu(val: bool) { APB_CTRL::regs().mem_power_up().modify(|_r, w| unsafe { w.sram_power_up() - .bits(if val { SYSCON_SRAM_POWER_UP } else { 0 }) - .rom_power_up() + .bits(if val { SYSCON_SRAM_POWER_UP } else { 0 }); + w.rom_power_up() .bits(if val { SYSCON_ROM_POWER_UP } else { 0 }) }); } @@ -364,36 +367,28 @@ impl RtcSleepConfig { let init_cfg = RtcInitConfig::default(); rtc_cntl.timer3().modify(|_, w| { - w - // set wifi timer - .wifi_powerup_timer() - .bits(init_cfg.wifi_powerup_cycles()) - .wifi_wait_timer() - .bits(init_cfg.wifi_wait_cycles()) - // set bt timer - .bt_powerup_timer() - .bits(init_cfg.bt_powerup_cycles()) - .bt_wait_timer() - .bits(init_cfg.bt_wait_cycles()) + // set wifi timer + w.wifi_powerup_timer().bits(init_cfg.wifi_powerup_cycles()); + w.wifi_wait_timer().bits(init_cfg.wifi_wait_cycles()); + // set bt timer + w.bt_powerup_timer().bits(init_cfg.bt_powerup_cycles()); + w.bt_wait_timer().bits(init_cfg.bt_wait_cycles()) }); rtc_cntl.timer4().modify(|_, w| { w.cpu_top_powerup_timer() - .bits(init_cfg.cpu_top_powerup_cycles()) - .cpu_top_wait_timer() - .bits(init_cfg.cpu_top_wait_cycles()) - // set digital wrap timer - .dg_wrap_powerup_timer() - .bits(init_cfg.dg_wrap_powerup_cycles()) - .dg_wrap_wait_timer() - .bits(init_cfg.dg_wrap_wait_cycles()) + .bits(init_cfg.cpu_top_powerup_cycles()); + w.cpu_top_wait_timer().bits(init_cfg.cpu_top_wait_cycles()); + // set digital wrap timer + w.dg_wrap_powerup_timer() + .bits(init_cfg.dg_wrap_powerup_cycles()); + w.dg_wrap_wait_timer().bits(init_cfg.dg_wrap_wait_cycles()) }); rtc_cntl.timer6().modify(|_, w| { w.dg_peri_powerup_timer() - .bits(init_cfg.dg_peri_powerup_cycles()) - .dg_peri_wait_timer() - .bits(init_cfg.dg_peri_wait_cycles()) + .bits(init_cfg.dg_peri_powerup_cycles()); + w.dg_peri_wait_timer().bits(init_cfg.dg_peri_wait_cycles()) }); // TODO: something about cali_ocode @@ -454,21 +449,15 @@ impl RtcSleepConfig { // cancel bbpll force pu if setting no force power up rtc_cntl.options0().modify(|_, w| { - w.bbpll_force_pu() - .bit(cfg.bbpll_fpu()) - .bbpll_i2c_force_pu() - .bit(cfg.bbpll_fpu()) - .bb_i2c_force_pu() - .bit(cfg.bbpll_fpu()) + w.bbpll_force_pu().bit(cfg.bbpll_fpu()); + w.bbpll_i2c_force_pu().bit(cfg.bbpll_fpu()); + w.bb_i2c_force_pu().bit(cfg.bbpll_fpu()) }); rtc_cntl.rtc_cntl().modify(|_, w| { - w.regulator_force_pu() - .clear_bit() - .dboost_force_pu() - .clear_bit() - .dboost_force_pd() - .bit(cfg.rtc_dboost_fpd()) + w.regulator_force_pu().clear_bit(); + w.dboost_force_pu().clear_bit(); + w.dboost_force_pd().bit(cfg.rtc_dboost_fpd()) }); // If this mask is enabled, all soc memories cannot enter power down mode @@ -485,29 +474,19 @@ impl RtcSleepConfig { rtc_sleep_pu(false); rtc_cntl.dig_pwc().modify(|_, w| { - w.dg_wrap_force_pu() - .clear_bit() - .wifi_force_pu() - .clear_bit() - .bt_force_pu() - .clear_bit() - .cpu_top_force_pu() - .clear_bit() - .dg_peri_force_pu() - .clear_bit() + w.dg_wrap_force_pu().clear_bit(); + w.wifi_force_pu().clear_bit(); + w.bt_force_pu().clear_bit(); + w.cpu_top_force_pu().clear_bit(); + w.dg_peri_force_pu().clear_bit() }); rtc_cntl.dig_iso().modify(|_, w| { - w.dg_wrap_force_noiso() - .clear_bit() - .wifi_force_noiso() - .clear_bit() - .bt_force_noiso() - .clear_bit() - .cpu_top_force_noiso() - .clear_bit() - .dg_peri_force_noiso() - .clear_bit() + w.dg_wrap_force_noiso().clear_bit(); + w.wifi_force_noiso().clear_bit(); + w.bt_force_noiso().clear_bit(); + w.cpu_top_force_noiso().clear_bit(); + w.dg_peri_force_noiso().clear_bit() }); // if SYSTEM_CPU_WAIT_MODE_FORCE_ON == 0 , the cpu clk will be closed when cpu @@ -520,10 +499,8 @@ impl RtcSleepConfig { // cancel digital PADS force no iso rtc_cntl.dig_iso().modify(|_, w| { - w.dg_pad_force_unhold() - .clear_bit() - .dg_pad_force_noiso() - .clear_bit() + w.dg_pad_force_unhold().clear_bit(); + w.dg_pad_force_noiso().clear_bit() }); } @@ -596,15 +573,26 @@ impl RtcSleepConfig { w.pd_cur_monitor().bit(RTC_CNTL_PD_CUR_MONITOR_DEFAULT) }); - assert!(!self.pd_cur_slp() || self.bias_sleep_slp()); + // Like `rtc_sleep_get_default_config`: a crystal that stays on through a light sleep + // needs the bias current and the voltage of the active mode. + let xtal_on = self.xtal_fpu() && !self.deep_slp(); + let bias_sleep_slp = self.bias_sleep_slp() && !xtal_on; + let pd_cur_slp = self.pd_cur_slp() && !xtal_on; + let dbg_atten_slp = if xtal_on { + RTC_CNTL_DBG_ATTEN_LIGHTSLEEP_NODROP + } else { + self.dbg_atten_slp() + }; + + assert!(!pd_cur_slp || bias_sleep_slp); regi2c::I2C_DIG_REG_EXT_RTC_DREG_SLEEP.write_field(self.rtc_dbias_slp()); regi2c::I2C_DIG_REG_EXT_DIG_DREG_SLEEP.write_field(self.dig_dbias_slp()); rtc_cntl.bias_conf().modify(|_, w| { - w.dbg_atten_deep_slp().bits(self.dbg_atten_slp()); - w.bias_sleep_deep_slp().bit(self.bias_sleep_slp()); - w.pd_cur_deep_slp().bit(self.pd_cur_slp()) + w.dbg_atten_deep_slp().bits(dbg_atten_slp); + w.bias_sleep_deep_slp().bit(bias_sleep_slp); + w.pd_cur_deep_slp().bit(pd_cur_slp) }); if self.deep_slp() { @@ -672,9 +660,9 @@ impl RtcSleepConfig { } } - /// Configures the wakeup options and requests the sleep. + /// Configures the wakeup and reject sources of the sleep. /// - /// The caller waits for the result of the request. + /// [`Self::enter_sleep`] requests the sleep after this call. pub(crate) fn start_sleep(&self, wakeup_mask: u32, reject_mask: u32) { // set bits for what can wake us up LPWR::regs() @@ -686,8 +674,15 @@ impl RtcSleepConfig { LPWR::regs() .slp_reject_conf() .modify(|_, w| unsafe { w.sleep_reject_ena().bits(reject_mask) }); + } + /// Requests the sleep. + /// + /// The caller waits for the result of the request. + #[inline(always)] + pub(crate) fn enter_sleep(&self) -> bool { LPWR::regs().state0().modify(|_, w| w.sleep_en().set_bit()); + super::wait_for_sleep_result() } pub(crate) fn finish_sleep(&self) { diff --git a/esp-hal/src/rtc_cntl/sleep/esp32c5.rs b/esp-hal/src/rtc_cntl/sleep/esp32c5.rs index 03b7fd8dea7..1b36947b073 100644 --- a/esp-hal/src/rtc_cntl/sleep/esp32c5.rs +++ b/esp-hal/src/rtc_cntl/sleep/esp32c5.rs @@ -6,10 +6,13 @@ use crate::{ rtc_cntl::{ Rtc, rtc::{HpAnalog, HpSysCntlReg, HpSysPower, LpAnalog, LpSysPower}, - sleep::{SleepKind, pmu_common::SleepTimeConfig}, + sleep::{ + SleepKind, + pmu_common::{SleepTimeConfig, request_sleep}, + }, }, soc::{ - clocks::{self, ClockTree, HpRootClkConfig, LpSlowClkConfig}, + clocks::{self, ClockTree, HpRootClkConfig}, xtal32k, }, }; @@ -595,7 +598,7 @@ impl SleepTimeConfig { pub struct RtcSleepConfig { /// Deep Sleep flag pub deep: bool, - /// Power Down flags + /// Powers Down flags. pub pd_flags: PowerDownFlags, } @@ -613,7 +616,7 @@ impl Default for RtcSleepConfig { bitfield::bitfield! { #[derive(Clone, Copy)] - /// Power domains to be powered down during sleep + /// Power domains to be powered down during sleep. pub struct PowerDownFlags(u32); /// Controls the power-down status of the top power domain. @@ -625,7 +628,10 @@ bitfield::bitfield! { /// Controls the power-down status of the high-performance peripheral power domain. pub u32, pd_hp_periph, set_pd_hp_periph: 3; /// Controls the power-down status of the CPU power domain. - pub u32, pd_cpu , set_pd_cpu : 4; + /// + /// Crate-private, because a light sleep needs CPU retention to power this domain down. A + /// power-down without retention loses the CPU state. + pub(crate) u32, pd_cpu, set_pd_cpu: 4; /// Controls the power-down status of the high-performance always-on domain. pub u32, pd_hp_aon , set_pd_hp_aon : 5; /// Controls the power-down status of memory group 0. @@ -640,16 +646,16 @@ bitfield::bitfield! { pub u32, pd_xtal , set_pd_xtal : 10; /// Controls the power-down status of the fast RC oscillator. pub u32, pd_rc_fast , set_pd_rc_fast : 11; - /// Controls the power-down status of the 32kHz crystal oscillator. + /// Controls the power-down status of the 32 kHz crystal oscillator. pub u32, pd_xtal32k , set_pd_xtal32k : 12; - /// Controls the power-down status of the 32kHz RC oscillator. + /// Controls the power-down status of the 32 kHz RC oscillator. pub u32, pd_rc32k , set_pd_rc32k : 13; /// Controls the power-down status of the low-power peripheral domain. pub u32, pd_lp_periph, set_pd_lp_periph: 14; } impl PowerDownFlags { - /// Checks whether all memory groups (G0, G1, G2, G3) are powered down. + /// Returns whether all memory groups (G0, G1, G2, G3) are powered down. pub fn pd_mem(self) -> bool { self.pd_mem_g0() && self.pd_mem_g1() && self.pd_mem_g2() && self.pd_mem_g3() } @@ -721,20 +727,24 @@ impl RtcSleepConfig { self.deep } + pub(crate) fn base_settings(_rtc: &Rtc<'_>) {} + + /// Selects the kind of the sleep, and what the sleep powers down. + /// + /// Sleep entry calls this before the hooks of the wakeup sources, so that a source can keep + /// powered what it needs. pub(crate) fn set_sleep_kind(&mut self, kind: SleepKind) { self.deep = kind == SleepKind::Deep; - } - - pub(crate) fn base_settings(_rtc: &Rtc<'_>) {} - /// Finalize power-down flags, apply configuration based on the flags. - pub(crate) fn apply(&mut self) { - let lp_slow_uses_xtal32k = ClockTree::with(|clocks| { - matches!( - clocks::lp_slow_clk_config(clocks), - Some(LpSlowClkConfig::Xtal32k) - ) - }); + let lp_slow_uses_xtal32k = cfg_select! { + use_xtal32k => ClockTree::with(|clocks| { + matches!( + clocks::lp_slow_clk_config(clocks), + Some(clocks::LpSlowClkConfig::Xtal32k) + ) + }), + _ => false, + }; if self.deep { // force-disable certain power domains @@ -764,10 +774,12 @@ impl RtcSleepConfig { } } - /// Configures the wakeup options and requests the sleep. + /// Configures the wakeup and reject sources of the sleep. /// - /// The caller waits for the result of the request. The return value is a guard that restores - /// what sleep entry changed for the sleep only, so the caller keeps it until the sleep ends. + /// [`Self::enter_sleep`] requests the sleep after this call. The return value is a guard that + /// restores what sleep entry changed for the sleep only, so the caller keeps it until the + /// sleep ends. + #[crate::ram] pub(crate) fn start_sleep(&self, wakeup_mask: u32, reject_mask: u32) -> impl Sized { let restore_clock_config = ClockTree::with(|clocks| { let old_root = clocks.hp_root_clk(); @@ -777,6 +789,7 @@ impl RtcSleepConfig { // Restore the old clock settings when we return DropGuard::new((), move |_| { ClockTree::with(|clocks| { + crate::soc::clocks::reconfigure_pll(clocks); if let Some(old_root) = old_root { clocks::configure_hp_root_clk(clocks, old_root); } @@ -848,15 +861,19 @@ impl RtcSleepConfig { // Start entry into sleep mode - // pmu_ll_hp_set_sleep_enable - PMU::regs() - .slp_wakeup_cntl0() - .write(|w| w.sleep_req().bit(true)); - restore_clock_config } - /// Cleans up after sleep + /// Requests the sleep. + /// + /// The caller waits for the result of the request. + #[inline(always)] + pub(crate) fn enter_sleep(&self) -> bool { + request_sleep() + } + + /// Cleans up after sleep. + #[inline(always)] pub(crate) fn finish_sleep(&self) { // like esp-idf pmu_sleep_finish() // In "pd_cpu lightsleep" and "deepsleep" modes we never get here diff --git a/esp-hal/src/rtc_cntl/sleep/esp32c6.rs b/esp-hal/src/rtc_cntl/sleep/esp32c6.rs index 5b45a12d7b3..576591159af 100644 --- a/esp-hal/src/rtc_cntl/sleep/esp32c6.rs +++ b/esp-hal/src/rtc_cntl/sleep/esp32c6.rs @@ -5,11 +5,14 @@ use crate::{ private::DropGuard, rtc_cntl::{ Rtc, - rtc::{HpAnalog, HpSysCntlReg, HpSysPower, LpAnalog, LpSysPower}, - sleep::{SleepKind, pmu_common::SleepTimeConfig}, + rtc::{HpAnalog, HpBackupClk, HpSysCntlReg, HpSysPower, LpAnalog, LpSysPower}, + sleep::{ + SleepKind, + pmu_common::{SleepTimeConfig, request_sleep}, + }, }, soc::{ - clocks::{self, ClockTree, LpSlowClkConfig, SocRootClkConfig}, + clocks::{self, ClockTree, SocRootClkConfig}, xtal32k, }, }; @@ -230,24 +233,8 @@ impl PowerSleepConfig { self.hp_sys.dig_power.set_aon_pd_en(pd_flags.pd_hp_aon()); self.hp_sys.dig_power.set_top_pd_en(pd_flags.pd_top()); - if pd_flags.pd_modem() { - // The modem (Wi-Fi/BLE) power domain is powered down during sleep, so - // isolate and retain its analog I2C buses as before. - self.hp_sys.clk.set_i2c_iso_en(true); - self.hp_sys.clk.set_i2c_retention(true); - } else { - // The modem power domain is kept on across (light-)sleep - // (`pd_modem == false`, the default). In that case its analog blocks - - // the BBPLL and the analog I2C buses used to (re)configure it - must be - // kept powered too, matching the `HP_MODEM` power state. Otherwise the - // radio comes back without a usable PLL and can no longer transmit - // (e.g. BLE advertising silently stops working) after wakeup. - self.hp_sys.clk.set_i2c_iso_en(false); - self.hp_sys.clk.set_i2c_retention(false); - self.hp_sys.clk.set_xpd_bb_i2c(true); - self.hp_sys.clk.set_xpd_bbpll_i2c(true); - self.hp_sys.clk.set_xpd_bbpll(true); - } + self.hp_sys.clk.set_i2c_iso_en(true); + self.hp_sys.clk.set_i2c_retention(true); self.hp_sys.xtal.set_xpd_xtal(pd_flags.pd_xtal().not()); @@ -573,7 +560,7 @@ impl SleepTimeConfig { pub struct RtcSleepConfig { /// Deep Sleep flag pub deep: bool, - /// Power Down flags + /// Powers Down flags. pub pd_flags: PowerDownFlags, } @@ -591,7 +578,7 @@ impl Default for RtcSleepConfig { bitfield::bitfield! { #[derive(Clone, Copy)] - /// Power domains to be powered down during sleep + /// Power domains to be powered down during sleep. pub struct PowerDownFlags(u32); /// Controls the power-down status of the top power domain. @@ -603,7 +590,10 @@ bitfield::bitfield! { /// Controls the power-down status of the high-performance peripheral power domain. pub u32, pd_hp_periph, set_pd_hp_periph: 3; /// Controls the power-down status of the CPU power domain. - pub u32, pd_cpu , set_pd_cpu : 4; + /// + /// Crate-private, because a light sleep needs CPU retention to power this domain down. A + /// power-down without retention loses the CPU state. + pub(crate) u32, pd_cpu, set_pd_cpu: 4; /// Controls the power-down status of the high-performance always-on domain. pub u32, pd_hp_aon , set_pd_hp_aon : 5; /// Controls the power-down status of memory group 0. @@ -618,16 +608,16 @@ bitfield::bitfield! { pub u32, pd_xtal , set_pd_xtal : 10; /// Controls the power-down status of the fast RC oscillator. pub u32, pd_rc_fast , set_pd_rc_fast : 11; - /// Controls the power-down status of the 32kHz crystal oscillator. + /// Controls the power-down status of the 32 kHz crystal oscillator. pub u32, pd_xtal32k , set_pd_xtal32k : 12; - /// Controls the power-down status of the 32kHz RC oscillator. + /// Controls the power-down status of the 32 kHz RC oscillator. pub u32, pd_rc32k , set_pd_rc32k : 13; /// Controls the power-down status of the low-power peripheral domain. pub u32, pd_lp_periph, set_pd_lp_periph: 14; } impl PowerDownFlags { - /// Checks whether all memory groups (G0, G1, G2, G3) are powered down. + /// Returns whether all memory groups (G0, G1, G2, G3) are powered down. pub fn pd_mem(self) -> bool { self.pd_mem_g0() && self.pd_mem_g1() && self.pd_mem_g2() && self.pd_mem_g3() } @@ -695,20 +685,24 @@ impl RtcSleepConfig { self.deep } + pub(crate) fn base_settings(_rtc: &Rtc<'_>) {} + + /// Selects the kind of the sleep, and what the sleep powers down. + /// + /// Sleep entry calls this before the hooks of the wakeup sources, so that a source can keep + /// powered what it needs. pub(crate) fn set_sleep_kind(&mut self, kind: SleepKind) { self.deep = kind == SleepKind::Deep; - } - pub(crate) fn base_settings(_rtc: &Rtc<'_>) {} - - /// Finalize power-down flags, apply configuration based on the flags. - pub(crate) fn apply(&mut self) { - let lp_slow_uses_xtal32k = ClockTree::with(|clocks| { - matches!( - clocks::lp_slow_clk_config(clocks), - Some(LpSlowClkConfig::Xtal32k) - ) - }); + let lp_slow_uses_xtal32k = cfg_select! { + use_xtal32k => ClockTree::with(|clocks| { + matches!( + clocks::lp_slow_clk_config(clocks), + Some(clocks::LpSlowClkConfig::Xtal32k) + ) + }), + _ => false, + }; if self.deep { // force-disable certain power domains @@ -738,10 +732,12 @@ impl RtcSleepConfig { } } - /// Configures the wakeup options and requests the sleep. + /// Configures the wakeup and reject sources of the sleep. /// - /// The caller waits for the result of the request. The return value is a guard that restores - /// what sleep entry changed for the sleep only, so the caller keeps it until the sleep ends. + /// [`Self::enter_sleep`] requests the sleep after this call. The return value is a guard that + /// restores what sleep entry changed for the sleep only, so the caller keeps it until the + /// sleep ends. + #[crate::ram] pub(crate) fn start_sleep(&self, wakeup_mask: u32, reject_mask: u32) -> impl Sized { let restore_clock_config = ClockTree::with(|clocks| { let old_root = clocks.soc_root_clk(); @@ -751,6 +747,7 @@ impl RtcSleepConfig { // Restore the old clock settings when we return DropGuard::new((), move |_| { ClockTree::with(|clocks| { + crate::soc::clocks::reconfigure_pll(clocks); if let Some(old_root) = old_root { clocks::configure_soc_root_clk(clocks, old_root); } @@ -784,6 +781,17 @@ impl RtcSleepConfig { DigitalSleepConfig::defaults_light_sleep(self.pd_flags).apply(); } + // https://github.com/espressif/esp-idf/blob/ce2100d/components/esp_hw_support/lowpower/port/esp32c6/sleep_clock_icg.c#L40-L48 + // https://github.com/espressif/esp-idf/blob/ce2100d/components/esp_hw_support/port/esp32c6/pmu_sleep.c#L299-L302 + let mut icg_func = HpBackupClk::default(); + icg_func.set_retention(!self.deep && clocks::wifi_pwr_clk_runs_in_sleep()); + PMU::regs() + .hp_sleep_sysclk() + .modify(|_, w| w.hp_sleep_icg_sys_clock_en().bit(icg_func.0 != 0)); + PMU::regs() + .hp_sleep_icg_hp_func() + .write(|w| unsafe { w.hp_sleep_dig_icg_func_en().bits(icg_func.0) }); + param.apply(); // like esp-idf pmu_sleep_start() @@ -822,15 +830,19 @@ impl RtcSleepConfig { // Start entry into sleep mode - // pmu_ll_hp_set_sleep_enable - PMU::regs() - .slp_wakeup_cntl0() - .write(|w| w.sleep_req().bit(true)); - restore_clock_config } - /// Cleans up after sleep + /// Requests the sleep. + /// + /// The caller waits for the result of the request. + #[inline(always)] + pub(crate) fn enter_sleep(&self) -> bool { + request_sleep() + } + + /// Cleans up after sleep. + #[inline(always)] pub(crate) fn finish_sleep(&self) { // like esp-idf pmu_sleep_finish() // In "pd_cpu lightsleep" and "deepsleep" modes we never get here diff --git a/esp-hal/src/rtc_cntl/sleep/esp32c61.rs b/esp-hal/src/rtc_cntl/sleep/esp32c61.rs index ac2a1ff302d..3e37e34b46b 100644 --- a/esp-hal/src/rtc_cntl/sleep/esp32c61.rs +++ b/esp-hal/src/rtc_cntl/sleep/esp32c61.rs @@ -6,10 +6,13 @@ use crate::{ rtc_cntl::{ Rtc, rtc::{HpAnalog, HpSysCntlReg, HpSysPower, LpAnalog, LpSysPower}, - sleep::{SleepKind, pmu_common::SleepTimeConfig}, + sleep::{ + SleepKind, + pmu_common::{SleepTimeConfig, request_sleep}, + }, }, soc::{ - clocks::{self, ClockTree, HpRootClkConfig, LpSlowClkConfig}, + clocks::{self, ClockTree, HpRootClkConfig}, xtal32k, }, }; @@ -597,7 +600,7 @@ impl SleepTimeConfig { pub struct RtcSleepConfig { /// Deep Sleep flag pub deep: bool, - /// Power Down flags + /// Powers Down flags. pub pd_flags: PowerDownFlags, } @@ -615,7 +618,7 @@ impl Default for RtcSleepConfig { bitfield::bitfield! { #[derive(Clone, Copy)] - /// Power domains to be powered down during sleep + /// Power domains to be powered down during sleep. pub struct PowerDownFlags(u32); /// Controls the power-down status of the top power domain. @@ -627,7 +630,10 @@ bitfield::bitfield! { /// Controls the power-down status of the high-performance peripheral power domain. pub u32, pd_hp_periph, set_pd_hp_periph: 3; /// Controls the power-down status of the CPU power domain. - pub u32, pd_cpu , set_pd_cpu : 4; + /// + /// Crate-private, because a light sleep needs CPU retention to power this domain down. A + /// power-down without retention loses the CPU state. + pub(crate) u32, pd_cpu, set_pd_cpu: 4; /// Controls the power-down status of the high-performance always-on domain. pub u32, pd_hp_aon , set_pd_hp_aon : 5; /// Controls the power-down status of memory group 0. @@ -642,16 +648,16 @@ bitfield::bitfield! { pub u32, pd_xtal , set_pd_xtal : 10; /// Controls the power-down status of the fast RC oscillator. pub u32, pd_rc_fast , set_pd_rc_fast : 11; - /// Controls the power-down status of the 32kHz crystal oscillator. + /// Controls the power-down status of the 32 kHz crystal oscillator. pub u32, pd_xtal32k , set_pd_xtal32k : 12; - /// Controls the power-down status of the 32kHz RC oscillator. + /// Controls the power-down status of the 32 kHz RC oscillator. pub u32, pd_rc32k , set_pd_rc32k : 13; /// Controls the power-down status of the low-power peripheral domain. pub u32, pd_lp_periph, set_pd_lp_periph: 14; } impl PowerDownFlags { - /// Checks whether all memory groups (G0, G1, G2, G3) are powered down. + /// Returns whether all memory groups (G0, G1, G2, G3) are powered down. pub fn pd_mem(self) -> bool { self.pd_mem_g0() && self.pd_mem_g1() && self.pd_mem_g2() && self.pd_mem_g3() } @@ -723,20 +729,24 @@ impl RtcSleepConfig { self.deep } + pub(crate) fn base_settings(_rtc: &Rtc<'_>) {} + + /// Selects the kind of the sleep, and what the sleep powers down. + /// + /// Sleep entry calls this before the hooks of the wakeup sources, so that a source can keep + /// powered what it needs. pub(crate) fn set_sleep_kind(&mut self, kind: SleepKind) { self.deep = kind == SleepKind::Deep; - } - - pub(crate) fn base_settings(_rtc: &Rtc<'_>) {} - /// Finalize power-down flags, apply configuration based on the flags. - pub(crate) fn apply(&mut self) { - let lp_slow_uses_xtal32k = ClockTree::with(|clocks| { - matches!( - clocks::lp_slow_clk_config(clocks), - Some(LpSlowClkConfig::Xtal32k) - ) - }); + let lp_slow_uses_xtal32k = cfg_select! { + use_xtal32k => ClockTree::with(|clocks| { + matches!( + clocks::lp_slow_clk_config(clocks), + Some(clocks::LpSlowClkConfig::Xtal32k) + ) + }), + _ => false, + }; if self.deep { // force-disable certain power domains @@ -766,10 +776,12 @@ impl RtcSleepConfig { } } - /// Configures the wakeup options and requests the sleep. + /// Configures the wakeup and reject sources of the sleep. /// - /// The caller waits for the result of the request. The return value is a guard that restores - /// what sleep entry changed for the sleep only, so the caller keeps it until the sleep ends. + /// [`Self::enter_sleep`] requests the sleep after this call. The return value is a guard that + /// restores what sleep entry changed for the sleep only, so the caller keeps it until the + /// sleep ends. + #[crate::ram] pub(crate) fn start_sleep(&self, wakeup_mask: u32, reject_mask: u32) -> impl Sized { let restore_clock_config = ClockTree::with(|clocks| { let old_root = clocks.hp_root_clk(); @@ -779,6 +791,7 @@ impl RtcSleepConfig { // Restore the old clock settings when we return DropGuard::new((), move |_| { ClockTree::with(|clocks| { + crate::soc::clocks::reconfigure_pll(clocks); if let Some(old_root) = old_root { clocks::configure_hp_root_clk(clocks, old_root); } @@ -850,15 +863,19 @@ impl RtcSleepConfig { // Start entry into sleep mode - // pmu_ll_hp_set_sleep_enable - PMU::regs() - .slp_wakeup_cntl0() - .write(|w| w.sleep_req().bit(true)); - restore_clock_config } - /// Cleans up after sleep + /// Requests the sleep. + /// + /// The caller waits for the result of the request. + #[inline(always)] + pub(crate) fn enter_sleep(&self) -> bool { + request_sleep() + } + + /// Cleans up after sleep. + #[inline(always)] pub(crate) fn finish_sleep(&self) { // like esp-idf pmu_sleep_finish() // In "pd_cpu lightsleep" and "deepsleep" modes we never get here diff --git a/esp-hal/src/rtc_cntl/sleep/esp32h2.rs b/esp-hal/src/rtc_cntl/sleep/esp32h2.rs index 208a79dbd80..dfb96ad3df6 100644 --- a/esp-hal/src/rtc_cntl/sleep/esp32h2.rs +++ b/esp-hal/src/rtc_cntl/sleep/esp32h2.rs @@ -6,10 +6,13 @@ use crate::{ rtc_cntl::{ Rtc, rtc::{HpSysCntlReg, HpSysPower, LpSysPower}, - sleep::{SleepKind, pmu_common::SleepTimeConfig}, + sleep::{ + SleepKind, + pmu_common::{SleepTimeConfig, request_sleep}, + }, }, soc::{ - clocks::{self, ClockTree, CpuClkConfig, HpRootClkConfig, LpSlowClkConfig}, + clocks::{self, ClockTree, CpuClkConfig, HpRootClkConfig}, xtal32k, }, }; @@ -73,7 +76,9 @@ impl DigitalSleepConfig { cfg }, - icg_func: 0xffff_ffff, // TODO: ESP-IDF determines this using get_sleep_clock_icg_flags + // ESP-IDF ungates only the clocks that `esp_sleep_clock_config` requested. No esp-hal + // driver needs a digital clock during light sleep. + icg_func: 0, deep_sleep: false, } } @@ -410,7 +415,7 @@ impl SleepTimeConfig { pub struct RtcSleepConfig { /// Deep Sleep flag pub deep: bool, - /// Power Down flags + /// Powers Down flags. pub pd_flags: PowerDownFlags, /// Indicates whether the top power domain should remain enabled during sleep. need_pd_top: bool, @@ -431,7 +436,7 @@ impl Default for RtcSleepConfig { bitfield::bitfield! { #[derive(Clone, Copy)] - /// Power domains to be powered down during sleep + /// Power domains to be powered down during sleep. pub struct PowerDownFlags(u32); /// Controls the power-down status of the top power domain. @@ -441,12 +446,15 @@ bitfield::bitfield! { /// Controls the power-down status of the modem power domain. pub u32, pd_modem , set_pd_modem : 2; /// Controls the power-down status of the CPU power domain. - pub u32, pd_cpu , set_pd_cpu : 3; + /// + /// Crate-private, because a light sleep needs CPU retention to power this domain down. A + /// power-down without retention loses the CPU state. + pub(crate) u32, pd_cpu, set_pd_cpu: 3; /// Controls the power-down status of the crystal oscillator. pub u32, pd_xtal , set_pd_xtal : 4; /// Controls the power-down status of the fast RC oscillator. pub u32, pd_rc_fast , set_pd_rc_fast : 5; - /// Controls the power-down status of the 32kHz crystal oscillator. + /// Controls the power-down status of the 32 kHz crystal oscillator. pub u32, pd_xtal32k , set_pd_xtal32k : 6; } @@ -489,20 +497,24 @@ impl RtcSleepConfig { self.deep } + pub(crate) fn base_settings(_rtc: &Rtc<'_>) {} + + /// Selects the kind of the sleep, and what the sleep powers down. + /// + /// Sleep entry calls this before the hooks of the wakeup sources, so that a source can keep + /// powered what it needs. pub(crate) fn set_sleep_kind(&mut self, kind: SleepKind) { self.deep = kind == SleepKind::Deep; - } - - pub(crate) fn base_settings(_rtc: &Rtc<'_>) {} - /// Finalize power-down flags, apply configuration based on the flags. - pub(crate) fn apply(&mut self) { - let lp_slow_uses_xtal32k = ClockTree::with(|clocks| { - matches!( - clocks::lp_slow_clk_config(clocks), - Some(LpSlowClkConfig::Xtal32k) - ) - }); + let lp_slow_uses_xtal32k = cfg_select! { + use_xtal32k => ClockTree::with(|clocks| { + matches!( + clocks::lp_slow_clk_config(clocks), + Some(clocks::LpSlowClkConfig::Xtal32k) + ) + }), + _ => false, + }; if self.deep { // force-disable certain power domains @@ -526,10 +538,12 @@ impl RtcSleepConfig { } } - /// Configures the wakeup options and requests the sleep. + /// Configures the wakeup and reject sources of the sleep. /// - /// The caller waits for the result of the request. The return value is a guard that restores - /// what sleep entry changed for the sleep only, so the caller keeps it until the sleep ends. + /// [`Self::enter_sleep`] requests the sleep after this call. The return value is a guard that + /// restores what sleep entry changed for the sleep only, so the caller keeps it until the + /// sleep ends. + #[crate::ram] pub(crate) fn start_sleep(&self, wakeup_mask: u32, reject_mask: u32) -> impl Sized { let restore_clock_config = ClockTree::with(|clocks| { let old_hp_root_clk = clocks.hp_root_clk(); @@ -609,15 +623,19 @@ impl RtcSleepConfig { // Start entry into sleep mode - // pmu_ll_hp_set_sleep_enable - PMU::regs() - .slp_wakeup_cntl0() - .write(|w| w.sleep_req().bit(true)); - restore_clock_config } - /// Cleans up after sleep + /// Requests the sleep. + /// + /// The caller waits for the result of the request. + #[inline(always)] + pub(crate) fn enter_sleep(&self) -> bool { + request_sleep() + } + + /// Cleans up after sleep. + #[inline(always)] pub(crate) fn finish_sleep(&self) { // The post-wake hook of the GPIO driver releases the pads that the sleep armed. Only that // driver knows which pads it prepared. diff --git a/esp-hal/src/rtc_cntl/sleep/esp32h4.rs b/esp-hal/src/rtc_cntl/sleep/esp32h4.rs new file mode 100644 index 00000000000..1ff39188185 --- /dev/null +++ b/esp-hal/src/rtc_cntl/sleep/esp32h4.rs @@ -0,0 +1,838 @@ +use core::ops::Not; + +use crate::{ + peripherals::{EFUSE, HP_APM, LP_AON, PMU}, + private::DropGuard, + rtc_cntl::{ + Rtc, + rtc::{ + HP_CALI_DRVB, + HpAnalog, + HpSysCntlReg, + HpSysPower, + LP_CALI_DBIAS, + LpAnalog, + LpSysPower, + }, + sleep::{ + SleepKind, + pmu_common::{SleepTimeConfig, request_sleep}, + }, + }, + soc::clocks::{self, AhbClkConfig, ClockTree, CpuClkConfig, CpuClkDivisor, HpRootClkConfig}, +}; + +/// Configuration for controlling the behavior during sleep modes. +#[derive(Clone, Copy)] +// pmu_sleep_analog_config_t +pub struct AnalogSleepConfig { + /// High-power system configuration. + pub hp_sys: HpAnalog, + /// Low-power system analog configuration. + pub lp_sys_sleep: LpAnalog, +} + +impl AnalogSleepConfig { + fn defaults_deep_sleep() -> Self { + Self { + // PMU_SLEEP_ANALOG_DSLP_CONFIG_DEFAULT + hp_sys: { + let mut cfg = HpAnalog::default(); + + cfg.bias.set_dcdc_ccm_enb(true); + cfg.bias.set_dig_reg_dpcur_bias(1); + cfg.bias.set_dig_reg_dsfmos(4); + cfg.bias.set_dcm_vset(20); + cfg.bias.set_dcm_mode(3); + cfg.bias.set_discnnt_dig_rtc(false); + cfg.bias.set_xpd_trx(false); + cfg.bias.set_pd_cur(false); + cfg.bias.set_bias_sleep(false); + cfg.regulator0.set_xpd(false); + + cfg + }, + lp_sys_sleep: { + let mut cfg = LpAnalog::default(); + + cfg.bias.set_dcdc_ccm_enb(true); + cfg.bias.set_dig_reg_dpcur_bias(1); + cfg.bias.set_dig_reg_dsfmos(4); + cfg.bias.set_dcm_vset(0); + cfg.bias.set_dcm_mode(3); + cfg.bias.set_discnnt_dig_rtc(true); + cfg.bias.set_pd_cur(true); + cfg.bias.set_bias_sleep(true); + cfg.regulator0.set_slp_xpd(false); + cfg.regulator0.set_slp_dbias(0); + cfg.regulator0.set_xpd(false); + cfg.regulator0.set_dbias(3); // PMU_LP_DBIAS_SLEEP_0V7_DEFAULT + cfg.regulator1.set_drv_b(0); + + cfg + }, + } + } + + fn defaults_light_sleep(pd_flags: PowerDownFlags) -> Self { + let mut this = Self { + // PMU_SLEEP_ANALOG_LSLP_CONFIG_DEFAULT + hp_sys: { + let mut cfg = HpAnalog::default(); + + cfg.bias.set_dcdc_ccm_enb(true); + cfg.bias.set_dig_reg_dpcur_bias(1); + cfg.bias.set_dig_reg_dsfmos(4); + cfg.bias.set_dcm_mode(3); + cfg.bias.set_discnnt_dig_rtc(false); + cfg.bias.set_xpd_trx(false); + cfg.bias.set_xpd_bias(false); + cfg.bias.set_pd_cur(true); + cfg.bias.set_bias_sleep(true); + cfg.regulator0.set_xpd(true); + cfg.regulator0.set_dbias(0); // PMU_HP_DBIAS_LIGHTSLEEP_0V6_DEFAULT + // PMU_HP_DRVB_LIGHTSLEEP_TOP_PD, PMU_HP_DRVB_LIGHTSLEEP_TOP_PU + cfg.regulator1 + .set_drv_b(if pd_flags.pd_top() { 23 } else { 25 }); + + cfg + }, + lp_sys_sleep: { + let mut cfg = LpAnalog::default(); + + cfg.bias.set_dcdc_ccm_enb(true); + cfg.bias.set_dig_reg_dpcur_bias(1); + cfg.bias.set_dig_reg_dsfmos(4); + cfg.bias.set_dcm_vset(20); + cfg.bias.set_dcm_mode(3); + cfg.bias.set_discnnt_dig_rtc(false); + cfg.bias.set_pd_cur(true); + cfg.bias.set_bias_sleep(true); + cfg.regulator0.set_slp_xpd(false); + cfg.regulator0.set_slp_dbias(0); + cfg.regulator0.set_xpd(true); + cfg.regulator0.set_dbias(3); // PMU_LP_DBIAS_SLEEP_0V7_DEFAULT + cfg.regulator1.set_drv_b(0); + + cfg + }, + }; + + // When XTAL or RC_FAST stays on during sleep, keep the regulators at their active-mode + // calibration values. + if !pd_flags.pd_xtal() { + this.hp_sys.bias.set_xpd_trx(true); + this.hp_sys.regulator1.set_drv_b(HP_CALI_DRVB); + this.hp_sys.bias.set_pd_cur(false); + this.hp_sys.bias.set_bias_sleep(false); + + this.lp_sys_sleep.bias.set_pd_cur(false); + this.lp_sys_sleep.bias.set_bias_sleep(false); + this.lp_sys_sleep.regulator0.set_dbias(LP_CALI_DBIAS); + this.lp_sys_sleep.bias.set_dcm_vset(20); + } else if !pd_flags.pd_rc_fast() { + this.hp_sys.regulator1.set_drv_b(HP_CALI_DRVB); + this.lp_sys_sleep.regulator0.set_dbias(LP_CALI_DBIAS); + } + + this + } + + fn apply(&self) { + // pmu_sleep_analog_init + + // HP SLEEP (hp_sleep_*) + PMU::regs().hp_sleep_bias().modify(|_, w| unsafe { + w.hp_sleep_pd_cur().bit(self.hp_sys.bias.pd_cur()); + w.sleep().bit(self.hp_sys.bias.bias_sleep()); + w.hp_sleep_xpd_trx().bit(self.hp_sys.bias.xpd_trx()); + w.hp_sleep_discnnt_dig_rtc() + .bit(self.hp_sys.bias.discnnt_dig_rtc()); + w.hp_sleep_dcm_mode().bits(self.hp_sys.bias.dcm_mode()); + w.hp_sleep_dcm_vset().bits(self.hp_sys.bias.dcm_vset()) + }); + PMU::regs().hp_sleep_hp_regulator0().modify(|_, w| { + w.hp_sleep_hp_regulator_xpd() + .bit(self.hp_sys.regulator0.xpd()) + }); + PMU::regs().hp_sleep_hp_regulator1().modify(|_, w| unsafe { + w.hp_sleep_hp_regulator_drv_b() + .bits(self.hp_sys.regulator1.drv_b()) + }); + + // LP SLEEP (lp_sleep_*) + PMU::regs().lp_sleep_bias().modify(|_, w| unsafe { + w.lp_sleep_pd_cur().bit(self.lp_sys_sleep.bias.pd_cur()); + w.sleep().bit(self.lp_sys_sleep.bias.bias_sleep()); + w.lp_sleep_discnnt_dig_rtc() + .bit(self.lp_sys_sleep.bias.discnnt_dig_rtc()); + w.lp_sleep_dcm_mode() + .bits(self.lp_sys_sleep.bias.dcm_mode()); + w.lp_sleep_dcm_vset() + .bits(self.lp_sys_sleep.bias.dcm_vset()) + }); + PMU::regs().lp_sleep_lp_regulator0().modify(|_, w| unsafe { + w.lp_sleep_lp_regulator_slp_xpd() + .bit(self.lp_sys_sleep.regulator0.slp_xpd()); + w.lp_sleep_lp_regulator_xpd() + .bit(self.lp_sys_sleep.regulator0.xpd()); + w.lp_sleep_lp_regulator_slp_dbias() + .bits(self.lp_sys_sleep.regulator0.slp_dbias()); + w.lp_sleep_lp_regulator_dbias() + .bits(self.lp_sys_sleep.regulator0.dbias()) + }); + PMU::regs().lp_sleep_lp_regulator1().modify(|_, w| unsafe { + w.lp_sleep_lp_regulator_drv_b() + .bits(self.lp_sys_sleep.regulator1.drv_b()) + }); + } +} + +/// Configuration for controlling the behavior of digital peripherals during +/// sleep modes. +#[derive(Clone, Copy)] +// pmu_sleep_digital_config_t +pub struct DigitalSleepConfig { + /// High-power system control register configuration. + pub syscntl: HpSysCntlReg, + /// The functional clocks that stay enabled during sleep. + pub sleep_icg_func: u32, +} + +impl DigitalSleepConfig { + fn defaults_light_sleep(pd_flags: PowerDownFlags) -> Self { + // PMU_SLEEP_DIGITAL_LSLP_CONFIG_DEFAULT + let mut syscntl = HpSysCntlReg::default(); + syscntl.set_dig_pad_slp_sel(pd_flags.pd_top().not()); + syscntl.set_dig_pause_wdt(true); + + Self { + syscntl, + sleep_icg_func: 0, + } + } + + fn defaults_deep_sleep() -> Self { + // PMU_SLEEP_DIGITAL_DSLP_CONFIG_DEFAULT + let mut syscntl = HpSysCntlReg::default(); + syscntl.set_dig_pad_slp_sel(true); + syscntl.set_dig_pause_wdt(true); + + Self { + syscntl, + sleep_icg_func: 0, + } + } + + fn apply(&self, deep: bool) { + // pmu_sleep_digital_init + PMU::regs().hp_sleep_hp_sys_cntl().modify(|_, w| { + w.hp_sleep_dig_pause_wdt().bit(self.syscntl.dig_pause_wdt()); + if !deep { + w.hp_sleep_dig_pad_slp_sel() + .bit(self.syscntl.dig_pad_slp_sel()); + } + w + }); + PMU::regs() + .hp_sleep_sysclk() + .modify(|_, w| w.hp_sleep_icg_sys_clock_en().bit(self.sleep_icg_func != 0)); + PMU::regs() + .hp_sleep_icg_hp_func() + .write(|w| unsafe { w.bits(self.sleep_icg_func) }); + } +} + +/// Configuration for controlling the power settings of high-power and low-power +/// systems during sleep modes. +#[derive(Clone, Copy)] +// pmu_sleep_power_config_t +pub struct PowerSleepConfig { + /// Power configuration for the high-power system during sleep. + pub hp_sys: HpSysPower, + /// Power configuration for the low-power system when it is active. + pub lp_sys_active: LpSysPower, + /// Power configuration for the low-power system when it is in sleep mode. + pub lp_sys_sleep: LpSysPower, +} + +impl PowerSleepConfig { + fn defaults(pd_flags: PowerDownFlags) -> Self { + // PMU_SLEEP_POWER_CONFIG_DEFAULT + let mut hp_sys = HpSysPower::default(); + hp_sys + .dig_power + .set_vdd_flash_mode(if pd_flags.pd_vddsdio() { 1 } else { 3 }); + hp_sys.dig_power.set_wifi_pd_en(pd_flags.pd_modem()); + hp_sys.dig_power.set_cpu_pd_en(pd_flags.pd_cpu()); + hp_sys.dig_power.set_aon_pd_en(pd_flags.pd_hp_aon()); + hp_sys.dig_power.set_top_pd_en(pd_flags.pd_top()); + hp_sys.clk.set_i2c_iso_en(true); + hp_sys.clk.set_i2c_retention(true); + hp_sys.xtal.set_xpd_xtal(pd_flags.pd_xtal().not()); + + let mut lp_sys_active = LpSysPower::default(); + lp_sys_active + .clk_power + .set_xpd_xtal32k(pd_flags.pd_xtal32k().not()); + lp_sys_active + .clk_power + .set_xpd_rc32k(pd_flags.pd_rc32k().not()); + lp_sys_active.clk_power.set_xpd_fosc(true); + + let mut lp_sys_sleep = LpSysPower::default(); + lp_sys_sleep.dig_power.set_vdd_io_mode(3); + lp_sys_sleep + .dig_power + .set_peri_pd_en(pd_flags.pd_lp_periph()); + lp_sys_sleep + .clk_power + .set_xpd_xtal32k(pd_flags.pd_xtal32k().not()); + lp_sys_sleep + .clk_power + .set_xpd_rc32k(pd_flags.pd_rc32k().not()); + lp_sys_sleep + .clk_power + .set_xpd_fosc(pd_flags.pd_rc_fast().not()); + lp_sys_sleep.xtal.set_xpd_xtal(pd_flags.pd_xtal().not()); + + Self { + hp_sys, + lp_sys_active, + lp_sys_sleep, + } + } + + fn apply(&self, deep: bool) { + // pmu_sleep_power_init + + // HP SLEEP (hp_sleep_*) + PMU::regs() + .hp_sleep_dig_power() + .write(|w| unsafe { w.bits(self.hp_sys.dig_power.0) }); + PMU::regs() + .hp_sleep_hp_ck_power() + .write(|w| unsafe { w.bits(self.hp_sys.clk.0) }); + PMU::regs().hp_sleep_xtal().modify(|_, w| { + w.hp_sleep_xpd_xtal().bit(self.hp_sys.xtal.xpd_xtal()); + w.hp_sleep_xpd_xtalx2().bit(self.hp_sys.xtal.xpd_xtalx2()) + }); + + // pmu_ll_hp_set_memory_power_on_mask + let mem_mask = if deep { 0 } else { 1 }; + PMU::regs().power_pd_mem_mask().modify(|_, w| unsafe { + w.pd_hp_mem0_mask().bits(mem_mask); + w.pd_hp_mem1_mask().bits(mem_mask); + w.pd_hp_mem2_mask().bits(mem_mask) + }); + + // LP ACTIVE (hp_sleep_lp_*) + PMU::regs() + .hp_sleep_lp_dig_power() + .write(|w| unsafe { w.bits(self.lp_sys_active.dig_power.0) }); + PMU::regs() + .hp_sleep_lp_ck_power() + .write(|w| unsafe { w.bits(self.lp_sys_active.clk_power.0) }); + + // LP SLEEP (lp_sleep_*) + PMU::regs() + .lp_sleep_lp_dig_power() + .write(|w| unsafe { w.bits(self.lp_sys_sleep.dig_power.0) }); + PMU::regs() + .lp_sleep_lp_ck_power() + .write(|w| unsafe { w.bits(self.lp_sys_sleep.clk_power.0) }); + PMU::regs().lp_sleep_xtal().modify(|_, w| { + w.lp_sleep_xpd_xtal().bit(self.lp_sys_sleep.xtal.xpd_xtal()); + w.lp_sleep_xpd_xtalx2() + .bit(self.lp_sys_sleep.xtal.xpd_xtalx2()) + }); + } +} + +/// Parameters for high-power system configurations during sleep modes. +#[derive(Clone, Copy)] +// pmu_hp_param_t +pub struct HpParam { + /// Number of cycles to wait for the modem to wake up. + pub modem_wakeup_wait_cycle: u32, + /// Number of cycles to wait for the analog component stabilization. + pub analog_wait_target_cycle: u16, + /// Number of cycles to wait for the digital power supply to stabilize. + pub digital_power_supply_wait_cycle: u16, + /// Number of cycles to wait for the digital power-up sequence. + pub digital_power_up_wait_cycle: u16, + /// Number of cycles to wait for the PLL to stabilize. + pub pll_stable_wait_cycle: u16, + /// Minimum sleep time measured in slow clock cycles. + pub min_slp_slow_clk_cycle: u8, + /// Number of cycles to wait for all isolate signals to be ready. + pub isolate_wait_cycle: u8, + /// Number of cycles to wait for all reset signals to be ready. + pub reset_wait_cycle: u8, +} + +/// Parameters for low-power system configurations during sleep modes. +#[derive(Clone, Copy)] +// pmu_lp_param_t +pub struct LpParam { + /// Number of cycles to wait for the digital power supply to stabilize. + pub digital_power_supply_wait_cycle: u16, + /// Minimum sleep time measured in slow clock cycles. + pub min_slp_slow_clk_cycle: u8, + /// Number of cycles to wait for the analog component stabilization. + pub analog_wait_target_cycle: u8, + /// Number of cycles to wait for the digital power-up sequence. + pub digital_power_up_wait_cycle: u8, + /// Number of cycles to wait for all isolate signals to be ready. + pub isolate_wait_cycle: u8, + /// Number of cycles to wait for all reset signals to be ready. + pub reset_wait_cycle: u8, +} + +/// Parameters for high-power and low-power system configurations during sleep +/// modes. +#[derive(Clone, Copy)] +// pmu_hp_lp_param_t +pub struct HpLpParam { + /// Number of cycles to wait for the crystal oscillator to stabilize. + /// + /// The unit is the slow clock if XTAL stays on during sleep, else the fast clock. + pub xtal_stable_wait_cycle: u16, +} + +/// Configuration of parameters for sleep modes +#[derive(Clone, Copy)] +// pmu_sleep_param_config_t +pub struct ParamSleepConfig { + /// Configuration of high-power system parameters. + pub hp_sys: HpParam, + /// Configuration of low-power system parameters. + pub lp_sys: LpParam, + /// Shared configuration parameters for high-power and low-power systems. + pub hp_lp: HpLpParam, +} + +impl ParamSleepConfig { + const PMU_SLEEP_PARAM_CONFIG_DEFAULT: Self = Self { + hp_sys: HpParam { + min_slp_slow_clk_cycle: 10, + analog_wait_target_cycle: 2419, + digital_power_supply_wait_cycle: 32, + digital_power_up_wait_cycle: 32, + modem_wakeup_wait_cycle: 0, + pll_stable_wait_cycle: 2, + isolate_wait_cycle: 0, + reset_wait_cycle: 0, + }, + lp_sys: LpParam { + min_slp_slow_clk_cycle: 10, + analog_wait_target_cycle: 23, + digital_power_supply_wait_cycle: 32, + digital_power_up_wait_cycle: 32, + isolate_wait_cycle: 0, + reset_wait_cycle: 0, + }, + hp_lp: HpLpParam { + xtal_stable_wait_cycle: 30, + }, + }; + + fn apply(&self) { + // pmu_sleep_param_init + + PMU::regs().slp_wakeup_cntl3().modify(|_, w| unsafe { + w.hp_min_slp_val().bits(self.hp_sys.min_slp_slow_clk_cycle); + w.lp_min_slp_val().bits(self.lp_sys.min_slp_slow_clk_cycle) + }); + + PMU::regs().slp_wakeup_cntl7().modify(|_, w| unsafe { + w.ana_wait_target() + .bits(self.hp_sys.analog_wait_target_cycle) + }); + + PMU::regs().power_wait_timer0().modify(|_, w| unsafe { + w.dg_hp_pd_wait_timer() + .bits(self.hp_sys.digital_power_supply_wait_cycle); + w.dg_hp_powerup_timer() + .bits(self.hp_sys.digital_power_up_wait_cycle) + }); + + PMU::regs().power_wait_timer1().modify(|_, w| unsafe { + w.dg_lp_pd_wait_timer() + .bits(self.lp_sys.digital_power_supply_wait_cycle); + w.dg_lp_powerup_timer() + .bits(self.lp_sys.digital_power_up_wait_cycle) + }); + + PMU::regs().power_wait_timer2().modify(|_, w| unsafe { + w.dg_hp_iso_wait_timer() + .bits(self.hp_sys.isolate_wait_cycle); + w.dg_hp_rst_wait_timer().bits(self.hp_sys.reset_wait_cycle); + w.dg_lp_iso_wait_timer() + .bits(self.lp_sys.isolate_wait_cycle); + w.dg_lp_rst_wait_timer().bits(self.lp_sys.reset_wait_cycle) + }); + + PMU::regs().slp_wakeup_cntl5().modify(|_, w| unsafe { + w.lp_ana_wait_target() + .bits(self.lp_sys.analog_wait_target_cycle); + w.modem_wait_target() + .bits(self.hp_sys.modem_wakeup_wait_cycle) + }); + + PMU::regs().power_ck_wait_cntl().modify(|_, w| unsafe { + w.wait_xtl_stable().bits(self.hp_lp.xtal_stable_wait_cycle); + w.wait_pll_stable().bits(self.hp_sys.pll_stable_wait_cycle) + }); + } + + fn defaults(config: SleepTimeConfig, xpd_xtal: bool) -> Self { + let mut param = Self::PMU_SLEEP_PARAM_CONFIG_DEFAULT; + + // pmu_sleep_param_config_default + param.hp_sys.min_slp_slow_clk_cycle = + config.us_to_slowclk(MachineConstants::HP_MIN_SLP_TIME_US) as u8; + param.hp_sys.analog_wait_target_cycle = + config.us_to_fastclk(MachineConstants::HP_ANALOG_WAIT_TIME_US) as u16; + param.hp_sys.digital_power_supply_wait_cycle = + config.us_to_fastclk(MachineConstants::HP_POWER_SUPPLY_WAIT_TIME_US) as u16; + param.hp_sys.digital_power_up_wait_cycle = + config.us_to_fastclk(MachineConstants::HP_POWER_UP_WAIT_TIME_US) as u16; + param.hp_sys.pll_stable_wait_cycle = + config.us_to_fastclk(MachineConstants::HP_PLL_WAIT_STABLE_TIME_US) as u16; + param.hp_sys.isolate_wait_cycle = + config.us_to_fastclk(MachineConstants::HP_ISOLATE_WAIT_TIME_US) as u8; + param.hp_sys.reset_wait_cycle = + config.us_to_fastclk(MachineConstants::HP_RESET_WAIT_TIME_US) as u8; + + param.lp_sys.min_slp_slow_clk_cycle = + config.us_to_slowclk(MachineConstants::LP_MIN_SLP_TIME_US) as u8; + param.lp_sys.analog_wait_target_cycle = + config.us_to_slowclk(MachineConstants::LP_ANALOG_WAIT_TIME_US) as u8; + param.lp_sys.digital_power_supply_wait_cycle = + config.us_to_fastclk(MachineConstants::LP_POWER_SUPPLY_WAIT_TIME_US) as u16; + param.lp_sys.digital_power_up_wait_cycle = + config.us_to_fastclk(MachineConstants::LP_POWER_UP_WAIT_TIME_US) as u8; + param.lp_sys.isolate_wait_cycle = + config.us_to_fastclk(MachineConstants::LP_ISOLATE_WAIT_TIME_US) as u8; + param.lp_sys.reset_wait_cycle = + config.us_to_fastclk(MachineConstants::LP_RESET_WAIT_TIME_US) as u8; + + param.hp_lp.xtal_stable_wait_cycle = if xpd_xtal { + config.us_to_slowclk(MachineConstants::LP_XTAL_WAIT_STABLE_TIME_US) as u16 + } else { + config.us_to_fastclk(MachineConstants::HP_XTAL_WAIT_STABLE_TIME_US) as u16 + }; + + param + } +} + +impl SleepTimeConfig { + pub(crate) const CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ: u32 = 96; + pub(crate) const LIGHT_SLEEP_TIME_OVERHEAD_US: u32 = 9; + + pub(crate) fn pmu_sleep_calculate_hw_wait_time(&self, pd_flags: PowerDownFlags) -> u32 { + // The LP fast clock is always RC_FAST. + + // LP core hardware wait time, microsecond + let lp_clk_switch_time_us = self.slowclk_to_us(MachineConstants::LP_CLK_SWITCH_CYCLE); + let lp_clk_power_on_wait_time_us = + self.slowclk_to_us(MachineConstants::LP_CLK_POWER_ON_WAIT_CYCLE); + let lp_hw_wait_time_us = MachineConstants::LP_MIN_SLP_TIME_US + + MachineConstants::LP_ANALOG_WAIT_TIME_US + + lp_clk_power_on_wait_time_us + + lp_clk_switch_time_us + + MachineConstants::LP_POWER_SUPPLY_WAIT_TIME_US + + MachineConstants::LP_POWER_UP_WAIT_TIME_US; + + // HP core hardware wait time, microsecond + let hp_regdma_s2a_work_time_us = if pd_flags.pd_top() { + MachineConstants::HP_REGDMA_S2A_WORK_TIME_PD_TOP_US + } else { + MachineConstants::HP_REGDMA_S2A_WORK_TIME_PU_TOP_US + }; + let hp_digital_power_up_wait_time_us = MachineConstants::HP_POWER_SUPPLY_WAIT_TIME_US + + MachineConstants::HP_POWER_UP_WAIT_TIME_US; + let hp_control_wait_time_us = + MachineConstants::HP_ISOLATE_WAIT_TIME_US + MachineConstants::HP_RESET_WAIT_TIME_US; + let hp_regdma_wait_time_us = u32::max( + MachineConstants::HP_REGDMA_S2M_WORK_TIME_US + + MachineConstants::HP_REGDMA_M2A_WORK_TIME_US, + hp_regdma_s2a_work_time_us, + ); + let hp_clock_wait_time_us = if pd_flags.pd_xtal() { + MachineConstants::HP_XTAL_WAIT_STABLE_TIME_US + + MachineConstants::HP_PLL_WAIT_STABLE_TIME_US + } else { + MachineConstants::HP_PLL_WAIT_STABLE_TIME_US + }; + let hp_hw_wait_time_us = MachineConstants::HP_ANALOG_WAIT_TIME_US + + hp_digital_power_up_wait_time_us + + hp_regdma_wait_time_us + + hp_clock_wait_time_us + + hp_control_wait_time_us; + + lp_hw_wait_time_us + hp_hw_wait_time_us + } +} + +/// Configuration for the RTC sleep behavior. +#[derive(Clone, Copy)] +// pmu_sleep_config_t + deep sleep flag + pd flags +pub struct RtcSleepConfig { + /// Deep Sleep flag + pub deep: bool, + /// Powers Down flags. + pub pd_flags: PowerDownFlags, +} + +impl Default for RtcSleepConfig { + fn default() -> Self { + Self { + deep: false, + pd_flags: PowerDownFlags(0), + } + } +} + +bitfield::bitfield! { + #[derive(Clone, Copy)] + /// Power domains to be powered down during sleep. + pub struct PowerDownFlags(u32); + + /// Controls the power-down status of the top power domain. + pub u32, pd_top , set_pd_top : 0; + /// Controls the power-down status of the VDD_SDIO power domain. + pub u32, pd_vddsdio , set_pd_vddsdio : 1; + /// Controls the power-down status of the modem power domain. + pub u32, pd_modem , set_pd_modem : 2; + /// Controls the power-down status of the high-performance peripheral power domain. + pub u32, pd_hp_periph, set_pd_hp_periph: 3; + /// Controls the power-down status of the CPU power domain. + /// + /// Crate-private, because a light sleep needs CPU retention to power this domain down. A + /// power-down without retention loses the CPU state. + pub(crate) u32, pd_cpu, set_pd_cpu: 4; + /// Controls the power-down status of the high-performance always-on domain. + pub u32, pd_hp_aon , set_pd_hp_aon : 5; + /// Controls the power-down status of the crystal oscillator. + pub u32, pd_xtal , set_pd_xtal : 10; + /// Controls the power-down status of the fast RC oscillator. + pub u32, pd_rc_fast , set_pd_rc_fast : 11; + /// Controls the power-down status of the 32 kHz crystal oscillator. + pub u32, pd_xtal32k , set_pd_xtal32k : 12; + /// Controls the power-down status of the 32 kHz RC oscillator. + pub u32, pd_rc32k , set_pd_rc32k : 13; + /// Controls the power-down status of the low-power peripheral domain. + pub u32, pd_lp_periph, set_pd_lp_periph: 14; +} + +// Constants defined in `PMU_SLEEP_MC_DEFAULT()` (ESP32-H4 values) +struct MachineConstants; +impl MachineConstants { + const LP_MIN_SLP_TIME_US: u32 = 450; + const LP_ANALOG_WAIT_TIME_US: u32 = 154; + const LP_XTAL_WAIT_STABLE_TIME_US: u32 = 250; + const LP_CLK_SWITCH_CYCLE: u32 = 1; + const LP_CLK_POWER_ON_WAIT_CYCLE: u32 = 1; + const LP_ISOLATE_WAIT_TIME_US: u32 = 1; + const LP_RESET_WAIT_TIME_US: u32 = 1; + const LP_POWER_SUPPLY_WAIT_TIME_US: u32 = 2; + const LP_POWER_UP_WAIT_TIME_US: u32 = 2; + + const HP_MIN_SLP_TIME_US: u32 = 450; + const HP_ANALOG_WAIT_TIME_US: u32 = 154; + const HP_ISOLATE_WAIT_TIME_US: u32 = 1; + const HP_RESET_WAIT_TIME_US: u32 = 1; + const HP_POWER_SUPPLY_WAIT_TIME_US: u32 = 2; + const HP_POWER_UP_WAIT_TIME_US: u32 = 2; + const HP_REGDMA_S2M_WORK_TIME_US: u32 = 172; + const HP_REGDMA_M2A_WORK_TIME_US: u32 = 278; + const HP_REGDMA_S2A_WORK_TIME_PD_TOP_US: u32 = 0; + const HP_REGDMA_S2A_WORK_TIME_PU_TOP_US: u32 = 390; + const HP_XTAL_WAIT_STABLE_TIME_US: u32 = 250; + const HP_PLL_WAIT_STABLE_TIME_US: u32 = 1; +} + +impl RtcSleepConfig { + /// Returns whether the device is in deep sleep mode. + pub fn deep_slp(&self) -> bool { + self.deep + } + + /// Configures the device for deep sleep mode with ultra-low power settings. + pub fn deep() -> Self { + Self { + deep: true, + ..Self::default() + } + } + + pub(crate) fn is_deep_sleep(&self) -> bool { + self.deep + } + + pub(crate) fn base_settings(_rtc: &Rtc<'_>) {} + + /// Selects the kind of the sleep, and what the sleep powers down. + /// + /// Sleep entry calls this before the hooks of the wakeup sources, so that a source can keep + /// powered what it needs. + pub(crate) fn set_sleep_kind(&mut self, kind: SleepKind) { + self.deep = kind == SleepKind::Deep; + + let lp_slow_uses_xtal32k = cfg_select! { + use_xtal32k => ClockTree::with(|clocks| { + matches!( + clocks::lp_slow_clk_config(clocks), + Some(clocks::LpSlowClkConfig::Xtal32k) + ) + }), + _ => false, + }; + + if self.deep { + // Like esp-idf `esp_deep_sleep_start`. A wakeup source that needs the LP peripherals + // keeps them powered. + self.pd_flags.set_pd_top(true); + self.pd_flags.set_pd_vddsdio(true); + self.pd_flags.set_pd_modem(true); + self.pd_flags.set_pd_hp_periph(true); + self.pd_flags.set_pd_cpu(true); + self.pd_flags.set_pd_hp_aon(true); + self.pd_flags.set_pd_xtal(true); + self.pd_flags.set_pd_lp_periph(true); + self.pd_flags.set_pd_xtal32k(!lp_slow_uses_xtal32k); + self.pd_flags.set_pd_rc32k(true); + self.pd_flags.set_pd_rc_fast(true); + } else { + // Light sleep: the digital domain (CPU, RAM, peripherals) stays powered and only + // clock gated, so execution resumes in place. The sleep powers down the clock sources + // that nothing uses while the core is gated. With XTAL and RC_FAST off, the analog + // configuration also drops the regulators to their sleep voltages. + self.pd_flags.set_pd_xtal(true); + self.pd_flags.set_pd_rc_fast(true); + self.pd_flags.set_pd_xtal32k(!lp_slow_uses_xtal32k); + } + } + + /// Configures the wakeup and reject sources of the sleep. + /// + /// [`Self::enter_sleep`] requests the sleep after this call. The return value is a guard that + /// restores what sleep entry changed for the sleep only, so the caller keeps it until the + /// sleep ends. + #[crate::ram] + pub(crate) fn start_sleep(&self, wakeup_mask: u32, reject_mask: u32) -> impl Sized { + // rtc_clk_cpu_freq_set_xtal_for_sleep: XTAL as the root clock, without dividers. + let restore_clock_config = ClockTree::with(|clocks| { + let old_root = clocks.hp_root_clk(); + let old_cpu = clocks.cpu_clk(); + let old_ahb = clocks.ahb_clk(); + + clocks::configure_hp_root_clk(clocks, HpRootClkConfig::Xtal); + clocks::configure_cpu_clk(clocks, CpuClkConfig::new(CpuClkDivisor::_0)); + clocks::configure_ahb_clk(clocks, AhbClkConfig::new(0)); + + DropGuard::new((), move |_| { + ClockTree::with(|clocks| { + crate::soc::clocks::reconfigure_pll(clocks); + // AHB_CLK may not exceed 32 MHz, so the dividers change before the root + // clock. + if let Some(old_ahb) = old_ahb { + clocks::configure_ahb_clk(clocks, old_ahb); + } + if let Some(old_cpu) = old_cpu { + clocks::configure_cpu_clk(clocks, old_cpu); + } + if let Some(old_root) = old_root { + clocks::configure_hp_root_clk(clocks, old_root); + } + }); + }) + }); + + // pmu_sleep_config_default + pmu_sleep_init. + + let power = PowerSleepConfig::defaults(self.pd_flags); + power.apply(self.deep); + + // Needs to happen after rtc_clk_cpu_freq_set_xtal + let config = if self.deep { + SleepTimeConfig::deep_sleep() + } else { + SleepTimeConfig::light_sleep(self.pd_flags) + }; + + let mut param = ParamSleepConfig::defaults(config, power.hp_sys.xtal.xpd_xtal()); + + if self.deep { + const PMU_LP_ANALOG_WAIT_TARGET_TIME_DSLP_US: u32 = 500; + param.lp_sys.analog_wait_target_cycle = + config.us_to_slowclk(PMU_LP_ANALOG_WAIT_TARGET_TIME_DSLP_US) as u8; + + DigitalSleepConfig::defaults_deep_sleep().apply(true); + AnalogSleepConfig::defaults_deep_sleep().apply(); + } else { + DigitalSleepConfig::defaults_light_sleep(self.pd_flags).apply(false); + AnalogSleepConfig::defaults_light_sleep(self.pd_flags).apply(); + } + + param.apply(); + + // like esp-idf pmu_sleep_start() + + // lp_aon_hal_inform_wakeup_type - tells ROM which wakeup stub to run + LP_AON::regs() + .store8() + .modify(|r, w| unsafe { w.bits(r.bits() & !0x01 | self.deep as u32) }); + + // pmu_ll_hp_set_wakeup_enable + PMU::regs() + .slp_wakeup_cntl2() + .write(|w| unsafe { w.bits(wakeup_mask) }); + + // pmu_ll_hp_set_reject_enable + PMU::regs().slp_wakeup_cntl1().modify(|_, w| unsafe { + w.slp_reject_en().bit(reject_mask != 0); + w.sleep_reject_ena().bits(reject_mask) + }); + + PMU::regs().int_clr().write(|w| { + // pmu_ll_hp_clear_wakeup_intr_status + w.soc_wakeup().clear_bit_by_one(); + // pmu_ll_hp_clear_reject_intr_status + w.soc_sleep_reject().clear_bit_by_one() + }); + + // pmu_ll_hp_clear_reject_cause + PMU::regs() + .slp_wakeup_cntl4() + .write(|w| w.slp_reject_cause_clr().bit(true)); + + restore_clock_config + } + + /// Requests the sleep. + /// + /// The caller waits for the result of the request. + #[inline(always)] + pub(crate) fn enter_sleep(&self) -> bool { + request_sleep() + } + + /// Cleans up after sleep. + #[inline(always)] + pub(crate) fn finish_sleep(&self) { + // like esp-idf pmu_sleep_finish() + + // Wait until the eFuse controller is idle. + while EFUSE::regs().status().read().state().bits() != 1 {} + + // apm_hal_enable_ctrl_filter_all(false), see `soc::pre_init`. + HP_APM::regs().func_ctrl().write(|w| unsafe { w.bits(0) }); + + // The post-wake hook of the GPIO driver releases the pads that the sleep armed. Only that + // driver knows which pads it prepared. + } +} diff --git a/esp-hal/src/rtc_cntl/sleep/esp32p4.rs b/esp-hal/src/rtc_cntl/sleep/esp32p4.rs index 0d62be9a465..82d933b8581 100644 --- a/esp-hal/src/rtc_cntl/sleep/esp32p4.rs +++ b/esp-hal/src/rtc_cntl/sleep/esp32p4.rs @@ -1,8 +1,4 @@ -//! Light- and deep-sleep support for the ESP32-P4 (chip revision v3.x / eco5). -//! -//! v1 scope: timer wakeup only, single core. Ported from the ESP32-C6 PMU sleep -//! driver and adapted to the P4 PMU (DCDC, no wireless modem, no regdma -//! retention) using the esp-idf `pmu_sleep.c` / `pmu_param.h` references. +//! Light- and deep-sleep support for the ESP32-P4. use core::{ ops::Not, @@ -15,9 +11,12 @@ use crate::{ rtc_cntl::{ Rtc, rtc::{HpAnalog, HpSysCntlReg, HpSysPower, LpAnalog, LpSysPower}, - sleep::{SleepKind, pmu_common::SleepTimeConfig}, + sleep::{ + SleepKind, + pmu_common::{SleepTimeConfig, request_sleep}, + }, }, - soc::clocks::{self, ClockTree, CpuRootClkConfig, LpSlowClkConfig}, + soc::clocks::{self, ClockTree, CpuRootClkConfig}, }; // ---------------------------------------------------------------------------- @@ -101,7 +100,7 @@ fn usj_pad_backup_and_disable() { USJ_PAD_WAS_ENABLED.store(pad_enabled, Ordering::Relaxed); } -/// Restore the USJ pad on wake. esp-idf `sleep_console_usj_pad_restore`. +/// Restores the USJ pad on wake. esp-idf `sleep_console_usj_pad_restore`. fn usj_pad_restore() { usj_enable_bus_clock(true); usj_set_pad_enable(USJ_PAD_WAS_ENABLED.load(Ordering::Relaxed)); @@ -784,7 +783,10 @@ bitfield::bitfield! { /// Controls the power-down status of the high-performance peripheral domain. pub u32, pd_hp_periph, set_pd_hp_periph: 3; /// Controls the power-down status of the CPU power domain. - pub u32, pd_cpu , set_pd_cpu : 4; + /// + /// Crate-private, because a light sleep needs CPU retention to power this domain down. A + /// power-down without retention loses the CPU state. + pub(crate) u32, pd_cpu, set_pd_cpu: 4; /// Controls the power-down status of the high-performance always-on domain. pub u32, pd_hp_aon , set_pd_hp_aon : 5; /// Controls the power-down status of memory group 0. @@ -799,16 +801,16 @@ bitfield::bitfield! { pub u32, pd_xtal , set_pd_xtal : 10; /// Controls the power-down status of the fast RC oscillator. pub u32, pd_rc_fast , set_pd_rc_fast : 11; - /// Controls the power-down status of the 32kHz crystal oscillator. + /// Controls the power-down status of the 32 kHz crystal oscillator. pub u32, pd_xtal32k , set_pd_xtal32k : 12; - /// Controls the power-down status of the 32kHz RC oscillator. + /// Controls the power-down status of the 32 kHz RC oscillator. pub u32, pd_rc32k , set_pd_rc32k : 13; /// Controls the power-down status of the low-power peripheral domain. pub u32, pd_lp_periph, set_pd_lp_periph: 14; } impl PowerDownFlags { - /// Checks whether all memory groups are powered down. + /// Returns whether all memory groups are powered down. pub fn pd_mem(self) -> bool { self.pd_mem_g0() && self.pd_mem_g1() && self.pd_mem_g2() && self.pd_mem_g3() } @@ -870,20 +872,24 @@ impl RtcSleepConfig { self.deep_slp() } + pub(crate) fn base_settings(_rtc: &Rtc<'_>) {} + + /// Selects the kind of the sleep, and what the sleep powers down. + /// + /// Sleep entry calls this before the hooks of the wakeup sources, so that a source can keep + /// powered what it needs. pub(crate) fn set_sleep_kind(&mut self, kind: SleepKind) { self.deep = kind == SleepKind::Deep; - } - - pub(crate) fn base_settings(_rtc: &Rtc<'_>) {} - /// Finalize power-down flags, apply configuration based on the flags. - pub(crate) fn apply(&mut self) { - let lp_slow_uses_xtal32k = ClockTree::with(|clocks| { - matches!( - clocks::lp_slow_clk_config(clocks), - Some(LpSlowClkConfig::Xtal32k) - ) - }); + let lp_slow_uses_xtal32k = cfg_select! { + use_xtal32k => ClockTree::with(|clocks| { + matches!( + clocks::lp_slow_clk_config(clocks), + Some(clocks::LpSlowClkConfig::Xtal32k) + ) + }), + _ => false, + }; if self.deep { self.pd_flags.set_pd_top(true); @@ -910,10 +916,11 @@ impl RtcSleepConfig { } } - /// Configures the wakeup options and requests the sleep. + /// Configures the wakeup and reject sources of the sleep. /// - /// The caller waits for the result of the request. The return value is a guard that restores - /// what sleep entry changed for the sleep only, so the caller keeps it until the sleep ends. + /// [`Self::enter_sleep`] requests the sleep after this call. The return value is a guard that + /// restores what sleep entry changed for the sleep only, so the caller keeps it until the + /// sleep ends. #[crate::ram] pub(crate) fn start_sleep(&self, wakeup_mask: u32, reject_mask: u32) -> impl Sized { // Switch the CPU root clock to XTAL for the duration of sleep. @@ -1041,13 +1048,17 @@ impl RtcSleepConfig { // Start entry into sleep mode. - PMU::regs() - .slp_wakeup_cntl0() - .write(|w| w.sleep_req().bit(true)); - (restore_clock_config, restore_boot_vector) } + /// Requests the sleep. + /// + /// The caller waits for the result of the request. + #[inline(always)] + pub(crate) fn enter_sleep(&self) -> bool { + request_sleep() + } + /// Cleans up after sleep. #[crate::ram] pub(crate) fn finish_sleep(&self) { diff --git a/esp-hal/src/rtc_cntl/sleep/esp32s2.rs b/esp-hal/src/rtc_cntl/sleep/esp32s2.rs index 83c09eca4d8..e5a1138a1d4 100644 --- a/esp-hal/src/rtc_cntl/sleep/esp32s2.rs +++ b/esp-hal/src/rtc_cntl/sleep/esp32s2.rs @@ -42,7 +42,7 @@ pub const RTC_CNTL_MIN_SLP_VAL_MIN: u8 = 2; pub const RTC_CNTL_DBG_ATTEN_DEEPSLEEP_DEFAULT: u8 = 15; /// Power-up setting for other blocks. pub const OTHER_BLOCKS_POWERUP: u8 = 1; -/// Wait cycles for other blocks. +/// Waits cycles for other blocks. pub const OTHER_BLOCKS_WAIT: u16 = 1; /// WiFi power-up cycles. pub const WIFI_POWERUP_CYCLES: u8 = OTHER_BLOCKS_POWERUP; @@ -82,7 +82,7 @@ bitfield::bitfield! { pub rtc_peri_pd_en, set_rtc_peri_pd_en: 4; /// power down Wifi pub wifi_pd_en, set_wifi_pd_en: 5; - /// Power down Internal 8M oscillator + /// Powers down Internal 8M oscillator. pub int_8m_pd_en, set_int_8m_pd_en: 6; /// power down digital domain pub deep_slp, set_deep_slp: 8; @@ -582,9 +582,9 @@ impl RtcSleepConfig { } } - /// Configures the wakeup options and requests the sleep. + /// Configures the wakeup and reject sources of the sleep. /// - /// The caller waits for the result of the request. + /// [`Self::enter_sleep`] requests the sleep after this call. pub(crate) fn start_sleep(&self, wakeup_mask: u32, reject_mask: u32) { unsafe { LPWR::regs() @@ -601,11 +601,18 @@ impl RtcSleepConfig { LPWR::regs() .slp_reject_conf() .modify(|_, w| w.sleep_reject_ena().bits(reject_mask)); - - LPWR::regs().state0().modify(|_, w| w.sleep_en().set_bit()); } } + /// Requests the sleep. + /// + /// The caller waits for the result of the request. + #[inline(always)] + pub(crate) fn enter_sleep(&self) -> bool { + LPWR::regs().state0().modify(|_, w| w.sleep_en().set_bit()); + super::wait_for_sleep_result() + } + pub(crate) fn finish_sleep(&self) { // In deep sleep mode, we never get here unsafe { diff --git a/esp-hal/src/rtc_cntl/sleep/esp32s3.rs b/esp-hal/src/rtc_cntl/sleep/esp32s3.rs index 9f99ae3dbe0..ebf9d122740 100644 --- a/esp-hal/src/rtc_cntl/sleep/esp32s3.rs +++ b/esp-hal/src/rtc_cntl/sleep/esp32s3.rs @@ -28,6 +28,8 @@ pub const RTC_CNTL_DBIAS_1V25: u8 = 30; pub const RTC_CNTL_DBIAS_1V30: u8 = 31; /// Default monitor debug attenuation value. pub const RTC_CNTL_DBG_ATTEN_MONITOR_DEFAULT: u8 = 0; +/// Light sleep debug attenuation setting that keeps the voltage up. +const RTC_CNTL_DBG_ATTEN_LIGHTSLEEP_NODROP: u8 = 0; /// ULP co-processor touch start wait time during sleep, set to maximum. pub const RTC_CNTL_ULPCP_TOUCH_START_WAIT_IN_SLEEP: u16 = 0xFF; /// ULP co-processor touch start wait time default value. @@ -42,7 +44,7 @@ pub const RTC_CNTL_MIN_SLP_VAL_MIN: u8 = 2; pub const RTC_CNTL_DBG_ATTEN_DEEPSLEEP_ULTRA_LOW: u8 = 15; /// Power-up setting for other blocks. pub const OTHER_BLOCKS_POWERUP: u8 = 1; -/// Wait cycles for other blocks. +/// Waits cycles for other blocks. pub const OTHER_BLOCKS_WAIT: u16 = 1; /// WiFi power-up cycles. pub const WIFI_POWERUP_CYCLES: u8 = OTHER_BLOCKS_POWERUP; @@ -91,8 +93,11 @@ bitfield::bitfield! { /// power down Modem(wifi and ble) pub modem_pd_en, set_modem_pd_en: 5; /// power down CPU, but not restart when lightsleep. - pub cpu_pd_en, set_cpu_pd_en: 6; - /// Power down Internal 8M oscillator + /// + /// Crate-private, because a light sleep derives this from the installed retention memory. A + /// CPU power-down without retention loses the CPU state. + pub(crate) cpu_pd_en, set_cpu_pd_en: 6; + /// Powers down Internal 8M oscillator. pub int_8m_pd_en, set_int_8m_pd_en: 7; /// power down digital peripherals pub dig_peri_pd_en, set_dig_peri_pd_en: 8; @@ -151,7 +156,7 @@ const SYSCON_ROM_POWER_UP: u8 = 0x7; fn rtc_sleep_pu(val: bool) { let rtc_cntl = LPWR::regs(); - let syscon = unsafe { &*esp32s3::APB_CTRL::ptr() }; + let syscon = APB_CTRL::regs(); let bb = unsafe { &*esp32s3::BB::ptr() }; let nrx = unsafe { &*esp32s3::NRX::ptr() }; let fe = unsafe { &*esp32s3::FE::ptr() }; @@ -258,10 +263,8 @@ impl RtcSleepConfig { rtc_cntl.ana_conf().modify(|_, w| w.pvtmon_pu().clear_bit()); rtc_cntl.timer1().modify(|_, w| { - w.pll_buf_wait() - .bits(RTC_CNTL_PLL_BUF_WAIT_DEFAULT) - .ck8m_wait() - .bits(RTC_CNTL_CK8M_WAIT_DEFAULT) + w.pll_buf_wait().bits(RTC_CNTL_PLL_BUF_WAIT_DEFAULT); + w.ck8m_wait().bits(RTC_CNTL_CK8M_WAIT_DEFAULT) }); // Moved from rtc sleep to rtc init to save sleep function running time @@ -354,12 +357,10 @@ impl RtcSleepConfig { .modify(|_, w| w.xtl_force_pu().clear_bit()); rtc_cntl.ana_conf().modify(|_, w| { - w - // open sar_i2c protect function to avoid sar_i2c reset when rtc_ldo is low. - // clear i2c_reset_protect pd force, need tested in low temperature. - // NOTE: this bit is written again in esp-idf, but it's not clear why. - .i2c_reset_por_force_pd() - .clear_bit() + // open sar_i2c protect function to avoid sar_i2c reset when rtc_ldo is low. + // clear i2c_reset_protect pd force, need tested in low temperature. + // NOTE: this bit is written again in esp-idf, but it's not clear why. + w.i2c_reset_por_force_pd().clear_bit() }); // cancel bbpll force pu if setting no force power up @@ -417,9 +418,10 @@ impl RtcSleepConfig { .dig_pwc() .modify(|_, w| w.wifi_force_pu().clear_bit()); - rtc_cntl - .dig_iso() - .modify(|_, w| w.bt_force_noiso().clear_bit().bt_force_iso().clear_bit()); + rtc_cntl.dig_iso().modify(|_, w| { + w.bt_force_noiso().clear_bit(); + w.bt_force_iso().clear_bit() + }); rtc_cntl .dig_pwc() @@ -491,31 +493,29 @@ impl RtcSleepConfig { w.wifi_force_noiso().clear_bit(); w.wifi_force_iso().clear_bit() }); - - rtc_cntl - .dig_pwc() - .modify(|_, w| w.wifi_force_pu().clear_bit().wifi_pd_en().set_bit()); } else { rtc_cntl.options0().modify(|_, w| { w.bbpll_force_pu().set_bit(); w.bbpll_i2c_force_pu().set_bit(); w.bb_i2c_force_pu().set_bit() }); - - rtc_cntl - .dig_pwc() - .modify(|_, w| w.wifi_force_pu().set_bit().wifi_pd_en().clear_bit()); } + rtc_cntl.dig_pwc().modify(|_, w| { + w.wifi_force_pu().bit(self.modem_pd_en()); + w.wifi_pd_en().bit(self.modem_pd_en()) + }); + if self.cpu_pd_en() { rtc_cntl.dig_iso().modify(|_, w| { w.cpu_top_force_noiso().clear_bit(); w.cpu_top_force_iso().clear_bit() }); - rtc_cntl - .dig_pwc() - .modify(|_, w| w.cpu_top_force_pu().clear_bit().cpu_top_pd_en().set_bit()); + rtc_cntl.dig_pwc().modify(|_, w| { + w.cpu_top_force_pu().clear_bit(); + w.cpu_top_pd_en().set_bit() + }); } else { rtc_cntl .dig_pwc() @@ -528,9 +528,10 @@ impl RtcSleepConfig { w.dg_peri_force_iso().clear_bit() }); - rtc_cntl - .dig_pwc() - .modify(|_, w| w.dg_peri_force_pu().clear_bit().dg_peri_pd_en().set_bit()); + rtc_cntl.dig_pwc().modify(|_, w| { + w.dg_peri_force_pu().clear_bit(); + w.dg_peri_pd_en().set_bit() + }); } else { rtc_cntl .dig_pwc() @@ -548,14 +549,25 @@ impl RtcSleepConfig { rtc_cntl.pwc().modify(|_, w| w.pd_en().clear_bit()); } + // Like `rtc_sleep_get_default_config`: a crystal that stays on through a light sleep needs + // the bias current and the voltage of the active mode. + let xtal_on = self.xtal_fpu() && !self.deep_slp(); + let bias_sleep_slp = self.bias_sleep_slp() && !xtal_on; + let pd_cur_slp = self.pd_cur_slp() && !xtal_on; + let dbg_atten_slp = if xtal_on { + RTC_CNTL_DBG_ATTEN_LIGHTSLEEP_NODROP + } else { + self.dbg_atten_slp() + }; + unsafe { regi2c::I2C_DIG_REG_EXT_RTC_DREG_SLEEP.write_field(self.rtc_dbias_slp()); regi2c::I2C_DIG_REG_EXT_DIG_DREG_SLEEP.write_field(self.dig_dbias_slp()); rtc_cntl.bias_conf().modify(|_, w| { - w.dbg_atten_deep_slp().bits(self.dbg_atten_slp()); - w.bias_sleep_deep_slp().bit(self.bias_sleep_slp()); - w.pd_cur_deep_slp().bit(self.pd_cur_slp()); + w.dbg_atten_deep_slp().bits(dbg_atten_slp); + w.bias_sleep_deep_slp().bit(bias_sleep_slp); + w.pd_cur_deep_slp().bit(pd_cur_slp); w.dbg_atten_monitor() .bits(RTC_CNTL_DBG_ATTEN_MONITOR_DEFAULT); w.bias_sleep_monitor().bit(self.bias_sleep_monitor()); @@ -631,9 +643,9 @@ impl RtcSleepConfig { } } - /// Configures the wakeup options and requests the sleep. + /// Configures the wakeup and reject sources of the sleep. /// - /// The caller waits for the result of the request. + /// [`Self::enter_sleep`] requests the sleep after this call. pub(crate) fn start_sleep(&self, wakeup_mask: u32, reject_mask: u32) { unsafe { LPWR::regs() @@ -650,11 +662,18 @@ impl RtcSleepConfig { LPWR::regs() .slp_reject_conf() .modify(|_, w| w.sleep_reject_ena().bits(reject_mask)); - - LPWR::regs().state0().modify(|_, w| w.sleep_en().set_bit()); } } + /// Requests the sleep. + /// + /// The caller waits for the result of the request. + #[inline(always)] + pub(crate) fn enter_sleep(&self) -> bool { + LPWR::regs().state0().modify(|_, w| w.sleep_en().set_bit()); + super::wait_for_sleep_result() + } + pub(crate) fn finish_sleep(&self) { // In deep sleep mode, we never get here unsafe { diff --git a/esp-hal/src/rtc_cntl/sleep/esp32s31.rs b/esp-hal/src/rtc_cntl/sleep/esp32s31.rs new file mode 100644 index 00000000000..e7f700007d8 --- /dev/null +++ b/esp-hal/src/rtc_cntl/sleep/esp32s31.rs @@ -0,0 +1,755 @@ +//! Light- and deep-sleep support for the ESP32-S31. +use core::ops::Not; + +use crate::{ + peripherals::{LP_SYS as LP_AON, PMU}, + private::DropGuard, + rtc_cntl::{ + Rtc, + rtc::{HpAnalog, HpSysCntlReg, HpSysPower, LpAnalog, LpSysPower}, + sleep::{ + SleepKind, + pmu_common::{SleepTimeConfig, request_sleep}, + }, + }, + soc::{ + clocks::{self, ClockTree, CpuRootClkConfig}, + xtal32k, + }, +}; + +const HP_CALI_DBIAS: u8 = 26; +const LP_CALI_DBIAS: u8 = 26; + +/// Configuration for controlling analog behavior during sleep. +#[derive(Clone, Copy)] +pub struct AnalogSleepConfig { + /// High-power system analog configuration. + pub hp_sys: HpAnalog, + /// Low-power system analog configuration. + pub lp_sys_sleep: LpAnalog, +} + +impl AnalogSleepConfig { + fn defaults_deep_sleep() -> Self { + // PMU_SLEEP_ANALOG_DSLP_CONFIG_DEFAULT + Self { + hp_sys: { + let mut cfg = HpAnalog::default(); + cfg.bias.set_pd_cur(true); + cfg.bias.set_bias_sleep(true); + cfg.regulator0.set_xpd(false); + cfg.bias.set_dbg_atten(0); + cfg + }, + lp_sys_sleep: { + let mut cfg = LpAnalog::default(); + cfg.regulator1.set_drv_b(0); + cfg.bias.set_pd_cur(true); + cfg.bias.set_bias_sleep(true); + cfg.regulator0.set_slp_xpd(false); + cfg.regulator0.set_slp_dbias(0); + cfg.regulator0.set_xpd(true); + cfg.bias.set_dbg_atten(12); + cfg.regulator0.set_dbias(23); + cfg + }, + } + } + + fn defaults_light_sleep(pd_flags: PowerDownFlags) -> Self { + let mut this = Self { + hp_sys: { + let mut cfg = HpAnalog::default(); + cfg.regulator1.set_drv_b(0); + cfg.bias.set_pd_cur(true); + cfg.bias.set_bias_sleep(true); + cfg.regulator0.set_xpd(true); + cfg.bias.set_dbg_atten(0); + cfg.regulator0.set_dbias(1); + cfg + }, + lp_sys_sleep: { + let mut cfg = LpAnalog::default(); + cfg.regulator1.set_drv_b(0); + cfg.bias.set_pd_cur(true); + cfg.bias.set_bias_sleep(true); + cfg.regulator0.set_slp_xpd(false); + cfg.regulator0.set_slp_dbias(0); + cfg.regulator0.set_xpd(true); + cfg.bias.set_dbg_atten(0); + cfg.regulator0.set_dbias(12); + cfg + }, + }; + + if !pd_flags.pd_xtal() { + this.hp_sys.bias.set_pd_cur(false); + this.lp_sys_sleep.bias.set_pd_cur(false); + } + + if !pd_flags.pd_xtal() || !pd_flags.pd_rc_fast() { + this.hp_sys.bias.set_dbg_atten(0); + this.hp_sys.regulator0.set_dbias(HP_CALI_DBIAS); + this.lp_sys_sleep.bias.set_dbg_atten(0); + this.lp_sys_sleep.regulator0.set_dbias(LP_CALI_DBIAS); + } + + this + } + + fn apply(&self) { + // pmu_sleep_analog_init + PMU::regs().hp_sleep_bias().modify(|_, w| unsafe { + w.hp_sleep_dbg_atten().bits(self.hp_sys.bias.dbg_atten()); + w.hp_sleep_pd_cur().bit(self.hp_sys.bias.pd_cur()); + w.sleep().bit(self.hp_sys.bias.bias_sleep()) + }); + PMU::regs().hp_sleep_hp_regulator0().modify(|_, w| unsafe { + w.hp_sleep_hp_regulator_slp_mem_xpd() + .bit(self.hp_sys.regulator0.slp_mem_xpd()); + w.hp_sleep_hp_regulator_slp_logic_xpd() + .bit(self.hp_sys.regulator0.slp_logic_xpd()); + w.hp_sleep_hp_regulator_xpd() + .bit(self.hp_sys.regulator0.xpd()); + w.hp_sleep_hp_regulator_slp_logic_dbias() + .bits(self.hp_sys.regulator0.slp_logic_dbias()); + w.hp_sleep_hp_regulator_dbias() + .bits(self.hp_sys.regulator0.dbias()) + }); + PMU::regs().hp_sleep_hp_regulator1().modify(|_, w| unsafe { + w.hp_sleep_hp_regulator_drv_b() + .bits(self.hp_sys.regulator1.drv_b()) + }); + + PMU::regs().lp_sleep_bias().modify(|_, w| unsafe { + w.lp_sleep_dbg_atten() + .bits(self.lp_sys_sleep.bias.dbg_atten()); + w.lp_sleep_pd_cur().bit(self.lp_sys_sleep.bias.pd_cur()); + w.sleep().bit(self.lp_sys_sleep.bias.bias_sleep()) + }); + PMU::regs().lp_sleep_lp_regulator0().modify(|_, w| unsafe { + w.lp_sleep_lp_regulator_slp_xpd() + .bit(self.lp_sys_sleep.regulator0.slp_xpd()); + w.lp_sleep_lp_regulator_xpd() + .bit(self.lp_sys_sleep.regulator0.xpd()); + w.lp_sleep_lp_regulator_slp_dbias() + .bits(self.lp_sys_sleep.regulator0.slp_dbias()); + w.lp_sleep_lp_regulator_dbias() + .bits(self.lp_sys_sleep.regulator0.dbias()) + }); + PMU::regs().lp_sleep_lp_regulator1().modify(|_, w| unsafe { + w.lp_sleep_lp_regulator_drv_b() + .bits(self.lp_sys_sleep.regulator1.drv_b()) + }); + } +} + +/// Configuration for digital peripherals during sleep. +#[derive(Clone, Copy)] +pub struct DigitalSleepConfig { + /// High-power system control register configuration. + pub syscntl: HpSysCntlReg, +} + +impl DigitalSleepConfig { + fn defaults_deep_sleep(pd_flags: PowerDownFlags) -> Self { + let mut syscntl = HpSysCntlReg::default(); + syscntl.set_dig_pad_slp_sel(false); + syscntl.set_lp_pad_hold_all(true); + syscntl.set_hp_pad_hold_all(true); + syscntl.set_dig_pause_wdt(true); + syscntl.set_c_channel(!pd_flags.pd_top()); + Self { syscntl } + } + + fn defaults_light_sleep(pd_flags: PowerDownFlags) -> Self { + let mut syscntl = HpSysCntlReg::default(); + syscntl.set_dig_pad_slp_sel(!pd_flags.pd_top()); + syscntl.set_lp_pad_hold_all(pd_flags.pd_top()); + syscntl.set_hp_pad_hold_all(pd_flags.pd_top()); + syscntl.set_dig_pause_wdt(true); + syscntl.set_c_channel(!pd_flags.pd_top()); + Self { syscntl } + } + + fn apply(&self) { + PMU::regs().hp_sleep_hp_sys_cntl().modify(|_, w| { + w.hp_sleep_c_channel().bit(self.syscntl.c_channel()); + w.hp_sleep_dig_pad_slp_sel() + .bit(self.syscntl.dig_pad_slp_sel()); + w.hp_sleep_lp_pad_hold_all() + .bit(self.syscntl.lp_pad_hold_all()); + w.hp_sleep_hp_pad_hold_all() + .bit(self.syscntl.hp_pad_hold_all()); + w.hp_sleep_dig_pause_wdt().bit(self.syscntl.dig_pause_wdt()); + w.hp_sleep_dig_cpu_stall().bit(true) + }); + } +} + +/// Configuration of HP and LP power domains during sleep. +#[derive(Clone, Copy)] +pub struct PowerSleepConfig { + /// Power configuration for the high-power system during sleep. + pub hp_sys: HpSysPower, + /// Power configuration for the low-power system when it is active. + pub lp_sys_active: LpSysPower, + /// Power configuration for the low-power system when it is in sleep mode. + pub lp_sys_sleep: LpSysPower, +} + +impl PowerSleepConfig { + fn defaults(pd_flags: PowerDownFlags) -> Self { + let mut this = Self { + hp_sys: HpSysPower::default(), + lp_sys_active: LpSysPower::default(), + lp_sys_sleep: LpSysPower::default(), + }; + this.apply_flags(pd_flags); + this + } + + fn apply_flags(&mut self, pd_flags: PowerDownFlags) { + // PMU_SLEEP_POWER_CONFIG_DEFAULT + self.hp_sys + .dig_power + .set_vdd_spi_pd_en(pd_flags.pd_vddsdio()); + self.hp_sys + .dig_power + .set_hp_alive_pd_en(pd_flags.pd_mem() || pd_flags.pd_hp_aon()); + self.hp_sys + .dig_power + .set_modem_top_pd_en(pd_flags.pd_modem()); + self.hp_sys.dig_power.set_hp_cnnt_pd_en(pd_flags.pd_modem()); + self.hp_sys.dig_power.set_hp_cpu_pd_en(pd_flags.pd_cpu()); + self.hp_sys.dig_power.set_modem_pwr_pd_en(pd_flags.pd_mem()); + self.hp_sys.dig_power.set_top_pd_en(pd_flags.pd_top()); + + self.hp_sys.clk.set_i2c_iso_en(true); + self.hp_sys.clk.set_i2c_retention(true); + + self.hp_sys.xtal.set_xpd_xtal(pd_flags.pd_xtal().not()); + + self.lp_sys_active + .clk_power + .set_xpd_xtal32k(pd_flags.pd_xtal32k().not()); + self.lp_sys_active + .clk_power + .set_xpd_rc32k(pd_flags.pd_rc32k().not()); + self.lp_sys_active.clk_power.set_xpd_fosc(true); + + self.lp_sys_sleep + .dig_power + .set_peri_pd_en(pd_flags.pd_lp_periph()); + + self.lp_sys_sleep + .clk_power + .set_xpd_xtal32k(pd_flags.pd_xtal32k().not()); + self.lp_sys_sleep + .clk_power + .set_xpd_rc32k(pd_flags.pd_rc32k().not()); + self.lp_sys_sleep + .clk_power + .set_xpd_fosc(pd_flags.pd_rc_fast().not()); + + self.lp_sys_sleep + .xtal + .set_xpd_xtal(pd_flags.pd_xtal().not()); + } + + fn apply(&self, dslp: bool) { + // pmu_sleep_power_init + PMU::regs() + .hp_sleep_dig_power() + .modify(|_, w| unsafe { w.bits(self.hp_sys.dig_power.0) }); + PMU::regs() + .hp_sleep_hp_ck_power() + .modify(|_, w| unsafe { w.bits(self.hp_sys.clk.0) }); + PMU::regs() + .hp_sleep_xtal() + .modify(|_, w| w.hp_sleep_xpd_xtal().bit(self.hp_sys.xtal.xpd_xtal())); + + set_memory_power_on_mask(!dslp); + + PMU::regs() + .hp_sleep_lp_dig_power() + .modify(|_, w| unsafe { w.bits(self.lp_sys_active.dig_power.0) }); + PMU::regs() + .hp_sleep_lp_ck_power() + .modify(|_, w| unsafe { w.bits(self.lp_sys_active.clk_power.0) }); + + PMU::regs() + .lp_sleep_lp_dig_power() + .modify(|_, w| unsafe { w.bits(self.lp_sys_sleep.dig_power.0) }); + PMU::regs() + .lp_sleep_lp_ck_power() + .modify(|_, w| unsafe { w.bits(self.lp_sys_sleep.clk_power.0) }); + PMU::regs() + .lp_sleep_xtal() + .modify(|_, w| w.lp_sleep_xpd_xtal().bit(self.lp_sys_sleep.xtal.xpd_xtal())); + } +} + +fn set_memory_power_on_mask(keep_on: bool) { + // pmu_ll_hp_set_memory_power_on_mask: 0 in deep sleep, 0xf in light sleep. + let mask = if keep_on { 0x1f } else { 0 }; + PMU::regs().power_pd_mem_mask().modify(|_, w| unsafe { + w.pd_hp_mem0_mask().bits(mask); + w.pd_hp_mem1_mask().bits(mask); + w.pd_hp_mem2_mask().bits(mask) + }); + PMU::regs().power_pd_mem_cntl().modify(|r, w| unsafe { + let mut pu = r.force_hp_mem_pu().bits(); + if keep_on { + pu |= 1 << 3; + } else { + pu &= !(1 << 3); + } + w.force_hp_mem_pu().bits(pu) + }); +} + +/// High-power system sleep timing parameters. +#[derive(Clone, Copy, Default)] +pub struct HpParam { + analog_wait_target_cycle: u16, + digital_power_supply_wait_cycle: u16, + digital_power_up_wait_cycle: u16, + pll_stable_wait_cycle: u16, + modem_wakeup_wait_cycle: u32, + isolate_wait_cycle: u8, + reset_wait_cycle: u8, + min_slp_slow_clk_cycle: u8, +} + +/// Low-power system sleep timing parameters. +#[derive(Clone, Copy, Default)] +pub struct LpParam { + digital_power_supply_wait_cycle: u16, + min_slp_slow_clk_cycle: u8, + analog_wait_target_cycle: u8, + digital_power_up_wait_cycle: u8, + isolate_wait_cycle: u8, + reset_wait_cycle: u8, +} + +/// Shared HP/LP sleep timing parameters. +#[derive(Clone, Copy, Default)] +pub struct HpLpParam { + xtal_stable_wait_cycle: u16, +} + +/// Sleep timing parameter configuration. +#[derive(Clone, Copy)] +pub struct ParamSleepConfig { + hp_sys: HpParam, + lp_sys: LpParam, + hp_lp: HpLpParam, +} + +impl ParamSleepConfig { + fn apply(&self) { + // pmu_sleep_param_init + PMU::regs().slp_wakeup_cntl3().modify(|_, w| unsafe { + w.hp_min_slp_val().bits(self.hp_sys.min_slp_slow_clk_cycle); + w.lp_min_slp_val().bits(self.lp_sys.min_slp_slow_clk_cycle) + }); + + PMU::regs().slp_wakeup_cntl7().modify(|_, w| unsafe { + w.ana_wait_target() + .bits(self.hp_sys.analog_wait_target_cycle) + }); + + PMU::regs().power_wait_timer0().modify(|_, w| unsafe { + w.dg_hp_pd_wait_timer() + .bits(self.hp_sys.digital_power_supply_wait_cycle); + w.dg_hp_powerup_timer() + .bits(self.hp_sys.digital_power_up_wait_cycle) + }); + + PMU::regs().power_wait_timer1().modify(|_, w| unsafe { + w.dg_lp_pd_wait_timer() + .bits(self.lp_sys.digital_power_supply_wait_cycle); + w.dg_lp_powerup_timer() + .bits(self.lp_sys.digital_power_up_wait_cycle) + }); + + PMU::regs().power_wait_timer2().modify(|_, w| unsafe { + w.dg_hp_iso_wait_timer() + .bits(self.hp_sys.isolate_wait_cycle); + w.dg_hp_rst_wait_timer().bits(self.hp_sys.reset_wait_cycle); + w.dg_lp_iso_wait_timer() + .bits(self.lp_sys.isolate_wait_cycle); + w.dg_lp_rst_wait_timer().bits(self.lp_sys.reset_wait_cycle) + }); + + PMU::regs().slp_wakeup_cntl5().modify(|_, w| unsafe { + w.lp_ana_wait_target() + .bits(self.lp_sys.analog_wait_target_cycle); + w.modem_wait_target() + .bits(self.hp_sys.modem_wakeup_wait_cycle) + }); + + PMU::regs().power_ck_wait_cntl().modify(|_, w| unsafe { + w.pmu_wait_xtl_stable() + .bits(self.hp_lp.xtal_stable_wait_cycle); + w.pmu_wait_pll_stable() + .bits(self.hp_sys.pll_stable_wait_cycle) + }); + } + + fn defaults(config: SleepTimeConfig, pd_flags: PowerDownFlags, xpd_xtal: bool) -> Self { + let hw_wait_time_us = config.pmu_sleep_calculate_hw_wait_time(pd_flags); + let modem_wakeup_wait_time_us = (config.sleep_time_adjustment + + MachineConstants::MODEM_STATE_SKIP_TIME_US + + MachineConstants::HP_REGDMA_RF_ON_WORK_TIME_US) + .saturating_sub(hw_wait_time_us); + + let hp_sys = HpParam { + min_slp_slow_clk_cycle: config.us_to_slowclk(MachineConstants::HP_MIN_SLP_TIME_US) + as u8, + analog_wait_target_cycle: config.us_to_fastclk(MachineConstants::HP_ANALOG_WAIT_TIME_US) + as u16, + digital_power_supply_wait_cycle: config + .us_to_fastclk(MachineConstants::HP_POWER_SUPPLY_WAIT_TIME_US) + as u16, + digital_power_up_wait_cycle: config + .us_to_fastclk(MachineConstants::HP_POWER_UP_WAIT_TIME_US) + as u16, + pll_stable_wait_cycle: config + .us_to_fastclk(MachineConstants::HP_PLL_WAIT_STABLE_TIME_US) + as u16, + modem_wakeup_wait_cycle: config.us_to_fastclk(modem_wakeup_wait_time_us), + isolate_wait_cycle: config.us_to_fastclk(MachineConstants::HP_ISOLATE_WAIT_TIME_US) + as u8, + reset_wait_cycle: config.us_to_fastclk(MachineConstants::HP_RESET_WAIT_TIME_US) as u8, + }; + + let lp_sys = LpParam { + min_slp_slow_clk_cycle: config.us_to_slowclk(MachineConstants::LP_MIN_SLP_TIME_US) + as u8, + analog_wait_target_cycle: config.us_to_slowclk(MachineConstants::LP_ANALOG_WAIT_TIME_US) + as u8, + digital_power_supply_wait_cycle: config + .us_to_fastclk(MachineConstants::LP_POWER_SUPPLY_WAIT_TIME_US) + as u16, + digital_power_up_wait_cycle: config + .us_to_fastclk(MachineConstants::LP_POWER_UP_WAIT_TIME_US) + as u8, + isolate_wait_cycle: config.us_to_fastclk(MachineConstants::LP_ISOLATE_WAIT_TIME_US) + as u8, + reset_wait_cycle: config.us_to_fastclk(MachineConstants::LP_RESET_WAIT_TIME_US) as u8, + }; + + let xtal_stable_wait_cycle = if xpd_xtal { + config.us_to_slowclk(MachineConstants::LP_XTAL_WAIT_STABLE_TIME_US) as u16 + } else { + config.us_to_fastclk(MachineConstants::HP_XTAL_WAIT_STABLE_TIME_US) as u16 + }; + + Self { + hp_sys, + lp_sys, + hp_lp: HpLpParam { + xtal_stable_wait_cycle, + }, + } + } +} + +impl SleepTimeConfig { + pub(crate) const CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ: u32 = 160; + pub(crate) const LIGHT_SLEEP_TIME_OVERHEAD_US: u32 = 780; + + pub(crate) fn pmu_sleep_calculate_hw_wait_time(&self, pd_flags: PowerDownFlags) -> u32 { + let lp_wakeup_wait_time_us = self.slowclk_to_us(MachineConstants::LP_WAKEUP_WAIT_CYCLE); + let lp_clk_switch_time_us = self.slowclk_to_us(MachineConstants::LP_CLK_SWITCH_CYCLE); + let lp_clk_power_on_wait_time_us = + self.slowclk_to_us(MachineConstants::LP_CLK_POWER_ON_WAIT_CYCLE); + let lp_control_wait_time_us = + MachineConstants::LP_ISOLATE_WAIT_TIME_US + MachineConstants::LP_RESET_WAIT_TIME_US; + + let lp_hw_wait_time_us = MachineConstants::LP_MIN_SLP_TIME_US + + MachineConstants::LP_ANALOG_WAIT_TIME_US + + lp_clk_power_on_wait_time_us + + lp_wakeup_wait_time_us + + lp_clk_switch_time_us + + MachineConstants::LP_POWER_SUPPLY_WAIT_TIME_US + + MachineConstants::LP_POWER_UP_WAIT_TIME_US + + lp_control_wait_time_us; + + let hp_digital_power_up_wait_time_us = MachineConstants::HP_POWER_SUPPLY_WAIT_TIME_US + + MachineConstants::HP_POWER_UP_WAIT_TIME_US; + let hp_control_wait_time_us = + MachineConstants::HP_ISOLATE_WAIT_TIME_US + MachineConstants::HP_RESET_WAIT_TIME_US; + // The sleep backs up no register with REGDMA, so the wake needs no restore time. + let hp_regdma_wait_time_us = 0; + let hp_clock_wait_time_us = if pd_flags.pd_xtal() { + MachineConstants::HP_XTAL_WAIT_STABLE_TIME_US + + MachineConstants::HP_PLL_WAIT_STABLE_TIME_US + } else { + MachineConstants::HP_PLL_WAIT_STABLE_TIME_US + }; + + let hp_hw_wait_time_us = MachineConstants::HP_ANALOG_WAIT_TIME_US + + hp_digital_power_up_wait_time_us + + hp_regdma_wait_time_us + + hp_clock_wait_time_us + + hp_control_wait_time_us; + + lp_hw_wait_time_us + hp_hw_wait_time_us + } +} + +/// Configuration for the RTC sleep behavior. +#[derive(Clone, Copy)] +pub struct RtcSleepConfig { + /// Deep sleep flag. + pub deep: bool, + /// Power-down flags. + pub pd_flags: PowerDownFlags, +} + +impl Default for RtcSleepConfig { + fn default() -> Self { + Self { + deep: false, + pd_flags: PowerDownFlags(0), + } + } +} + +bitfield::bitfield! { + #[derive(Clone, Copy)] + /// Power domains to be powered down during sleep. + pub struct PowerDownFlags(u32); + + /// Controls the power-down status of the top power domain. + pub u32, pd_top , set_pd_top : 0; + /// Controls the power-down status of the VDD_SDIO power domain. + pub u32, pd_vddsdio , set_pd_vddsdio : 1; + /// Controls the power-down status of the modem / connectivity power domain. + pub u32, pd_modem , set_pd_modem : 2; + /// Controls the power-down status of the high-performance peripheral power domain. + pub u32, pd_hp_periph, set_pd_hp_periph: 3; + /// Controls the power-down status of the CPU power domain. + /// + /// Crate-private, because a light sleep needs CPU retention to power this domain down. A + /// power-down without retention loses the CPU state. + pub(crate) u32, pd_cpu, set_pd_cpu: 4; + /// Controls the power-down status of the high-performance always-on domain. + pub u32, pd_hp_aon , set_pd_hp_aon : 5; + /// Controls the power-down status of memory group 0. + pub u32, pd_mem_g0 , set_pd_mem_g0 : 6; + /// Controls the power-down status of memory group 1. + pub u32, pd_mem_g1 , set_pd_mem_g1 : 7; + /// Controls the power-down status of memory group 2. + pub u32, pd_mem_g2 , set_pd_mem_g2 : 8; + /// Controls the power-down status of memory group 3. + pub u32, pd_mem_g3 , set_pd_mem_g3 : 9; + /// Controls the power-down status of the crystal oscillator. + pub u32, pd_xtal , set_pd_xtal : 10; + /// Controls the power-down status of the fast RC oscillator. + pub u32, pd_rc_fast , set_pd_rc_fast : 11; + /// Controls the power-down status of the 32 kHz crystal oscillator. + pub u32, pd_xtal32k , set_pd_xtal32k : 12; + /// Controls the power-down status of the 32 kHz RC oscillator. + pub u32, pd_rc32k , set_pd_rc32k : 13; + /// Controls the power-down status of the low-power peripheral domain. + pub u32, pd_lp_periph, set_pd_lp_periph: 14; +} + +impl PowerDownFlags { + /// Returns whether all memory groups are powered down. + pub fn pd_mem(self) -> bool { + self.pd_mem_g0() && self.pd_mem_g1() && self.pd_mem_g2() && self.pd_mem_g3() + } + + /// Sets the power-down status for all memory groups at once. + pub fn set_pd_mem(&mut self, value: bool) { + self.set_pd_mem_g0(value); + self.set_pd_mem_g1(value); + self.set_pd_mem_g2(value); + self.set_pd_mem_g3(value); + } +} + +// Constants from `PMU_SLEEP_MC_DEFAULT()` in esp-idf pmu_param.h. +struct MachineConstants; +impl MachineConstants { + const LP_MIN_SLP_TIME_US: u32 = 450; + const LP_WAKEUP_WAIT_CYCLE: u32 = 4; + const LP_ANALOG_WAIT_TIME_US: u32 = 154; + const LP_XTAL_WAIT_STABLE_TIME_US: u32 = 250; + const LP_CLK_SWITCH_CYCLE: u32 = 1; + const LP_CLK_POWER_ON_WAIT_CYCLE: u32 = 1; + const LP_ISOLATE_WAIT_TIME_US: u32 = 1; + const LP_RESET_WAIT_TIME_US: u32 = 1; + const LP_POWER_SUPPLY_WAIT_TIME_US: u32 = 2; + const LP_POWER_UP_WAIT_TIME_US: u32 = 2; + + const HP_MIN_SLP_TIME_US: u32 = 450; + const HP_ANALOG_WAIT_TIME_US: u32 = 154; + const HP_ISOLATE_WAIT_TIME_US: u32 = 1; + const HP_RESET_WAIT_TIME_US: u32 = 1; + const HP_POWER_SUPPLY_WAIT_TIME_US: u32 = 2; + const HP_POWER_UP_WAIT_TIME_US: u32 = 2; + const HP_REGDMA_M2A_WORK_TIME_US: u32 = 278; + const HP_REGDMA_RF_ON_WORK_TIME_US: u32 = 70; + const HP_SYSTEM_DFS_UP_WORK_TIME_US: u32 = 124; + const HP_XTAL_WAIT_STABLE_TIME_US: u32 = 250; + const HP_PLL_WAIT_STABLE_TIME_US: u32 = 50; + + const MODEM_STATE_SKIP_TIME_US: u32 = Self::HP_REGDMA_M2A_WORK_TIME_US + + Self::HP_SYSTEM_DFS_UP_WORK_TIME_US + + Self::LP_MIN_SLP_TIME_US; +} + +impl RtcSleepConfig { + /// Returns whether the device is in deep sleep mode. + pub fn deep_slp(&self) -> bool { + self.deep + } + + /// Configures the device for deep sleep mode. + pub fn deep() -> Self { + Self { + deep: true, + ..Self::default() + } + } + + pub(crate) fn is_deep_sleep(&self) -> bool { + self.deep + } + + pub(crate) fn base_settings(_rtc: &Rtc<'_>) {} + + /// Selects the kind of the sleep, and what the sleep powers down. + /// + /// Sleep entry calls this before the hooks of the wakeup sources, so that a source can keep + /// powered what it needs. + pub(crate) fn set_sleep_kind(&mut self, kind: SleepKind) { + self.deep = kind == SleepKind::Deep; + + let lp_slow_uses_xtal32k = cfg_select! { + use_xtal32k => ClockTree::with(|clocks| { + matches!( + clocks::lp_slow_clk_config(clocks), + Some(clocks::LpSlowClkConfig::Xtal32k) + ) + }), + _ => false, + }; + + if self.deep { + self.pd_flags.set_pd_top(true); + self.pd_flags.set_pd_vddsdio(true); + self.pd_flags.set_pd_modem(true); + self.pd_flags.set_pd_hp_periph(true); + self.pd_flags.set_pd_cpu(true); + self.pd_flags.set_pd_mem(true); + self.pd_flags.set_pd_xtal(true); + self.pd_flags.set_pd_hp_aon(true); + self.pd_flags.set_pd_lp_periph(true); + self.pd_flags.set_pd_xtal32k(!lp_slow_uses_xtal32k); + self.pd_flags.set_pd_rc32k(true); + self.pd_flags.set_pd_rc_fast(true); + } else { + self.pd_flags.set_pd_xtal(true); + self.pd_flags.set_pd_rc_fast(true); + self.pd_flags + .set_pd_xtal32k(!lp_slow_uses_xtal32k && !xtal32k::use_xtal32k()); + } + } + + /// Configures the wakeup and reject sources of the sleep. + /// + /// [`Self::enter_sleep`] requests the sleep after this call. The return value is a guard that + /// restores what sleep entry changed for the sleep only, so the caller keeps it until the + /// sleep ends. + #[crate::ram] + pub(crate) fn start_sleep(&self, wakeup_mask: u32, reject_mask: u32) -> impl Sized { + let restore_clock_config = ClockTree::with(|clocks| { + let old_cpu_root_clk = clocks.cpu_root_clk(); + + clocks::configure_cpu_root_clk(clocks, CpuRootClkConfig::Xtal); + + DropGuard::new((), move |_| { + ClockTree::with(|clocks| { + if let Some(old) = old_cpu_root_clk { + clocks::configure_cpu_root_clk(clocks, old); + } + }); + }) + }); + + let power = PowerSleepConfig::defaults(self.pd_flags); + power.apply(self.deep); + + let config = if self.deep { + SleepTimeConfig::deep_sleep() + } else { + SleepTimeConfig::light_sleep(self.pd_flags) + }; + + let mut param = + ParamSleepConfig::defaults(config, self.pd_flags, power.hp_sys.xtal.xpd_xtal()); + + if self.deep { + const PMU_LP_ANALOG_WAIT_TARGET_TIME_DSLP_US: u32 = 500; + param.lp_sys.analog_wait_target_cycle = + config.us_to_slowclk(PMU_LP_ANALOG_WAIT_TARGET_TIME_DSLP_US) as u8; + + DigitalSleepConfig::defaults_deep_sleep(self.pd_flags).apply(); + AnalogSleepConfig::defaults_deep_sleep().apply(); + } else { + AnalogSleepConfig::defaults_light_sleep(self.pd_flags).apply(); + DigitalSleepConfig::defaults_light_sleep(self.pd_flags).apply(); + } + + param.apply(); + + // lp_aon_hal_inform_wakeup_type: RTC_SLEEP_MODE_REG is LP_STORE8. + LP_AON::regs() + .lp_store(8) + .modify(|r, w| unsafe { w.bits(r.bits() & !0x01 | self.deep as u32) }); + + PMU::regs() + .slp_wakeup_cntl2() + .write(|w| unsafe { w.bits(wakeup_mask) }); + + PMU::regs() + .slp_wakeup_cntl1() + .write(|w| unsafe { w.sleep_reject_ena().bits(reject_mask) }); + + PMU::regs() + .slp_wakeup_cntl4() + .write(|w| w.slp_reject_cause_clr().bit(true)); + + PMU::regs().int_clr().write(|w| { + w.sw().clear_bit_by_one(); + w.soc_sleep_reject().clear_bit_by_one(); + w.soc_wakeup().clear_bit_by_one() + }); + + PMU::regs() + .slp_wakeup_cntl0() + .write(|w| w.slp_reject_en().bit(reject_mask != 0)); + + restore_clock_config + } + + /// Requests the sleep. + /// + /// The caller waits for the result of the request. + #[inline(always)] + pub(crate) fn enter_sleep(&self) -> bool { + request_sleep() + } + + /// Cleans up after sleep. + #[inline(always)] + pub(crate) fn finish_sleep(&self) {} +} diff --git a/esp-hal/src/rtc_cntl/sleep/mod.rs b/esp-hal/src/rtc_cntl/sleep/mod.rs index 1b39ede2152..1655c5d71df 100644 --- a/esp-hal/src/rtc_cntl/sleep/mod.rs +++ b/esp-hal/src/rtc_cntl/sleep/mod.rs @@ -14,14 +14,14 @@ //! * `ULP (Ultra-Low Power)` wake //! * `BT (Bluetooth) wake` - light sleep only -use crate::{ - gpio, - peripherals::LPWR, - rtc_cntl::{Rtc, WakeupSource}, -}; +use esp_sync::raw::{RawLock, SingleCoreInterruptLock}; + +#[cfg(sleep_deep_sleep)] +use crate::rtc_cntl::WakeupSource; +use crate::{gpio, peripherals::LPWR, rtc_cntl::Rtc}; #[cfg(soc_has_pmu)] -mod pmu_common; +pub(crate) mod pmu_common; #[cfg_attr(esp32, path = "esp32.rs")] #[cfg_attr(esp32s2, path = "esp32s2.rs")] @@ -32,7 +32,9 @@ mod pmu_common; #[cfg_attr(esp32c6, path = "esp32c6.rs")] #[cfg_attr(esp32c2, path = "esp32c2.rs")] #[cfg_attr(esp32h2, path = "esp32h2.rs")] +#[cfg_attr(esp32h4, path = "esp32h4.rs")] #[cfg_attr(esp32p4, path = "esp32p4.rs")] +#[cfg_attr(esp32s31, path = "esp32s31.rs")] mod sleep_impl; pub use sleep_impl::*; @@ -41,6 +43,66 @@ mod timer; mod wakeup; pub(crate) use wakeup::*; +#[instability::unstable] +pub use wakeup::{SleepEntryHook, SleepExitHook, WrappedSleepConfig}; + +/// The result of a light sleep. +#[cfg(sleep_light_sleep)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[instability::unstable] +pub enum LightSleep { + /// The call returned from the sleep. + /// + /// The sleep may also never have started, because no wakeup source was enabled, because the + /// hardware rejected the request, or because a sleep limit was too short for the transition to + /// catch. This result does not tell those apart from a sleep that a wakeup source ended. + Ended, + + /// A wakeup source refused the sleep, so the chip stayed awake. + /// + /// The refusal holds until the state that caused it changes, so a second call refuses too. + /// Wait for an interrupt instead. + Refused, +} + +#[cfg(supports_cpu_power_down)] +use crate::rtc_cntl::cpu_retention; + +/// The handler that answers whether this core still agrees to a light sleep, or null. +/// +/// Only the rendezvous of the software retention path reads this, which is why the read lives +/// there. +#[cfg(all(multi_core, sleep_driver_supported))] +pub(crate) static CAN_SLEEP_HANDLER: portable_atomic::AtomicPtr<()> = + portable_atomic::AtomicPtr::new(core::ptr::null_mut()); + +/// The parts of the sleep path that an RTOS fills in. +#[cfg(all(multi_core, sleep_driver_supported))] +#[doc(hidden)] +#[instability::unstable] +pub mod __rtos_implementation { + use portable_atomic::Ordering; + + /// Registers the function that answers whether the core that runs it agrees to a light sleep. + /// + /// A light sleep that powers the CPU domain down needs every running core to save itself, so + /// the core that calls the sleep function asks the other core to join it. The core that calls + /// decides for itself. The other core answers this function, and a `false` answer stops the + /// sleep. Either core can be the one that answers. + /// + /// The answer holds for the whole sleep. The core that gives it has its interrupts disabled + /// already, so nothing can give that core work while the sleep runs. + /// + /// # Safety + /// + /// The handler runs in an interrupt handler, with interrupts disabled and with the caches of + /// the sleep path. It must return, it must take no lock that a core can hold across a sleep, + /// and it must stay callable for the life of the program. + pub unsafe fn set_can_sleep_handler(handler: fn() -> bool) { + super::CAN_SLEEP_HANDLER.store(handler as *mut (), Ordering::Release); + } +} /// Prepares the sleep hardware, and clears the wakeup sources of the previous run. /// @@ -90,6 +152,9 @@ impl<'d> LowPower<'d> { /// disarm it, a later call replaces it, and [`Self::clear_wakeup_deadline`] removes it. /// /// A deadline in the past ends a light sleep immediately, and makes [`Self::sleep_deep`] panic. + /// + /// A wakeup source can limit one sleep to an earlier wake. The limit does not replace this + /// deadline. The deadline stays armed for the next sleep. #[cfg(sleep_has_wakeup_source_timer)] pub fn set_wakeup_deadline(&mut self, deadline: crate::time::Instant) { timer::set_deadline(deadline); @@ -111,12 +176,17 @@ impl<'d> LowPower<'d> { /// The hardware cannot reject this sleep, because the function cannot return to report the /// rejection. Use [`Self::sleep_deep_with_rejection`] for that. /// + /// A wakeup source cannot refuse this sleep. The wake resets the chip, so the call cannot + /// return a refusal. [`Self::sleep_light`] reports a refusal. + /// /// # Panics /// /// Panics if no wakeup source is enabled, because then nothing can end the sleep. Panics also - /// if the armed wakeup deadline is too near for the sleep transition to catch it. In both - /// cases the chip never wakes again, and it gives no report of the cause. + /// if the armed wakeup deadline is too near for the sleep transition to catch it, or if a + /// wakeup source limits the sleep to less time than the transition can catch. In these cases + /// the chip never wakes again, and it gives no report of the cause. #[cfg(sleep_deep_sleep)] + #[cfg(feature = "rt")] pub fn sleep_deep(&mut self, config: RtcSleepConfig) -> ! { #[cfg(sleep_has_wakeup_source_timer)] if enabled_sources().contains(WakeupSource::Timer) { @@ -137,6 +207,10 @@ impl<'d> LowPower<'d> { /// rejection, the chip sleeps through the event that the caller wants to wake on. The return of /// this function is the complete report, so it gives no other result. /// + /// A wakeup source cannot refuse this sleep. A wakeup source can limit it. The function also + /// returns when that limit is too short for the sleep transition to catch. The chip stays + /// awake. The return does not say which case it was. + /// /// A rejected request returns the wake pads to their drivers, but it cannot return every pad. /// Sleep entry disconnects the pads that no hold keeps, on the chips that need that step to /// reach the deep-sleep current, and it cannot know their earlier configuration. Configure @@ -147,6 +221,7 @@ impl<'d> LowPower<'d> { /// /// Panics if no wakeup source is enabled. #[cfg(sleep_deep_sleep)] + #[cfg(feature = "rt")] pub fn sleep_deep_with_rejection(&mut self, config: RtcSleepConfig) { self.sleep(config, SleepKind::Deep, true); } @@ -156,39 +231,171 @@ impl<'d> LowPower<'d> { /// Light sleep keeps the state of the digital domain, so the program continues at the same /// place. /// - /// The function also returns immediately, without a sleep, if no wakeup source is enabled, or - /// if the hardware rejects the request because a wakeup source is already asserted. It - /// reports neither case. For the caller, a refused sleep, a rejected sleep and a very short - /// sleep have the same result. + /// A wakeup source can refuse the sleep, which keeps the chip awake. A direct call and + /// automatic light sleep both honor a refusal. The return reports it, because the caller then + /// has to wait for the event itself. + /// + /// A wakeup source can also limit the length of the sleep. The chip wakes at the sooner of that + /// limit and the armed wakeup deadline. When the timer source is not enabled, the limit enables + /// it for this sleep and disables it again afterwards. The sleep does not start when that wake + /// is already due, or when the transition cannot catch it. The result is [`LightSleep::Ended`], + /// not [`LightSleep::Refused`]. + /// + /// The function also returns without a sleep if no wakeup source is enabled, or if the + /// hardware rejects the request because a wakeup source is already asserted. It reports + /// neither case. For the caller, a rejected sleep and a very short sleep have the same + /// result. #[cfg(sleep_light_sleep)] - pub fn sleep_light(&mut self, config: RtcSleepConfig) { - self.sleep(config, SleepKind::Light, true); + #[cfg(feature = "rt")] + pub fn sleep_light(&mut self, config: RtcSleepConfig) -> LightSleep { + if self.sleep(config, SleepKind::Light, true) { + LightSleep::Refused + } else { + LightSleep::Ended + } } /// Calculates the sleep configuration from the wakeup-enable mask, and enters the sleep. + /// + /// Returns whether a wakeup source refused a light sleep. A deep sleep ignores a refusal, + /// so this function does not return `true` for a deep sleep. + /// + /// A sleep limit can end the call before the sleep starts. That result is `false`. It is not a + /// refusal. A deep sleep whose limit the transition cannot catch panics when the caller cannot + /// accept a rejection. #[cfg(sleep_driver_supported)] #[crate::ram] - fn sleep(&mut self, config: RtcSleepConfig, kind: SleepKind, allow_reject: bool) { + #[cfg(feature = "rt")] + pub(crate) fn sleep( + &mut self, + config: RtcSleepConfig, + kind: SleepKind, + allow_reject: bool, + ) -> bool { + // ESP-IDF runs `esp_light_sleep_start` inside `portENTER_CRITICAL(&light_sleep_lock)`. + // A sleep ends when `wait_for_sleep_result` sees a wakeup or reject bit, so nothing in + // this path needs interrupts. + let irq_token = unsafe { SingleCoreInterruptLock.enter() }; + let refused = cfg_select! { + all(cpu_retention = "software", multi_core) => { + // The PRO CPU requests every light sleep, because the wake releases the APP CPU + // from the PRO CPU. + match (kind, crate::system::Cpu::current()) { + (SleepKind::Light, crate::system::Cpu::ProCpu) => { + cpu_retention::rendezvous::take_request(); + let refused = + self.sleep_with_interrupts_disabled(config, kind, allow_reject); + cpu_retention::rendezvous::release_app_cpu(); + refused + } + // The APP CPU does not learn whether a wakeup source refused the sleep. + (SleepKind::Light, _) => { + cpu_retention::rendezvous::sleep_from_app_cpu(config); + false + } + _ => self.sleep_with_interrupts_disabled(config, kind, allow_reject), + } + } + _ => self.sleep_with_interrupts_disabled(config, kind, allow_reject), + }; + unsafe { SingleCoreInterruptLock.exit(irq_token) }; + refused + } + + #[cfg(sleep_driver_supported)] + #[crate::ram] + #[cfg(feature = "rt")] + fn sleep_with_interrupts_disabled( + &mut self, + config: RtcSleepConfig, + kind: SleepKind, + allow_reject: bool, + ) -> bool { let rtc = Rtc::new(unsafe { crate::peripherals::RTC_TIMER::steal() }); let mut config = config; config.set_sleep_kind(kind); + // Retention serves light sleep only. Deep sleep resets the chip, so it has no CPU state to + // bring back, and an armed descriptor would outlive the sleep in the RTC domain. esp-idf + // arms retention from its light sleep path alone. + // + // The buffer is read once, because the rendezvous and the power-down must agree on it. A + // buffer that another core installs during this sleep serves the next one. + #[cfg(supports_cpu_power_down)] + let retention_buffer = match kind { + SleepKind::Light => crate::rtc_cntl::installed_buffer_ptr(), + SleepKind::Deep => None, + }; + + // A chip that retains the CPU in software needs every running core to save itself, so the + // rendezvous comes first, before any step that a refusal would have to undo. A return + // after it must call `rendezvous::finish`. + #[cfg(all(cpu_retention = "software", multi_core))] + if retention_buffer.is_some() && !cpu_retention::rendezvous::engage() { + return false; + } + // The hooks run before `apply`, so that a request to keep a power domain powered reaches // the hardware. They also run before the last read of the mask, because a hook can // enable another source. The GPIO hook does this while it allocates its pins to the // paths. - run_entry_hooks(&mut config); + let entry = run_entry_hooks(&mut config); + + // Stop before `apply` when a hook refused a light sleep. `apply` writes the sleep + // configuration, and the chip must stay awake with that configuration unchanged. + // Entry hooks can already have moved a pad. The exit hooks put the pad back. + // A deep sleep ignores the refusal. The wake resets the chip, so there is no caller. + if kind == SleepKind::Light && entry.refused { + #[cfg(sleep_has_wakeup_source_timer)] + if let Some(clamp) = entry.clamp { + timer::restore_after_limit(clamp); + } + run_exit_hooks(); + #[cfg(all(cpu_retention = "software", multi_core))] + cpu_retention::rendezvous::finish(); + return true; + } + // A limit inside the transition window cannot wake the chip. esp32 cannot reject on the + // timer, so the hardware does not report the miss. Stay awake. The exit hooks undo pad + // changes from the entry hooks. The comparator was not written. + #[cfg(sleep_has_wakeup_source_timer)] + if matches!(&entry.clamp, Some(timer::LimitClamp::TooShort)) { + run_exit_hooks(); + #[cfg(all(cpu_retention = "software", multi_core))] + cpu_retention::rendezvous::finish(); + if kind == SleepKind::Deep && !allow_reject { + panic!("the wakeup deadline is too near to be caught by the sleep transition"); + } + return false; + } + + // A deep sleep keeps what `RtcSleepConfig::deep` asked for, because the wake resets the + // chip and keeps no CPU state to lose. + #[cfg(supports_cpu_power_down)] + if kind == SleepKind::Light { + cpu_retention::configure_cpu_retention(&mut config, retention_buffer); + } + + // The PMU chips write the configuration when the sleep starts. + #[cfg(not(soc_has_pmu))] config.apply(); // A sleep with no wakeup source never ends. No counter overflow ends it either. let wakeup_mask = mask(); if wakeup_mask == 0 { + // No sleep starts, so a clamp must not keep the comparator. + #[cfg(sleep_has_wakeup_source_timer)] + if let Some(clamp) = entry.clamp { + timer::restore_after_limit(clamp); + } + #[cfg(all(cpu_retention = "software", multi_core))] + cpu_retention::rendezvous::finish(); + match kind { - // A refused sleep gives the same result as a rejected sleep, and light sleep does - // not report that case either. - SleepKind::Light => return, + // Not a software refusal. Light sleep does not report a missing wakeup source. + SleepKind::Light => return false, SleepKind::Deep => { panic!("no wakeup source is enabled, so nothing could end the sleep") } @@ -199,13 +406,6 @@ impl<'d> LowPower<'d> { sleep_uart_prepare(); - // Last, because this step takes the pads away from the peripherals that drove them. The - // wakeup sources have their holds now, and no later step needs a pad. - #[cfg(sleep_deep_sleep_needs_gpio_isolation)] - if kind == SleepKind::Deep { - gpio::wakeup::isolate_pads_for_deep_sleep(); - } - // Latch the systimer value *before* sleeping. The systimer keeps running during // the sleep enter/exit sequences, so we must not advance from the post-wake // value (that would count the enter/exit time twice). Instead we set an absolute @@ -214,12 +414,45 @@ impl<'d> LowPower<'d> { let before = rtc.time_since_boot_raw(); let _uart0_sclk_guard = crate::system::ensure_uart0_sclk_enabled(); + + #[cfg(multi_core)] + let parked = match kind { + SleepKind::Light => park_other_cores(), + // A deep sleep resets the chip, so the other core needs no stall, and nothing thaws + // it afterwards. + SleepKind::Deep => 0, + }; + let rejected = { // A chip can keep a guard for the length of the sleep, to restore what sleep entry // changed for the sleep only. The guard must therefore outlive the wait below. + // ESP-IDF arms RTC_CNTL retention in `misc_modules_sleep_prepare`, before it arms the + // wakeup sources. + + #[cfg(cpu_retention = "rtc_cntl")] + cpu_retention::prepare_cpu_retention(retention_buffer); + #[allow(clippy::let_unit_value)] let _sleep_guard = config.start_sleep(wakeup_mask, reject_mask); - let rejected = wait_for_sleep_result(); + + // Last, because this step takes the pads away from the peripherals that drove them. The + // wakeup sources have their holds now, and no later step needs a pad. + #[cfg(any( + sleep_deep_sleep_needs_gpio_isolation, + gpio_need_soft_isolate_during_pd + ))] + if kind == SleepKind::Deep { + gpio::wakeup::isolate_pads_for_deep_sleep(); + } + + let rejected = cfg_select! { + cpu_retention = "software" => { + // The software chips save the CPU inside the request, so the request belongs to + // them. ESP-IDF wraps `pmu_sleep_start` the same way (`sleep_modes.c:963-964`). + cpu_retention::enter_sleep_with_retention(&config, retention_buffer) + } + _ => config.enter_sleep(), + }; if config.is_deep_sleep() && !rejected { // The chip is entering deep sleep, and the wake resets it. Because RTC is in a @@ -232,8 +465,21 @@ impl<'d> LowPower<'d> { rejected }; + #[cfg(supports_cpu_power_down)] + if kind == SleepKind::Light && retention_buffer.is_some() { + // First, because the other core comes back through the wake stub that the next call + // disarms. + #[cfg(all(cpu_retention = "software", multi_core))] + cpu_retention::rendezvous::finish(); + + cpu_retention::finish_cpu_retention(rejected); + } + config.finish_sleep(); + #[cfg(multi_core)] + unpark_cores(parked); + let after = rtc.time_since_boot_raw(); let slept_us = crate::clock::rtc_ticks_to_us(after.wrapping_sub(before)); @@ -255,6 +501,66 @@ impl<'d> LowPower<'d> { // Last, because this call reads the wakeup cause, and after a light sleep the cause is // available only after the line above. gpio::wakeup::record_wakeup(); + + // After the cause is recorded. A limit must not keep the comparator, or the next sleep + // inherits a deadline that no hook requested. + #[cfg(sleep_has_wakeup_source_timer)] + if let Some(clamp) = entry.clamp { + timer::restore_after_limit(clamp); + } + + false + } +} + +/// Hardware-stalls the other running cores for the length of a light sleep, or thaws them. +/// +/// A stall is enough where the retention DMA saves the CPU domain, because the domain holds every +/// core and the hardware brings the stalled core back with this one. esp-idf stalls the other core +/// the same way and adds nothing more (`sleep_modes.c`, where the SMP retention work is gated on +/// `SOC_PM_CPU_RETENTION_BY_SW`). +/// +/// FIXME: a stall freezes the other core wherever it stands, which can be inside an interrupt +/// handler that holds a cross-core lock, such as the clock tree, the peripheral reference counts, +/// or the UART locks that this path takes. This core then spins for that lock for ever, because the +/// frozen core cannot release it. +/// +/// A chip that retains the CPU in software needs more than a stall, because each core saves +/// itself, and a frozen core saves nothing. The rendezvous of that path keeps the other core +/// running, so this function stalls nothing while that core waits in the rendezvous. +/// +/// Returns the cores that it stalled, as a bit for each [`Cpu`], for [`unpark_cores`]. A core that +/// the program stalled before the sleep stays stalled after it. +#[cfg(all(multi_core, sleep_driver_supported))] +#[crate::ram] +fn park_other_cores() -> u8 { + // A core that saves itself in the rendezvous must keep running, because a stalled core saves + // nothing. + #[cfg(all(cpu_retention = "software", multi_core, feature = "rt"))] + if cpu_retention::rendezvous::helper_saved() { + return 0; + } + + let mut parked = 0; + for cpu in crate::system::Cpu::other() { + if crate::soc::cpu_control::is_running(cpu) { + // SAFETY: [`unpark_cores`] runs before this function returns to its caller. + unsafe { crate::soc::cpu_control::internal_park_core(cpu, true) }; + parked |= 1 << cpu as u8; + } + } + parked +} + +/// Thaws the cores that [`park_other_cores`] stalled. +#[cfg(all(multi_core, sleep_driver_supported))] +#[crate::ram] +fn unpark_cores(parked: u8) { + for cpu in crate::system::Cpu::other() { + if parked & (1 << cpu as u8) != 0 { + // SAFETY: this core stalled that core for the sleep, and the sleep is over. + unsafe { crate::soc::cpu_control::internal_park_core(cpu, false) }; + } } } @@ -266,22 +572,25 @@ impl<'d> LowPower<'d> { /// only report of that case. ESP-IDF waits in the same place, in `rtc_sleep_start` and in /// `pmu_sleep_start`. #[cfg(sleep_driver_supported)] -fn wait_for_sleep_result() -> bool { +#[inline(always)] +pub(crate) fn wait_for_sleep_result() -> bool { loop { cfg_select! { soc_has_pmu => { let int_raw = crate::peripherals::PMU::regs().int_raw().read(); - if int_raw.soc_wakeup().bit_is_set() || int_raw.soc_sleep_reject().bit_is_set() { - return int_raw.soc_sleep_reject().bit_is_set(); - } + let rejected = int_raw.soc_sleep_reject().bit_is_set(); + let wakeup = int_raw.soc_wakeup().bit_is_set(); } _ => { let int_raw = LPWR::regs().int_raw().read(); - if int_raw.slp_wakeup().bit_is_set() || int_raw.slp_reject().bit_is_set() { - return int_raw.slp_reject().bit_is_set(); - } + let rejected = int_raw.slp_reject().bit_is_set(); + let wakeup = int_raw.slp_wakeup().bit_is_set(); } } + + if wakeup || rejected { + return rejected; + } } } diff --git a/esp-hal/src/rtc_cntl/sleep/pmu_common.rs b/esp-hal/src/rtc_cntl/sleep/pmu_common.rs index 7fe0ccab2e9..d49ce8596f6 100644 --- a/esp-hal/src/rtc_cntl/sleep/pmu_common.rs +++ b/esp-hal/src/rtc_cntl/sleep/pmu_common.rs @@ -1,19 +1,15 @@ use crate::{ - clock::{ - RtcClock, - calibrate_rtc_fast_clock, - calibrate_rtc_slow_clock, - rtc_fast_cal_period, - rtc_slow_cal_period, - }, + clock::{RtcClock, calibrate_rtc_fast_clock, calibrate_rtc_slow_clock, rtc_slow_cal_period}, + peripherals::PMU, rtc_cntl::sleep::PowerDownFlags, + soc::clocks, }; #[derive(Clone, Copy)] pub(super) struct SleepTimeConfig { pub sleep_time_adjustment: u32, pub slowclk_period: u32, - pub fastclk_period: u32, + pub fastclk_frequency: u32, } impl SleepTimeConfig { @@ -22,7 +18,7 @@ impl SleepTimeConfig { calibrate_rtc_fast_clock(); } - rtc_fast_cal_period() + clocks::rc_fast_clk_frequency() } fn rtc_clk_cal_slow(deep: bool) -> u32 { @@ -37,7 +33,7 @@ impl SleepTimeConfig { Self { sleep_time_adjustment: 0, slowclk_period: Self::rtc_clk_cal_slow(deep), - fastclk_period: Self::rtc_clk_cal_fast(deep), + fastclk_frequency: Self::rtc_clk_cal_fast(deep), } } @@ -52,6 +48,7 @@ impl SleepTimeConfig { this } + #[cfg(sleep_deep_sleep)] pub fn deep_sleep() -> Self { let mut this = Self::new(true); @@ -69,6 +66,44 @@ impl SleepTimeConfig { } pub fn us_to_fastclk(&self, us: u32) -> u32 { - (us << RtcClock::CAL_FRACT) / self.fastclk_period + (us as u64 * self.fastclk_frequency as u64 / 1_000_000) as u32 } } + +/// Writes the dirty lines of the level-one data cache back to memory. +/// +/// The cache belongs to the CPU power domain, so a sleep that powers the domain down loses every +/// dirty line. The retention frames are among them, because the save writes them through the cache. +/// esp-idf writes the cache back in `pmu_sleep_start` (`esp32p4/pmu_sleep.c:410`), and it uses the +/// registers and not the ROM helper, because the return of a call dirties the cache again. +#[crate::ram] +#[cfg(soc_internal_memory_cached)] +fn writeback_data_cache() { + // `CACHE_MAP_L1_DCACHE` of `esp32p4/rom/cache.h`. + const L1_DATA_CACHE: u8 = 1 << 4; + + let cache = crate::peripherals::CACHE::regs(); + cache.sync_addr().write(|w| unsafe { w.bits(0) }); + cache.sync_size().write(|w| unsafe { w.bits(0) }); + cache + .sync_map() + .write(|w| unsafe { w.sync_map().bits(L1_DATA_CACHE) }); + cache.sync_ctrl().modify(|_, w| w.writeback_ena().set_bit()); + while !cache.sync_ctrl().read().sync_done().bit_is_set() {} +} + +/// Requests the sleep and returns whether the hardware rejected the request. +/// +/// The software retention path calls this through a function pointer after the critical frame is +/// saved. +#[inline(always)] +pub(crate) fn request_sleep() -> bool { + #[cfg(soc_internal_memory_cached)] + writeback_data_cache(); + + PMU::regs() + .slp_wakeup_cntl0() + .write(|w| w.sleep_req().bit(true)); + + super::wait_for_sleep_result() +} diff --git a/esp-hal/src/rtc_cntl/sleep/timer.rs b/esp-hal/src/rtc_cntl/sleep/timer.rs index d7cb0e1b3a4..8f908ceb7e5 100644 --- a/esp-hal/src/rtc_cntl/sleep/timer.rs +++ b/esp-hal/src/rtc_cntl/sleep/timer.rs @@ -7,7 +7,7 @@ use crate::{ peripherals::RTC_TIMER, rtc_cntl::{WakeupSource, sleep::WrappedSleepConfig}, - time::Instant, + time::{Duration, Instant}, }; /// The time that ESP-IDF reserves between the arming of the alarm and the start of the sleep, in @@ -45,18 +45,114 @@ pub(crate) fn clear_deadline() { /// Returns whether the armed deadline is too near for the sleep transition to catch it. /// -/// Only a deep sleep needs this result. The hardware rejects a light sleep that misses the alarm, -/// because the enabled sources are also the reject sources, and the alarm keeps its status. +/// A deep sleep that misses the alarm does not wake. The transition is not rejected, and the +/// counter needs decades to reach the deadline again. A light sleep on most chips rejects, because +/// the timer is a reject source. esp32 cannot reject on the timer, so a missed alarm is not safe +/// there either. /// /// The comparator holds the deadline, so esp-hal keeps no copy of it. The target of the comparator /// is readable on every chip, also where the alarm enable beside it is not readable. Only a caller /// that finds the timer source enabled calls this function, so the target always comes from this /// run. +#[cfg(sleep_deep_sleep)] pub(crate) fn deadline_missed() -> bool { + target_ticks() < crate::rtc_cntl::time_since_boot_raw() + ALARM_TO_SLEEP_TICKS +} + +/// How [`clamp_to_limit`] changed the wake timer. +/// +/// A limit applies to one sleep. It must not replace a deadline the caller armed. Restore it with +/// [`restore_after_limit`] on every path that returns to the caller. +#[must_use = "restore the wake timer after the sleep"] +pub(crate) enum LimitClamp { + /// The armed deadline is at or before the limit, and the transition can catch it. + Unchanged, + /// The limit replaced the armed deadline. `previous` is that deadline, in RTC ticks. + Shortened { + /// The comparator value from before the clamp. + previous: u64, + }, + /// The timer source was off, so the limit enabled it. + Enabled, + /// The sleep does not wake at or before the limit. + /// + /// The limit is already due, the transition cannot catch the limit, or the armed deadline is + /// sooner and the transition cannot catch that deadline. The comparator is unchanged. The + /// sleep must not start. + TooShort, +} + +impl LimitClamp { + /// Runs the timer entry hook when this limit enabled the source. + /// + /// The hook keeps the low-power peripherals powered on chips whose comparator is not in the + /// always-on domain. The hook of a source that was already enabled has run. Hooks do not run + /// again, so a source that this limit enabled would otherwise sleep without that request. + pub(crate) fn apply_entry_hook(&self, config: &mut WrappedSleepConfig<'_>) { + if matches!(self, Self::Enabled) { + entry_hook(config); + } + } +} + +/// Shortens the wake timer so the sleep lasts at most `limit`. +/// +/// The duration is measured from this call, on the RTC counter the comparator uses. An armed +/// deadline that is sooner than the limit stays, when the transition can catch that deadline. +/// +/// When the timer wakeup source is off, the limit enables it. Nothing else wakes the chip at the +/// limit. +/// +/// Returns [`LimitClamp::TooShort`] when the sleep does not wake at or before the limit. The +/// timer is unchanged. The caller must not start the sleep. esp32 cannot reject on the timer, so a +/// missed alarm does not wake the chip. +pub(crate) fn clamp_to_limit(limit: Duration) -> LimitClamp { + let now = crate::rtc_cntl::time_since_boot_raw(); + let ahead = crate::clock::us_to_rtc_ticks(limit.as_micros()); + let limit_ticks = now.saturating_add(ahead); + + // Same window as `deadline_missed`. Check it before any write. A later armed deadline must + // not hide a limit the transition cannot catch, and arming that limit clears the status + // of the caller's deadline. + if limit_ticks < now + ALARM_TO_SLEEP_TICKS { + return LimitClamp::TooShort; + } + + if super::enabled_sources().contains(WakeupSource::Timer) { + let current = target_ticks(); + if current <= limit_ticks { + // The armed deadline is sooner. When the transition cannot catch it, the chip does + // not wake at the limit either. esp32 cannot reject on the timer. + if current < now + ALARM_TO_SLEEP_TICKS { + return LimitClamp::TooShort; + } + LimitClamp::Unchanged + } else { + arm(limit_ticks); + LimitClamp::Shortened { previous: current } + } + } else { + arm(limit_ticks); + WakeupSource::Timer.enable_with_hooks(Some(entry_hook), None); + LimitClamp::Enabled + } +} + +/// Puts the wake timer back to the state from before [`clamp_to_limit`]. +pub(crate) fn restore_after_limit(clamp: LimitClamp) { + match clamp { + LimitClamp::Unchanged | LimitClamp::TooShort => {} + LimitClamp::Shortened { previous } => arm(previous), + LimitClamp::Enabled => clear_deadline(), + } +} + +/// Reads the comparator target, in RTC counter ticks. +fn target_ticks() -> u64 { let regs = RTC_TIMER::regs(); let (low, high) = cfg_select! { - any(esp32c5, esp32c6, esp32c61, esp32h2, esp32p4) => ( + any(esp32c5, esp32c6, esp32c61, esp32h2, esp32h4, esp32p4, esp32s31) => ( regs.tar0_low().read().main_timer_tar_low0().bits(), regs.tar0_high().read().main_timer_tar_high0().bits(), ), @@ -65,9 +161,8 @@ pub(crate) fn deadline_missed() -> bool { regs.slp_timer1().read().slp_val_hi().bits(), ), }; - let deadline = (u64::from(high) << 32) | u64::from(low); - deadline < crate::rtc_cntl::time_since_boot_raw() + ALARM_TO_SLEEP_TICKS + (u64::from(high) << 32) | u64::from(low) } #[crate::ram] @@ -81,15 +176,15 @@ fn entry_hook(config: &mut WrappedSleepConfig<'_>) { /// Writes the comparator, and clears the status that the previous deadline can leave set. /// -/// Only this function clears the status. Sleep entry must not clear it, because the status is the -/// only report of an expired deadline. +/// Only this function clears the status. Sleep entry must not clear it on its own, because the +/// status is the only report of an expired deadline. Arming a new deadline clears it here. fn arm(ticks: u64) { let low = (ticks & 0xffff_ffff) as u32; let high = ((ticks >> 32) & 0xffff) as u16; let regs = RTC_TIMER::regs(); cfg_select! { - any(esp32c5, esp32c6, esp32c61, esp32h2, esp32p4) => { + any(esp32c5, esp32c6, esp32c61, esp32h2, esp32h4, esp32p4, esp32s31) => { regs.int_clr().write(|w| w.soc_wakeup().clear_bit_by_one()); regs.tar0_low() .write(|w| unsafe { w.main_timer_tar_low0().bits(low) }); @@ -114,7 +209,7 @@ fn disarm() { let regs = RTC_TIMER::regs(); cfg_select! { - any(esp32c5, esp32c6, esp32c61, esp32h2, esp32p4) => { + any(esp32c5, esp32c6, esp32c61, esp32h2, esp32h4, esp32p4, esp32s31) => { regs.tar0_high() .modify(|_, w| w.main_timer_tar_en0().clear_bit()); regs.int_clr().write(|w| w.soc_wakeup().clear_bit_by_one()); diff --git a/esp-hal/src/rtc_cntl/sleep/wakeup.rs b/esp-hal/src/rtc_cntl/sleep/wakeup.rs index cc06e165375..e0a93070fd8 100644 --- a/esp-hal/src/rtc_cntl/sleep/wakeup.rs +++ b/esp-hal/src/rtc_cntl/sleep/wakeup.rs @@ -9,9 +9,14 @@ //! A driver can also register hooks in the call that sets its mask bit. Use them to do work at //! sleep entry, or to restore state after a light sleep. +use enumset::EnumSet; use esp_sync::NonReentrantMutex; -use crate::rtc_cntl::{WakeupSource, sleep::RtcSleepConfig}; +use crate::{ + rtc_cntl::{WakeupSource, sleep::RtcSleepConfig}, + soc::clocks::ClockSource, + time::Duration, +}; /// Which sleep the chip is entering. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -22,13 +27,14 @@ pub(crate) enum SleepKind { Deep, } -/// A resource that a wakeup source needs powered while the chip sleeps. +/// A power domain that a wakeup source needs powered while the chip sleeps. /// -/// The names are the same for all chips. A request for a resource that the target chip does not +/// The names are the same for all chips. A request for a domain that the target chip does not /// have, or that it cannot power down, does nothing. +/// +/// A clock is not a domain. Ask for one with [`WrappedSleepConfig::keep_clock_running`]. #[derive(Debug, Clone, Copy, PartialEq, Eq)] -// The requested resources are different on each chip, and no wakeup source requests an oscillator -// yet. +// The names are the same for all chips, and each chip uses a different subset. #[allow(dead_code, reason = "the names are the same for all chips")] pub(crate) enum SleepResource { /// The low-power peripherals, including the RTC IO pads. @@ -37,35 +43,42 @@ pub(crate) enum SleepResource { LpMemory, /// The high-performance peripherals, including the digital GPIO pads. HpPeripherals, - /// The main crystal oscillator. - Xtal, - /// The fast RC oscillator. - RcFast, - /// The 32kHz crystal oscillator. - Xtal32k, - /// The 32kHz RC oscillator. - Rc32k, } /// The sleep configuration, as the entry hook of a wakeup source can see it. /// -/// A hook can only prevent a power-down. It cannot request one, because the caller of the sleep -/// function selects how much of the chip to power down, and a wakeup source only adds the resources -/// that it needs. A hook thus clears bits, which is idempotent and commutative. The order of the -/// hooks cannot change the result, and the source with the highest demand wins. +/// A hook can only relax the sleep. It can keep a power domain powered, keep a clock running, +/// refuse a light sleep, or shorten the sleep. The caller of the sleep function selects how much +/// of the chip to power down, and it arms the wake timer. A wakeup source only adds the resources +/// that it needs, refuses the sleep, or sets a shorter limit. It cannot request a power-down, stop +/// a clock, cancel a refusal, or lengthen a limit. +/// +/// Each request is idempotent. The order of the hooks cannot change the result. The source with +/// the strongest request wins. One refusal is enough. The shortest limit wins. /// -/// Keep this property. A method that sets a power-down bit removes it. -pub(crate) struct WrappedSleepConfig<'a> { +/// Keep this property. A method that requests a power-down, stops a clock, cancels a refusal, or +/// lengthens a limit removes it. +#[instability::unstable] +pub struct WrappedSleepConfig<'a> { config: &'a mut RtcSleepConfig, + clocks: EnumSet, + refused: bool, + limit: Option, } impl<'a> WrappedSleepConfig<'a> { pub(crate) fn new(config: &'a mut RtcSleepConfig) -> Self { - Self { config } + Self { + config, + clocks: EnumSet::empty(), + refused: false, + limit: None, + } } /// Returns whether the chip is entering deep sleep, which resets it when it wakes. - pub(crate) fn is_deep_sleep(&self) -> bool { + #[instability::unstable] + pub fn is_deep_sleep(&self) -> bool { self.config.is_deep_sleep() } @@ -101,31 +114,103 @@ impl<'a> WrappedSleepConfig<'a> { _ => _config.set_dig_peri_pd_en(false), } } - SleepResource::Xtal => { - cfg_select! { - soc_has_pmu => _config.pd_flags.set_pd_xtal(false), - // This flag has the opposite sense. It forces the crystal on. - _ => _config.set_xtal_fpu(true), + } + } + + /// Keeps `source` running during the sleep. + /// + /// Ask a clock tree node which source it runs on, and name the answer. A source that the chip + /// keeps running anyway, or that it cannot power down, needs nothing. + #[instability::unstable] + pub fn keep_clock_running(&mut self, source: ClockSource) { + self.clocks.insert(source); + } + + /// Refuses a light sleep. + /// + /// Call this when software state makes the sleep unsafe and the hardware cannot see that + /// state. One call is enough. A later hook cannot cancel it. + /// + /// A deep sleep ignores the call. The wake resets the chip, so there is no caller to report + /// the refusal to. Read [`Self::is_deep_sleep`] when other work in the hook depends on the + /// kind of sleep. + /// + /// The hardware also rejects a sleep when an enabled source is already asserted at sleep + /// entry. This call is the software refusal. + #[instability::unstable] + pub fn reject_sleep(&mut self) { + self.refused = true; + } + + /// Limits this sleep to `duration`. + /// + /// The duration starts when the driver programs the wake timer, after every hook has run. The + /// shortest request wins. A later hook cannot make it longer. + /// + /// The driver clamps the wake timer to the limit. When the timer wakeup source is not enabled, + /// the limit enables it for this sleep. Nothing else wakes the chip at the limit. After a + /// light sleep the driver restores the timer. A deadline the caller armed stays armed. A timer + /// that only the limit enabled is disabled again. + /// + /// The limit applies to deep sleep as well. The wake resets the chip. Read + /// [`Self::is_deep_sleep`] when the hook should bound only one kind of sleep. + /// + /// A duration that the sleep transition cannot catch does not start the sleep. A light sleep + /// then returns as if it had ended. A deep sleep without rejection panics, because it cannot + /// return and the chip does not wake. This is not a refusal. Use [`Self::reject_sleep`] to + /// refuse a light sleep. A duration of zero is too short to sleep. + #[instability::unstable] + pub fn limit_sleep(&mut self, duration: Duration) { + let already_shorter = match self.limit { + Some(current) => current.as_micros() <= duration.as_micros(), + None => false, + }; + if !already_shorter { + self.limit = Some(duration); + } + } + + /// Prevents the power-down of every clock source a hook asked for. + /// + /// The set is what makes the requests of the hooks independent of their order. + fn apply_clock_requests(&mut self) { + // One function for all chips, like `keep_alive`. + let _config = &mut self.config; + for source in self.clocks { + match source { + ClockSource::XtalClk => { + cfg_select! { + soc_has_pmu => _config.pd_flags.set_pd_xtal(false), + // This flag has the opposite sense. It forces the crystal on. + _ => _config.set_xtal_fpu(true), + } } - } - SleepResource::RcFast => { - cfg_select! { - soc_has_pmu => _config.pd_flags.set_pd_rc_fast(false), - _ => _config.set_int_8m_pd_en(false), + ClockSource::RcFastClk => { + cfg_select! { + soc_has_pmu => _config.pd_flags.set_pd_rc_fast(false), + _ => _config.set_int_8m_pd_en(false), + } } - } - SleepResource::Xtal32k => { - cfg_select! { - soc_has_pmu => _config.pd_flags.set_pd_xtal32k(false), - _ => {} + #[cfg(use_xtal32k)] + ClockSource::Xtal32kClk => { + cfg_select! { + soc_has_pmu => _config.pd_flags.set_pd_xtal32k(false), + _ => {} + } } - } - SleepResource::Rc32k => { - cfg_select! { - esp32h2 => {} - soc_has_pmu => _config.pd_flags.set_pd_rc32k(false), - _ => {} + #[cfg(soc_has_clock_node_rc32k_clk)] + ClockSource::Rc32kClk => { + cfg_select! { + // esp32h2 has no separate flag for the 32 kHz RC oscillator. + esp32h2 => {} + _ => _config.pd_flags.set_pd_rc32k(false), + } } + // The slow RC oscillator runs in the always-on domain, and the external 32 kHz + // oscillator arrives on a pad, so neither has a power-down to prevent. + #[cfg(soc_has_clock_node_osc_slow_clk)] + ClockSource::OscSlowClk => {} + ClockSource::RcSlowClk => {} } } } @@ -134,11 +219,22 @@ impl<'a> WrappedSleepConfig<'a> { /// Runs at sleep entry, before the sleep configuration reaches hardware. /// /// The configuration already holds the kind of the sleep, so a hook that needs it asks -/// [`WrappedSleepConfig::is_deep_sleep`]. -pub(crate) type SleepEntryHook = fn(&mut WrappedSleepConfig<'_>); +/// [`WrappedSleepConfig::is_deep_sleep`]. A hook keeps a clock running with +/// [`WrappedSleepConfig::keep_clock_running`]. A hook refuses a light sleep with +/// [`WrappedSleepConfig::reject_sleep`]. +/// +/// The hook can run with interrupts disabled, for example from automatic light sleep. Do not +/// allocate, take a blocking lock, or log in it. +#[instability::unstable] +pub type SleepEntryHook = fn(&mut WrappedSleepConfig<'_>); -/// Runs after a light sleep. A deep sleep resets the chip, which runs the initialization again. -pub(crate) type SleepExitHook = fn(); +/// Runs after a light sleep. +/// +/// It also runs when a hook refuses a light sleep. An entry hook may already have changed a pad, +/// and the exit hook puts that pad back. A deep sleep resets the chip, which runs the +/// initialization again. +#[instability::unstable] +pub type SleepExitHook = fn(); for_each_wakeup_source! { (all $( ($variant:ident, $bit:literal) ),*) => { @@ -169,7 +265,7 @@ static HOOKS: NonReentrantMutex = NonReentrantMutex::new(Hooks { impl WakeupSource { /// Enables this source, so that it can end a sleep. /// - /// The source stays enabled until you call [`Self::disable`]. It also stays enabled through a + /// The source stays enabled until [`Self::disable`] is called. It also stays enabled through a /// sleep and through a deep-sleep wake. While the chip is awake, an enabled source does /// nothing. // On a chip where all the implemented sources need hooks, nothing calls this function. @@ -184,15 +280,16 @@ impl WakeupSource { /// first call. One driver owns each source, so only that driver can replace its own hooks. /// A call for a source that is already enabled does this. /// - /// Both hooks run with the flash accessible. The entry hook runs before esp-hal writes the - /// sleep configuration to hardware, and the exit hook runs after the wake sequence restores - /// it. Both hooks are part of sleep entry, so keep them short. Give them the - /// [`ram`][crate::ram] attribute, to keep the flash out of the sleep path. - pub(crate) fn enable_with_hooks( - self, - entry: Option, - exit: Option, - ) { + /// Both hooks run with the flash accessible, so they need no [`ram`][crate::ram] attribute. The + /// entry hook runs before esp-hal writes the sleep configuration to hardware, and the exit hook + /// runs after the wake sequence restores it. Both hooks are part of sleep entry, so keep them + /// short. + /// + /// Only the driver that owns the source calls this. esp-hal owns the sources of its own + /// drivers, for example the timer source. A call for such a source replaces the hooks of that + /// driver, and the driver then does not work through a sleep. + #[instability::unstable] + pub fn enable_with_hooks(self, entry: Option, exit: Option) { HOOKS.with(|hooks| { hooks.entry[self as usize] = entry; hooks.exit[self as usize] = exit; @@ -202,7 +299,10 @@ impl WakeupSource { } /// Disables this source, and removes its hooks. - pub(crate) fn disable(self) { + /// + /// Only the driver that owns the source calls this, as for [`Self::enable_with_hooks`]. + #[instability::unstable] + pub fn disable(self) { HOOKS.with(|hooks| { hooks.entry[self as usize] = None; hooks.exit[self as usize] = None; @@ -228,8 +328,28 @@ pub(crate) fn reject_mask() -> u32 { mask() & property!("sleep.rejectable_mask") } +/// What the entry hooks asked for, other than power domains and clocks. +/// +/// The clock requests reach the configuration before this value is returned, and so does the +/// wake timer. The refusal does not, because only the caller knows what to do with it. +pub(crate) struct SleepEntry { + /// A hook called [`WrappedSleepConfig::reject_sleep`]. + pub(crate) refused: bool, + + /// How [`WrappedSleepConfig::limit_sleep`] changed the wake timer. + /// + /// `None` when no hook set a limit. The caller restores the timer on every path that does not + /// sleep, and after a light sleep. + #[cfg(sleep_has_wakeup_source_timer)] + pub(crate) clamp: Option, +} + /// Runs the sleep-entry hook of every enabled source. /// +/// One [`WrappedSleepConfig::reject_sleep`] is enough. The caller ignores the refusal for a deep +/// sleep. The wake resets the chip, so there is no caller to report the refusal to. The shortest +/// [`WrappedSleepConfig::limit_sleep`] wins. +/// /// The mask as read at sleep entry selects the hooks. A hook can enable another source. The GPIO /// hook does this, because it selects between the `ext0`, `ext1` and per-pin paths. The caller /// therefore reads the mask again after the hooks. It does not run the hooks again until the mask @@ -237,7 +357,7 @@ pub(crate) fn reject_mask() -> u32 { /// /// The caller writes the kind of the sleep to the configuration before this call, so that the hooks /// can read it. -pub(crate) fn run_entry_hooks(config: &mut RtcSleepConfig) { +pub(crate) fn run_entry_hooks(config: &mut RtcSleepConfig) -> SleepEntry { let mut wrapped = WrappedSleepConfig::new(config); for source in enabled_sources() { @@ -246,9 +366,31 @@ pub(crate) fn run_entry_hooks(config: &mut RtcSleepConfig) { hook(&mut wrapped); } } + + // The clamp writes the comparator, so it runs after every hook has asked for its limit. A + // source that the clamp enables has not run its entry hook. It runs here, where the requests + // of a hook still reach the configuration. + #[cfg(sleep_has_wakeup_source_timer)] + let clamp = wrapped.limit.map(|limit| { + let clamp = super::timer::clamp_to_limit(limit); + clamp.apply_entry_hook(&mut wrapped); + clamp + }); + + wrapped.apply_clock_requests(); + + SleepEntry { + refused: wrapped.refused, + #[cfg(sleep_has_wakeup_source_timer)] + clamp, + } } -/// Runs the post-wake hook of every enabled source. Only a light sleep calls this. +/// Runs the post-wake hook of every enabled source. +/// +/// A light sleep calls this after the wake. A refused light sleep calls it too, so an entry hook +/// can undo a pad change. A sleep that a limit ends before it starts calls it for the same reason. +/// A deep sleep that resets the chip does not call this. pub(crate) fn run_exit_hooks() { for source in enabled_sources() { let hook = HOOKS.with(|hooks| hooks.exit[source as usize]); diff --git a/esp-hal/src/sdm.rs b/esp-hal/src/sdm.rs index 0dd9c1acea5..9d139083a8a 100644 --- a/esp-hal/src/sdm.rs +++ b/esp-hal/src/sdm.rs @@ -170,7 +170,7 @@ impl ChannelConfig { /// /// # Errors /// - /// Returns [`Error::UnreachableTargetFrequency`] when no hardware + /// [`Error::UnreachableTargetFrequency`] when no hardware /// prescaler can represent the requested frequency. pub fn with_frequency(mut self, frequency: Rate) -> Result { self.raw_prescaler = raw_prescaler(prescaler_from_frequency(frequency)?); @@ -183,7 +183,7 @@ impl ChannelConfig { /// /// # Errors /// - /// Returns [`Error::PrescalerOutOfRange`] when `prescaler` is not in + /// [`Error::PrescalerOutOfRange`] when `prescaler` is not in /// `1..=256`. pub fn with_prescaler(mut self, prescaler: u16) -> Result { check_prescaler(prescaler)?; @@ -211,7 +211,7 @@ pub struct Channel<'d> { } impl<'d> Channel<'d> { - /// Creates a connected sigma-delta channel. + /// Creates a new connected sigma-delta channel. pub fn new( channel: impl Instance + 'd, pin: impl PeripheralOutput<'d>, diff --git a/esp-hal/src/sdmmc/mod.rs b/esp-hal/src/sdmmc/mod.rs index de1bf4145e4..153df69f76d 100644 --- a/esp-hal/src/sdmmc/mod.rs +++ b/esp-hal/src/sdmmc/mod.rs @@ -82,7 +82,7 @@ pub enum ClockSource { /// 160 MHz PLL. #[cfg(not(esp32s31))] Pll160m, - /// 500 MHz PLL. + /// Configured MPLL clock. #[cfg(esp32s31)] Mpll, /// Crystal oscillator. @@ -90,7 +90,7 @@ pub enum ClockSource { Xtal, } -/// Clock input sampling phase used for high-speed tuning. +/// Clocks input sampling phase used for high-speed tuning. #[cfg(sdmmc_delay_phase_num_is_set)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] @@ -192,11 +192,11 @@ pub enum ResponseLen { #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub struct CommandFlags { - /// Wait for the data line to be free before issuing. + /// Waits for the data line to be free before issuing. pub wait_complete: bool, /// Stop/abort command (CMD12, CMD52 abort). pub stop_abort: bool, - /// Poll DAT0 until the card releases busy (R1b). + /// Polls DAT0 until the card releases busy (R1b). pub busy: bool, } @@ -1637,8 +1637,8 @@ impl<'d, const S: u8, Dm: DriverMode> Slot<'d, S, Dm> { self } - /// Returns `true` if a card is detected, or if no card-detect pin is - /// wired (assume present). + /// Returns whether a card is detected. If no card-detect pin is wired, + /// assumes the card is present. pub fn is_card_present(&self) -> bool { if !self.cd_connected { return true; @@ -1646,7 +1646,7 @@ impl<'d, const S: u8, Dm: DriverMode> Slot<'d, S, Dm> { (SDHOST::regs().cdetect().read().card_detect_n().bits() & (1 << S)) == 0 } - /// Returns `true` if the card reports write protection. Returns `false` + /// Returns whether the card reports write protection. Returns `false` /// if no write-protect pin is wired. Polarity follows /// [`SlotConfig::with_wp_active_high`]. pub fn is_write_protected(&self) -> bool { @@ -1915,9 +1915,10 @@ impl<'d, const S: u8> sdio::MmcBus for Slot<'d, S, Async> { } async fn init_idle(&mut self, hz: u32) -> Result<(), MmcError> { - let mut session = lock_engine(slot_id(S)).await?; + let mut session = ENGINE.lock().await; self.validate_pins().map_err(|_| MmcError::Other)?; self.set_bus_low_level(BusWidth::Bit1, hz)?; + session.select_and_apply(slot_id(S))?; session.send_init_sequence(slot_id(S))?; Ok(()) } @@ -2355,7 +2356,7 @@ fn disable_idmac() { fn module_hz(source: ClockSource, div: u8) -> u32 { let base = match source { #[cfg(esp32s31)] - ClockSource::Mpll => 500_000_000, + ClockSource::Mpll => crate::clock::ll::mpll_clk_frequency(), #[cfg(not(esp32s31))] ClockSource::Pll160m => 160_000_000, //#[cfg(esp32p4)] diff --git a/esp-hal/src/sha.rs b/esp-hal/src/sha.rs index 4f8a6be690e..2123857d92e 100644 --- a/esp-hal/src/sha.rs +++ b/esp-hal/src/sha.rs @@ -6,13 +6,14 @@ //! significantly, compared to a SHA algorithm implemented solely in software //! //! ## Configuration -//! This driver allows you to perform cryptographic hash operations using +//! This driver performs cryptographic hash operations using //! various hash algorithms supported by the SHA peripheral, such as: //! * SHA-1 //! * SHA-224 //! * SHA-256 //! * SHA-384 //! * SHA-512 +//! * SM3 //! //! It provides functions to update the hash calculation with input data, finish //! the hash calculation and retrieve the resulting hash value. The SHA @@ -101,7 +102,7 @@ pub use digest_011::Digest as Digest011; use crate::{ peripherals::SHA, reg_access::{AlignmentHelper, SocDependentEndianess}, - system::GenericPeripheralGuard, + system::{CryptoClockGuard, GenericPeripheralGuard}, work_queue::{Handle, Poll, Status, VTable, WorkQueue, WorkQueueDriver, WorkQueueFrontend}, }; @@ -112,33 +113,47 @@ use crate::{ // - Each algorithm has its own register cluster // - No support for interleaved operation -/// The SHA Accelerator driver instance +/// The SHA Accelerator driver instance. pub struct Sha<'d> { sha: SHA<'d>, _guard: GenericPeripheralGuard<{ crate::system::Peripheral::Sha as u8 }>, + _clock_guard: CryptoClockGuard, } impl<'d> Sha<'d> { - /// Create a new instance of the SHA Accelerator driver. + /// Creates a new instance of the SHA Accelerator driver. pub fn new(sha: SHA<'d>) -> Self { + let clock_guard = CryptoClockGuard::new(); let guard = GenericPeripheralGuard::new(); - Self { sha, _guard: guard } + Self { + sha, + _guard: guard, + _clock_guard: clock_guard, + } } - /// Start a new digest. + /// Starts a new digest. + #[cfg_attr( + sha_has_sm3, + doc = "\n# Panics\nPanics if SM3 is selected and disabled by eFuse." + )] pub fn start<'a, A: ShaAlgorithm>(&'a mut self) -> ShaDigest<'d, A, &'a mut Self> { ShaDigest::new(self) } - /// Start a new digest and take ownership of the driver. + /// Starts a new digest and take ownership of the driver. /// This is useful for storage outside a function body. i.e. in static or /// struct. + #[cfg_attr( + sha_has_sm3, + doc = "\n# Panics\nPanics if SM3 is selected and disabled by eFuse." + )] pub fn start_owned(self) -> ShaDigest<'d, A, Self> { ShaDigest::new(self) } - /// Returns true if the hardware is processing the next message. + /// Returns whether the hardware is processing the next message. fn is_busy(&self, algo: ShaAlgorithmKind) -> bool { algo.is_busy(&self.sha) } @@ -343,10 +358,10 @@ impl crate::interrupt::InterruptConfigurable for Sha<'_> { // - Registers need to be written one u32 at a time, no u8 access // - This means that we need to buffer bytes coming in up to 4 u8's in order to create a full u32 -/// An active digest +/// An active digest. /// -/// This implementation might fail after u32::MAX/8 bytes, to increase please -/// see ::finish() length/self.cursor usage +/// This implementation might fail after u32::MAX/8 bytes. See `finish()` +/// length/`self.cursor` usage to increase the limit. pub struct ShaDigest<'d, A, S: BorrowMut>> { sha: S, state: DigestState, @@ -376,6 +391,8 @@ struct DigestState { impl DigestState { fn new(algorithm: ShaAlgorithmKind) -> Self { + assert!(algorithm.is_supported(), "SM3 is disabled by eFuse"); + Self { algorithm, alignment_helper: AlignmentHelper::default(), @@ -389,7 +406,11 @@ impl DigestState { } impl<'d, A: ShaAlgorithm, S: BorrowMut>> ShaDigest<'d, A, S> { - /// Creates a new digest + /// Creates a new digest. + #[cfg_attr( + sha_has_sm3, + doc = "\n# Panics\nPanics if SM3 is selected and disabled by eFuse." + )] #[allow(unused_mut)] pub fn new(mut sha: S) -> Self { #[cfg(not(esp32))] @@ -440,7 +461,7 @@ impl<'d, A: ShaAlgorithm, S: BorrowMut>> ShaDigest<'d, A, S> { } } - /// Returns true if the hardware is processing the next message. + /// Returns whether the hardware is processing the next message. pub fn is_busy(&self) -> bool { A::ALGORITHM_KIND.is_busy(&self.sha.borrow().sha) } @@ -450,18 +471,19 @@ impl<'d, A: ShaAlgorithm, S: BorrowMut>> ShaDigest<'d, A, S> { self.sha.borrow_mut().update(&mut self.state, incoming) } - /// Finish of the calculation (if not already) and copy result to output - /// After `finish()` is called `update()`s will contribute to a new hash - /// which can be calculated again with `finish()`. + /// Finishes the calculation (if not already finished) and copies the result to output. + /// + /// After `finish()` is called, `update()`s contribute to a new hash which can be + /// calculated again with `finish()` /// /// Typically, output is expected to be the size of - /// [ShaAlgorithm::DIGEST_LENGTH], but smaller inputs can be given to + /// [`ShaAlgorithm::DIGEST_LENGTH`], but smaller inputs can be given to /// get a "short hash" pub fn finish(&mut self, output: &mut [u8]) -> nb::Result<(), Infallible> { self.sha.borrow_mut().finish(&mut self.state, output) } - /// Save the current state of the digest for later continuation. + /// Saves the current state of the digest for later continuation. #[cfg(not(esp32))] pub fn save(&mut self, context: &mut Context) -> nb::Result<(), Infallible> { if self.is_busy() { @@ -489,7 +511,7 @@ impl<'d, A: ShaAlgorithm, S: BorrowMut>> ShaDigest<'d, A, S> { Ok(()) } - /// Discard the current digest and return the peripheral. + /// Discards the current digest and returns the peripheral. pub fn cancel(self) -> S { self.sha } @@ -509,7 +531,11 @@ pub struct Context { #[cfg(not(esp32))] impl Context { - /// Create a new empty context + /// Creates a new empty context. + #[cfg_attr( + sha_has_sm3, + doc = "\n# Panics\nPanics if SM3 is selected and disabled by eFuse." + )] pub fn new() -> Self { Self { state: DigestState::new(A::ALGORITHM_KIND), @@ -521,8 +547,8 @@ impl Context { /// Indicates if the SHA context is in the first run. /// - /// Returns `true` if this is the first time processing data with the SHA - /// instance, otherwise returns `false`. + /// Returns whether this is the first time processing data with the SHA + /// instance. pub fn first_run(&self) -> bool { self.state.first_run } @@ -535,7 +561,7 @@ impl Default for Context { } } -/// This trait encapsulates the configuration for a specific SHA algorithm. +/// Encapsulates the configuration for a specific SHA algorithm. pub trait ShaAlgorithm: crate::private::Sealed { /// Constant containing the name of the algorithm as a string. const ALGORITHM: &'static str; @@ -559,8 +585,8 @@ pub trait ShaAlgorithm: crate::private::Sealed { type Digest011OutputSize: digest_011::array::ArraySize; } -/// Note: digest has a blanket trait implementation for Digest for any -/// element that implements FixedOutput + Default + Update + HashMarker +/// `digest` has a blanket trait implementation for `Digest` for any +/// element that implements FixedOutput + Default + Update + HashMarker. impl<'d, A: ShaAlgorithm, S: BorrowMut>> digest_010::HashMarker for ShaDigest<'d, A, S> {} impl<'d, A: ShaAlgorithm, S: BorrowMut>> digest_011::HashMarker for ShaDigest<'d, A, S> {} @@ -652,6 +678,20 @@ for_each_sha_algorithm! { } impl ShaAlgorithmKind { + /// Returns whether the algorithm is enabled. + #[cfg_attr( + sha_has_sm3, + doc = "\nSM3 is disabled when the `DIS_SM_CRYPT` eFuse is set." + )] + #[instability::unstable] + pub fn is_supported(self) -> bool { + match self { + #[cfg(sha_has_sm3)] + Self::Sm3 => !crate::efuse::read_bit(crate::efuse::DIS_SM_CRYPT), + _ => true, + } + } + fn start(self, sha: &crate::peripherals::SHA<'_>) { let regs = sha.register_block(); cfg_select! { @@ -754,7 +794,7 @@ for_each_sha_algorithm! { ( $name:ident, $full_name:literal (sizes: $block_size:literal, $digest_len:literal, $message_length_bytes:literal) (insecure_against: $($attack_kind:literal),*), $mode_bits:literal ) => { #[doc = concat!("Hardware-accelerated ", $full_name, " implementation")] /// - /// This struct manages the context and state required for processing data using the selected hashing algorithm. + /// Manages the context and state required for processing data using the selected hashing algorithm. /// /// The struct provides various functionalities such as initializing the hashing @@ -762,7 +802,7 @@ for_each_sha_algorithm! { /// hashing operation to generate the final digest. $( #[doc = ""] - #[doc = concat!(" > ⚠️ Note that this algorithm is known to be insecure against ", $attack_kind, " attacks.")] + #[doc = concat!(" > ⚠️ This algorithm is known to be insecure against ", $attack_kind, " attacks.")] )* #[non_exhaustive] pub struct $name; @@ -878,7 +918,7 @@ enum ShaOperationKind { #[procmacros::doc_replace] /// CPU-driven SHA processing backend. /// -/// ## Example +/// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -897,8 +937,6 @@ enum ShaOperationKind { /// // Process data. The `update` function returns a handle which can be used to wait /// // for the operation to finish. /// sha1_ctx.update(b"input data").wait_blocking(); -/// sha1_ctx.update(b"input data").wait_blocking(); -/// sha1_ctx.update(b"input data").wait_blocking(); /// /// // Extract the final hash. This resets the context. /// sha1_ctx.finalize(&mut digest).wait_blocking(); @@ -914,7 +952,7 @@ pub struct ShaBackend<'d> { impl<'d> ShaBackend<'d> { /// Creates a new SHA backend. /// - /// The backend needs to be [`start`][Self::start]ed before it can execute SHA operations. + /// The backend must be started with [`Self::start`] before it can execute SHA operations. pub fn new(sha: SHA<'d>) -> Self { Self { driver: DriverState::Uninitialized(sha), @@ -1351,7 +1389,7 @@ pub struct ShaHandle<'t>(Handle<'t, ShaOperation>); impl ShaHandle<'_> { /// Polls the status of the work item. /// - /// This function returns `true` if the item has been processed. + /// Returns whether the item has been processed. #[inline] pub fn poll(&mut self) -> bool { self.0.poll() @@ -1359,7 +1397,7 @@ impl ShaHandle<'_> { /// Polls the work item to completion, by busy-looping. /// - /// This function returns immediately if `poll` returns `true`. + /// Returns immediately if `poll` returns `true`. #[inline] pub fn wait_blocking(self) -> Status { self.0.wait_blocking() @@ -1390,6 +1428,12 @@ pub enum FinalizeError { // Now implement the actual public types. // Helper macro to limit the scope of `paste` macro_rules! impl_worker_context { + (@panic_docs Sm3Context) => { + "\n# Panics\nPanics if SM3 is disabled by eFuse." + }; + (@panic_docs $name:ident) => { + "" + }; ($name:ident, $full_name:literal, $algo:expr, $digest_len:literal, $block_size:literal ) => { #[doc = concat!("A ", $full_name, " context.")] #[cfg_attr(not(esp32), derive(Clone))] @@ -1398,11 +1442,12 @@ macro_rules! impl_worker_context { impl $name { /// Creates a new context. /// - /// The context represents the in-progress processing of a single message. You need to - /// feed message bytes to [`Self::update`], then finalize the process using + /// The context represents the in-progress processing of a single message. + /// Feed message bytes to [`Self::update`], then finalize the process using /// [`Self::finalize`]. /// /// Any number of contexts can be created, to hash any number of messages concurrently. + #[doc = impl_worker_context!(@panic_docs $name)] pub fn new() -> Self { Self(ShaContext::new($algo)) } diff --git a/esp-hal/src/soc/branch_predictor.rs b/esp-hal/src/soc/branch_predictor.rs new file mode 100644 index 00000000000..0fbfa9ecccc --- /dev/null +++ b/esp-hal/src/soc/branch_predictor.rs @@ -0,0 +1,61 @@ +//! Branch predictor control. +//! +//! The branch predictor starts cache requests of its own, so it must be off while the cache is +//! off. + +/// Branch-predictor bits in `mhcr` (CSR `0x7c1`): return stack, predictive jump, and branch +/// target buffer. +const MHCR_BRANCH_PREDICTOR: u32 = (1 << 4) | (1 << 5) | (1 << 12); + +/// Turns the branch predictor on. +#[inline(always)] +pub(crate) fn enable() { + unsafe { + core::arch::asm!( + "fence iorw, iorw", + "csrs 0x7c1, {0}", + in(reg) MHCR_BRANCH_PREDICTOR, + ); + } +} + +#[cfg(any(feature = "unstable", all(multi_core, feature = "rt")))] +pub(crate) use guard::DisabledBranchPredictor; + +#[cfg(any(feature = "unstable", all(multi_core, feature = "rt")))] +mod guard { + use super::MHCR_BRANCH_PREDICTOR; + + /// Turns the branch predictor off. [`Drop`] sets the bits that were set before. + pub(crate) struct DisabledBranchPredictor(u32); + + impl DisabledBranchPredictor { + /// Turns the branch predictor off. + #[inline(always)] + pub(crate) fn new() -> Self { + let bits: u32; + unsafe { + core::arch::asm!( + "csrrc {0}, 0x7c1, {1}", + "fence iorw, iorw", + out(reg) bits, + in(reg) MHCR_BRANCH_PREDICTOR, + ); + } + Self(bits & MHCR_BRANCH_PREDICTOR) + } + } + + impl Drop for DisabledBranchPredictor { + #[inline(always)] + fn drop(&mut self) { + unsafe { + core::arch::asm!( + "fence iorw, iorw", + "csrs 0x7c1, {0}", + in(reg) self.0, + ); + } + } + } +} diff --git a/esp-hal/src/soc/esp32/clocks.rs b/esp-hal/src/soc/esp32/clocks.rs index bb9b3866279..469dbe3151a 100644 --- a/esp-hal/src/soc/esp32/clocks.rs +++ b/esp-hal/src/soc/esp32/clocks.rs @@ -17,10 +17,12 @@ use esp_rom_sys::rom::{ets_delay_us, ets_update_cpu_frequency_rom}; +#[cfg(use_xtal32k)] +use crate::peripherals::RTC_IO; use crate::{ clock::RtcClock, efuse::VOL_LEVEL_HP_INV, - peripherals::{APB_CTRL, LPWR, RMT, RTC_IO, SYSTEM, TIMG0}, + peripherals::{APB_CTRL, LPWR, RMT, SYSTEM, TIMG0}, rtc_cntl::Rtc, soc::{regi2c, xtal32k}, time::Rate, @@ -57,6 +59,7 @@ impl CpuClock { syscon_pre_div: None, cpu_clk: Some(CpuClkConfig::Pll), rtc_slow_clk: Some(xtal32k::default_rtc_slow_clk()), + ble_lp_clk: Some(BleLpClkConfig::Xtal), rtc_fast_clk: Some(RtcFastClkConfig::Rc), timg_calibration_clock: None, }; @@ -68,6 +71,7 @@ impl CpuClock { syscon_pre_div: None, cpu_clk: Some(CpuClkConfig::Pll), rtc_slow_clk: Some(xtal32k::default_rtc_slow_clk()), + ble_lp_clk: Some(BleLpClkConfig::Xtal), rtc_fast_clk: Some(RtcFastClkConfig::Rc), timg_calibration_clock: None, }; @@ -79,6 +83,7 @@ impl CpuClock { syscon_pre_div: None, cpu_clk: Some(CpuClkConfig::Pll), rtc_slow_clk: Some(xtal32k::default_rtc_slow_clk()), + ble_lp_clk: Some(BleLpClkConfig::Xtal), rtc_fast_clk: Some(RtcFastClkConfig::Rc), timg_calibration_clock: None, }; @@ -191,6 +196,16 @@ fn configure_xtal_clk_impl( // PLL_CLK +/// Configures and calibrates the BBPLL again. +/// +/// The BBPLL loses its analog configuration while the RTC controller powers it down, for example in +/// a light sleep. ESP-IDF configures it again before it uses the PLL after a wake. +pub(crate) fn reconfigure_pll(clocks: &mut ClockTree) { + if clocks.pll_clk_refcount > 0 { + enable_pll_clk_impl(clocks, true); + } +} + fn enable_pll_clk_impl(clocks: &mut ClockTree, en: bool) { // TODO: this should probably be refcounted with APLL, but ESP32 TRM states APLL_CLK is sourced // from PLL. Currently it's unclear how these relate to each other - but the internal I2C bus is @@ -364,6 +379,12 @@ fn enable_pll_f160m_clk_impl(_clocks: &mut ClockTree, _en: bool) { // Nothing to do. } +// PLL_D2_CLK + +fn enable_pll_d2_clk_impl(_clocks: &mut ClockTree, _en: bool) { + // Nothing to do. +} + // CPU_PLL_DIV_IN // Not an actual MUX, used to allow configuring the DIVA divider as one block. @@ -586,6 +607,7 @@ fn enable_apb_clk_80m_impl(_clocks: &mut ClockTree, _en: bool) { // XTAL32K_CLK +#[cfg(use_xtal32k)] fn enable_xtal32k_clk_impl(_clocks: &mut ClockTree, en: bool) { // RTCIO could be configured to allow an external oscillator to be used. We could model this // with a MUX, probably, but this is omitted for now for simplicity. @@ -664,6 +686,7 @@ fn configure_rtc_slow_clk_impl( ) { LPWR::regs().clk_conf().modify(|_, w| match new_config { RtcSlowClkConfig::RcSlow => w.ana_clk_rtc_sel().slow_ck(), + #[cfg(use_xtal32k)] RtcSlowClkConfig::Xtal32k => w.ana_clk_rtc_sel().ck_xtal_32k(), RtcSlowClkConfig::RcFast => w.ana_clk_rtc_sel().ck8m_d256_out(), }); @@ -721,6 +744,7 @@ fn configure_timg_calibration_clock_impl( w.rtc_cali_clk_sel().bits(match new_config { TimgCalibrationClockConfig::RcSlowClk => 0, TimgCalibrationClockConfig::RcFastDivClk => 1, + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => 2, }) }); @@ -761,3 +785,23 @@ impl RmtInstance { } } } + +// BLE_LP_XTAL_CLK + +fn enable_ble_lp_xtal_clk_impl(_clocks: &mut ClockTree, _en: bool) { + // Nothing to do. +} + +// BLE_LP_CLK + +fn enable_ble_lp_clk_impl(_clocks: &mut ClockTree, _en: bool) { + // Nothing to do. +} + +fn configure_ble_lp_clk_impl( + _clocks: &mut ClockTree, + _old_config: Option, + _new_config: BleLpClkConfig, +) { + // The BTDM controller programs the source and divider. +} diff --git a/esp-hal/src/soc/esp32/cpu_control.rs b/esp-hal/src/soc/esp32/cpu_control.rs index beaeccfcf39..82acbebb554 100644 --- a/esp-hal/src/soc/esp32/cpu_control.rs +++ b/esp-hal/src/soc/esp32/cpu_control.rs @@ -6,11 +6,11 @@ //! and managing the APP (second) CPU core on the `ESP32` chip. It is used to //! start and stop program execution on the APP core. -use core::sync::atomic::Ordering; - +#[cfg(feature = "unstable")] +use crate::peripherals::SPI0; use crate::{ - peripherals::{DPORT, LPWR, SPI0}, - system::{Cpu, multi_core::*}, + peripherals::{DPORT, LPWR}, + system::Cpu, }; pub(crate) unsafe fn internal_park_core(core: Cpu, park: bool) { @@ -36,7 +36,7 @@ pub(crate) unsafe fn internal_park_core(core: Cpu, park: bool) { } } -/// Returns `true` if the specified core is currently running (not stalled). +/// Returns whether the specified core is currently running (not stalled). #[instability::unstable] pub fn is_running(core: Cpu) -> bool { if core == Cpu::AppCpu { @@ -81,6 +81,7 @@ pub fn is_running(core: Cpu) -> bool { is_stalled != 0x86 } +#[cfg(feature = "unstable")] fn flush_cache(core: Cpu) { let dport_control = DPORT::regs(); @@ -123,6 +124,7 @@ fn flush_cache(core: Cpu) { }; } +#[cfg(feature = "unstable")] fn enable_cache(core: Cpu) { let spi0 = SPI0::regs(); let dport_control = DPORT::regs(); @@ -143,6 +145,7 @@ fn enable_cache(core: Cpu) { }; } +#[cfg(feature = "unstable")] pub(crate) fn start_core1(entry_point: *const u32) { let dport_control = DPORT::regs(); @@ -166,55 +169,3 @@ pub(crate) fn start_core1(entry_point: *const u32) { .appcpu_ctrl_a() .modify(|_, w| w.appcpu_resetting().clear_bit()); } - -pub(crate) fn start_core1_init() -> ! -where - F: FnOnce(), -{ - // disables interrupts - unsafe { - xtensa_lx::interrupt::set_mask(0); - } - - // reset cycle compare registers - xtensa_lx::timer::set_ccompare0(0); - xtensa_lx::timer::set_ccompare1(0); - xtensa_lx::timer::set_ccompare2(0); - - unsafe extern "C" { - static mut _init_start: u32; - } - - // set vector table and stack pointer - unsafe { - xtensa_lx::set_vecbase(&raw const _init_start); - xtensa_lx::set_stack_pointer(APP_CORE_STACK_TOP.load(Ordering::Acquire)); - - #[cfg(all(feature = "rt", stack_guard_monitoring))] - { - let stack_guard = APP_CORE_STACK_GUARD.load(Ordering::Acquire); - stack_guard.write_volatile(esp_config::esp_config_int!( - u32, - "ESP_HAL_CONFIG_STACK_GUARD_VALUE" - )); - // setting 0 effectively disables the functionality - crate::debugger::set_stack_watchpoint(stack_guard as usize); - } - } - - // The ROM has already handed off to us; clear the AppCpu boot address so a - // subsequent reset doesn't see a stale entry point. Matches IDF's - // `call_start_cpu1`. - DPORT::regs() - .appcpu_ctrl_d() - .write(|w| unsafe { w.appcpu_boot_addr().bits(0) }); - - // Do not call setup_interrupts as that would disable peripheral interrupts, too. - unsafe { crate::interrupt::init_vectoring() }; - - // Trampoline to run from the new stack. - // start_core1_run should _NEVER_ be inlined - // as we rely on the function call to use - // the new stack. - unsafe { CpuControl::start_core1_run::() } -} diff --git a/esp-hal/src/soc/esp32/gpio.rs b/esp-hal/src/soc/esp32/gpio.rs index 21cc3ea41db..0a89cdd0162 100644 --- a/esp-hal/src/soc/esp32/gpio.rs +++ b/esp-hal/src/soc/esp32/gpio.rs @@ -3,8 +3,8 @@ //! ## Overview //! //! The `GPIO` module provides functions and configurations for controlling the -//! `General Purpose Input/Output` pins on the `ESP32` chip. It allows you to -//! configure pins as inputs or outputs, set their state and read their state. +//! `General Purpose Input/Output` pins on the `ESP32` chip. It configures pins +//! as inputs or outputs, sets their state, and reads their state. //! //! Let's get through the functionality and configurations provided by this GPIO //! module: diff --git a/esp-hal/src/soc/esp32/mod.rs b/esp-hal/src/soc/esp32/mod.rs index 8478fc3de6c..b8064383c4e 100644 --- a/esp-hal/src/soc/esp32/mod.rs +++ b/esp-hal/src/soc/esp32/mod.rs @@ -8,20 +8,14 @@ crate::unstable_module! { pub mod clocks; pub mod trng; + // The light sleep path stalls the other core, and it is not gated on the feature. + pub mod cpu_control; } -#[cfg(feature = "unstable")] -pub mod cpu_control; pub mod gpio; pub(crate) mod regi2c; pub(crate) use esp32 as pac; -#[cfg(i2s_driver_supported)] -#[cfg_attr(not(feature = "unstable"), allow(unused))] -pub(crate) fn i2s_sclk_frequency() -> u32 { - clocks::pll_f160m_clk_frequency() -} - pub(crate) unsafe fn configure_cpu_caches() {} pub(crate) fn pre_init() {} diff --git a/esp-hal/src/soc/esp32/trng.rs b/esp-hal/src/soc/esp32/trng.rs index eab954a6be0..b3589b9cb11 100644 --- a/esp-hal/src/soc/esp32/trng.rs +++ b/esp-hal/src/soc/esp32/trng.rs @@ -1,6 +1,6 @@ //! Helper functions for TRNG functionality -/// Enable true randomness by enabling the entropy source. +/// Enables true randomness by enabling the entropy source. /// Blocks `ADC` usage. pub(crate) fn ensure_randomness() { let rtc_cntl = crate::peripherals::LPWR::regs(); @@ -106,7 +106,7 @@ pub(crate) fn ensure_randomness() { } } -/// Disable true randomness. Unlocks `ADC` peripheral. +/// Disables true randomness. Unlocks `ADC` peripheral. pub(crate) fn revert_trng() { let sens = crate::peripherals::SENS::regs(); let i2s0 = crate::peripherals::I2S0::regs(); diff --git a/esp-hal/src/soc/esp32c2/clocks.rs b/esp-hal/src/soc/esp32c2/clocks.rs index b23e925d3c8..d2b5801708b 100644 --- a/esp-hal/src/soc/esp32c2/clocks.rs +++ b/esp-hal/src/soc/esp32c2/clocks.rs @@ -19,7 +19,7 @@ use esp_rom_sys::rom::{ets_delay_us, ets_update_cpu_frequency_rom}; use crate::{ clock::RtcClock, - peripherals::{I2C_ANA_MST, LPWR, SYSTEM, TIMG0}, + peripherals::{I2C_ANA_MST, LPWR, MODEM_CLKRST, SYSTEM, TIMG0}, rtc_cntl::Rtc, soc::regi2c, time::Rate, @@ -52,6 +52,8 @@ impl CpuClock { cpu_clk: Some(CpuClkConfig::Pll), rc_fast_clk_div_n: Some(RcFastClkDivNConfig::new(0)), rtc_slow_clk: Some(RtcSlowClkConfig::RcSlow), + // The divisor follows the detected crystal. `configure` fills it in. + ble_lp_clk: None, rtc_fast_clk: Some(RtcFastClkConfig::Rc), low_power_clk: Some(LowPowerClkConfig::RtcSlow), timg_calibration_clock: None, @@ -63,6 +65,8 @@ impl CpuClock { cpu_clk: Some(CpuClkConfig::Pll), rc_fast_clk_div_n: Some(RcFastClkDivNConfig::new(0)), rtc_slow_clk: Some(RtcSlowClkConfig::RcSlow), + // The divisor follows the detected crystal. `configure` fills it in. + ble_lp_clk: None, rtc_fast_clk: Some(RtcFastClkConfig::Rc), low_power_clk: Some(LowPowerClkConfig::RtcSlow), timg_calibration_clock: None, @@ -111,6 +115,21 @@ impl ClockConfig { self.xtal_clk = Some(xtal); } + if self.ble_lp_clk.is_none() { + let xtal_hz = unwrap!(self.xtal_clk).value(); + // 26 MHz crystals run the timer at 40 kHz. 40 MHz crystals run it at 32 kHz. + // BLE_LP_XTAL_CLK already divides the crystal by 5. + let target_hz = if xtal_hz == 26_000_000 { + 40_000 + } else { + 32_000 + }; + self.ble_lp_clk = Some(BleLpClkConfig::new( + BleLpClkSclk::Xtal, + xtal_hz / (5 * target_hz) - 1, + )); + } + self.apply(clocks); } } @@ -571,6 +590,10 @@ fn configure_low_power_clk_impl( _old_config: Option, new_config: LowPowerClkConfig, ) { + // The divider resets to 255. The Wi-Fi light sleep timer expects the undivided clock. + SYSTEM::regs() + .bt_lpck_div_int() + .modify(|_, w| unsafe { w.bt_lpck_div_num().bits(0) }); SYSTEM::regs().bt_lpck_div_frac().modify(|_, w| { w.lpclk_sel_8m() .bit(new_config == LowPowerClkConfig::RcFast); @@ -663,3 +686,50 @@ impl TimgInstance { }); } } + +impl AdcInstance { + // ADC_FUNCTION_CLOCK + + fn enable_function_clock_impl(self, _clocks: &mut ClockTree, en: bool) { + crate::peripherals::APB_SARADC::regs() + .clkm_conf() + .modify(|_, w| unsafe { + w.clk_en().bit(en); + w.clk_sel().bits(if en { 2 } else { 0 }) + }); + } +} + +fn enable_ble_lp_xtal_clk_impl(_clocks: &mut ClockTree, _en: bool) { + // The divide-by-5 crystal input has no clock gate. +} + +fn enable_ble_lp_rc_slow_clk_impl(_clocks: &mut ClockTree, _en: bool) { + // The divide-by-5 RC_SLOW input has no clock gate + // (see esp_bt_rtc_slow_clk_select() and ble_rtc_clk_init() in bt.c). +} + +fn enable_ble_lp_clk_impl(_clocks: &mut ClockTree, _en: bool) {} + +fn configure_ble_lp_clk_impl( + _clocks: &mut ClockTree, + _old_config: Option, + new_config: BleLpClkConfig, +) { + let sclk = new_config.sclk(); + + MODEM_CLKRST::regs() + .modem_lp_timer_conf() + .modify(|_, w| unsafe { + w.lp_timer_sel_xtal32k().clear_bit(); + w.lp_timer_sel_xtal().bit(sclk == BleLpClkSclk::Xtal); + w.lp_timer_sel_8m().clear_bit(); + w.lp_timer_sel_rtc_slow().bit(sclk == BleLpClkSclk::RcSlow); + w.lp_timer_clk_div_num().bits(new_config.divisor() as u8) + }); + + MODEM_CLKRST::regs().etm_clk_conf().modify(|_, w| { + w.etm_clk_active().set_bit(); + w.etm_clk_sel().clear_bit() + }); +} diff --git a/esp-hal/src/soc/esp32c2/mod.rs b/esp-hal/src/soc/esp32c2/mod.rs index d581539ab46..8627d2d54a5 100644 --- a/esp-hal/src/soc/esp32c2/mod.rs +++ b/esp-hal/src/soc/esp32c2/mod.rs @@ -16,3 +16,15 @@ pub(crate) use esp32c2 as pac; #[cfg(feature = "rt")] pub(crate) fn riscv_preinit() {} pub(crate) fn pre_init() {} + +/// Invalidate a specific range of addresses in the cache. +#[cfg(feature = "unstable")] +#[crate::ram] +pub(crate) unsafe fn cache_invalidate_addr(addr: u32, size: u32) { + unsafe extern "C" { + fn Cache_Invalidate_Addr(addr: u32, size: u32); + } + unsafe { + Cache_Invalidate_Addr(addr, size); + } +} diff --git a/esp-hal/src/soc/esp32c2/trng.rs b/esp-hal/src/soc/esp32c2/trng.rs index 923775af8ba..2ee7e739b53 100644 --- a/esp-hal/src/soc/esp32c2/trng.rs +++ b/esp-hal/src/soc/esp32c2/trng.rs @@ -3,7 +3,7 @@ use crate::{ soc::regi2c, }; -/// Enable true randomness by enabling the entropy source. +/// Enables true randomness by enabling the entropy source. /// Blocks `ADC` usage. pub(crate) fn ensure_randomness() { let rtc_cntl = LPWR::regs(); @@ -81,7 +81,7 @@ pub(crate) fn ensure_randomness() { } } -/// Disable true randomness. Unlocks `ADC` peripheral. +/// Disables true randomness. Unlocks `ADC` peripheral. pub(crate) fn revert_trng() { let apb_saradc = APB_SARADC::regs(); let rtc_cntl = LPWR::regs(); diff --git a/esp-hal/src/soc/esp32c3/clocks.rs b/esp-hal/src/soc/esp32c3/clocks.rs index 985e2d20271..e5dd9eb0a8d 100644 --- a/esp-hal/src/soc/esp32c3/clocks.rs +++ b/esp-hal/src/soc/esp32c3/clocks.rs @@ -52,6 +52,7 @@ impl CpuClock { cpu_clk: Some(CpuClkConfig::Pll), rc_fast_clk_div_n: Some(RcFastClkDivNConfig::new(0)), rtc_slow_clk: Some(RtcSlowClkConfig::RcSlow), + ble_lp_clk: Some(BleLpClkConfig::Xtal), rtc_fast_clk: Some(RtcFastClkConfig::Rc), low_power_clk: Some(LowPowerClkConfig::RtcSlow), timg_calibration_clock: None, @@ -64,6 +65,7 @@ impl CpuClock { cpu_clk: Some(CpuClkConfig::Pll), rc_fast_clk_div_n: Some(RcFastClkDivNConfig::new(0)), rtc_slow_clk: Some(RtcSlowClkConfig::RcSlow), + ble_lp_clk: Some(BleLpClkConfig::Xtal), rtc_fast_clk: Some(RtcFastClkConfig::Rc), low_power_clk: Some(LowPowerClkConfig::RtcSlow), timg_calibration_clock: None, @@ -252,6 +254,7 @@ fn enable_rc_fast_clk_impl(_clocks: &mut ClockTree, en: bool) { // XTAL32K_CLK +#[cfg(use_xtal32k)] fn enable_xtal32k_clk_impl(_clocks: &mut ClockTree, en: bool) { // RTCIO could be configured to allow an external oscillator to be used. We could model this // with a MUX, probably, but this is omitted for now for simplicity. @@ -487,6 +490,7 @@ fn configure_rtc_slow_clk_impl( LPWR::regs().clk_conf().modify(|_, w| unsafe { // TODO: variants should be in PAC w.ana_clk_rtc_sel().bits(match new_config { + #[cfg(use_xtal32k)] RtcSlowClkConfig::Xtal32k => 1, RtcSlowClkConfig::RcSlow => 0, RtcSlowClkConfig::RcFast => 2, @@ -528,6 +532,10 @@ fn configure_low_power_clk_impl( _old_config: Option, new_config: LowPowerClkConfig, ) { + // The divider resets to 255. The Wi-Fi light sleep timer expects the undivided clock. + SYSTEM::regs() + .bt_lpck_div_int() + .modify(|_, w| unsafe { w.bt_lpck_div_num().bits(0) }); SYSTEM::regs().bt_lpck_div_frac().modify(|_, w| { w.lpclk_sel_8m() .bit(new_config == LowPowerClkConfig::RcFast); @@ -535,8 +543,12 @@ fn configure_low_power_clk_impl( .bit(new_config == LowPowerClkConfig::RtcSlow); w.lpclk_sel_xtal() .bit(new_config == LowPowerClkConfig::Xtal); - w.lpclk_sel_xtal32k() - .bit(new_config == LowPowerClkConfig::Xtal32k) + w.lpclk_sel_xtal32k().bit({ + cfg_select! { + use_xtal32k => new_config == LowPowerClkConfig::Xtal32k, + _ => false, + } + }) }); } @@ -575,11 +587,25 @@ fn configure_timg_calibration_clock_impl( w.rtc_cali_clk_sel().bits(match new_config { TimgCalibrationClockConfig::RcSlowClk => 0, TimgCalibrationClockConfig::RcFastDivClk => 1, + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => 2, }) }); } +impl AdcInstance { + // ADC_FUNCTION_CLOCK + + fn enable_function_clock_impl(self, _clocks: &mut ClockTree, en: bool) { + crate::peripherals::APB_SARADC::regs() + .clkm_conf() + .modify(|_, w| unsafe { + w.clk_en().bit(en); + w.clk_sel().bits(if en { 2 } else { 0 }) + }); + } +} + impl SdmInstance { // SDM_FUNCTION_CLOCK @@ -671,3 +697,23 @@ impl TimgInstance { }); } } + +// BLE_LP_XTAL_CLK + +fn enable_ble_lp_xtal_clk_impl(_clocks: &mut ClockTree, _en: bool) { + // Nothing to do. +} + +// BLE_LP_CLK + +fn enable_ble_lp_clk_impl(_clocks: &mut ClockTree, _en: bool) { + // Nothing to do. +} + +fn configure_ble_lp_clk_impl( + _clocks: &mut ClockTree, + _old_config: Option, + _new_config: BleLpClkConfig, +) { + // The BTDM controller programs the source and divider. +} diff --git a/esp-hal/src/soc/esp32c3/mod.rs b/esp-hal/src/soc/esp32c3/mod.rs index 9f02cfadec9..f40ee843db4 100644 --- a/esp-hal/src/soc/esp32c3/mod.rs +++ b/esp-hal/src/soc/esp32c3/mod.rs @@ -13,12 +13,18 @@ pub(crate) mod regi2c; pub(crate) use esp32c3 as pac; -#[cfg(i2s_driver_supported)] -#[cfg_attr(not(feature = "unstable"), allow(unused))] -pub(crate) fn i2s_sclk_frequency() -> u32 { - clocks::pll_160m_frequency() -} - #[cfg(feature = "rt")] pub(crate) fn riscv_preinit() {} pub(crate) fn pre_init() {} + +/// Invalidate a specific range of addresses in the cache. +#[cfg(feature = "unstable")] +#[crate::ram] +pub(crate) unsafe fn cache_invalidate_addr(addr: u32, size: u32) { + unsafe extern "C" { + fn Cache_Invalidate_Addr(addr: u32, size: u32); + } + unsafe { + Cache_Invalidate_Addr(addr, size); + } +} diff --git a/esp-hal/src/soc/esp32c3/regi2c.rs b/esp-hal/src/soc/esp32c3/regi2c.rs index 9dd3f28f93a..abf90f40660 100644 --- a/esp-hal/src/soc/esp32c3/regi2c.rs +++ b/esp-hal/src/soc/esp32c3/regi2c.rs @@ -130,7 +130,9 @@ define_regi2c! { reg: I2C_SAR_REG5(5) { field: ADC_SAR2_DREF(6..4) } - reg: I2C_SAR_REG6(6) {} + reg: I2C_SAR_REG6(6) { + field: I2C_SARADC_TSENS_DAC(3..0) + } reg: I2C_SAR_REG7(7) { field: ADC_SAR2_ENCAL_GND(7..7), field: ADC_SAR2_ENCAL_REF(6..6), diff --git a/esp-hal/src/soc/esp32c3/trng.rs b/esp-hal/src/soc/esp32c3/trng.rs index 8ad1d975045..f23bd0b8a8a 100644 --- a/esp-hal/src/soc/esp32c3/trng.rs +++ b/esp-hal/src/soc/esp32c3/trng.rs @@ -3,7 +3,7 @@ use crate::{ soc::regi2c, }; -/// Enable true randomness by enabling the entropy source. +/// Enables true randomness by enabling the entropy source. /// Blocks `ADC` usage. pub(crate) fn ensure_randomness() { let system = SYSTEM::regs(); @@ -81,7 +81,7 @@ pub(crate) fn ensure_randomness() { } } -/// Disable true randomness. Unlocks `ADC` peripheral. +/// Disables true randomness. Unlocks `ADC` peripheral. pub(crate) fn revert_trng() { let rtc_cntl = LPWR::regs(); let apb_saradc = APB_SARADC::regs(); diff --git a/esp-hal/src/soc/esp32c5/clocks.rs b/esp-hal/src/soc/esp32c5/clocks.rs index 6185291643d..2c75caf8dfa 100644 --- a/esp-hal/src/soc/esp32c5/clocks.rs +++ b/esp-hal/src/soc/esp32c5/clocks.rs @@ -16,7 +16,7 @@ // TODO: This is a temporary place for this, should probably be moved into clocks_ll. use crate::{ - peripherals::{I2C_ANA_MST, LP_CLKRST, PCR, PMU}, + peripherals::{I2C_ANA_MST, LP_CLKRST, MODEM_LPCON, PCR, PMU}, soc::{regi2c, xtal32k}, }; @@ -51,6 +51,7 @@ impl CpuClock { apb_clk: Some(ApbClkConfig::new(0)), lp_fast_clk: Some(LpFastClkConfig::RcFast), lp_slow_clk: Some(xtal32k::default_lp_slow_clk()), + ble_lp_clk: Some(BleLpClkConfig::Xtal), crypto_clk: Some(CryptoClkConfig::PllF480m), iomux_function_clock: Some(IomuxFunctionClockConfig::PllF80m), timg_calibration_clock: None, @@ -63,6 +64,7 @@ impl CpuClock { apb_clk: Some(ApbClkConfig::new(0)), lp_fast_clk: Some(LpFastClkConfig::RcFast), lp_slow_clk: Some(xtal32k::default_lp_slow_clk()), + ble_lp_clk: Some(BleLpClkConfig::Xtal), crypto_clk: Some(CryptoClkConfig::PllF480m), iomux_function_clock: Some(IomuxFunctionClockConfig::PllF80m), timg_calibration_clock: None, @@ -75,6 +77,7 @@ impl CpuClock { apb_clk: Some(ApbClkConfig::new(0)), lp_fast_clk: Some(LpFastClkConfig::RcFast), lp_slow_clk: Some(xtal32k::default_lp_slow_clk()), + ble_lp_clk: Some(BleLpClkConfig::Xtal), crypto_clk: Some(CryptoClkConfig::PllF480m), iomux_function_clock: Some(IomuxFunctionClockConfig::PllF80m), timg_calibration_clock: None, @@ -132,6 +135,16 @@ fn configure_xtal_clk_impl( // PLL_CLK +/// Configures and calibrates the BBPLL again. +/// +/// The BBPLL loses its analog configuration while the PMU powers it down, for example in a light +/// sleep. ESP-IDF configures it again before it uses the PLL after a wake. +pub(crate) fn reconfigure_pll(clocks: &mut ClockTree) { + if clocks.pll_clk_refcount > 0 { + enable_pll_clk_impl(clocks, true); + } +} + fn enable_pll_clk_impl(clocks: &mut ClockTree, en: bool) { if en { PMU::regs().imm_hp_ck_power().write(|w| { @@ -227,6 +240,7 @@ fn enable_rc_fast_clk_impl(_clocks: &mut ClockTree, en: bool) { // XTAL32K_CLK +#[cfg(use_xtal32k)] fn enable_xtal32k_clk_impl(_clocks: &mut ClockTree, en: bool) { LP_CLKRST::regs() .clk_to_hp() @@ -342,6 +356,21 @@ fn configure_hp_root_clk_impl( HpRootClkConfig::PllF240m => 3, }) }); + + bus_clock_update(); +} + +/// Applies the new `soc_clk_sel`, `cpu_div_num` and `ahb_div_num` values. +fn bus_clock_update() { + PCR::regs() + .bus_clk_update() + .write(|w| w.bus_clock_update().set_bit()); + while PCR::regs() + .bus_clk_update() + .read() + .bus_clock_update() + .bit_is_set() + {} } // CPU_CLK @@ -359,9 +388,7 @@ fn configure_cpu_clk_impl( .cpu_freq_conf() .modify(|_, w| unsafe { w.cpu_div_num().bits(new_config.divisor() as u8) }); - PCR::regs() - .bus_clk_update() - .write(|w| w.bus_clock_update().set_bit()); + bus_clock_update(); } // AHB_CLK @@ -379,9 +406,7 @@ fn configure_ahb_clk_impl( .ahb_freq_conf() .modify(|_, w| unsafe { w.ahb_div_num().bits(new_config.divisor() as u8) }); - PCR::regs() - .bus_clk_update() - .write(|w| w.bus_clock_update().set_bit()); + bus_clock_update(); } // APB_CLK @@ -440,6 +465,7 @@ fn configure_lp_slow_clk_impl( LP_CLKRST::regs().lp_clk_conf().modify(|_, w| unsafe { w.slow_clk_sel().bits(match new_config { LpSlowClkConfig::RcSlow => 0, + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => 1, // LpSlowClkConfig::Ext32k => 2, LpSlowClkConfig::OscSlow => 3, @@ -447,6 +473,12 @@ fn configure_lp_slow_clk_impl( }); } +// CRYPTO_PLL_DIV + +fn enable_crypto_pll_div_impl(_clocks: &mut ClockTree, _en: bool) { + // The divider is fixed in hardware, there is nothing to gate. +} + // CRYPTO_CLK fn enable_crypto_clk_impl(_clocks: &mut ClockTree, _en: bool) { @@ -496,6 +528,7 @@ fn configure_timg_calibration_clock_impl( PCR::regs().ctrl_32k_conf().modify(|_, w| unsafe { w._32k_sel().bits(match new_config { TimgCalibrationClockConfig::OscSlowClk => 0, + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => 1, // TimgCalibrationClockConfig::Ext32kClk => 2, TimgCalibrationClockConfig::RcSlowClk => 3, @@ -516,14 +549,14 @@ impl ParlIoInstance { fn configure_rx_clock_impl( self, _clocks: &mut ClockTree, - _old_config: Option, - new_config: ParlIoRxClockConfig, + _old_config: Option, + new_config: ParlIoClkConfig, ) { PCR::regs().parl_clk_rx_conf().modify(|_, w| unsafe { w.parl_clk_rx_sel().bits(match new_config { - ParlIoRxClockConfig::XtalClk => 0, - ParlIoRxClockConfig::RcFastClk => 1, - ParlIoRxClockConfig::PllF240m => 2, + ParlIoClkConfig::XtalClk => 0, + ParlIoClkConfig::RcFastClk => 1, + ParlIoClkConfig::PllF240m => 2, }) }); } @@ -539,14 +572,39 @@ impl ParlIoInstance { fn configure_tx_clock_impl( self, _clocks: &mut ClockTree, - _old_config: Option, - new_config: ParlIoTxClockConfig, + _old_config: Option, + new_config: ParlIoClkConfig, ) { PCR::regs().parl_clk_tx_conf().modify(|_, w| unsafe { w.parl_clk_tx_sel().bits(match new_config { - ParlIoTxClockConfig::XtalClk => 0, - ParlIoTxClockConfig::RcFastClk => 1, - ParlIoTxClockConfig::PllF240m => 2, + ParlIoClkConfig::XtalClk => 0, + ParlIoClkConfig::RcFastClk => 1, + ParlIoClkConfig::PllF240m => 2, + }) + }); + } +} + +impl AdcInstance { + // ADC_FUNCTION_CLOCK + + fn enable_function_clock_impl(self, _clocks: &mut ClockTree, en: bool) { + PCR::regs() + .saradc_clkm_conf() + .modify(|_, w| w.saradc_clkm_en().bit(en)); + } + + fn configure_function_clock_impl( + self, + _clocks: &mut ClockTree, + _old_config: Option, + new_config: AdcFunctionClockConfig, + ) { + PCR::regs().saradc_clkm_conf().modify(|_, w| unsafe { + w.saradc_clkm_sel().bits(match new_config { + AdcFunctionClockConfig::Xtal => 0, + AdcFunctionClockConfig::RcFast => 1, + AdcFunctionClockConfig::PllF80m => 2, }) }); } @@ -665,3 +723,99 @@ impl TimgInstance { }); } } + +impl TwaiInstance { + // TWAI_FUNCTION_CLOCK + + pub(crate) fn enable_function_clock_impl(self, _clocks: &mut ClockTree, en: bool) { + match self { + TwaiInstance::Twai0 => PCR::regs() + .twai0_func_clk_conf() + .modify(|_, w| w.twai0_func_clk_en().bit(en)), + TwaiInstance::Twai1 => PCR::regs() + .twai1_func_clk_conf() + .modify(|_, w| w.twai1_func_clk_en().bit(en)), + }; + } + + pub(crate) fn configure_function_clock_impl( + self, + _clocks: &mut ClockTree, + _old_config: Option, + new_config: TwaiFunctionClockConfig, + ) { + // ESP32-C5 TRM 38.3.1: 0 = XTAL_CLK (reset default), 1 = PLL_F80M_CLK. + let sel = match new_config { + TwaiFunctionClockConfig::Xtal => false, + TwaiFunctionClockConfig::PllF80m => true, + }; + match self { + TwaiInstance::Twai0 => PCR::regs() + .twai0_func_clk_conf() + .modify(|_, w| w.twai0_func_clk_sel().bit(sel)), + TwaiInstance::Twai1 => PCR::regs() + .twai1_func_clk_conf() + .modify(|_, w| w.twai1_func_clk_sel().bit(sel)), + }; + } +} + +// BLE_LP_XTAL_CLK + +fn enable_ble_lp_xtal_clk_impl(_clocks: &mut ClockTree, _en: bool) { + // Nothing to do. +} + +// BLE_LP_RC_SLOW_CLK + +fn enable_ble_lp_rc_slow_clk_impl(_clocks: &mut ClockTree, _en: bool) { + // Nothing to do, divisor and gate are configured in BLE_LP_CLK + // (see modem_clock_select_lp_clock_source() in modem_clock.c). +} + +// BLE_LP_CLK + +fn enable_ble_lp_clk_impl(_clocks: &mut ClockTree, en: bool) { + MODEM_LPCON::regs() + .clk_conf() + .modify(|_, w| w.clk_lp_timer_en().bit(en)); +} + +fn configure_ble_lp_clk_impl( + _clocks: &mut ClockTree, + _old_config: Option, + new_config: BleLpClkConfig, +) { + let divisor = match new_config { + BleLpClkConfig::Xtal => xtal_clk_frequency() / ble_lp_xtal_clk_frequency() - 1, + // Divided by 5 (div_num = 4), see esp_bt_rtc_slow_clk_select() in bt.c. + BleLpClkConfig::RcSlow => rc_slow_clk_frequency() / ble_lp_rc_slow_clk_frequency() - 1, + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => 0, + }; + let sel_xtal32k = cfg_select! { + use_xtal32k => new_config == BleLpClkConfig::Xtal32k, + _ => false, + }; + + MODEM_LPCON::regs() + .test_conf() + .modify(|_, w| w.clk_en().set_bit()); + + MODEM_LPCON::regs().lp_timer_conf().modify(|_, w| unsafe { + w.clk_lp_timer_sel_osc_slow() + .bit(new_config == BleLpClkConfig::RcSlow); + w.clk_lp_timer_sel_osc_fast().clear_bit(); + w.clk_lp_timer_sel_xtal() + .bit(new_config == BleLpClkConfig::Xtal); + w.clk_lp_timer_sel_xtal32k().bit(sel_xtal32k); + w.clk_lp_timer_div_num().bits(divisor as u16) + }); + + if sel_xtal32k { + // 0 routes XTAL32K to the modem 32 kHz input. + MODEM_LPCON::regs() + .modem_32k_clk_conf() + .modify(|_, w| unsafe { w.clk_modem_32k_sel().bits(0) }); + } +} diff --git a/esp-hal/src/soc/esp32c5/mod.rs b/esp-hal/src/soc/esp32c5/mod.rs index 8bf22cce929..5af3f4d9dac 100644 --- a/esp-hal/src/soc/esp32c5/mod.rs +++ b/esp-hal/src/soc/esp32c5/mod.rs @@ -7,17 +7,12 @@ crate::unstable_module! { pub mod clocks; + pub mod trng; } pub(crate) mod regi2c; pub(crate) use esp32c5 as pac; -#[cfg(i2s_driver_supported)] -#[cfg_attr(not(feature = "unstable"), allow(unused))] -pub(crate) fn i2s_sclk_frequency() -> u32 { - clocks::pll_f160m_frequency() -} - #[cfg(feature = "rt")] pub(crate) fn riscv_preinit() {} @@ -36,22 +31,12 @@ pub(crate) fn pre_init() { crate::peripherals::PCR::regs() .reset_event_bypass() .modify(|_, w| w.reset_event_bypass().clear_bit()); -} -pub(crate) fn enable_branch_predictor() { - // Enable branch predictor - // Note that the branch predictor will start cache requests and needs to be disabled when - // the cache is disabled. - // MHCR: CSR 0x7c1 - const MHCR_RS: u32 = 1 << 4; // R/W, address return stack set bit - const MHCR_BFE: u32 = 1 << 5; // R/W, allow predictive jump set bit - const MHCR_BTB: u32 = 1 << 12; // R/W, branch target prediction enable bit - unsafe { - core::arch::asm!("csrrs x0, 0x7c1, {0}", in(reg) MHCR_RS | MHCR_BFE | MHCR_BTB); - } + // Mirrors ESP-IDF's `init_rng`, see + trng::rng_ll_enable(); } -/// Write back a specific range of data in the cache. +/// Writes back a specific range of data in the cache. #[doc(hidden)] #[crate::ram] pub unsafe fn cache_writeback_addr(addr: u32, size: u32) { diff --git a/esp-hal/src/soc/esp32c5/regi2c.rs b/esp-hal/src/soc/esp32c5/regi2c.rs index 7cfd036c6d0..14ab2159393 100644 --- a/esp-hal/src/soc/esp32c5/regi2c.rs +++ b/esp-hal/src/soc/esp32c5/regi2c.rs @@ -134,15 +134,18 @@ define_regi2c! { field: ADC_SAR2_DREF(6..4) } reg: I2C_SAR_REG6(6) {} + // See reg: I2C_SAR_REG7(7) { - field: ADC_SAR2_ENCAL_GND(7..7), - field: ADC_SAR2_ENCAL_REF(6..6), - field: ADC_SAR1_ENCAL_GND(5..5), - field: ADC_SAR1_ENCAL_REF(4..4), - field: ADC_SAR_ENT_RTC(3..3), + field: ADC_SAR_ENT_PERIF(6..6), field: ADC_SAR_ENT_TSENS(2..2), field: ADC_SAR_DTEST_RTC(1..0) } + reg: I2C_SAR_REG8(8) { + field: ADC_SAR2_ENCAL_GND(3..3), + field: ADC_SAR2_EN_TOUT(2..2), + field: ADC_SAR1_ENCAL_GND(1..1), + field: ADC_SAR1_EN_TOUT(0..0) + } } } diff --git a/esp-hal/src/soc/esp32c5/trng.rs b/esp-hal/src/soc/esp32c5/trng.rs new file mode 100644 index 00000000000..198f8197469 --- /dev/null +++ b/esp-hal/src/soc/esp32c5/trng.rs @@ -0,0 +1,145 @@ +use crate::{ + peripherals::{APB_SARADC, PCR, PMU, RNG}, + soc::regi2c, +}; + +// `I2C_SAR_ADC_INIT_CODE_VAL` +const SAR_ADC_INIT_CODE: u16 = 2150; + +// `RNG_LL_CFG_PSCALE` +const RNG_TIMER_PSCALE: u8 = 255; + +// See +pub(crate) fn rng_ll_enable() { + let rng = RNG::regs(); + rng.clk_en().modify(|_, w| w.rng_ck_en().set_bit()); + rng.rng_cfg().modify(|_, w| unsafe { + w.rng_timer_pscale().bits(RNG_TIMER_PSCALE); + w.rng_sample_enable().set_bit(); + w.rtc_timer_en().enable(); + w.rng_timer_en().set_bit() + }); +} + +/// Enables true randomness by enabling the entropy source. +/// Blocks `ADC` usage. +// See +pub(crate) fn ensure_randomness() { + let pcr = PCR::regs(); + let apb_saradc = APB_SARADC::regs(); + + // `sar_periph_ctrl_adc_reset`: the ADC reset also clears the temperature sensor registers + let tsens_ctrl = apb_saradc.tsens_ctrl().read().bits(); + let tsens_ctrl2 = apb_saradc.tsens_ctrl2().read().bits(); + let tsens_wake = apb_saradc.tsens_wake().read().bits(); + let tsens_sample = apb_saradc.tsens_sample().read().bits(); + + pcr.saradc_conf().modify(|_, w| w.saradc_rst_en().set_bit()); + pcr.saradc_conf() + .modify(|_, w| w.saradc_rst_en().clear_bit()); + pcr.saradc_conf() + .modify(|_, w| w.saradc_reg_rst_en().set_bit()); + pcr.saradc_conf() + .modify(|_, w| w.saradc_reg_rst_en().clear_bit()); + + pcr.tsens_clk_conf() + .modify(|_, w| w.tsens_rst_en().set_bit()); + pcr.tsens_clk_conf() + .modify(|_, w| w.tsens_rst_en().clear_bit()); + apb_saradc + .tsens_ctrl() + .write(|w| unsafe { w.bits(tsens_ctrl) }); + apb_saradc + .tsens_ctrl2() + .write(|w| unsafe { w.bits(tsens_ctrl2) }); + apb_saradc + .tsens_wake() + .write(|w| unsafe { w.bits(tsens_wake) }); + apb_saradc + .tsens_sample() + .write(|w| unsafe { w.bits(tsens_sample) }); + + pcr.saradc_conf() + .modify(|_, w| w.saradc_reg_clk_en().set_bit()); + pcr.saradc_clkm_conf().modify(|_, w| unsafe { + w.saradc_clkm_en().set_bit(); + w.saradc_clkm_sel().xtal(); + w.saradc_clkm_div_num().bits(0); + w.saradc_clkm_div_b().bits(0); + w.saradc_clkm_div_a().bits(0) + }); + apb_saradc.ctrl().modify(|_, w| w.sar_clk_gated().set_bit()); + + // `regi2c_ctrl_ll_i2c_sar_periph_enable` + let pmu = PMU::regs(); + pmu.rf_pwc().modify(|_, w| w.perif_i2c_rstb().clear_bit()); + crate::rom::ets_delay_us(1); + pmu.rf_pwc().modify(|_, w| w.xpd_perif_i2c().set_bit()); + pmu.rf_pwc().modify(|_, w| w.perif_i2c_rstb().set_bit()); + + regi2c::ADC_SAR_DTEST_RTC.write_field(0); + regi2c::ADC_SAR_ENT_PERIF.write_field(1); + regi2c::ADC_SAR1_EN_TOUT.write_field(1); + regi2c::ADC_SAR2_EN_TOUT.write_field(1); + + let [init_code_high, init_code_low] = SAR_ADC_INIT_CODE.to_be_bytes(); + regi2c::ADC_SAR1_INITIAL_CODE_HIGH.write_field(init_code_high); + regi2c::ADC_SAR1_INITIAL_CODE_LOW.write_field(init_code_low); + regi2c::ADC_SAR2_INITIAL_CODE_HIGH.write_field(init_code_high); + regi2c::ADC_SAR2_INITIAL_CODE_LOW.write_field(init_code_low); + + apb_saradc.sar_patt_tab1().modify(|_, w| unsafe { + w.item0_unit().adc1(); + w.item0_channel().bits(7); + w.item0_atten().db12(); + w.item1_unit().adc2(); + w.item1_channel().bits(1); + w.item1_atten().db12() + }); + apb_saradc + .ctrl() + .modify(|_, w| unsafe { w.sar_patt_len().bits(1) }); + + pcr.sar_clk_div() + .modify(|_, w| unsafe { w.sar1_clk_div_num().bits(15) }); + + apb_saradc.ctrl2().modify(|_, w| unsafe { + w.timer_target().bits(200); + w.timer_en().set_bit() + }); + + rng_ll_enable(); +} + +/// Disables true randomness. Unlocks `ADC` peripheral. +// See +pub(crate) fn revert_trng() { + let apb_saradc = APB_SARADC::regs(); + + // `rng_ll_disable` is skipped: `Rng` keeps using the RNG. + + apb_saradc.ctrl2().modify(|_, w| w.timer_en().clear_bit()); + + apb_saradc.sar_patt_tab1().reset(); + apb_saradc.sar_patt_tab2().reset(); + + regi2c::ADC_SAR1_INITIAL_CODE_HIGH.write_field(0); + regi2c::ADC_SAR1_INITIAL_CODE_LOW.write_field(0); + regi2c::ADC_SAR2_INITIAL_CODE_HIGH.write_field(0); + regi2c::ADC_SAR2_INITIAL_CODE_LOW.write_field(0); + + regi2c::ADC_SAR_DTEST_RTC.write_field(0); + regi2c::ADC_SAR_ENT_PERIF.write_field(0); + regi2c::ADC_SAR1_EN_TOUT.write_field(0); + regi2c::ADC_SAR2_EN_TOUT.write_field(0); + + // `regi2c_saradc_disable` is skipped: PERIF_I2C stays powered as set up by + // `rtc_cntl::rtc::init`. + + PCR::regs().saradc_clkm_conf().modify(|_, w| unsafe { + w.saradc_clkm_div_num().bits(4); + w.saradc_clkm_div_b().bits(0); + w.saradc_clkm_div_a().bits(0); + w.saradc_clkm_sel().xtal() + }); +} diff --git a/esp-hal/src/soc/esp32c6/clocks.rs b/esp-hal/src/soc/esp32c6/clocks.rs index 0d550204e2f..b0090eab4dc 100644 --- a/esp-hal/src/soc/esp32c6/clocks.rs +++ b/esp-hal/src/soc/esp32c6/clocks.rs @@ -17,7 +17,9 @@ // TODO: This is a temporary place for this, should probably be moved into clocks_ll. use crate::{ - peripherals::{I2C_ANA_MST, LP_CLKRST, PCR, PMU, TIMG0}, + efuse::ChipRevision, + peripherals::{I2C_ANA_MST, LP_CLKRST, MODEM_LPCON, PCR, PMU, TIMG0}, + rtc_cntl::rtc::ICG_NOGATING_SLEEP, soc::{regi2c, xtal32k}, }; @@ -56,6 +58,7 @@ impl CpuClock { iomux_function_clock: Some(IomuxFunctionClockConfig::PllF80m), lp_fast_clk: Some(LpFastClkConfig::RcFastClk), lp_slow_clk: Some(xtal32k::default_lp_slow_clk()), + ble_lp_clk: Some(BleLpClkConfig::Xtal), timg_calibration_clock: None, }; const PRESET_160: ClockConfig = ClockConfig { @@ -73,6 +76,7 @@ impl CpuClock { iomux_function_clock: Some(IomuxFunctionClockConfig::PllF80m), lp_fast_clk: Some(LpFastClkConfig::RcFastClk), lp_slow_clk: Some(xtal32k::default_lp_slow_clk()), + ble_lp_clk: Some(BleLpClkConfig::Xtal), timg_calibration_clock: None, }; } @@ -128,6 +132,16 @@ fn configure_xtal_clk_impl( // PLL_CLK +/// Configures and calibrates the BBPLL again. +/// +/// The BBPLL loses its analog configuration while the PMU powers it down, for example in a light +/// sleep. ESP-IDF configures it again before it uses the PLL after a wake. +pub(crate) fn reconfigure_pll(clocks: &mut ClockTree) { + if clocks.pll_clk_refcount > 0 { + enable_pll_clk_impl(clocks, true); + } +} + fn enable_pll_clk_impl(_clocks: &mut ClockTree, en: bool) { if en { // TODO: these are WT fields, PAC should be fixed accordingly @@ -210,6 +224,7 @@ fn enable_rc_fast_clk_impl(_clocks: &mut ClockTree, en: bool) { // XTAL32K_CLK +#[cfg(use_xtal32k)] fn enable_xtal32k_clk_impl(_clocks: &mut ClockTree, en: bool) { LP_CLKRST::regs().xtal32k().write(|w| unsafe { w.dac_xtal32k().bits(3); @@ -539,6 +554,7 @@ fn configure_lp_slow_clk_impl( ) { LP_CLKRST::regs().lp_clk_conf().modify(|_, w| unsafe { w.slow_clk_sel().bits(match new_config { + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => 1, LpSlowClkConfig::RcSlow => 0, LpSlowClkConfig::OscSlow => 2, @@ -562,6 +578,7 @@ fn configure_timg_calibration_clock_impl( w.rtc_cali_clk_sel().bits(match new_config { TimgCalibrationClockConfig::RcSlowClk => 0, TimgCalibrationClockConfig::RcFastDivClk => 1, + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => 2, }) }); @@ -604,14 +621,14 @@ impl ParlIoInstance { fn configure_rx_clock_impl( self, _clocks: &mut ClockTree, - _old_config: Option, - new_config: ParlIoRxClockConfig, + _old_config: Option, + new_config: ParlIoClkConfig, ) { PCR::regs().parl_clk_rx_conf().modify(|_, w| unsafe { w.parl_clk_rx_sel().bits(match new_config { - ParlIoRxClockConfig::XtalClk => 0, - ParlIoRxClockConfig::RcFastClk => 2, - ParlIoRxClockConfig::PllF240m => 1, + ParlIoClkConfig::XtalClk => 0, + ParlIoClkConfig::RcFastClk => 2, + ParlIoClkConfig::PllF240m => 1, }) }); } @@ -627,14 +644,39 @@ impl ParlIoInstance { fn configure_tx_clock_impl( self, _clocks: &mut ClockTree, - _old_config: Option, - new_config: ParlIoTxClockConfig, + _old_config: Option, + new_config: ParlIoClkConfig, ) { PCR::regs().parl_clk_tx_conf().modify(|_, w| unsafe { w.parl_clk_tx_sel().bits(match new_config { - ParlIoTxClockConfig::XtalClk => 0, - ParlIoTxClockConfig::RcFastClk => 2, - ParlIoTxClockConfig::PllF240m => 1, + ParlIoClkConfig::XtalClk => 0, + ParlIoClkConfig::RcFastClk => 2, + ParlIoClkConfig::PllF240m => 1, + }) + }); + } +} + +impl AdcInstance { + // ADC_FUNCTION_CLOCK + + fn enable_function_clock_impl(self, _clocks: &mut ClockTree, en: bool) { + PCR::regs() + .saradc_clkm_conf() + .modify(|_, w| w.saradc_clkm_en().bit(en)); + } + + fn configure_function_clock_impl( + self, + _clocks: &mut ClockTree, + _old_config: Option, + new_config: AdcFunctionClockConfig, + ) { + PCR::regs().saradc_clkm_conf().modify(|_, w| unsafe { + w.saradc_clkm_sel().bits(match new_config { + AdcFunctionClockConfig::Xtal => 0, + AdcFunctionClockConfig::PllF80m => 1, + AdcFunctionClockConfig::RcFast => 2, }) }); } @@ -746,3 +788,98 @@ impl TimgInstance { }); } } + +// BLE_LP_XTAL_CLK + +/// Returns whether the BLE timer gets the crystal via the Wi-Fi power clock (crystal / 80). +fn ble_timer_uses_wifi_pwr_clk() -> bool { + crate::soc::chip_revision_above(ChipRevision::from_combined(1)) +} + +// https://github.com/espressif/esp-idf/blob/ce2100d/components/esp_hw_support/modem/port/esp32c6/modem_clock_impl.c#L335-L348 +fn enable_ble_lp_xtal_clk_impl(_clocks: &mut ClockTree, en: bool) { + if !ble_timer_uses_wifi_pwr_clk() { + return; + } + + // `rtc::init` turns the Wi-Fi power clock on for good. + MODEM_LPCON::regs() + .clk_conf_power_st() + .modify(|r, w| unsafe { + let map = r.clk_wifipwr_st_map().bits(); + w.clk_wifipwr_st_map().bits(if en { + map | ICG_NOGATING_SLEEP + } else { + map & !ICG_NOGATING_SLEEP + }) + }); +} + +pub(crate) fn wifi_pwr_clk_runs_in_sleep() -> bool { + let map = MODEM_LPCON::regs() + .clk_conf_power_st() + .read() + .clk_wifipwr_st_map() + .bits(); + (map & ICG_NOGATING_SLEEP) != 0 +} + +// BLE_LP_RC_SLOW_CLK + +fn enable_ble_lp_rc_slow_clk_impl(_clocks: &mut ClockTree, _en: bool) { + // Nothing to do, divisor and gate are configured in BLE_LP_CLK + // (see modem_clock_select_lp_clock_source() in modem_clock.c). +} + +// BLE_LP_CLK + +fn enable_ble_lp_clk_impl(_clocks: &mut ClockTree, en: bool) { + MODEM_LPCON::regs() + .clk_conf() + .modify(|_, w| w.clk_lp_timer_en().bit(en)); +} + +fn configure_ble_lp_clk_impl( + _clocks: &mut ClockTree, + _old_config: Option, + new_config: BleLpClkConfig, +) { + let divisor = match new_config { + BleLpClkConfig::Xtal => { + let mut ratio = xtal_clk_frequency() / ble_lp_xtal_clk_frequency(); + if ble_timer_uses_wifi_pwr_clk() { + ratio /= 80; + } + ratio - 1 + } + // Divided by 5 (div_num = 4), see esp_bt_rtc_slow_clk_select() in bt.c. + BleLpClkConfig::RcSlow => rc_slow_clk_frequency() / ble_lp_rc_slow_clk_frequency() - 1, + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => 0, + }; + let sel_xtal32k = cfg_select! { + use_xtal32k => new_config == BleLpClkConfig::Xtal32k, + _ => false, + }; + + MODEM_LPCON::regs() + .test_conf() + .modify(|_, w| w.clk_en().set_bit()); + + MODEM_LPCON::regs().lp_timer_conf().modify(|_, w| unsafe { + w.clk_lp_timer_sel_osc_slow() + .bit(new_config == BleLpClkConfig::RcSlow); + w.clk_lp_timer_sel_osc_fast().clear_bit(); + w.clk_lp_timer_sel_xtal() + .bit(new_config == BleLpClkConfig::Xtal); + w.clk_lp_timer_sel_xtal32k().bit(sel_xtal32k); + w.clk_lp_timer_div_num().bits(divisor as u16) + }); + + if sel_xtal32k { + // 0 routes XTAL32K to the modem 32 kHz input. + MODEM_LPCON::regs() + .modem_32k_clk_conf() + .modify(|_, w| unsafe { w.clk_modem_32k_sel().bits(0) }); + } +} diff --git a/esp-hal/src/soc/esp32c6/lp_core.rs b/esp-hal/src/soc/esp32c6/lp_core.rs index b0394ba7527..2561946d2ff 100644 --- a/esp-hal/src/soc/esp32c6/lp_core.rs +++ b/esp-hal/src/soc/esp32c6/lp_core.rs @@ -34,7 +34,7 @@ pub enum LpCoreWakeupSource { HpCpu, } -/// Clock sources for the LP core +/// Clock sources for the LP core. #[derive(Debug, Clone, Copy)] pub enum LpCoreClockSource { /// 17.5 MHz clock @@ -51,12 +51,12 @@ pub struct LpCore<'d> { } impl<'d> LpCore<'d> { - /// Create a new instance using [LpCoreClockSource::RcFastClk] + /// Creates a new instance using [LpCoreClockSource::RcFastClk]. pub fn new(lp_core: LP_CORE<'d>) -> Self { LpCore::new_with_clock(lp_core, LpCoreClockSource::RcFastClk) } - /// Create a new instance using the given clock + /// Creates a new instance using the given clock. pub fn new_with_clock(lp_core: LP_CORE<'d>, clk_src: LpCoreClockSource) -> Self { match clk_src { LpCoreClockSource::RcFastClk => LPWR::regs() @@ -78,21 +78,21 @@ impl<'d> LpCore<'d> { this } - /// Stop the LP core + /// Stops the LP core. pub fn stop(&mut self) { ulp_lp_core_stop(); } - /// Start the LP core + /// Starts the LP core. pub fn run(&mut self, wakeup_src: LpCoreWakeupSource) { ulp_lp_core_run(wakeup_src); } /// Lets the LP core wake the chip from sleep. /// - /// The request stays until you call [`Self::disable_wakeup`]. It stays through a sleep, through - /// a deep-sleep wake, and after a drop of this driver. While the chip is awake, it does - /// nothing. + /// The request stays until [`Self::disable_wakeup`] is called. It stays through a sleep, + /// through a deep-sleep wake, and after a drop of this driver. While the chip is awake, it + /// does nothing. pub fn enable_wakeup(&mut self) { WakeupSource::LpCore.enable_with_hooks(Some(keep_low_power_domain), None); } diff --git a/esp-hal/src/soc/esp32c6/mod.rs b/esp-hal/src/soc/esp32c6/mod.rs index c98213f6db0..d7e75a1fee4 100644 --- a/esp-hal/src/soc/esp32c6/mod.rs +++ b/esp-hal/src/soc/esp32c6/mod.rs @@ -17,12 +17,6 @@ pub(crate) mod regi2c; pub(crate) use esp32c6 as pac; -#[cfg(i2s_driver_supported)] -#[cfg_attr(not(feature = "unstable"), allow(unused))] -pub(crate) fn i2s_sclk_frequency() -> u32 { - clocks::pll_f160m_frequency() -} - #[cfg(feature = "rt")] pub(crate) fn riscv_preinit() {} @@ -44,4 +38,19 @@ pub(crate) fn pre_init() { crate::peripherals::HP_APM::regs() .func_ctrl() .write(|w| unsafe { w.bits(0x0) }); + + // Mirrors ESP-IDF's `init_rng`, see + trng::rng_ll_enable(); +} + +/// Invalidate a specific range of addresses in the cache. +#[cfg(feature = "unstable")] +#[crate::ram] +pub(crate) unsafe fn cache_invalidate_addr(addr: u32, size: u32) { + unsafe extern "C" { + fn Cache_Invalidate_Addr(addr: u32, size: u32); + } + unsafe { + Cache_Invalidate_Addr(addr, size); + } } diff --git a/esp-hal/src/soc/esp32c6/regi2c.rs b/esp-hal/src/soc/esp32c6/regi2c.rs index cec300f8769..d900f17d1d5 100644 --- a/esp-hal/src/soc/esp32c6/regi2c.rs +++ b/esp-hal/src/soc/esp32c6/regi2c.rs @@ -133,7 +133,9 @@ define_regi2c! { reg: I2C_SAR_REG5(5) { field: ADC_SAR2_DREF(6..4) } - reg: I2C_SAR_REG6(6) {} + reg: I2C_SAR_REG6(6) { + field: I2C_SARADC_TSENS_DAC(3..0) + } reg: I2C_SAR_REG7(7) { field: ADC_SAR2_ENCAL_GND(7..7), field: ADC_SAR2_ENCAL_REF(6..6), diff --git a/esp-hal/src/soc/esp32c6/trng.rs b/esp-hal/src/soc/esp32c6/trng.rs index 412aeee0f02..c3374a8a78c 100644 --- a/esp-hal/src/soc/esp32c6/trng.rs +++ b/esp-hal/src/soc/esp32c6/trng.rs @@ -1,15 +1,21 @@ use crate::{ - peripherals::{APB_SARADC, PCR}, + peripherals::{APB_SARADC, LP_PERI, PCR}, soc::regi2c, }; -const SAR2_CHANNEL: u32 = 9; -const SAR2_ATTEN: u32 = 1; -const SAR1_ATTEN: u32 = 1; -const PATTERN_BIT_WIDTH: u32 = 6; +// `I2C_SAR_ADC_INIT_CODE_VAL`, see +const SAR_ADC_INIT_CODE: u16 = 2150; -/// Enable true randomness by enabling the entropy source. +// See +pub(crate) fn rng_ll_enable() { + LP_PERI::regs() + .clk_en() + .modify(|_, w| w.rng_ck_en().set_bit()); +} + +/// Enables true randomness by enabling the entropy source. /// Blocks `ADC` usage. +// See pub(crate) fn ensure_randomness() { let pcr = PCR::regs(); let apb_saradc = APB_SARADC::regs(); @@ -31,12 +37,16 @@ pub(crate) fn ensure_randomness() { // Select XTAL clock (40 MHz) source for ADC_CTRL_CLK pcr.saradc_clkm_conf() - .modify(|_, w| w.saradc_clkm_sel().bits(0)); + .modify(|_, w| w.saradc_clkm_sel().xtal()); + apb_saradc.ctrl().modify(|_, w| w.sar_clk_gated().set_bit()); // Set the clock divider for ADC_CTRL_CLK to default value (in case it has been // changed) - pcr.saradc_clkm_conf() - .modify(|_, w| w.saradc_clkm_div_num().bits(0)); + pcr.saradc_clkm_conf().modify(|_, w| { + w.saradc_clkm_div_num().bits(0); + w.saradc_clkm_div_b().bits(0); + w.saradc_clkm_div_a().bits(0) + }); // Config ADC circuit (Analog part) with I2C(HOST ID 0x69) and chose internal // voltage as sampling source @@ -44,20 +54,20 @@ pub(crate) fn ensure_randomness() { regi2c::ADC_SAR_ENT_RTC.write_field(1); regi2c::ADC_SAR1_ENCAL_REF.write_field(1); regi2c::ADC_SAR2_ENCAL_REF.write_field(1); - regi2c::ADC_SAR2_INITIAL_CODE_HIGH.write_field(0x08); - regi2c::ADC_SAR2_INITIAL_CODE_LOW.write_field(0x66); - regi2c::ADC_SAR1_INITIAL_CODE_HIGH.write_field(0x08); - regi2c::ADC_SAR1_INITIAL_CODE_LOW.write_field(0x66); - - // create patterns and set them in pattern table - let pattern_one: u32 = (SAR2_CHANNEL << 2) | SAR2_ATTEN; // we want channel 9 with max attenuation - let pattern_two: u32 = SAR1_ATTEN; // we want channel 0 with max attenuation, channel doesn't really matter here - let pattern_table: u32 = - (pattern_two << (3 * PATTERN_BIT_WIDTH)) | (pattern_one << (2 * PATTERN_BIT_WIDTH)); - - apb_saradc - .sar_patt_tab1() - .modify(|_, w| w.bits(pattern_table)); + let [init_code_high, init_code_low] = SAR_ADC_INIT_CODE.to_be_bytes(); + regi2c::ADC_SAR2_INITIAL_CODE_HIGH.write_field(init_code_high); + regi2c::ADC_SAR2_INITIAL_CODE_LOW.write_field(init_code_low); + regi2c::ADC_SAR1_INITIAL_CODE_HIGH.write_field(init_code_high); + regi2c::ADC_SAR1_INITIAL_CODE_LOW.write_field(init_code_low); + + apb_saradc.sar_patt_tab1().modify(|_, w| { + w.item0_unit().adc2(); + w.item0_channel().bits(1); + w.item0_atten().db2_5(); + w.item1_unit().adc2(); + w.item1_channel().bits(1); + w.item1_atten().db2_5() + }); // set pattern length to 2 (APB_SARADC_SAR_PATT_LEN counts from 0) apb_saradc.ctrl().modify(|_, w| w.sar_patt_len().bits(1)); @@ -71,32 +81,27 @@ pub(crate) fn ensure_randomness() { // enable timer apb_saradc.ctrl2().modify(|_, w| w.timer_en().set_bit()); } + + rng_ll_enable(); } -/// Disable true randomness. Unlocks `ADC` peripheral. +/// Disables true randomness. Unlocks `ADC` peripheral. pub(crate) fn revert_trng() { - unsafe { - APB_SARADC::regs() - .ctrl2() - .modify(|_, w| w.timer_en().clear_bit()); - - APB_SARADC::regs() - .sar_patt_tab1() - .modify(|_, w| w.bits(0xFFFFFF)); - - regi2c::ADC_SAR2_INITIAL_CODE_HIGH.write_field(0x60); - regi2c::ADC_SAR2_INITIAL_CODE_LOW.write_field(0); - regi2c::ADC_SAR1_INITIAL_CODE_HIGH.write_field(0x60); - regi2c::ADC_SAR1_INITIAL_CODE_LOW.write_field(0); - regi2c::ADC_SAR_DTEST_RTC.write_field(0); - regi2c::ADC_SAR_ENT_RTC.write_field(0); - regi2c::ADC_SAR1_ENCAL_REF.write_field(0); - regi2c::ADC_SAR2_ENCAL_REF.write_field(0); - - PCR::regs() - .saradc_clkm_conf() - .modify(|_, w| w.bits(0x00404000)); - - PCR::regs().saradc_conf().modify(|_, w| w.bits(0x5)); - } + APB_SARADC::regs() + .ctrl2() + .modify(|_, w| w.timer_en().clear_bit()); + + APB_SARADC::regs().sar_patt_tab1().reset(); + + regi2c::ADC_SAR2_INITIAL_CODE_HIGH.write_field(0); + regi2c::ADC_SAR2_INITIAL_CODE_LOW.write_field(0); + regi2c::ADC_SAR1_INITIAL_CODE_HIGH.write_field(0); + regi2c::ADC_SAR1_INITIAL_CODE_LOW.write_field(0); + regi2c::ADC_SAR_DTEST_RTC.write_field(0); + regi2c::ADC_SAR_ENT_RTC.write_field(0); + regi2c::ADC_SAR1_ENCAL_REF.write_field(0); + regi2c::ADC_SAR2_ENCAL_REF.write_field(0); + + PCR::regs().saradc_clkm_conf().reset(); + PCR::regs().saradc_conf().reset(); } diff --git a/esp-hal/src/soc/esp32c61/clocks.rs b/esp-hal/src/soc/esp32c61/clocks.rs index d1a49d74424..2a818184d1d 100644 --- a/esp-hal/src/soc/esp32c61/clocks.rs +++ b/esp-hal/src/soc/esp32c61/clocks.rs @@ -14,7 +14,7 @@ #![allow(missing_docs, reason = "Experimental")] use crate::{ - peripherals::{I2C_ANA_MST, LP_CLKRST, PCR, PMU}, + peripherals::{I2C_ANA_MST, LP_CLKRST, MODEM_LPCON, PCR, PMU}, soc::{regi2c, xtal32k}, }; @@ -46,6 +46,8 @@ impl CpuClock { apb_clk: Some(ApbClkConfig::new(0)), lp_fast_clk: Some(LpFastClkConfig::RcFast), lp_slow_clk: Some(xtal32k::default_lp_slow_clk()), + ble_lp_clk: Some(BleLpClkConfig::Xtal), + crypto_clk: Some(CryptoClkConfig::PllF480m), timg_calibration_clock: None, }; const PRESET_160: ClockConfig = ClockConfig { @@ -56,6 +58,8 @@ impl CpuClock { apb_clk: Some(ApbClkConfig::new(0)), lp_fast_clk: Some(LpFastClkConfig::RcFast), lp_slow_clk: Some(xtal32k::default_lp_slow_clk()), + ble_lp_clk: Some(BleLpClkConfig::Xtal), + crypto_clk: Some(CryptoClkConfig::PllF480m), timg_calibration_clock: None, }; } @@ -103,6 +107,16 @@ fn configure_xtal_clk_impl( // Nothing to do here. } +/// Configures and calibrates the BBPLL again. +/// +/// The BBPLL loses its analog configuration while the PMU powers it down, for example in a light +/// sleep. ESP-IDF configures it again before it uses the PLL after a wake. +pub(crate) fn reconfigure_pll(clocks: &mut ClockTree) { + if clocks.pll_clk_refcount > 0 { + enable_pll_clk_impl(clocks, true); + } +} + fn enable_pll_clk_impl(_clocks: &mut ClockTree, en: bool) { if en { PMU::regs().imm_hp_ck_power().write(|w| { @@ -179,6 +193,7 @@ fn enable_rc_fast_clk_impl(_clocks: &mut ClockTree, en: bool) { // XTAL32K_CLK +#[cfg(use_xtal32k)] fn enable_xtal32k_clk_impl(_clocks: &mut ClockTree, en: bool) { LP_CLKRST::regs() .clk_to_hp() @@ -277,6 +292,21 @@ fn configure_hp_root_clk_impl( HpRootClkConfig::PllF160m => 2, }) }); + + bus_clock_update(); +} + +/// Applies the new `soc_clk_sel`, `cpu_div_num` and `ahb_div_num` values. +fn bus_clock_update() { + PCR::regs() + .bus_clk_update() + .write(|w| w.bus_clock_update().set_bit()); + while PCR::regs() + .bus_clk_update() + .read() + .bus_clock_update() + .bit_is_set() + {} } // CPU_CLK @@ -294,9 +324,7 @@ fn configure_cpu_clk_impl( .cpu_freq_conf() .modify(|_, w| unsafe { w.cpu_div_num().bits(new_config.divisor() as u8) }); - PCR::regs() - .bus_clk_update() - .write(|w| w.bus_clock_update().set_bit()); + bus_clock_update(); } // AHB_CLK @@ -314,9 +342,7 @@ fn configure_ahb_clk_impl( .ahb_freq_conf() .modify(|_, w| unsafe { w.ahb_div_num().bits(new_config.divisor() as u8) }); - PCR::regs() - .bus_clk_update() - .write(|w| w.bus_clock_update().set_bit()); + bus_clock_update(); } // APB_CLK @@ -375,6 +401,7 @@ fn configure_lp_slow_clk_impl( LP_CLKRST::regs().lp_clk_conf().modify(|_, w| unsafe { w.slow_clk_sel().bits(match new_config { LpSlowClkConfig::RcSlow => 0, + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => 1, // LpSlowClkConfig::Ext32k => 2, LpSlowClkConfig::OscSlow => 3, @@ -382,6 +409,32 @@ fn configure_lp_slow_clk_impl( }); } +// CRYPTO_PLL_DIV + +fn enable_crypto_pll_div_impl(_clocks: &mut ClockTree, _en: bool) { + // The divider is fixed in hardware, there is nothing to gate. +} + +// CRYPTO_CLK + +fn enable_crypto_clk_impl(_clocks: &mut ClockTree, _en: bool) { + // Nothing to do here. +} + +fn configure_crypto_clk_impl( + _clocks: &mut ClockTree, + _old_config: Option, + new_config: CryptoClkConfig, +) { + PCR::regs().sec_conf().modify(|_, w| unsafe { + w.sec_clk_sel().bits(match new_config { + CryptoClkConfig::Xtal => 0, + CryptoClkConfig::RcFast => 1, + CryptoClkConfig::PllF480m => 2, + }) + }); +} + // TIMG_CALIBRATION_CLOCK fn enable_timg_calibration_clock_impl(_clocks: &mut ClockTree, _en: bool) { @@ -396,6 +449,7 @@ fn configure_timg_calibration_clock_impl( PCR::regs().ctrl_32k_conf().modify(|_, w| unsafe { w._32k_sel().bits(match new_config { TimgCalibrationClockConfig::OscSlowClk => 0, + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => 1, // TimgCalibrationClockConfig::Ext32kClk => 2, TimgCalibrationClockConfig::RcSlowClk => 3, @@ -404,6 +458,31 @@ fn configure_timg_calibration_clock_impl( }); } +impl AdcInstance { + // ADC_FUNCTION_CLOCK + + fn enable_function_clock_impl(self, _clocks: &mut ClockTree, en: bool) { + PCR::regs() + .saradc_clkm_conf() + .modify(|_, w| w.saradc_clkm_en().bit(en)); + } + + fn configure_function_clock_impl( + self, + _clocks: &mut ClockTree, + _old_config: Option, + new_config: AdcFunctionClockConfig, + ) { + PCR::regs().saradc_clkm_conf().modify(|_, w| unsafe { + w.saradc_clkm_sel().bits(match new_config { + AdcFunctionClockConfig::Xtal => 0, + AdcFunctionClockConfig::RcFast => 1, + AdcFunctionClockConfig::PllF80m => 2, + }) + }); + } +} + impl TimgInstance { // TIMG_FUNCTION_CLOCK @@ -478,3 +557,63 @@ impl TimgInstance { }); } } + +// BLE_LP_XTAL_CLK + +fn enable_ble_lp_xtal_clk_impl(_clocks: &mut ClockTree, _en: bool) { + // Nothing to do. +} + +// BLE_LP_RC_SLOW_CLK + +fn enable_ble_lp_rc_slow_clk_impl(_clocks: &mut ClockTree, _en: bool) { + // Nothing to do, divisor and gate are configured in BLE_LP_CLK + // (see modem_clock_select_lp_clock_source() in modem_clock.c). +} + +// BLE_LP_CLK + +fn enable_ble_lp_clk_impl(_clocks: &mut ClockTree, en: bool) { + MODEM_LPCON::regs() + .clk_conf() + .modify(|_, w| w.clk_lp_timer_en().bit(en)); +} + +fn configure_ble_lp_clk_impl( + _clocks: &mut ClockTree, + _old_config: Option, + new_config: BleLpClkConfig, +) { + let divisor = match new_config { + BleLpClkConfig::Xtal => xtal_clk_frequency() / ble_lp_xtal_clk_frequency() - 1, + // Divided by 5 (div_num = 4), see esp_bt_rtc_slow_clk_select() in esp32c6/bt.c. + BleLpClkConfig::RcSlow => rc_slow_clk_frequency() / ble_lp_rc_slow_clk_frequency() - 1, + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => 0, + }; + let sel_xtal32k = cfg_select! { + use_xtal32k => new_config == BleLpClkConfig::Xtal32k, + _ => false, + }; + + MODEM_LPCON::regs() + .test_conf() + .modify(|_, w| w.clk_en().set_bit()); + + MODEM_LPCON::regs().lp_timer_conf().modify(|_, w| unsafe { + w.clk_lp_timer_sel_osc_slow() + .bit(new_config == BleLpClkConfig::RcSlow); + w.clk_lp_timer_sel_osc_fast().clear_bit(); + w.clk_lp_timer_sel_xtal() + .bit(new_config == BleLpClkConfig::Xtal); + w.clk_lp_timer_sel_xtal32k().bit(sel_xtal32k); + w.clk_lp_timer_div_num().bits(divisor as u16) + }); + + if sel_xtal32k { + // 0 routes XTAL32K to the modem 32 kHz input. + MODEM_LPCON::regs() + .modem_32k_clk_conf() + .modify(|_, w| unsafe { w.clk_modem_32k_sel().bits(0) }); + } +} diff --git a/esp-hal/src/soc/esp32c61/mod.rs b/esp-hal/src/soc/esp32c61/mod.rs index c245c945c96..b5894d0f247 100644 --- a/esp-hal/src/soc/esp32c61/mod.rs +++ b/esp-hal/src/soc/esp32c61/mod.rs @@ -7,17 +7,12 @@ crate::unstable_module! { pub mod clocks; + pub mod trng; } pub(crate) mod regi2c; pub(crate) use esp32c61 as pac; -#[cfg(i2s_driver_supported)] -#[cfg_attr(not(feature = "unstable"), allow(unused))] -pub(crate) fn i2s_sclk_frequency() -> u32 { - clocks::pll_f160m_frequency() -} - #[cfg(feature = "rt")] pub(crate) fn riscv_preinit() {} @@ -37,22 +32,12 @@ pub(crate) fn pre_init() { crate::peripherals::PCR::regs() .reset_event_bypass() .modify(|_, w| w.reset_event_bypass().clear_bit()); -} -pub(crate) fn enable_branch_predictor() { - // Enable branch predictor - // Note that the branch predictor will start cache requests and needs to be disabled when - // the cache is disabled. - // MHCR: CSR 0x7c1 - const MHCR_RS: u32 = 1 << 4; // R/W, address return stack set bit - const MHCR_BFE: u32 = 1 << 5; // R/W, allow predictive jump set bit - const MHCR_BTB: u32 = 1 << 12; // R/W, branch target prediction enable bit - unsafe { - core::arch::asm!("csrrs x0, 0x7c1, {0}", in(reg) MHCR_RS | MHCR_BFE | MHCR_BTB); - } + // Mirrors ESP-IDF's `init_rng`, see + trng::rng_ll_enable(); } -/// Write back a specific range of data in the cache. +/// Writes back a specific range of data in the cache. #[doc(hidden)] #[crate::ram] pub unsafe fn cache_writeback_addr(addr: u32, size: u32) { diff --git a/esp-hal/src/soc/esp32c61/trng.rs b/esp-hal/src/soc/esp32c61/trng.rs new file mode 100644 index 00000000000..a9f0785a8e5 --- /dev/null +++ b/esp-hal/src/soc/esp32c61/trng.rs @@ -0,0 +1,145 @@ +use crate::{ + peripherals::{APB_SARADC, PCR, PMU, RNG}, + soc::regi2c, +}; + +// `I2C_SAR_ADC_INIT_CODE_VAL` +const SAR_ADC_INIT_CODE: u16 = 2150; + +// `RNG_LL_CFG_PSCALE` +const RNG_TIMER_PSCALE: u8 = 255; + +// See +pub(crate) fn rng_ll_enable() { + let rng = RNG::regs(); + rng.clk_en().modify(|_, w| w.rng_ck_en().set_bit()); + rng.rng_cfg().modify(|_, w| unsafe { + w.rng_timer_pscale().bits(RNG_TIMER_PSCALE); + w.rng_sample_enable().set_bit(); + w.rtc_timer_en().enable(); + w.rng_timer_en().set_bit() + }); +} + +/// Enables true randomness by enabling the entropy source. +/// Blocks `ADC` usage. +// See +pub(crate) fn ensure_randomness() { + let pcr = PCR::regs(); + let apb_saradc = APB_SARADC::regs(); + + // `sar_periph_ctrl_adc_reset`: the ADC reset also clears the temperature sensor registers + let tsens_ctrl = apb_saradc.tsens_ctrl().read().bits(); + let tsens_ctrl2 = apb_saradc.tsens_ctrl2().read().bits(); + let tsens_wake = apb_saradc.tsens_wake().read().bits(); + let tsens_sample = apb_saradc.tsens_sample().read().bits(); + + pcr.saradc_conf().modify(|_, w| w.saradc_rst_en().set_bit()); + pcr.saradc_conf() + .modify(|_, w| w.saradc_rst_en().clear_bit()); + pcr.saradc_conf() + .modify(|_, w| w.saradc_reg_rst_en().set_bit()); + pcr.saradc_conf() + .modify(|_, w| w.saradc_reg_rst_en().clear_bit()); + + pcr.tsens_clk_conf() + .modify(|_, w| w.tsens_rst_en().set_bit()); + pcr.tsens_clk_conf() + .modify(|_, w| w.tsens_rst_en().clear_bit()); + apb_saradc + .tsens_ctrl() + .write(|w| unsafe { w.bits(tsens_ctrl) }); + apb_saradc + .tsens_ctrl2() + .write(|w| unsafe { w.bits(tsens_ctrl2) }); + apb_saradc + .tsens_wake() + .write(|w| unsafe { w.bits(tsens_wake) }); + apb_saradc + .tsens_sample() + .write(|w| unsafe { w.bits(tsens_sample) }); + + pcr.saradc_conf() + .modify(|_, w| w.saradc_reg_clk_en().set_bit()); + pcr.saradc_clkm_conf().modify(|_, w| unsafe { + w.saradc_clkm_en().set_bit(); + w.saradc_clkm_sel().xtal(); + w.saradc_clkm_div_num().bits(0); + w.saradc_clkm_div_b().bits(0); + w.saradc_clkm_div_a().bits(0) + }); + apb_saradc.ctrl().modify(|_, w| w.sar_clk_gated().set_bit()); + + // `regi2c_ctrl_ll_i2c_sar_periph_enable` + let pmu = PMU::regs(); + pmu.rf_pwc().modify(|_, w| w.perif_i2c_rstb().clear_bit()); + crate::rom::ets_delay_us(1); + pmu.rf_pwc().modify(|_, w| w.xpd_perif_i2c().set_bit()); + pmu.rf_pwc().modify(|_, w| w.perif_i2c_rstb().set_bit()); + + regi2c::ADC_SAR_DTEST_RTC.write_field(0); + regi2c::ADC_SAR_ENT_RTC.write_field(1); + regi2c::ADC_SAR1_ENCAL_REF.write_field(1); + regi2c::ADC_SAR2_ENCAL_REF.write_field(1); + + let [init_code_high, init_code_low] = SAR_ADC_INIT_CODE.to_be_bytes(); + regi2c::ADC_SAR1_INITIAL_CODE_HIGH.write_field(init_code_high); + regi2c::ADC_SAR1_INITIAL_CODE_LOW.write_field(init_code_low); + regi2c::ADC_SAR2_INITIAL_CODE_HIGH.write_field(init_code_high); + regi2c::ADC_SAR2_INITIAL_CODE_LOW.write_field(init_code_low); + + apb_saradc.sar_patt_tab1().modify(|_, w| unsafe { + w.item0_unit().adc1(); + w.item0_channel().bits(7); + w.item0_atten().db12(); + w.item1_unit().adc2(); + w.item1_channel().bits(1); + w.item1_atten().db12() + }); + apb_saradc + .ctrl() + .modify(|_, w| unsafe { w.sar_patt_len().bits(1) }); + + pcr.sar_clk_div() + .modify(|_, w| unsafe { w.sar1_clk_div_num().bits(15) }); + + apb_saradc.ctrl2().modify(|_, w| unsafe { + w.timer_target().bits(200); + w.timer_en().set_bit() + }); + + rng_ll_enable(); +} + +/// Disables true randomness. Unlocks `ADC` peripheral. +// See +pub(crate) fn revert_trng() { + let apb_saradc = APB_SARADC::regs(); + + // `rng_ll_disable` is skipped: `Rng` keeps using the RNG. + + apb_saradc.ctrl2().modify(|_, w| w.timer_en().clear_bit()); + + apb_saradc.sar_patt_tab1().reset(); + apb_saradc.sar_patt_tab2().reset(); + + regi2c::ADC_SAR1_INITIAL_CODE_HIGH.write_field(0); + regi2c::ADC_SAR1_INITIAL_CODE_LOW.write_field(0); + regi2c::ADC_SAR2_INITIAL_CODE_HIGH.write_field(0); + regi2c::ADC_SAR2_INITIAL_CODE_LOW.write_field(0); + + regi2c::ADC_SAR_DTEST_RTC.write_field(0); + regi2c::ADC_SAR_ENT_RTC.write_field(0); + regi2c::ADC_SAR1_ENCAL_REF.write_field(0); + regi2c::ADC_SAR2_ENCAL_REF.write_field(0); + + // `regi2c_saradc_disable` is skipped: PERIF_I2C stays powered as set up by + // `rtc_cntl::rtc::init`. + + PCR::regs().saradc_clkm_conf().modify(|_, w| unsafe { + w.saradc_clkm_div_num().bits(4); + w.saradc_clkm_div_b().bits(0); + w.saradc_clkm_div_a().bits(0); + w.saradc_clkm_sel().xtal() + }); +} diff --git a/esp-hal/src/soc/esp32h2/clocks.rs b/esp-hal/src/soc/esp32h2/clocks.rs index 6cec85409bf..a045f6fadc0 100644 --- a/esp-hal/src/soc/esp32h2/clocks.rs +++ b/esp-hal/src/soc/esp32h2/clocks.rs @@ -42,9 +42,11 @@ impl CpuClock { cpu_clk: Some(CpuClkConfig::new(0)), ahb_clk: Some(AhbClkConfig::new(0)), apb_clk: Some(ApbClkConfig::new(0)), + crypto_clk: Some(CryptoClkConfig::PllF96m), iomux_function_clock: Some(IomuxFunctionClockConfig::PllF48m), lp_fast_clk: Some(LpFastClkConfig::RcFastClk), lp_slow_clk: Some(xtal32k::default_lp_slow_clk()), + ble_lp_clk: Some(BleLpClkConfig::Xtal), timg_calibration_clock: None, }; } @@ -183,6 +185,7 @@ fn enable_rc_fast_clk_impl(_clocks: &mut ClockTree, en: bool) { // XTAL32K_CLK +#[cfg(use_xtal32k)] fn enable_xtal32k_clk_impl(_clocks: &mut ClockTree, en: bool) { PMU::regs() .hp_sleep_lp_ck_power() @@ -222,6 +225,7 @@ fn enable_rc_slow_clk_impl(_clocks: &mut ClockTree, en: bool) { // PLL_LP_CLK +#[cfg(use_xtal32k)] fn enable_pll_lp_clk_impl(_clocks: &mut ClockTree, en: bool) { PMU::regs() .hp_sleep_lp_ck_power() @@ -344,6 +348,7 @@ fn configure_lp_fast_clk_impl( w.fast_clk_sel().bits(match new_config { LpFastClkConfig::RcFastClk => 0, LpFastClkConfig::XtalD2Clk => 1, + #[cfg(use_xtal32k)] LpFastClkConfig::PllLpClk => 2, }) }); @@ -363,12 +368,34 @@ fn configure_lp_slow_clk_impl( LP_CLKRST::regs().lp_clk_conf().modify(|_, w| unsafe { w.slow_clk_sel().bits(match new_config { LpSlowClkConfig::RcSlow => 0, + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => 1, LpSlowClkConfig::OscSlow => 2, }) }); } +// CRYPTO_CLK + +fn enable_crypto_clk_impl(_clocks: &mut ClockTree, _en: bool) { + // Nothing to do here. +} + +fn configure_crypto_clk_impl( + _clocks: &mut ClockTree, + _old_config: Option, + new_config: CryptoClkConfig, +) { + PCR::regs().sec_conf().modify(|_, w| unsafe { + w.sec_clk_sel().bits(match new_config { + CryptoClkConfig::Xtal => 0, + CryptoClkConfig::RcFast => 1, + CryptoClkConfig::PllF64m => 2, + CryptoClkConfig::PllF96m => 3, + }) + }); +} + // TIMG_CALIBRATION_CLOCK fn enable_timg_calibration_clock_impl(_clocks: &mut ClockTree, _en: bool) { @@ -385,6 +412,7 @@ fn configure_timg_calibration_clock_impl( w.rtc_cali_clk_sel().bits(match new_config { TimgCalibrationClockConfig::RcSlowClk => 0, TimgCalibrationClockConfig::RcFastDivClk => 1, + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => 2, }) }); @@ -427,14 +455,14 @@ impl ParlIoInstance { fn configure_rx_clock_impl( self, _clocks: &mut ClockTree, - _old_config: Option, - new_config: ParlIoRxClockConfig, + _old_config: Option, + new_config: ParlIoClkConfig, ) { PCR::regs().parl_clk_rx_conf().modify(|_, w| unsafe { w.parl_clk_rx_sel().bits(match new_config { - ParlIoRxClockConfig::XtalClk => 0, - ParlIoRxClockConfig::RcFastClk => 2, - ParlIoRxClockConfig::PllF96m => 1, + ParlIoClkConfig::XtalClk => 0, + ParlIoClkConfig::RcFastClk => 2, + ParlIoClkConfig::PllF96m => 1, }) }); } @@ -450,14 +478,39 @@ impl ParlIoInstance { fn configure_tx_clock_impl( self, _clocks: &mut ClockTree, - _old_config: Option, - new_config: ParlIoTxClockConfig, + _old_config: Option, + new_config: ParlIoClkConfig, ) { PCR::regs().parl_clk_tx_conf().modify(|_, w| unsafe { w.parl_clk_tx_sel().bits(match new_config { - ParlIoTxClockConfig::XtalClk => 0, - ParlIoTxClockConfig::RcFastClk => 2, - ParlIoTxClockConfig::PllF96m => 1, + ParlIoClkConfig::XtalClk => 0, + ParlIoClkConfig::RcFastClk => 2, + ParlIoClkConfig::PllF96m => 1, + }) + }); + } +} + +impl AdcInstance { + // ADC_FUNCTION_CLOCK + + fn enable_function_clock_impl(self, _clocks: &mut ClockTree, en: bool) { + PCR::regs() + .saradc_clkm_conf() + .modify(|_, w| w.saradc_clkm_en().bit(en)); + } + + fn configure_function_clock_impl( + self, + _clocks: &mut ClockTree, + _old_config: Option, + new_config: AdcFunctionClockConfig, + ) { + PCR::regs().saradc_clkm_conf().modify(|_, w| unsafe { + w.saradc_clkm_sel().bits(match new_config { + AdcFunctionClockConfig::Xtal => 0, + AdcFunctionClockConfig::PllF96m => 1, + AdcFunctionClockConfig::RcFast => 2, }) }); } @@ -574,3 +627,54 @@ impl TimgInstance { }); } } + +// BLE_LP_XTAL_CLK + +fn enable_ble_lp_xtal_clk_impl(_clocks: &mut ClockTree, _en: bool) { + // Nothing to do. +} + +// BLE_LP_RC_SLOW_CLK + +fn enable_ble_lp_rc_slow_clk_impl(_clocks: &mut ClockTree, _en: bool) { + // Nothing to do, divisor and mux are configured in BLE_LP_CLK + // (see modem_clock_select_lp_clock_source() in modem_clock.c). +} + +// BLE_LP_CLK + +fn enable_ble_lp_clk_impl(_clocks: &mut ClockTree, _en: bool) { + // ESP32-H2 has no BLE RTC timer clock gate. +} + +fn configure_ble_lp_clk_impl( + _clocks: &mut ClockTree, + _old_config: Option, + new_config: BleLpClkConfig, +) { + let divisor = match new_config { + BleLpClkConfig::Xtal => xtal_clk_frequency() / ble_lp_xtal_clk_frequency() - 1, + // Divided by 5 (div_num = 4), see esp_bt_rtc_slow_clk_select() in bt.c. + BleLpClkConfig::RcSlow => rc_slow_clk_frequency() / ble_lp_rc_slow_clk_frequency() - 1, + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => 0, + }; + let sel_xtal32k = cfg_select! { + use_xtal32k => new_config == BleLpClkConfig::Xtal32k, + _ => false, + }; + + LP_CLKRST::regs().lpperi().modify(|_, w| unsafe { + w.lp_sel_osc_slow() + .bit(new_config == BleLpClkConfig::RcSlow); + w.lp_sel_osc_fast().clear_bit(); + w.lp_sel_xtal().bit(new_config == BleLpClkConfig::Xtal); + w.lp_sel_xtal32k().bit(sel_xtal32k); + w.lp_bletimer_div_num().bits(divisor as u16); + if sel_xtal32k { + // 0 routes XTAL32K to the BLE timer 32 kHz input. + w.lp_bletimer_32k_sel().bits(0); + } + w + }); +} diff --git a/esp-hal/src/soc/esp32h2/mod.rs b/esp-hal/src/soc/esp32h2/mod.rs index c5bf6b5e28f..de16bc4508b 100644 --- a/esp-hal/src/soc/esp32h2/mod.rs +++ b/esp-hal/src/soc/esp32h2/mod.rs @@ -16,12 +16,6 @@ pub(crate) mod regi2c; pub(crate) use esp32h2 as pac; -#[cfg(i2s_driver_supported)] -#[cfg_attr(not(feature = "unstable"), allow(unused))] -pub(crate) fn i2s_sclk_frequency() -> u32 { - clocks::pll_f96m_clk_frequency() -} - #[cfg(feature = "rt")] pub(crate) fn riscv_preinit() {} @@ -43,4 +37,19 @@ pub(crate) fn pre_init() { crate::peripherals::HP_APM::regs() .func_ctrl() .write(|w| unsafe { w.bits(0x0) }); + + // Mirrors ESP-IDF's `init_rng`, see + trng::rng_ll_enable(); +} + +/// Invalidate a specific range of addresses in the cache. +#[cfg(feature = "unstable")] +#[crate::ram] +pub(crate) unsafe fn cache_invalidate_addr(addr: u32, size: u32) { + unsafe extern "C" { + fn Cache_Invalidate_Addr(addr: u32, size: u32); + } + unsafe { + Cache_Invalidate_Addr(addr, size); + } } diff --git a/esp-hal/src/soc/esp32h2/trng.rs b/esp-hal/src/soc/esp32h2/trng.rs index 59647947fd2..9438d60040b 100644 --- a/esp-hal/src/soc/esp32h2/trng.rs +++ b/esp-hal/src/soc/esp32h2/trng.rs @@ -1,15 +1,21 @@ use crate::{ - peripherals::{APB_SARADC, PCR, PMU}, + peripherals::{APB_SARADC, LP_PERI, PCR, PMU}, soc::regi2c, }; -const SAR2_CHANNEL: u32 = 9; -const SAR2_ATTEN: u32 = 1; -const SAR1_ATTEN: u32 = 1; -const PATTERN_BIT_WIDTH: u32 = 6; +// `I2C_SAR_ADC_INIT_CODE_VAL`, see +const SAR_ADC_INIT_CODE: u16 = 2150; -/// Enable true randomness by enabling the entropy source. +// See +pub(crate) fn rng_ll_enable() { + LP_PERI::regs() + .clk_en() + .modify(|_, w| w.rng_ck_en().set_bit()); +} + +/// Enables true randomness by enabling the entropy source. /// Blocks `ADC` usage. +// See pub(crate) fn ensure_randomness() { let pcr = PCR::regs(); let pmu = PMU::regs(); @@ -32,12 +38,16 @@ pub(crate) fn ensure_randomness() { // Select XTAL clock (40 MHz) source for ADC_CTRL_CLK pcr.saradc_clkm_conf() - .modify(|_, w| w.saradc_clkm_sel().bits(0)); + .modify(|_, w| w.saradc_clkm_sel().xtal()); + apb_saradc.ctrl().modify(|_, w| w.sar_clk_gated().set_bit()); // Set the clock divider for ADC_CTRL_CLK to default value (in case it has been // changed) - pcr.saradc_clkm_conf() - .modify(|_, w| w.saradc_clkm_div_num().bits(0)); + pcr.saradc_clkm_conf().modify(|_, w| { + w.saradc_clkm_div_num().bits(0); + w.saradc_clkm_div_b().bits(0); + w.saradc_clkm_div_a().bits(0) + }); // some ADC sensor registers are in power group PERIF_I2C and need to be enabled // via PMU @@ -45,30 +55,30 @@ pub(crate) fn ensure_randomness() { // Config ADC circuit (Analog part) with I2C(HOST ID 0x69) and chose internal // voltage as sampling source - regi2c::ADC_SARADC_DTEST.write_field(2); + regi2c::ADC_SARADC_DTEST.write_field(0); regi2c::ADC_SARADC_ENT_SAR.write_field(1); regi2c::ADC_SARADC_EN_TOUT_SAR1_BUS.write_field(1); - regi2c::ADC_SAR2_INITIAL_CODE_HIGH.write_field(0x08); - regi2c::ADC_SAR2_INITIAL_CODE_LOW.write_field(0x66); - regi2c::ADC_SAR1_INITIAL_CODE_HIGH.write_field(0x08); - regi2c::ADC_SAR1_INITIAL_CODE_LOW.write_field(0x66); - - // create patterns and set them in pattern table - let pattern_one: u32 = (SAR2_CHANNEL << 2) | SAR2_ATTEN; // we want channel 9 with max attenuation - let pattern_two: u32 = SAR1_ATTEN; // we want channel 0 with max attenuation, channel doesn't really matter here - let pattern_table: u32 = - (pattern_two << (3 * PATTERN_BIT_WIDTH)) | (pattern_one << (2 * PATTERN_BIT_WIDTH)); - - apb_saradc - .sar_patt_tab1() - .modify(|_, w| w.bits(pattern_table)); - - // set pattern length to 2 (APB_SARADC_SAR_PATT_LEN counts from 0) + let [init_code_high, init_code_low] = SAR_ADC_INIT_CODE.to_be_bytes(); + regi2c::ADC_SAR2_INITIAL_CODE_HIGH.write_field(init_code_high); + regi2c::ADC_SAR2_INITIAL_CODE_LOW.write_field(init_code_low); + regi2c::ADC_SAR1_INITIAL_CODE_HIGH.write_field(init_code_high); + regi2c::ADC_SAR1_INITIAL_CODE_LOW.write_field(init_code_low); + + apb_saradc.sar_patt_tab1().modify(|_, w| { + w.item0_unit().adc1(); + w.item0_channel().bits(0); + w.item0_atten().db2_5(); + w.item1_unit().adc2(); + w.item1_channel().bits(1); + w.item1_atten().db2_5() + }); + + // set pattern length to 1 (APB_SARADC_SAR_PATT_LEN counts from 0) apb_saradc.ctrl().modify(|_, w| w.sar_patt_len().bits(0)); - // Same as in C3 - apb_saradc.ctrl().modify(|_, w| w.sar_clk_div().bits(15)); + pcr.sar_clk_div() + .modify(|_, w| w.sar1_clk_div_num().bits(15)); // set timer expiry (timer is ADC_CTRL_CLK) apb_saradc.ctrl2().modify(|_, w| w.timer_target().bits(200)); @@ -76,33 +86,29 @@ pub(crate) fn ensure_randomness() { // enable timer apb_saradc.ctrl2().modify(|_, w| w.timer_en().set_bit()); } + + rng_ll_enable(); } -/// Disable true randomness. Unlocks `ADC` peripheral. +/// Disables true randomness. Unlocks `ADC` peripheral. pub(crate) fn revert_trng() { - unsafe { - APB_SARADC::regs() - .ctrl2() - .modify(|_, w| w.timer_en().clear_bit()); - - APB_SARADC::regs() - .sar_patt_tab1() - .modify(|_, w| w.bits(0xFFFFFF)); - - // Revert ADC I2C configuration and initial voltage source setting - regi2c::ADC_SAR2_INITIAL_CODE_HIGH.write_field(0x60); - regi2c::ADC_SAR2_INITIAL_CODE_LOW.write_field(0); - regi2c::ADC_SAR1_INITIAL_CODE_HIGH.write_field(0x60); - regi2c::ADC_SAR1_INITIAL_CODE_LOW.write_field(0); - regi2c::ADC_SARADC_DTEST.write_field(0); - regi2c::ADC_SARADC_ENT_SAR.write_field(0); - regi2c::ADC_SARADC_EN_TOUT_SAR1_BUS.write_field(0); - // disable ADC_CTRL_CLK (SAR ADC function clock) - PCR::regs() - .saradc_clkm_conf() - .modify(|_, w| w.bits(0x00404000)); - - // Set PCR_SARADC_CONF_REG to initial state - PCR::regs().saradc_conf().modify(|_, w| w.bits(0x5)); - } + APB_SARADC::regs() + .ctrl2() + .modify(|_, w| w.timer_en().clear_bit()); + + APB_SARADC::regs().sar_patt_tab1().reset(); + + // Revert ADC I2C configuration and initial voltage source setting + regi2c::ADC_SAR2_INITIAL_CODE_HIGH.write_field(0); + regi2c::ADC_SAR2_INITIAL_CODE_LOW.write_field(0); + regi2c::ADC_SAR1_INITIAL_CODE_HIGH.write_field(0); + regi2c::ADC_SAR1_INITIAL_CODE_LOW.write_field(0); + regi2c::ADC_SARADC_DTEST.write_field(0); + regi2c::ADC_SARADC_ENT_SAR.write_field(0); + regi2c::ADC_SARADC_EN_TOUT_SAR1_BUS.write_field(0); + // disable ADC_CTRL_CLK (SAR ADC function clock) + PCR::regs().saradc_clkm_conf().reset(); + + // Set PCR_SARADC_CONF_REG to initial state + PCR::regs().saradc_conf().reset(); } diff --git a/esp-hal/src/soc/esp32h4/clocks.rs b/esp-hal/src/soc/esp32h4/clocks.rs new file mode 100644 index 00000000000..624cd8f191a --- /dev/null +++ b/esp-hal/src/soc/esp32h4/clocks.rs @@ -0,0 +1,554 @@ +//! Clock tree definitions and implementations for ESP32-H4. +//! +//! Remarks: +//! - Enabling a clock node assumes it has first been configured. Some fixed clock nodes don't need +//! to be configured. +//! - Internal RC oscillators (32 kHz OSC_SLOW, 600 kHz RC_SLOW and 20 MHz RC_FAST) are not +//! calibrated here, this system can only give a rough estimate of their frequency. They can be +//! calibrated separately using a known crystal frequency. +#![allow(dead_code, reason = "Some of this is bound to be unused")] +#![allow(missing_docs, reason = "Experimental")] + +use core::sync::atomic::{AtomicBool, Ordering}; + +use esp_rom_sys::rom::ets_update_cpu_frequency_rom; + +use crate::{ + peripherals::{I2C_ANA_MST, LP_CLKRST, PCR, PMU}, + soc::{regi2c, xtal32k}, +}; + +define_clock_tree_types!(); + +/// Clock configuration options. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[allow( + clippy::enum_variant_names, + reason = "MHz suffix indicates physical unit." +)] +#[non_exhaustive] +pub enum CpuClock { + /// 32 MHz CPU clock, driven by the crystal + _32MHz = 32, + + /// 96 MHz CPU clock, driven by the BBPLL + #[default] + _96MHz = 96, +} + +impl CpuClock { + const PRESET_32: ClockConfig = ClockConfig { + hp_root_clk: Some(HpRootClkConfig::Xtal), + cpu_clk: Some(CpuClkConfig::new(CpuClkDivisor::_0)), + ahb_clk: Some(AhbClkConfig::new(0)), + apb_clk: Some(ApbClkConfig::new(ApbClkDivisor::_0)), + lp_fast_clk: Some(LpFastClkConfig::RcFastClk), + lp_slow_clk: Some(xtal32k::default_lp_slow_clk()), + ble_lp_clk: Some(BleLpClkConfig::Xtal), + timg_calibration_clock: None, + iomux_function_clock: Some(IomuxFunctionClockConfig::PllF48m), + }; + const PRESET_96: ClockConfig = ClockConfig { + hp_root_clk: Some(HpRootClkConfig::Pll), + cpu_clk: Some(CpuClkConfig::new(CpuClkDivisor::_0)), + // AHB_CLK may not exceed 32 MHz, see rtc_clk_cpu_freq_to_pll_mhz(). + ahb_clk: Some(AhbClkConfig::new(2)), + apb_clk: Some(ApbClkConfig::new(ApbClkDivisor::_0)), + lp_fast_clk: Some(LpFastClkConfig::RcFastClk), + lp_slow_clk: Some(xtal32k::default_lp_slow_clk()), + ble_lp_clk: Some(BleLpClkConfig::Xtal), + timg_calibration_clock: None, + iomux_function_clock: Some(IomuxFunctionClockConfig::PllF48m), + }; +} + +impl From for ClockConfig { + fn from(value: CpuClock) -> ClockConfig { + match value { + CpuClock::_32MHz => CpuClock::PRESET_32, + CpuClock::_96MHz => CpuClock::PRESET_96, + } + } +} + +impl Default for ClockConfig { + fn default() -> Self { + Self::from(CpuClock::default()) + } +} + +impl ClockConfig { + pub(crate) fn try_get_preset(self) -> Option { + match self { + v if v == CpuClock::PRESET_32 => Some(CpuClock::_32MHz), + v if v == CpuClock::PRESET_96 => Some(CpuClock::_96MHz), + _ => None, + } + } + + pub(crate) fn configure(self, clocks: &mut ClockTree) { + // HP_ROOT_CLK and the CPU, AHB and APB dividers share one update signal. Write the + // complete configuration before latching it, applying each change separately would + // temporarily overclock the buses. + BUS_CLOCK_UPDATE_DEFERRED.store(true, Ordering::Relaxed); + self.apply(clocks); + BUS_CLOCK_UPDATE_DEFERRED.store(false, Ordering::Relaxed); + + update_bus_clocks(); + + // esp_rom_set_cpu_ticks_per_us(), the ROM delay functions need this. + ets_update_cpu_frequency_rom(cpu_clk_frequency() / 1_000_000); + } +} + +static BUS_CLOCK_UPDATE_DEFERRED: AtomicBool = AtomicBool::new(false); + +/// Applies a new `soc_clk_sel`, `cpu_div_num`, `ahb_div_num` or `apb_div_num`. +/// +/// The bus may get stuck if the new combination is invalid. +fn update_bus_clocks() { + if BUS_CLOCK_UPDATE_DEFERRED.load(Ordering::Relaxed) { + return; + } + + PCR::regs() + .bus_clk_update() + .write(|w| w.bus_clock_update().set_bit()); + while PCR::regs() + .bus_clk_update() + .read() + .bus_clock_update() + .bit_is_set() + {} +} + +/// Powers up and configures the BBPLL and the XTAL frequency doubler again, if a clock uses them. +/// +/// The PMU powers both circuits down in light sleep, and the BBPLL loses its analog configuration. +pub(crate) fn reconfigure_pll(clocks: &mut ClockTree) { + if clocks.pll_f96m_clk_refcount > 0 { + enable_pll_f96m_clk_impl(clocks, true); + } + if clocks.xtal_x2_clk_refcount > 0 { + enable_xtal_x2_clk_impl(clocks, true); + } +} + +// PLL_F96M_CLK + +fn enable_pll_f96m_clk_impl(_clocks: &mut ClockTree, en: bool) { + if en { + PMU::regs().imm_hp_ck_power().write(|w| { + w.tie_high_xpd_bbpll().set_bit(); + w.tie_high_xpd_bbpll_i2c().set_bit() + }); + } else { + PMU::regs() + .imm_hp_ck_power() + .write(|w| w.tie_low_global_bbpll_icg().set_bit()); + PMU::regs().imm_hp_ck_power().write(|w| { + w.tie_low_xpd_bbpll().set_bit(); + w.tie_low_xpd_bbpll_i2c().set_bit() + }); + } + + PCR::regs() + .pll_div_clk_en() + .modify(|_, w| w.pll_96m_clk_en().bit(en)); + + if en { + configure_bbpll(); + } +} + +/// The analog part of the BBPLL, same shape as on the ESP32-H2 but with this chip's dividers. +/// +/// See rtc_clk_bbpll_configure() and clk_ll_bbpll_set_config(). The output frequency is fixed to +/// 96 MHz, so there is nothing to configure on the digital side. +fn configure_bbpll() { + // BBPLL CALIBRATION START + I2C_ANA_MST::regs().ana_conf0().modify(|_, w| { + w.bbpll_stop_force_high().clear_bit(); + w.bbpll_stop_force_low().set_bit() + }); + + regi2c::I2C_BBPLL_OC_REF_DIV.write_field(8); + regi2c::I2C_BBPLL_OC_DIV.write_field(24); + regi2c::I2C_BBPLL_OC_DHREF_SEL.write_field(3); + regi2c::I2C_BBPLL_OC_DLREF_SEL.write_field(1); + + // WAIT CALIBRATION DONE + while I2C_ANA_MST::regs() + .ana_conf0() + .read() + .cal_done() + .bit_is_clear() + {} + + // Wait for the calibration to truly stop. + crate::rom::ets_delay_us(10); + + // BBPLL CALIBRATION STOP + I2C_ANA_MST::regs().ana_conf0().modify(|_, w| { + w.bbpll_stop_force_low().clear_bit(); + w.bbpll_stop_force_high().set_bit() + }); +} + +// PLL_F48M_CLK + +fn enable_pll_f48m_clk_impl(_clocks: &mut ClockTree, en: bool) { + PCR::regs() + .pll_div_clk_en() + .modify(|_, w| w.pll_48m_clk_en().bit(en)); +} + +// IOMUX_FUNCTION_CLOCK + +fn configure_iomux_function_clock_impl( + _clocks: &mut ClockTree, + _old_config: Option, + new_config: IomuxFunctionClockConfig, +) { + PCR::regs().iomux_clk_conf().modify(|_, w| unsafe { + w.iomux_func_clk_sel().bits(match new_config { + IomuxFunctionClockConfig::XtalClk => 0, + IomuxFunctionClockConfig::RcFastClk => 1, + IomuxFunctionClockConfig::PllF48m => 2, + }); + w.iomux_func_clk_en().set_bit() + }); +} + +// XTAL_X2_CLK + +fn enable_xtal_x2_clk_impl(_clocks: &mut ClockTree, en: bool) { + // The frequency doubler is a separate circuit, it does not depend on the BBPLL. + if en { + PMU::regs().imm_hp_ck_power().write(|w| { + w.tie_low_xpd_xtalx2().clear_bit(); + w.tie_low_global_xtalx2_icg().clear_bit() + }); + PMU::regs().imm_hp_ck_power().write(|w| { + w.tie_high_xtalx2().set_bit(); + w.tie_high_global_xtalx2_icg().set_bit() + }); + } else { + PMU::regs().imm_hp_ck_power().write(|w| { + w.tie_high_xtalx2().clear_bit(); + w.tie_high_global_xtalx2_icg().clear_bit() + }); + PMU::regs().imm_hp_ck_power().write(|w| { + w.tie_low_xpd_xtalx2().set_bit(); + w.tie_low_global_xtalx2_icg().set_bit() + }); + } +} + +// RC_FAST_CLK + +fn enable_rc_fast_clk_impl(_clocks: &mut ClockTree, en: bool) { + PMU::regs() + .hp_sleep_lp_ck_power() + .modify(|_, w| w.hp_sleep_xpd_fosc_clk().bit(en)); + LP_CLKRST::regs() + .clk_to_hp() + .modify(|_, w| w.icg_hp_fosc().bit(en)); +} + +// XTAL32K_CLK + +#[cfg(use_xtal32k)] +fn enable_xtal32k_clk_impl(_clocks: &mut ClockTree, en: bool) { + PMU::regs() + .hp_sleep_lp_ck_power() + .modify(|_, w| w.hp_sleep_xpd_xtal32k().bit(en)); + LP_CLKRST::regs() + .clk_to_hp() + .modify(|_, w| w.icg_hp_xtal32k().bit(en)); +} + +// OSC_SLOW_CLK + +fn enable_osc_slow_clk_impl(_clocks: &mut ClockTree, en: bool) { + LP_CLKRST::regs() + .clk_to_hp() + .modify(|_, w| w.icg_hp_osc32k().bit(en)); +} + +// RC_SLOW_CLK + +fn enable_rc_slow_clk_impl(_clocks: &mut ClockTree, en: bool) { + LP_CLKRST::regs() + .clk_to_hp() + .modify(|_, w| w.icg_hp_sosc().bit(en)); +} + +// RC_SLOW_D4_CLK + +fn enable_rc_slow_d4_clk_impl(_clocks: &mut ClockTree, _en: bool) { + // The divider is fixed in hardware, there is nothing to gate. +} + +// HP_ROOT_CLK + +fn enable_hp_root_clk_impl(_clocks: &mut ClockTree, _en: bool) { + // Nothing to do here. +} + +fn configure_hp_root_clk_impl( + _clocks: &mut ClockTree, + _old_config: Option, + new_config: HpRootClkConfig, +) { + PCR::regs().sysclk_conf().modify(|_, w| unsafe { + w.soc_clk_sel().bits(match new_config { + HpRootClkConfig::Xtal => 0, + HpRootClkConfig::RcFast => 1, + HpRootClkConfig::XtalX2 => 2, + HpRootClkConfig::Pll => 3, + }) + }); + + update_bus_clocks(); +} + +// CPU_CLK + +fn configure_cpu_clk_impl( + _clocks: &mut ClockTree, + _old_config: Option, + new_config: CpuClkConfig, +) { + PCR::regs() + .cpu_freq_conf() + .modify(|_, w| unsafe { w.cpu_div_num().bits(new_config.divisor() as u8) }); + + update_bus_clocks(); +} + +// AHB_CLK + +fn configure_ahb_clk_impl( + _clocks: &mut ClockTree, + _old_config: Option, + new_config: AhbClkConfig, +) { + PCR::regs() + .ahb_freq_conf() + .modify(|_, w| unsafe { w.ahb_div_num().bits(new_config.divisor() as u8) }); + + update_bus_clocks(); +} + +// APB_CLK + +fn enable_apb_clk_impl(_clocks: &mut ClockTree, _en: bool) { + // Nothing to do here. +} + +fn configure_apb_clk_impl( + _clocks: &mut ClockTree, + _old_config: Option, + new_config: ApbClkConfig, +) { + PCR::regs() + .apb_freq_conf() + .modify(|_, w| unsafe { w.apb_div_num().bits(new_config.divisor() as u8) }); + + update_bus_clocks(); +} + +// XTAL_D2_CLK + +fn enable_xtal_d2_clk_impl(_clocks: &mut ClockTree, _en: bool) { + // Nothing to do here. +} + +// LP_FAST_CLK + +fn enable_lp_fast_clk_impl(_clocks: &mut ClockTree, _en: bool) { + // Nothing to do here. +} + +fn configure_lp_fast_clk_impl( + _clocks: &mut ClockTree, + _old_config: Option, + new_config: LpFastClkConfig, +) { + // The mux only selects between two sources, so the selector is a single bit. + LP_CLKRST::regs().lp_clk_conf().modify(|_, w| { + w.fast_clk_sel().bit(match new_config { + LpFastClkConfig::RcFastClk => false, + LpFastClkConfig::XtalD2Clk => true, + }) + }); +} + +// LP_SLOW_CLK + +fn enable_lp_slow_clk_impl(_clocks: &mut ClockTree, _en: bool) { + // Nothing to do here. +} + +fn configure_lp_slow_clk_impl( + _clocks: &mut ClockTree, + _old_config: Option, + new_config: LpSlowClkConfig, +) { + LP_CLKRST::regs().lp_clk_conf().modify(|_, w| unsafe { + w.slow_clk_sel().bits(match new_config { + LpSlowClkConfig::RcSlow => 0, + #[cfg(use_xtal32k)] + LpSlowClkConfig::Xtal32k => 1, + LpSlowClkConfig::OscSlow => 3, + }) + }); +} + +// BLE_LP_XTAL_CLK + +fn enable_ble_lp_xtal_clk_impl(_clocks: &mut ClockTree, _en: bool) { + // Nothing to do. +} + +// BLE_LP_CLK + +fn enable_ble_lp_clk_impl(_clocks: &mut ClockTree, _en: bool) { + // ESP32-H4 has no BLE RTC timer clock gate. +} + +fn configure_ble_lp_clk_impl( + _clocks: &mut ClockTree, + _old_config: Option, + new_config: BleLpClkConfig, +) { + let divisor = match new_config { + BleLpClkConfig::Xtal => xtal_clk_frequency() / ble_lp_xtal_clk_frequency() - 1, + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => 0, + }; + let sel_xtal32k = cfg_select! { + use_xtal32k => new_config == BleLpClkConfig::Xtal32k, + _ => false, + }; + + LP_CLKRST::regs().lpperi().modify(|_, w| unsafe { + w.lp_sel_osc_slow().clear_bit(); + w.lp_sel_osc_fast().clear_bit(); + w.lp_sel_xtal().bit(new_config == BleLpClkConfig::Xtal); + w.lp_sel_xtal32k().bit(sel_xtal32k); + w.lp_bletimer_div_num().bits(divisor as u16); + if sel_xtal32k { + // 0 routes XTAL32K to the BLE timer 32 kHz input. + w.lp_bletimer_32k_sel().bits(0); + } + w + }); +} + +// TIMG_CALIBRATION_CLOCK + +fn enable_timg_calibration_clock_impl(_clocks: &mut ClockTree, _en: bool) { + // Nothing to do here. +} + +fn configure_timg_calibration_clock_impl( + _clocks: &mut ClockTree, + _old_config: Option, + new_config: TimgCalibrationClockConfig, +) { + // RC_FAST is only reachable through the secondary mux, behind a divider. esp-idf divides it + // by 32 (rtc_time.c, CLK_CAL_DIV_VAL) because calibration needs a relatively slow signal; + // device metadata describes the same divider. + const RC_FAST_SECURE_CLK_SEL: u8 = 11; + const RC_FAST_DIVIDER: u8 = 32; + + PCR::regs().timg_cali_clk_conf().modify(|_, w| unsafe { + match new_config { + #[cfg(use_xtal32k)] + TimgCalibrationClockConfig::Xtal32kClk => w.timg_cali_clk_sel().bits(1), + TimgCalibrationClockConfig::RcSlowClk => w.timg_cali_clk_sel().bits(3), + TimgCalibrationClockConfig::RcFastDivClk => { + w.timg_cali_clk_sel().bits(4); + w.timg_secure_clk_sel().bits(RC_FAST_SECURE_CLK_SEL); + w.timg_secure_clk_div_num().bits(RC_FAST_DIVIDER - 1) + } + } + }); +} + +impl TimgInstance { + // TIMG_FUNCTION_CLOCK + + fn enable_function_clock_impl(self, _clocks: &mut ClockTree, en: bool) { + match self { + TimgInstance::Timg0 => PCR::regs() + .timergroup0_timer_clk_conf() + .modify(|_, w| w.tg0_timer_clk_en().bit(en)), + TimgInstance::Timg1 => PCR::regs() + .timergroup1_timer_clk_conf() + .modify(|_, w| w.tg1_timer_clk_en().bit(en)), + }; + } + + fn configure_function_clock_impl( + self, + _clocks: &mut ClockTree, + _old_config: Option, + new_config: TimgFunctionClockConfig, + ) { + let sel = match new_config { + TimgFunctionClockConfig::XtalClk => 0, + TimgFunctionClockConfig::RcFastClk => 1, + TimgFunctionClockConfig::PllF48m => 2, + }; + + match self { + TimgInstance::Timg0 => PCR::regs() + .timergroup0_timer_clk_conf() + .modify(|_, w| unsafe { w.tg0_timer_clk_sel().bits(sel) }), + TimgInstance::Timg1 => PCR::regs() + .timergroup1_timer_clk_conf() + .modify(|_, w| unsafe { w.tg1_timer_clk_sel().bits(sel) }), + }; + } + + // TIMG_WDT_CLOCK + + fn enable_wdt_clock_impl(self, _clocks: &mut ClockTree, en: bool) { + match self { + TimgInstance::Timg0 => PCR::regs() + .timergroup0_wdt_clk_conf() + .modify(|_, w| w.tg0_wdt_clk_en().bit(en)), + TimgInstance::Timg1 => PCR::regs() + .timergroup1_wdt_clk_conf() + .modify(|_, w| w.tg1_wdt_clk_en().bit(en)), + }; + } + + fn configure_wdt_clock_impl( + self, + _clocks: &mut ClockTree, + _old_config: Option, + new_config: TimgWdtClockConfig, + ) { + // The watchdogs encode their sources differently from the timers, see mwdt_ll.h and + // timer_ll.h. + let sel = match new_config { + TimgWdtClockConfig::XtalClk => 0, + TimgWdtClockConfig::PllF48m => 1, + TimgWdtClockConfig::RcFastClk => 2, + }; + + match self { + TimgInstance::Timg0 => PCR::regs() + .timergroup0_wdt_clk_conf() + .modify(|_, w| unsafe { w.tg0_wdt_clk_sel().bits(sel) }), + TimgInstance::Timg1 => PCR::regs() + .timergroup1_wdt_clk_conf() + .modify(|_, w| unsafe { w.tg1_wdt_clk_sel().bits(sel) }), + }; + } +} diff --git a/esp-hal/src/soc/esp32h4/cpu_control.rs b/esp-hal/src/soc/esp32h4/cpu_control.rs new file mode 100644 index 00000000000..f8a6efe0e60 --- /dev/null +++ b/esp-hal/src/soc/esp32h4/cpu_control.rs @@ -0,0 +1,98 @@ +use crate::{ + peripherals::{HP_SYS, LP_AON, PCR}, + system::Cpu, +}; + +pub(crate) unsafe fn internal_park_core(core: Cpu, park: bool) { + // 0x86 = stalled, 0xFF = running (matches IDF cpu_utility_ll.h). + let code: u8 = if park { 0x86 } else { 0xFF }; + LP_AON::regs().cpucore_cfg().modify(|_, w| unsafe { + match core { + Cpu::ProCpu => w.cpu_core0_sw_stall().bits(code), + Cpu::AppCpu => w.cpu_core1_sw_stall().bits(code), + } + }); + + // IDF waits for the run-stalled status to clear after unstalling. + if !park { + let status = HP_SYS::regs().core_debug_runstall_conf(); + match core { + Cpu::ProCpu => while status.read().core0_runstalled().bit_is_set() {}, + Cpu::AppCpu => while status.read().core1_runstalled().bit_is_set() {}, + } + } +} + +#[instability::unstable] +pub fn is_running(core: Cpu) -> bool { + let stall = LP_AON::regs().cpucore_cfg().read(); + let code = match core { + Cpu::ProCpu => stall.cpu_core0_sw_stall().bits(), + Cpu::AppCpu => stall.cpu_core1_sw_stall().bits(), + }; + if code == 0x86 { + return false; + } + + match core { + Cpu::ProCpu => true, + Cpu::AppCpu => { + let core1 = PCR::regs().core1_conf().read(); + core1.core1_clk_en().bit_is_set() && core1.core1_rst_en().bit_is_clear() + } + } +} + +pub(crate) fn pre_system_reset() { + // Match IDF's esp_restart_noos(): reset and stall only the other core. + // The caller must remain alive to request the subsequent system reset. + let other_core = match Cpu::current() { + Cpu::ProCpu => Cpu::AppCpu, + Cpu::AppCpu => Cpu::ProCpu, + }; + LP_AON::regs() + .cpucore_cfg() + .modify(|_, w| match other_core { + Cpu::ProCpu => w.cpu_core0_sw_reset().set_bit(), + Cpu::AppCpu => w.cpu_core1_sw_reset().set_bit(), + }); + unsafe { internal_park_core(other_core, true) }; + + // Prevent ROM from jumping to an entry point from the previous image. + crate::rom::ets_set_appcpu_boot_addr(0); +} + +pub(crate) fn disable_core1() { + // The reset defaults of the register, which is how ESP-IDF leaves Core 1 in single-core mode: + // the core is clock gated and held in reset. + PCR::regs().core1_conf().modify(|_, w| { + w.core1_clk_en().clear_bit(); + w.core1_rst_en().set_bit() + }); +} + +/// Releases Core 1's interrupt matrix from its power-on state, in which it is clock gated and held +/// in reset. +/// +/// ESP-IDF only does this while starting Core 1, because it allocates interrupts for a core after +/// the core is running. esp-hal maps interrupts to Core 1 before that - `init` already binds the +/// default GPIO handler on both cores - and writes to the matrix are dropped while it is in reset, +/// so keep it running from the start. +pub(crate) fn enable_core1_interrupt_matrix() { + PCR::regs().intmtx_conf().modify(|_, w| { + w.intmtx_core1_clk_en().set_bit(); + w.intmtx_core1_rst_en().clear_bit() + }); +} + +#[cfg(feature = "unstable")] +pub(crate) fn start_core1(entry_point: *const u32) { + // cpu_utility_ll_enable_clock_and_reset_app_cpu() + PCR::regs().core1_conf().modify(|_, w| { + w.core1_clk_en().set_bit(); + w.core1_rst_en().clear_bit() + }); + + // Core 1's ROM waits for this address before handing control to the app. + crate::rom::ets_set_appcpu_boot_addr(entry_point as u32); +} diff --git a/esp-hal/src/soc/esp32h4/mod.rs b/esp-hal/src/soc/esp32h4/mod.rs new file mode 100644 index 00000000000..9b7f898079c --- /dev/null +++ b/esp-hal/src/soc/esp32h4/mod.rs @@ -0,0 +1,76 @@ +//! # SOC (System-on-Chip) module (ESP32-H4) +//! +//! ## Overview +//! +//! The `SOC` module provides access, functions and structures that are useful +//! for interacting with various system-related peripherals on `ESP32-H4` chip. + +crate::unstable_module! { + pub mod clocks; +} + +pub(crate) mod cpu_control; +pub(crate) mod regi2c; + +pub(crate) use esp32h4 as pac; + +#[cfg(feature = "rt")] +pub(crate) fn riscv_preinit() {} + +pub(crate) fn pre_init() { + // Core 1 is gated and held in reset after a chip reset, but a software reset of Core 0 leaves + // whatever start_core1() set up. Undo it so that Core 1 cannot run during startup. + unsafe { cpu_control::internal_park_core(crate::system::Cpu::AppCpu, true) }; + cpu_control::disable_core1(); + cpu_control::enable_core1_interrupt_matrix(); + + // By default, the APM access-path filters only allow masters that are in TEE mode. Every + // master except the HP CPU boots in REE mode, so the GDMA can neither fetch descriptors nor + // access memory until the filters are disabled. Reads return zeroes and writes are dropped, + // without a bus error. Mirrors ESP-IDF's `bootloader_init_mem`. + crate::peripherals::HP_APM::regs() + .func_ctrl() + .write(|w| unsafe { w.bits(0) }); + + // The RNG's clocks and its sampling logic are off after reset, and the driver has no way to + // request them - `Peripheral::KEEP_ENABLED` only prevents the clock from being disabled later. + // Run the same sequence as ESP-IDF's `rng_ll_enable` so that reads return random data. + crate::peripherals::LP_PERI::regs().clk_en().modify(|_, w| { + w.rng_apb_ck_en().set_bit(); + w.rng_ck_en().set_bit() + }); + crate::peripherals::RNG::regs().cfg().modify(|_, w| unsafe { + w.sample_enable().set_bit(); + w.timer_en().set_bit(); + w.rtc_timer_en().bits(3) + }); +} + +/// Writes back a specific range of data in the cache. +#[doc(hidden)] +#[crate::ram] +#[expect(dead_code, reason = "No enabled driver needs cache maintenance yet.")] +pub unsafe fn cache_writeback_addr(addr: u32, size: u32) { + unsafe extern "C" { + fn Cache_WriteBack_Addr(addr: u32, size: u32); + } + + unsafe { + Cache_WriteBack_Addr(addr, size); + } +} + +/// Invalidate a specific range of addresses in the cache. +#[doc(hidden)] +#[crate::ram] +#[expect(dead_code, reason = "No enabled driver needs cache maintenance yet.")] +pub unsafe fn cache_invalidate_addr(addr: u32, size: u32) { + const CACHE_MAP_L1_DCACHE: u32 = 1 << 4; + + unsafe extern "C" { + fn Cache_Invalidate_Addr(map: u32, addr: u32, size: u32); + } + unsafe { + Cache_Invalidate_Addr(CACHE_MAP_L1_DCACHE, addr, size); + } +} diff --git a/esp-hal/src/soc/esp32h4/regi2c.rs b/esp-hal/src/soc/esp32h4/regi2c.rs new file mode 100644 index 00000000000..fe2bb613b28 --- /dev/null +++ b/esp-hal/src/soc/esp32h4/regi2c.rs @@ -0,0 +1,166 @@ +//! Analog register access over the internal I2C master. +//! +//! Each analog slave is reachable through one of the two I2C masters. `ANA_CONF2` says which one, +//! `ANA_CONF1` selects the slave itself. + +use crate::{ + peripherals::{I2C_ANA_MST, MODEM_LPCON, MODEM_SYSCON}, + rom::regi2c::{RawRegI2cField, RegI2cMaster, RegI2cRegister, define_regi2c}, +}; + +define_regi2c! { + master: REGI2C_ULP(0x61, 0) { + reg: I2C_ULP_IR(0) { + field: I2C_ULP_IR_FORCE_XPD_IPH(4..4), + field: I2C_ULP_IR_FORCE_XPD_CK(2..2), + field: I2C_ULP_IR_RESETB(0..0) + } + reg: I2C_ULP_O(3) { + field: I2C_ULP_BG_O_DONE_FLAG(3..3), + field: I2C_ULP_O_DONE_FLAG(0..0) + } + reg: I2C_ULP_OCODE_REG(4) { + field: I2C_ULP_OCODE(7..0) + } + reg: I2C_ULP_IR_FORCE(5) { + field: I2C_ULP_IR_FORCE_CODE(3..3) + } + reg: I2C_ULP_EXT_CODE_REG(6) { + field: I2C_ULP_EXT_CODE(7..0) + } + reg: I2C_ULP_CPREG(8) { + field: I2C_ULP_CPREG_DREG1P1(4..3), + field: I2C_ULP_CPREG_DREG(2..0) + } + } + master: REGI2C_PLL(0x62, 0) {} + master: REGI2C_SDM(0x63, 0) {} + master: REGI2C_BBPLL(0x66, 0) { + reg: I2C_BBPLL_IR_CAL(0) { + field: I2C_BBPLL_IR_CAL_CK_DIV(7..4), + field: I2C_BBPLL_IR_CAL_DELAY(3..0) + } + reg: I2C_BBPLL_IR_CAL_EXT_REG(1) { + field: I2C_BBPLL_IR_CAL_UNSTOP(7..7), + field: I2C_BBPLL_IR_CAL_START(6..6), + field: I2C_BBPLL_IR_CAL_RSTB(5..5), + field: I2C_BBPLL_IR_CAL_ENX_CAP(4..4), + field: I2C_BBPLL_IR_CAL_EXT_CAP(3..0) + } + reg: I2C_BBPLL_OC_REF(2) { + field: I2C_BBPLL_OC_REF_DIV(3..0) + } + reg: I2C_BBPLL_OC_DIV_REG(3) { + field: I2C_BBPLL_OC_DIV(5..0) + } + reg: I2C_BBPLL_REG4(4) { + field: I2C_BBPLL_OC_TSCHGP(6..6) + } + reg: I2C_BBPLL_REG5(5) { + field: I2C_BBPLL_OC_DLREF_SEL(7..6), + field: I2C_BBPLL_OC_DHREF_SEL(5..4) + } + reg: I2C_BBPLL_REG8(8) { + field: I2C_BBPLL_OR_LOCK(7..7), + field: I2C_BBPLL_OR_CAL_END(6..6), + field: I2C_BBPLL_OR_CAL_OVF(5..5), + field: I2C_BBPLL_OR_CAL_UDF(4..4), + field: I2C_BBPLL_OR_CAL_CAP(3..0) + } + reg: I2C_BBPLL_REG10(10) { + field: I2C_BBPLL_ENT_PLL(2..2), + field: I2C_BBPLL_DTEST(1..0) + } + } + master: REGI2C_BBTOP(0x67, 0) {} + master: REGI2C_PERIF(0x69, 0) {} + master: REGI2C_DCDC(0x6d, 0) { + reg: I2C_DCDC_REG1(1) { + field: I2C_DCDC_XPD_TRX(7..7) + } + reg: I2C_DCDC_CCM(7) { + field: I2C_DCDC_CCM_PCUR_LIMIT0(7..5), + field: I2C_DCDC_CCM_DREG0(4..0) + } + reg: I2C_DCDC_VCM(10) { + field: I2C_DCDC_VCM_PCUR_LIMIT0(7..5), + field: I2C_DCDC_VCM_DREG0(4..0) + } + reg: I2C_BOD(13) { + field: I2C_BOD_THRESHOLD(6..3) + } + } +} + +/// The `ANA_CONF1` bit that selects a slave, see the `REGI2C_CONF1_*_SEL` bit list in esp-idf's +/// `i2c_ana_mst_reg.h`. The matching `ANA_CONF2` bits sit two positions higher. +fn slave_select_bit(block: u8) -> u32 { + match block { + v if v == REGI2C_BBTOP.master => 2, + v if v == REGI2C_SDM.master => 4, + v if v == REGI2C_PLL.master => 5, + v if v == REGI2C_BBPLL.master => 7, + v if v == REGI2C_ULP.master => 8, + v if v == REGI2C_PERIF.master => 9, + v if v == REGI2C_DCDC.master => 10, + _ => unreachable!(), + } +} + +fn regi2c_enable_block(block: u8) -> usize { + // esp-idf only asserts that the master clock is running (the modem clock driver turns it on), + // so enable it here. The clock is also lost across sleep with the top domain powered down, + // which needs the ICG bitmaps that the sleep code will have to set up. + MODEM_SYSCON::regs() + .clk_conf() + .modify(|_, w| w.clk_i2c_mst_sel_160m().set_bit()); + MODEM_LPCON::regs() + .clk_conf() + .modify(|_, w| w.clk_i2c_mst_en().set_bit()); + + let select_bit = slave_select_bit(block); + + // A set bit means the slave is wired to I2C0, a clear bit means I2C1. + const CONF2_SELECT_SHIFT: u32 = 2; + let uses_i2c0 = I2C_ANA_MST::regs().ana_conf2().read().ana_conf2().bits() + & (1 << (select_bit + CONF2_SELECT_SHIFT)) + != 0; + + // Enabling a slave means clearing its bit while leaving every other one set. + const ANA_CONF1_MASK: u32 = 0x00FF_FFFF; + I2C_ANA_MST::regs() + .ana_conf1() + .write(|w| unsafe { w.ana_conf1().bits(!(1 << select_bit) & ANA_CONF1_MASK) }); + + if uses_i2c0 { 0 } else { 1 } +} + +pub(crate) fn regi2c_read(block: u8, _host_id: u8, reg_add: u8) -> u8 { + let master = regi2c_enable_block(block); + + while I2C_ANA_MST::regs().i2c_ctrl(master).read().busy().bit() {} + + I2C_ANA_MST::regs().i2c_ctrl(master).write(|w| unsafe { + w.slave_addr().bits(block); + w.slave_reg_addr().bits(reg_add) + }); + + while I2C_ANA_MST::regs().i2c_ctrl(master).read().busy().bit() {} + + I2C_ANA_MST::regs().i2c_ctrl(master).read().data().bits() +} + +pub(crate) fn regi2c_write(block: u8, _host_id: u8, reg_add: u8, data: u8) { + let master = regi2c_enable_block(block); + + while I2C_ANA_MST::regs().i2c_ctrl(master).read().busy().bit() {} + + I2C_ANA_MST::regs().i2c_ctrl(master).write(|w| unsafe { + w.slave_addr().bits(block); + w.slave_reg_addr().bits(reg_add); + w.read_write().set_bit(); + w.data().bits(data) + }); + + while I2C_ANA_MST::regs().i2c_ctrl(master).read().busy().bit() {} +} diff --git a/esp-hal/src/soc/esp32p4/clocks.rs b/esp-hal/src/soc/esp32p4/clocks.rs index cdd6abafa01..168a07838dd 100644 --- a/esp-hal/src/soc/esp32p4/clocks.rs +++ b/esp-hal/src/soc/esp32p4/clocks.rs @@ -35,15 +35,15 @@ define_clock_tree_types!(); #[non_exhaustive] pub enum CpuClock { /// 400 MHz CPU clock (eco5 / v3.x maximum) - /// CPLL -> CPU_ROOT -> CPU/1, APB divider /4 = 100MHz + /// CPLL -> CPU_ROOT -> CPU/1, APB divider /4 = 100 MHz _400MHz = 400, /// 200 MHz CPU clock (low power) - /// CPLL -> CPU_ROOT -> CPU/2, APB /2 = 100MHz + /// CPLL -> CPU_ROOT -> CPU/2, APB /2 = 100 MHz _200MHz = 200, /// 100 MHz CPU clock (ultra low power) - /// CPLL -> CPU_ROOT -> CPU/4, APB /1 = 100MHz + /// CPLL -> CPU_ROOT -> CPU/4, APB /1 = 100 MHz #[default] _100MHz = 100, } @@ -58,6 +58,7 @@ impl CpuClock { mem_clk: Some(MemClkConfig::new(1)), // /2 = 200 MHz sys_clk: Some(SysClkConfig::new(0)), // /1 = 200 MHz apb_clk: Some(ApbClkConfig::new(1)), // /2 = 100 MHz + crypto_clk: Some(CryptoClkConfig::PllF240m), iomux_function_clock: Some(IomuxFunctionClockConfig::new( IomuxFunctionClockSource::PllF80m, 0, @@ -77,6 +78,7 @@ impl CpuClock { mem_clk: Some(MemClkConfig::new(0)), // /1 = 200 MHz sys_clk: Some(SysClkConfig::new(0)), // /1 = 200 MHz apb_clk: Some(ApbClkConfig::new(1)), // /2 = 100 MHz + crypto_clk: Some(CryptoClkConfig::PllF240m), iomux_function_clock: Some(IomuxFunctionClockConfig::new( IomuxFunctionClockSource::PllF80m, 0, @@ -94,6 +96,7 @@ impl CpuClock { mem_clk: Some(MemClkConfig::new(0)), // /1 = 100 MHz sys_clk: Some(SysClkConfig::new(0)), // /1 = 100 MHz apb_clk: Some(ApbClkConfig::new(0)), // /1 = 100 MHz + crypto_clk: Some(CryptoClkConfig::PllF240m), iomux_function_clock: Some(IomuxFunctionClockConfig::new( IomuxFunctionClockSource::PllF80m, 0, @@ -434,6 +437,7 @@ fn configure_lp_slow_clk_impl( .modify(|_, w| unsafe { w.lp_aonclkrst_slow_clk_sel().bits(match new_selector { LpSlowClkConfig::RcSlow => 0, + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => 1, // LpSlowClkConfig::Rc32k => 2, LpSlowClkConfig::OscSlow => 3, @@ -516,6 +520,7 @@ fn enable_lp_slow_clk_impl(_clocks: &mut ClockTree, _en: bool) {} // Source clock enable/disable stubs (PLLs, oscillators) fn enable_rc_fast_clk_impl(_clocks: &mut ClockTree, _en: bool) {} +#[cfg(use_xtal32k)] fn enable_xtal32k_clk_impl(_clocks: &mut ClockTree, _en: bool) {} fn enable_osc_slow_clk_impl(_clocks: &mut ClockTree, _en: bool) {} fn enable_rc_slow_clk_impl(_clocks: &mut ClockTree, _en: bool) {} @@ -528,6 +533,30 @@ fn enable_pll_f240m_impl(_clocks: &mut ClockTree, _en: bool) {} fn enable_pll_f25m_impl(_clocks: &mut ClockTree, _en: bool) {} fn enable_pll_f50m_impl(_clocks: &mut ClockTree, _en: bool) {} fn enable_xtal_d2_clk_impl(_clocks: &mut ClockTree, _en: bool) {} +fn enable_spll_d3_clock_impl(_clocks: &mut ClockTree, _en: bool) {} + +// CRYPTO_CLK + +fn enable_crypto_clk_impl(_clocks: &mut ClockTree, _en: bool) { + // Nothing to do here. +} + +fn configure_crypto_clk_impl( + _clocks: &mut ClockTree, + _old_config: Option, + new_config: CryptoClkConfig, +) { + HP_SYS_CLKRST::regs() + .peri_clk_ctrl25() + .modify(|_, w| unsafe { + w.crypto_clk_src_sel().bits(match new_config { + CryptoClkConfig::Xtal => 0, + CryptoClkConfig::RcFast => 1, + CryptoClkConfig::PllF240m => 2, + CryptoClkConfig::PllF160m => 3, + }) + }); +} // TIMG_CALIBRATION_CLOCK @@ -638,6 +667,7 @@ fn configure_timg_calibration_clock_impl( TimgCalibrationClockConfig::CpllClk => 2, TimgCalibrationClockConfig::RcFastDivClk => 7, TimgCalibrationClockConfig::RcSlowClk => 8, + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => 10, }) }); diff --git a/esp-hal/src/soc/esp32p4/cpu_control.rs b/esp-hal/src/soc/esp32p4/cpu_control.rs index cc98c81a25a..50a15a5a134 100644 --- a/esp-hal/src/soc/esp32p4/cpu_control.rs +++ b/esp-hal/src/soc/esp32p4/cpu_control.rs @@ -1,5 +1,3 @@ -#[cfg(feature = "unstable")] -use crate::system::multi_core; use crate::{ peripherals::{HP_SYS, HP_SYS_CLKRST, LP_AON_CLKRST, PMU}, system::Cpu, @@ -38,7 +36,7 @@ pub fn is_running(core: Cpu) -> bool { code != 0x86 } -/// Prepare Core 1 for an imminent system reset. +/// Prepares Core 1 for an imminent system reset. /// /// Mirrors IDF's `esp_restart_noos()` pre-reset sequence for ESP32-P4: /// 1. Briefly reset Core 1's CPU (LP AON domain, so it takes effect even with global reset still @@ -66,7 +64,7 @@ pub(crate) fn pre_system_reset() { crate::rom::ets_set_appcpu_boot_addr(0); } -/// Disable Core 1's CPU clock and hold it in global reset. +/// Disables Core 1's CPU clock and hold it in global reset. /// /// Called from `pre_init` on every boot to undo any state left by a previous /// run that survived a software reset (HP_SYS_CLKRST registers are not @@ -81,6 +79,28 @@ pub(crate) fn disable_core1() { .modify(|_, w| w.rst_en_core1_global().set_bit()); } +/// Releases core 1 from reset after a CPU-domain power-down wake. +/// +/// esp-idf keys this on `core_id == 0` in both the initiator and the helper paths. +#[cfg(all( + cpu_retention = "software", + multi_core, + supports_cpu_power_down, + feature = "rt" +))] +#[crate::ram] +pub(crate) fn restart_core1_after_wake() { + if Cpu::current() != Cpu::ProCpu { + return; + } + HP_SYS_CLKRST::regs() + .soc_clk_ctrl0() + .modify(|_, w| w.core1_cpu_clk_en().set_bit()); + HP_SYS_CLKRST::regs() + .hp_rst_en0() + .modify(|_, w| w.rst_en_core1_global().clear_bit()); +} + #[cfg(feature = "unstable")] pub(crate) fn start_core1(entry_point: *const u32) { // Enable Core 1's CPU clock. @@ -96,63 +116,3 @@ pub(crate) fn start_core1(entry_point: *const u32) { // Hand the entry point to the ROM, which Core 1 is polling. crate::rom::ets_set_appcpu_boot_addr(entry_point as u32); } - -/// Core 1 entry point set as the boot address. -/// -/// The ROM jumps here directly, bypassing `_start`, so `gp` and the FPU -/// are not yet initialised. The naked prologue handles that before calling -/// regular Rust. -#[unsafe(naked)] -#[cfg(feature = "unstable")] -pub(crate) extern "C" fn start_core1_init() -> ! -where - F: FnOnce(), -{ - core::arch::naked_asm!( - // Set up the global pointer so GP-relative symbol accesses work. - ".option push", - ".option norelax", - "la gp, __global_pointer$", - ".option pop", - // Initialize the FPU (riscv32imafc has F). - "li t0, 0x6000", - "csrrs x0, mstatus, t0", - "fscsr x0", - // Switch to Core 1's stack (stored by Core 0 before releasing this core). - "la t0, {stack_top}", - "lw sp, 0(t0)", - // Tail-call into regular Rust. - "j {init}", - stack_top = sym multi_core::APP_CORE_STACK_TOP, - init = sym start_core1_init_impl::, - ) -} - -#[cfg(feature = "unstable")] -fn start_core1_init_impl() -> ! -where - F: FnOnce(), -{ - crate::soc::enable_branch_predictor(); - - // The ROM has already handed off to us; clear the AppCpu boot address so a - // subsequent software reset doesn't re-enter this stale entry point. - // Matches IDF's `call_start_cpu1`. - crate::rom::ets_set_appcpu_boot_addr(0); - - unsafe { - #[cfg(all(feature = "rt", stack_guard_monitoring))] - { - let guard = - multi_core::APP_CORE_STACK_GUARD.load(core::sync::atomic::Ordering::Acquire); - guard.write_volatile(esp_config::esp_config_int!( - u32, - "ESP_HAL_CONFIG_STACK_GUARD_VALUE" - )); - crate::debugger::set_stack_watchpoint(guard as usize); - } - crate::interrupt::init_vectoring(); - } - - unsafe { multi_core::CpuControl::start_core1_run::() } -} diff --git a/esp-hal/src/soc/esp32p4/mod.rs b/esp-hal/src/soc/esp32p4/mod.rs index c1e19c73a39..a937ed55ada 100644 --- a/esp-hal/src/soc/esp32p4/mod.rs +++ b/esp-hal/src/soc/esp32p4/mod.rs @@ -1,5 +1,6 @@ crate::unstable_module! { pub mod clocks; + pub mod trng; } pub(crate) mod cpu_control; @@ -28,19 +29,6 @@ pub(crate) fn pre_init() { } } -pub(crate) fn enable_branch_predictor() { - // Enable branch predictor - // Note that the branch predictor will start cache requests and needs to be disabled when - // the cache is disabled. - // MHCR: CSR 0x7c1 - const MHCR_RS: u32 = 1 << 4; // R/W, address return stack set bit - const MHCR_BFE: u32 = 1 << 5; // R/W, allow predictive jump set bit - const MHCR_BTB: u32 = 1 << 12; // R/W, branch target prediction enable bit - unsafe { - core::arch::asm!("csrrs x0, 0x7c1, {0}", in(reg) MHCR_RS | MHCR_BFE | MHCR_BTB); - } -} - const CACHE_MAP_L1_ICACHE_0: u32 = 1 << 0; const CACHE_MAP_L1_ICACHE_1: u32 = 1 << 1; const CACHE_MAP_L1_DCACHE: u32 = 1 << 4; @@ -52,7 +40,7 @@ fn cache_l2_bus(addr: u32) -> u32 { if internal { 0 } else { CACHE_MAP_L2_CACHE } } -/// Write back a specific range of data in the cache. +/// Writes back a specific range of data in the cache. pub(crate) unsafe fn cache_writeback_addr(addr: u32, size: u32) { unsafe extern "C" { fn Cache_WriteBack_Addr(bus: u32, addr: u32, size: u32); @@ -87,9 +75,3 @@ pub(crate) unsafe fn cache_invalidate_icache_addr(addr: u32, size: u32) { ); } } - -#[cfg(i2s_driver_supported)] -#[cfg_attr(not(feature = "unstable"), allow(unused))] -pub(crate) fn i2s_sclk_frequency() -> u32 { - clocks::pll_f160m_frequency() -} diff --git a/esp-hal/src/soc/esp32p4/regi2c.rs b/esp-hal/src/soc/esp32p4/regi2c.rs index 7302817e473..7518ddb7790 100644 --- a/esp-hal/src/soc/esp32p4/regi2c.rs +++ b/esp-hal/src/soc/esp32p4/regi2c.rs @@ -94,7 +94,7 @@ const REGI2C_RTC_ADDR_MASK: u32 = 0xFF; const REGI2C_RTC_SLAVE_ID_SHIFT: u32 = 0; const REGI2C_RTC_SLAVE_ID_MASK: u32 = 0xFF; -/// Select the I2C master for the given analog block. +/// Selects the I2C master for the given analog block. fn regi2c_enable_block(block: u8) { // Enable I2C master clock LP_PERI::regs() @@ -134,7 +134,7 @@ fn regi2c_enable_block(block: u8) { .modify(|r, w| unsafe { w.ana_conf2().bits(r.ana_conf2().bits() | sel_bit) }); } -/// Wait for I2C bus to become idle. +/// Waits for I2C bus to become idle. #[inline] fn wait_i2c_idle() { while LP_I2C_ANA_MST::regs() @@ -147,7 +147,7 @@ fn wait_i2c_idle() { } } -/// Read an analog I2C register. +/// Reads an analog I2C register. pub(crate) fn regi2c_read(block: u8, _host_id: u8, reg_add: u8) -> u8 { regi2c_enable_block(block); wait_i2c_idle(); @@ -166,7 +166,7 @@ pub(crate) fn regi2c_read(block: u8, _host_id: u8, reg_add: u8) -> u8 { ((val >> REGI2C_RTC_DATA_SHIFT) & REGI2C_RTC_DATA_MASK) as u8 } -/// Write an analog I2C register. +/// Writes an analog I2C register. pub(crate) fn regi2c_write(block: u8, _host_id: u8, reg_add: u8, data: u8) { regi2c_enable_block(block); wait_i2c_idle(); diff --git a/esp-hal/src/soc/esp32p4/trng.rs b/esp-hal/src/soc/esp32p4/trng.rs new file mode 100644 index 00000000000..d1407bf8c21 --- /dev/null +++ b/esp-hal/src/soc/esp32p4/trng.rs @@ -0,0 +1,155 @@ +use crate::{ + peripherals::{APB_SARADC, HP_SYS_CLKRST, LP_ADC, PMU, RNG}, + soc::regi2c, +}; + +// `I2C_SAR_ADC_INIT_CODE_VAL`, see +const SAR_ADC_INIT_CODE: u16 = 2166; + +// `RNG_LL_CFG_PSCALE`, see +const RNG_TIMER_PSCALE: u8 = 255; + +// See +pub(crate) fn rng_ll_enable() { + let rng = RNG::regs(); + rng.date().modify(|_, w| w.clk_en().set_bit()); + rng.rstn().modify(|_, w| w.rstn().clear_bit()); + rng.rstn().modify(|_, w| w.rstn().set_bit()); + rng.cfg() + .modify(|_, w| unsafe { w.timer_pscale().bits(RNG_TIMER_PSCALE) }); + rng.cfg().modify(|_, w| w.timer_en().set_bit()); + rng.cfg().modify(|_, w| w.sample_enable().set_bit()); +} + +/// Enables true randomness by enabling the entropy source. +/// Blocks `ADC` usage. +// See +pub(crate) fn ensure_randomness() { + let clkrst = HP_SYS_CLKRST::regs(); + let apb_saradc = APB_SARADC::regs(); + let lp_adc = LP_ADC::regs(); + + clkrst.hp_rst_en2().modify(|_, w| w.rst_en_adc().set_bit()); + clkrst + .hp_rst_en2() + .modify(|_, w| w.rst_en_adc().clear_bit()); + + clkrst + .soc_clk_ctrl2() + .modify(|_, w| w.adc_apb_clk_en().set_bit()); + clkrst + .peri_clk_ctrl23() + .modify(|_, w| w.adc_clk_en().set_bit()); + + clkrst + .peri_clk_ctrl22() + .modify(|_, w| w.adc_clk_src_sel().xtal()); + clkrst.peri_clk_ctrl23().modify(|_, w| unsafe { + w.adc_clk_div_num().bits(0); + w.adc_clk_div_numerator().bits(0); + w.adc_clk_div_denominator().bits(0) + }); + + // `regi2c_ctrl_ll_i2c_sar_periph_enable`, see + let pmu = PMU::regs(); + pmu.rf_pwc().modify(|_, w| w.perif_i2c_rstb().clear_bit()); + crate::rom::ets_delay_us(1); + pmu.rf_pwc().modify(|_, w| w.xpd_perif_i2c().set_bit()); + pmu.rf_pwc().modify(|_, w| w.perif_i2c_rstb().set_bit()); + + regi2c::I2C_SAR_ADC_DTEST_VDD_GRP1.write_field(0); + regi2c::I2C_SAR_ADC_ENT_VDD_GRP1.write_field(1); + + let [init_code_high, init_code_low] = SAR_ADC_INIT_CODE.to_be_bytes(); + regi2c::ADC_SAR1_INITIAL_CODE_HIGH.write_field(init_code_high); + regi2c::ADC_SAR1_INITIAL_CODE_LOW.write_field(init_code_low); + + apb_saradc.sar1_patt_tab1().modify(|_, w| unsafe { + w.item0_channel().bits(10); + w.item0_atten().db12(); + w.item1_channel().bits(10); + w.item1_atten().db12(); + w.item2_channel().bits(10); + w.item2_atten().db12(); + w.item3_channel().bits(10); + w.item3_atten().db12() + }); + apb_saradc + .ctrl() + .modify(|_, w| unsafe { w.sar1_patt_len().bits(0) }); + + lp_adc + .meas1_mux() + .modify(|_, w| w.sar1_dig_force().set_bit()); + lp_adc.meas1_ctrl2().modify(|_, w| { + w.meas1_start_force().set_bit(); + w.sar1_en_pad_force().set_bit() + }); + + apb_saradc.ctrl().modify(|_, w| { + w.sar_clk_gated().set_bit(); + w.xpd_sar1_force().pu() + }); + + apb_saradc + .ctrl() + .modify(|_, w| unsafe { w.sar_clk_div().bits(15) }); + + apb_saradc.ctrl2().modify(|_, w| unsafe { + w.timer_target().bits(100); + w.timer_sel().set_bit(); + w.timer_en().set_bit() + }); + + rng_ll_enable(); +} + +/// Disables true randomness. Unlocks `ADC` peripheral. +// See +pub(crate) fn revert_trng() { + let clkrst = HP_SYS_CLKRST::regs(); + let apb_saradc = APB_SARADC::regs(); + let lp_adc = LP_ADC::regs(); + + // `rng_ll_disable` is skipped: `Rng` keeps using the RNG. + + apb_saradc.ctrl2().modify(|_, w| w.timer_en().clear_bit()); + + unsafe { + apb_saradc.sar1_patt_tab1().write(|w| w.bits(0xFF_FFFF)); + apb_saradc.sar1_patt_tab2().write(|w| w.bits(0xFF_FFFF)); + apb_saradc.sar1_patt_tab3().write(|w| w.bits(0xFF_FFFF)); + apb_saradc.sar1_patt_tab4().write(|w| w.bits(0xFF_FFFF)); + apb_saradc.sar2_patt_tab1().write(|w| w.bits(0xFF_FFFF)); + apb_saradc.sar2_patt_tab2().write(|w| w.bits(0xFF_FFFF)); + apb_saradc.sar2_patt_tab3().write(|w| w.bits(0xFF_FFFF)); + apb_saradc.sar2_patt_tab4().write(|w| w.bits(0xFF_FFFF)); + } + + regi2c::ADC_SAR1_INITIAL_CODE_HIGH.write_field(0); + regi2c::ADC_SAR1_INITIAL_CODE_LOW.write_field(0); + regi2c::ADC_SAR2_INITIAL_CODE_HIGH.write_field(0); + regi2c::ADC_SAR2_INITIAL_CODE_LOW.write_field(0); + + regi2c::I2C_SAR_ADC_DTEST_VDD_GRP1.write_field(0); + regi2c::I2C_SAR_ADC_ENT_VDD_GRP1.write_field(0); + + // `regi2c_saradc_disable` is skipped: the ADC driver doesn't power PERIF_I2C itself. + + clkrst.peri_clk_ctrl23().modify(|_, w| unsafe { + w.adc_clk_div_num().bits(4); + w.adc_clk_div_numerator().bits(0); + w.adc_clk_div_denominator().bits(0) + }); + clkrst + .peri_clk_ctrl22() + .modify(|_, w| w.adc_clk_src_sel().xtal()); + + lp_adc + .meas1_mux() + .modify(|_, w| w.sar1_dig_force().clear_bit()); + lp_adc.meas1_ctrl2().modify(|_, w| { + w.meas1_start_force().set_bit(); + w.sar1_en_pad_force().set_bit() + }); +} diff --git a/esp-hal/src/soc/esp32s2/clocks.rs b/esp-hal/src/soc/esp32s2/clocks.rs index bdb279857fa..3d2ebef0572 100644 --- a/esp-hal/src/soc/esp32s2/clocks.rs +++ b/esp-hal/src/soc/esp32s2/clocks.rs @@ -227,6 +227,12 @@ fn configure_pll_clk_impl( // `enable_pll_clk_impl`. } +// PLL_F160M_CLK + +fn enable_pll_f160m_clk_impl(_clocks: &mut ClockTree, _en: bool) { + // Nothing to do. +} + // APLL_CLK fn enable_apll_clk_impl(_clocks: &mut ClockTree, en: bool) { @@ -502,6 +508,7 @@ fn enable_apb_clk_80m_impl(_clocks: &mut ClockTree, _en: bool) { // XTAL32K_CLK +#[cfg(use_xtal32k)] fn enable_xtal32k_clk_impl(_clocks: &mut ClockTree, en: bool) { // This bit only enables the clock for the digital core, what about RTC? Should we split the // clock node in two? @@ -583,6 +590,7 @@ fn configure_rtc_slow_clk_impl( LPWR::regs().clk_conf().modify(|_, w| unsafe { w.ana_clk_rtc_sel().bits(match new_config { RtcSlowClkConfig::RcSlow => 0, + #[cfg(use_xtal32k)] RtcSlowClkConfig::Xtal32k => 1, RtcSlowClkConfig::RcFast => 2, }) @@ -644,6 +652,7 @@ fn configure_timg_calibration_clock_impl( w.rtc_cali_clk_sel().bits(match new_config { TimgCalibrationClockConfig::RtcClk => 0, TimgCalibrationClockConfig::RcFastDivClk => 1, + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => 2, }) }); diff --git a/esp-hal/src/soc/esp32s2/gpio.rs b/esp-hal/src/soc/esp32s2/gpio.rs index 13f9725630d..f279f2f79a2 100644 --- a/esp-hal/src/soc/esp32s2/gpio.rs +++ b/esp-hal/src/soc/esp32s2/gpio.rs @@ -3,8 +3,8 @@ //! ## Overview //! //! The `GPIO` module provides functions and configurations for controlling the -//! `General Purpose Input/Output` pins on the `ESP32-S2` chip. It allows you to -//! configure pins as inputs or outputs, set their state and read their state. +//! `General Purpose Input/Output` pins on the `ESP32-S2` chip. It configures pins +//! as inputs or outputs, sets their state, and reads their state. //! //! Let's get through the functionality and configurations provided by this GPIO //! module: diff --git a/esp-hal/src/soc/esp32s2/lp_core.rs b/esp-hal/src/soc/esp32s2/lp_core.rs index 1989932027f..73cf690defc 100644 --- a/esp-hal/src/soc/esp32s2/lp_core.rs +++ b/esp-hal/src/soc/esp32s2/lp_core.rs @@ -59,14 +59,14 @@ pub enum UlpCoreWakeupSource { Timer(UlpCoreTimerCycles), } -/// ULP Timer cycles are clocked at a rate of approximately 8MHz / 32768 = ~244 Hz. +/// ULP Timer cycles are clocked at a rate of approximately 8 MHz / 32768 = ~244 Hz. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct UlpCoreTimerCycles { cycles: u32, } impl UlpCoreTimerCycles { /// Creates a new Ulp Timer cycle count configuration. - /// ## Panics + /// # Panics /// /// Panics if the cycles value is outside of the value range (0 ..= 0xFFFFFF). pub const fn new(cycles: u32) -> Self { @@ -118,9 +118,9 @@ impl<'d> UlpCore<'d> { /// Lets the ULP core wake the chip from sleep. /// - /// The request stays until you call [`Self::disable_wakeup`]. It stays through a sleep, through - /// a deep-sleep wake, and after a drop of this driver. While the chip is awake, it does - /// nothing. + /// The request stays until [`Self::disable_wakeup`] is called. It stays through a sleep, + /// through a deep-sleep wake, and after a drop of this driver. While the chip is awake, it + /// does nothing. pub fn enable_wakeup(&mut self, config: WakeupConfig) { enable_wakeup(config); } diff --git a/esp-hal/src/soc/esp32s2/mod.rs b/esp-hal/src/soc/esp32s2/mod.rs index fca753435d8..414ee7a108c 100644 --- a/esp-hal/src/soc/esp32s2/mod.rs +++ b/esp-hal/src/soc/esp32s2/mod.rs @@ -15,18 +15,7 @@ pub(crate) mod regi2c; pub(crate) use esp32s2 as pac; -#[cfg(i2s_driver_supported)] -#[cfg_attr(not(feature = "unstable"), allow(unused))] -pub(crate) fn i2s_sclk_frequency() -> u32 { - // I2S uses the 160 MHz PLL tap, derived from either supported PLL frequency. - match clocks::pll_clk_frequency() { - 320_000_000 => 320_000_000 / 2, - 480_000_000 => 480_000_000 / 3, - _ => unreachable!(), - } -} - -/// Write back a specific range of data in the cache. +/// Writes back a specific range of data in the cache. #[doc(hidden)] #[unsafe(link_section = ".rwtext")] pub unsafe fn cache_writeback_addr(addr: u32, size: u32) { @@ -66,12 +55,11 @@ pub(crate) const CONFIG_INSTRUCTION_CACHE_SIZE: usize = cfg_select! { instruction_cache_size_8kb => 0, instruction_cache_size_16kb => 1, }; -pub(crate) const CONFIG_DATA_CACHE_SIZE: usize = - cfg_select! { - data_cache_size_0kb => 0, // doesn't matter according to esp-idf - data_cache_size_8kb => 0, - data_cache_size_16kb => 1, - }; +pub(crate) const CONFIG_DATA_CACHE_SIZE: usize = cfg_select! { + data_cache_size_0kb => 0, // doesn't matter according to esp-idf + data_cache_size_8kb => 0, + data_cache_size_16kb => 1, +}; #[crate::ram] pub(crate) unsafe fn configure_cpu_caches() { @@ -80,7 +68,7 @@ pub(crate) unsafe fn configure_cpu_caches() { /// Invalidate all cache items in ICache. fn Cache_Invalidate_ICache_All(); - /// Set ICache modes: cache size, associate ways and cache line size. + /// Sets ICache modes: cache size, associate ways and cache line size. /// /// @param cache_size_t cache_size : the cache size, can be CACHE_SIZE_HALF and /// CACHE_SIZE_FULL @@ -91,12 +79,12 @@ pub(crate) unsafe fn configure_cpu_caches() { /// CACHE_LINE_SIZE_16B, CACHE_LINE_SIZE_32B fn Cache_Set_ICache_Mode(cache_size: u32, ways: u32, cache_line_size: u32); - /// Resume ICache access for the cpu. + /// Resumes ICache access for the cpu. /// /// @param uint32_t autoload : ICache will preload then. fn Cache_Resume_ICache(autoload: u32); - /// Allocate memory to used by ICache and DCache. + /// Allocates memory to used by ICache and DCache. /// /// [`sram0_layout`]: u32 the usage of first 8KB internal memory block, /// can be CACHE_MEMORY_INVALID, @@ -112,7 +100,7 @@ pub(crate) unsafe fn configure_cpu_caches() { sram3_layout: u32, ); - /// Set DCache modes: cache size, associate ways and cache line size. + /// Sets DCache modes: cache size, associate ways and cache line size. /// /// [`cache_size`]: u32 the cache size, can be CACHE_SIZE_HALF and CACHE_SIZE_FULL /// [`ways`]: u32 the associate ways of cache, can only be CACHE_4WAYS_ASSOC @@ -122,7 +110,7 @@ pub(crate) unsafe fn configure_cpu_caches() { /// Invalidate all cache items in DCache. fn Cache_Invalidate_DCache_All(); - /// Enable DCache access for the cpu. + /// Enables DCache access for the cpu. /// /// @param uint32_t autoload : DCache will preload then. fn Cache_Enable_DCache(autoload: u32); diff --git a/esp-hal/src/soc/esp32s2/regi2c.rs b/esp-hal/src/soc/esp32s2/regi2c.rs index 3e52eb001da..5964ddd79cc 100644 --- a/esp-hal/src/soc/esp32s2/regi2c.rs +++ b/esp-hal/src/soc/esp32s2/regi2c.rs @@ -39,8 +39,10 @@ define_regi2c! { } master: REGI2C_BOD(0x61, 1) { reg: I2C_BOD_REG5(5) { + field: I2C_ULP_IR_FORCE_CODE(6..6), field: I2C_BOD_REG_THRESHOLD(2..0) } + reg: I2C_ULP_EXT_CODE(6) {} } master: REGI2C_BBPLL(0x66, 1) { reg: I2C_BBPLL_REG0(0) { diff --git a/esp-hal/src/soc/esp32s2/trng.rs b/esp-hal/src/soc/esp32s2/trng.rs index 6de8fc5fa3d..669da5042f5 100644 --- a/esp-hal/src/soc/esp32s2/trng.rs +++ b/esp-hal/src/soc/esp32s2/trng.rs @@ -3,7 +3,7 @@ use crate::{ soc::regi2c, }; -/// Enable true randomness by enabling the entropy source. +/// Enables true randomness by enabling the entropy source. /// Blocks `ADC` usage. pub(crate) fn ensure_randomness() { // Enable 8M clock source for RNG (this is actually enough to produce strong @@ -84,7 +84,7 @@ pub(crate) fn ensure_randomness() { .modify(|_, w| w.timer_en().set_bit()); } -/// Disable true randomness. Unlocks `ADC` peripheral. +/// Disables true randomness. Unlocks `ADC` peripheral. pub(crate) fn revert_trng() { unsafe { // Restore internal I2C bus state diff --git a/esp-hal/src/soc/esp32s3/clocks.rs b/esp-hal/src/soc/esp32s3/clocks.rs index 7ed8daa31ac..03495b5eb21 100644 --- a/esp-hal/src/soc/esp32s3/clocks.rs +++ b/esp-hal/src/soc/esp32s3/clocks.rs @@ -55,6 +55,7 @@ impl CpuClock { cpu_clk: Some(CpuClkConfig::Pll), rc_fast_clk_div_n: Some(RcFastClkDivNConfig::new(0)), rtc_slow_clk: Some(xtal32k::default_rtc_slow_clk()), + ble_lp_clk: Some(BleLpClkConfig::Xtal), rtc_fast_clk: Some(RtcFastClkConfig::Rc), low_power_clk: Some(LowPowerClkConfig::RtcSlow), timg_calibration_clock: None, @@ -67,6 +68,7 @@ impl CpuClock { cpu_clk: Some(CpuClkConfig::Pll), rc_fast_clk_div_n: Some(RcFastClkDivNConfig::new(0)), rtc_slow_clk: Some(xtal32k::default_rtc_slow_clk()), + ble_lp_clk: Some(BleLpClkConfig::Xtal), rtc_fast_clk: Some(RtcFastClkConfig::Rc), low_power_clk: Some(LowPowerClkConfig::RtcSlow), timg_calibration_clock: None, @@ -79,6 +81,7 @@ impl CpuClock { cpu_clk: Some(CpuClkConfig::Pll), rc_fast_clk_div_n: Some(RcFastClkDivNConfig::new(0)), rtc_slow_clk: Some(xtal32k::default_rtc_slow_clk()), + ble_lp_clk: Some(BleLpClkConfig::Xtal), rtc_fast_clk: Some(RtcFastClkConfig::Rc), low_power_clk: Some(LowPowerClkConfig::RtcSlow), timg_calibration_clock: None, @@ -280,6 +283,7 @@ fn enable_rc_fast_clk_impl(_clocks: &mut ClockTree, en: bool) { // XTAL32K_CLK +#[cfg(use_xtal32k)] fn enable_xtal32k_clk_impl(_clocks: &mut ClockTree, en: bool) { // RTCIO could be configured to allow an external oscillator to be used. We could model this // with a MUX, probably, but this is omitted for now for simplicity. @@ -681,6 +685,7 @@ fn configure_rtc_slow_clk_impl( LPWR::regs().clk_conf().modify(|_, w| unsafe { // TODO: variants should be in PAC w.ana_clk_rtc_sel().bits(match new_config { + #[cfg(use_xtal32k)] RtcSlowClkConfig::Xtal32k => 1, RtcSlowClkConfig::RcSlow => 0, RtcSlowClkConfig::RcFast => 2, @@ -719,6 +724,10 @@ fn configure_low_power_clk_impl( _old_config: Option, new_config: LowPowerClkConfig, ) { + // The divider resets to 255. The Wi-Fi light sleep timer expects the undivided clock. + SYSTEM::regs() + .bt_lpck_div_int() + .modify(|_, w| unsafe { w.bt_lpck_div_num().bits(0) }); SYSTEM::regs().bt_lpck_div_frac().modify(|_, w| { w.lpclk_sel_8m() .bit(new_config == LowPowerClkConfig::RcFast); @@ -726,8 +735,12 @@ fn configure_low_power_clk_impl( .bit(new_config == LowPowerClkConfig::RtcSlow); w.lpclk_sel_xtal() .bit(new_config == LowPowerClkConfig::Xtal); - w.lpclk_sel_xtal32k() - .bit(new_config == LowPowerClkConfig::Xtal32k) + w.lpclk_sel_xtal32k().bit({ + cfg_select! { + use_xtal32k => new_config == LowPowerClkConfig::Xtal32k, + _ => false, + } + }) }); } @@ -766,6 +779,7 @@ fn configure_timg_calibration_clock_impl( w.rtc_cali_clk_sel().bits(match new_config { TimgCalibrationClockConfig::RcSlowClk => 0, TimgCalibrationClockConfig::RcFastDivClk => 1, + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => 2, }) }); @@ -910,3 +924,23 @@ impl TimgInstance { }); } } + +// BLE_LP_XTAL_CLK + +fn enable_ble_lp_xtal_clk_impl(_clocks: &mut ClockTree, _en: bool) { + // Nothing to do. +} + +// BLE_LP_CLK + +fn enable_ble_lp_clk_impl(_clocks: &mut ClockTree, _en: bool) { + // Nothing to do. +} + +fn configure_ble_lp_clk_impl( + _clocks: &mut ClockTree, + _old_config: Option, + _new_config: BleLpClkConfig, +) { + // The BTDM controller programs the source and divider. +} diff --git a/esp-hal/src/soc/esp32s3/cpu_control.rs b/esp-hal/src/soc/esp32s3/cpu_control.rs index 03f1d1e3214..ffd72ef6ac8 100644 --- a/esp-hal/src/soc/esp32s3/cpu_control.rs +++ b/esp-hal/src/soc/esp32s3/cpu_control.rs @@ -6,11 +6,9 @@ //! and managing the APP (second) CPU core on the `ESP32-S3` chip. It is used to //! start and stop program execution on the APP core. -use core::sync::atomic::Ordering; - use crate::{ peripherals::{LPWR, SYSTEM}, - system::{Cpu, multi_core::*}, + system::Cpu, }; pub(crate) unsafe fn internal_park_core(core: Cpu, park: bool) { @@ -36,7 +34,7 @@ pub(crate) unsafe fn internal_park_core(core: Cpu, park: bool) { } } -/// Returns `true` if the specified core is currently running (not stalled). +/// Returns whether the specified core is currently running (not stalled). #[instability::unstable] pub fn is_running(core: Cpu) -> bool { if core == Cpu::AppCpu { @@ -77,6 +75,7 @@ pub fn is_running(core: Cpu) -> bool { is_stalled != 0x86 } +#[cfg(feature = "unstable")] pub(crate) fn start_core1(entry_point: *const u32) { let system_control = SYSTEM::regs(); @@ -95,53 +94,3 @@ pub(crate) fn start_core1(entry_point: *const u32) { .core_1_control_0() .modify(|_, w| w.control_core_1_reseting().clear_bit()); } - -pub(crate) fn start_core1_init() -> ! -where - F: FnOnce(), -{ - // disables interrupts - unsafe { - xtensa_lx::interrupt::set_mask(0); - } - - // reset cycle compare registers - xtensa_lx::timer::set_ccompare0(0); - xtensa_lx::timer::set_ccompare1(0); - xtensa_lx::timer::set_ccompare2(0); - - unsafe extern "C" { - static mut _init_start: u32; - } - - // set vector table and stack pointer - unsafe { - xtensa_lx::set_vecbase(&raw const _init_start); - xtensa_lx::set_stack_pointer(APP_CORE_STACK_TOP.load(Ordering::Acquire)); - - #[cfg(all(feature = "rt", stack_guard_monitoring))] - { - let stack_guard = APP_CORE_STACK_GUARD.load(Ordering::Acquire); - stack_guard.write_volatile(esp_config::esp_config_int!( - u32, - "ESP_HAL_CONFIG_STACK_GUARD_VALUE" - )); - // setting 0 effectively disables the functionality - crate::debugger::set_stack_watchpoint(stack_guard as usize); - } - } - - // The ROM has already handed off to us; clear the AppCpu boot address so a - // subsequent reset doesn't see a stale entry point. Matches IDF's - // `call_start_cpu1`. - crate::rom::ets_set_appcpu_boot_addr(0); - - // Do not call setup_interrupts as that would disable peripheral interrupts, too. - unsafe { crate::interrupt::init_vectoring() }; - - // Trampoline to run from the new stack. - // start_core1_run should _NEVER_ be inlined - // as we rely on the function call to use - // the new stack. - unsafe { CpuControl::start_core1_run::() } -} diff --git a/esp-hal/src/soc/esp32s3/gpio.rs b/esp-hal/src/soc/esp32s3/gpio.rs index 76288360af3..941debd1a0b 100644 --- a/esp-hal/src/soc/esp32s3/gpio.rs +++ b/esp-hal/src/soc/esp32s3/gpio.rs @@ -3,8 +3,8 @@ //! ## Overview //! //! The `GPIO` module provides functions and configurations for controlling the -//! `General Purpose Input/Output` pins on the `ESP32-S3` chip. It allows you to -//! configure pins as inputs or outputs, set their state and read their state. +//! `General Purpose Input/Output` pins on the `ESP32-S3` chip. It configures pins +//! as inputs or outputs, sets their state, and reads their state. //! //! Let's get through the functionality and configurations provided by this GPIO //! module: diff --git a/esp-hal/src/soc/esp32s3/lp_core.rs b/esp-hal/src/soc/esp32s3/lp_core.rs index 718a1cd56f7..e31108d69d1 100644 --- a/esp-hal/src/soc/esp32s3/lp_core.rs +++ b/esp-hal/src/soc/esp32s3/lp_core.rs @@ -59,14 +59,14 @@ pub enum UlpCoreWakeupSource { Timer(UlpCoreTimerCycles), } -/// ULP Timer cycles are clocked at a rate of approximately 17.5MHz / 32768 = ~534 Hz. +/// ULP Timer cycles are clocked at a rate of approximately 17.5 MHz / 32768 = ~534 Hz. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct UlpCoreTimerCycles { cycles: u32, } impl UlpCoreTimerCycles { /// Creates a new Ulp Timer cycle count configuration. - /// ## Panics + /// # Panics /// /// Panics if the cycles value is outside of the value range (0 ..= 0xFFFFFF). pub const fn new(cycles: u32) -> Self { @@ -119,9 +119,9 @@ impl<'d> UlpCore<'d> { /// Lets the ULP core wake the chip from sleep. /// - /// The request stays until you call [`Self::disable_wakeup`]. It stays through a sleep, through - /// a deep-sleep wake, and after a drop of this driver. While the chip is awake, it does - /// nothing. + /// The request stays until [`Self::disable_wakeup`] is called. It stays through a sleep, + /// through a deep-sleep wake, and after a drop of this driver. While the chip is awake, it + /// does nothing. pub fn enable_wakeup(&mut self, config: WakeupConfig) { enable_wakeup(config); } diff --git a/esp-hal/src/soc/esp32s3/mod.rs b/esp-hal/src/soc/esp32s3/mod.rs index 32a31582f09..b2b19959d2e 100644 --- a/esp-hal/src/soc/esp32s3/mod.rs +++ b/esp-hal/src/soc/esp32s3/mod.rs @@ -9,20 +9,14 @@ crate::unstable_module! { pub mod clocks; pub mod trng; pub mod lp_core; + // The light sleep path stalls the other core, and it is not gated on the feature. + pub mod cpu_control; } -#[cfg(feature = "unstable")] -pub mod cpu_control; pub mod gpio; pub(crate) mod regi2c; pub use esp32s3 as pac; -#[cfg(i2s_driver_supported)] -#[cfg_attr(not(feature = "unstable"), allow(unused))] -pub(crate) fn i2s_sclk_frequency() -> u32 { - clocks::pll_160m_frequency() -} - pub(crate) const CONFIG_INSTRUCTION_CACHE_SIZE: usize = cfg_select! { instruction_cache_size_32kb => 0x8000, instruction_cache_size_16kb => 0x4000, @@ -68,7 +62,7 @@ pub(crate) unsafe fn configure_cpu_caches() { // see https://github.com/apache/nuttx/blob/f25db331136351dbf8ebe6925a98d3b77e1ca983/arch/xtensa/src/esp32s3/esp32s3_start.c#L213 unsafe extern "C" { - fn Cache_Suspend_DCache(); + fn Cache_Suspend_DCache() -> u32; fn Cache_Resume_DCache(param: u32); @@ -106,7 +100,7 @@ pub(crate) unsafe fn configure_cpu_caches() { } } -/// Write back a specific range of data in the cache. +/// Writes back a specific range of data in the cache. #[doc(hidden)] #[unsafe(link_section = ".rwtext")] pub unsafe fn cache_writeback_addr(addr: u32, size: u32) { @@ -135,4 +129,40 @@ pub unsafe fn cache_invalidate_addr(addr: u32, size: u32) { } } +/// Writes back all dirty data cache lines. +#[doc(hidden)] +#[unsafe(link_section = ".rwtext")] +pub unsafe fn cache_writeback_all() { + unsafe extern "C" { + fn Cache_WriteBack_All(); + } + unsafe { + Cache_WriteBack_All(); + } +} + +/// Invalidates the entire instruction cache. +#[doc(hidden)] +#[unsafe(link_section = ".rwtext")] +pub unsafe fn cache_invalidate_icache_all() { + unsafe extern "C" { + fn Cache_Invalidate_ICache_All(); + } + unsafe { + Cache_Invalidate_ICache_All(); + } +} + +/// Invalidates the entire data cache. +#[doc(hidden)] +#[unsafe(link_section = ".rwtext")] +pub unsafe fn cache_invalidate_dcache_all() { + unsafe extern "C" { + fn Cache_Invalidate_DCache_All(); + } + unsafe { + Cache_Invalidate_DCache_All(); + } +} + pub(crate) fn pre_init() {} diff --git a/esp-hal/src/soc/esp32s3/regi2c.rs b/esp-hal/src/soc/esp32s3/regi2c.rs index cf6fa2064f5..6021375b311 100644 --- a/esp-hal/src/soc/esp32s3/regi2c.rs +++ b/esp-hal/src/soc/esp32s3/regi2c.rs @@ -113,6 +113,12 @@ define_regi2c! { field: I2C_DIG_REG_XPD_RTC_REG(2..2) } } + master: REGI2C_ULP_CAL(0x61, 1) { + reg: I2C_ULP_IR_FORCE(5) { + field: I2C_ULP_IR_FORCE_CODE(6..6) + } + reg: I2C_ULP_EXT_CODE(6) {} + } } pub(crate) fn regi2c_read(block: u8, host_id: u8, reg_add: u8) -> u8 { diff --git a/esp-hal/src/soc/esp32s3/trng.rs b/esp-hal/src/soc/esp32s3/trng.rs index c9375d9fca9..e19f8bf0e03 100644 --- a/esp-hal/src/soc/esp32s3/trng.rs +++ b/esp-hal/src/soc/esp32s3/trng.rs @@ -2,7 +2,7 @@ use crate::soc::regi2c; const SYSTEM_WIFI_CLK_RNG_EN: u32 = 1 << 15; -/// Enable true randomness by enabling the entropy source. +/// Enables true randomness by enabling the entropy source. /// Blocks `ADC` usage. pub(crate) fn ensure_randomness() { unsafe { @@ -93,7 +93,7 @@ pub(crate) fn ensure_randomness() { } } -/// Disable true randomness. Unlocks `ADC` peripheral. +/// Disables true randomness. Unlocks `ADC` peripheral. pub(crate) fn revert_trng() { let system = crate::peripherals::SYSTEM::regs(); let apb_saradc = crate::peripherals::APB_SARADC::regs(); diff --git a/esp-hal/src/soc/esp32s31/clocks.rs b/esp-hal/src/soc/esp32s31/clocks.rs index bc2159d7e3f..f120c40924d 100644 --- a/esp-hal/src/soc/esp32s31/clocks.rs +++ b/esp-hal/src/soc/esp32s31/clocks.rs @@ -13,8 +13,8 @@ use core::sync::atomic::{AtomicBool, Ordering}; use esp_rom_sys::rom::ets_update_cpu_frequency_rom; use crate::{ - peripherals::{HP_ALIVE_SYS, HP_SYS, HP_SYS_CLKRST, LP_AON_CLK_RST, PMU}, - soc::xtal32k, + peripherals::{HP_ALIVE_SYS, HP_SYS, HP_SYS_CLKRST, LP_AON_CLK_RST, MODEM_LPCON, PMU}, + soc::{regi2c, xtal32k}, }; define_clock_tree_types!(); @@ -40,11 +40,15 @@ pub enum CpuClock { impl CpuClock { const PRESET_160: ClockConfig = ClockConfig { cpu_root_clk: Some(CpuRootClkConfig::Cpll), + mpll_clk: Some(MpllClkConfig::_400), cpu_clk: Some(CpuClkConfig::new(1)), - ahb_clk: Some(AhbClkConfig::new(1)), - apb_clk: Some(ApbClkConfig::new(1)), + mem_clk: Some(MemClkConfig::new(0)), // Max 160 MHz + sys_clk: Some(SysClkConfig::new(1)), // Max ~320/3 MHz + apb_clk: Some(ApbClkConfig::new(1)), // MAX ~320/6MHz lp_fast_clk: Some(LpFastClkConfig::RcFast), lp_slow_clk: Some(xtal32k::default_lp_slow_clk()), + ble_lp_clk: Some(BleLpClkConfig::Xtal), + crypto_clk: Some(CryptoClkConfig::PllF240m), iomux_function_clock: Some(IomuxFunctionClockConfig::new( IomuxFunctionClockSource::PllF80m, 0, @@ -53,11 +57,15 @@ impl CpuClock { }; const PRESET_240: ClockConfig = ClockConfig { cpu_root_clk: Some(CpuRootClkConfig::PllF240m), + mpll_clk: Some(MpllClkConfig::_400), cpu_clk: Some(CpuClkConfig::new(0)), - ahb_clk: Some(AhbClkConfig::new(2)), - apb_clk: Some(ApbClkConfig::new(1)), + mem_clk: Some(MemClkConfig::new(1)), // Max 160 MHz + sys_clk: Some(SysClkConfig::new(2)), // Max ~320/3 MHz + apb_clk: Some(ApbClkConfig::new(1)), // MAX ~320/6MHz lp_fast_clk: Some(LpFastClkConfig::RcFast), lp_slow_clk: Some(xtal32k::default_lp_slow_clk()), + ble_lp_clk: Some(BleLpClkConfig::Xtal), + crypto_clk: Some(CryptoClkConfig::PllF240m), iomux_function_clock: Some(IomuxFunctionClockConfig::new( IomuxFunctionClockSource::PllF80m, 0, @@ -66,11 +74,15 @@ impl CpuClock { }; const PRESET_320: ClockConfig = ClockConfig { cpu_root_clk: Some(CpuRootClkConfig::Cpll), + mpll_clk: Some(MpllClkConfig::_400), cpu_clk: Some(CpuClkConfig::new(0)), - ahb_clk: Some(AhbClkConfig::new(2)), - apb_clk: Some(ApbClkConfig::new(1)), + mem_clk: Some(MemClkConfig::new(1)), // Max 160 MHz + sys_clk: Some(SysClkConfig::new(2)), // Max ~320/3 MHz + apb_clk: Some(ApbClkConfig::new(1)), // MAX ~320/6MHz lp_fast_clk: Some(LpFastClkConfig::RcFast), lp_slow_clk: Some(xtal32k::default_lp_slow_clk()), + ble_lp_clk: Some(BleLpClkConfig::Xtal), + crypto_clk: Some(CryptoClkConfig::PllF240m), iomux_function_clock: Some(IomuxFunctionClockConfig::new( IomuxFunctionClockSource::PllF80m, 0, @@ -180,6 +192,23 @@ fn enable_bbpll_clk_impl(_clocks: &mut ClockTree, en: bool) { fn enable_cpll_clk_impl(_clocks: &mut ClockTree, en: bool) { if en { + // Power the PLL up before the calibration, which cannot end without it. The PMU state + // must agree: a sleep that the PMU rejects does not apply the `HP_ACTIVE` state again. + PMU::regs().imm_hp_ck_power_1().modify(|_, w| { + w.tie_high_xpd_pll().set_bit(); + w.tie_high_xpd_pll_i2c().set_bit() + }); + PMU::regs() + .imm_hp_ck_power_1() + .modify(|_, w| w.tie_high_global_pll_icg().set_bit()); + HP_ALIVE_SYS::regs() + .hp_clk_ctrl() + .modify(|_, w| w.hp_cpll_300m_clk_en().set_bit()); + PMU::regs().hp_active_hp_ck_power().modify(|_, w| { + w.hp_active_xpd_pll_i2c().set_bit(); + w.hp_active_xpd_pll().set_bit() + }); + HP_SYS_CLKRST::regs() .ana_pll_ctrl0() .modify(|_, w| w.cpu_pll_cal_stop().clear_bit()); @@ -195,36 +224,38 @@ fn enable_cpll_clk_impl(_clocks: &mut ClockTree, en: bool) { HP_SYS_CLKRST::regs() .ana_pll_ctrl0() .modify(|_, w| w.cpu_pll_cal_stop().set_bit()); - - PMU::regs().imm_hp_ck_power_1().modify(|_, w| { - w.tie_high_xpd_pll().set_bit(); - w.tie_high_xpd_pll_i2c().set_bit(); - w.tie_high_global_pll_icg().set_bit() - }); } else { + PMU::regs() + .imm_hp_ck_power_1() + .modify(|_, w| w.tie_low_global_pll_icg().set_bit()); PMU::regs().imm_hp_ck_power_1().modify(|_, w| { - w.tie_low_global_pll_icg().set_bit(); w.tie_low_xpd_pll().set_bit(); w.tie_low_xpd_pll_i2c().set_bit() }); + HP_ALIVE_SYS::regs() + .hp_clk_ctrl() + .modify(|_, w| w.hp_cpll_300m_clk_en().clear_bit()); + PMU::regs().hp_active_hp_ck_power().modify(|_, w| { + w.hp_active_xpd_pll_i2c().clear_bit(); + w.hp_active_xpd_pll().clear_bit() + }); } - HP_ALIVE_SYS::regs() - .hp_clk_ctrl() - .modify(|_, w| w.hp_cpll_300m_clk_en().bit(en)); } // MPLL_CLK -fn enable_mpll_clk_impl(_clocks: &mut ClockTree, en: bool) { - if en { +fn enable_mpll_clk_impl(clocks: &mut ClockTree, en: bool) { + let mpll_mhz = en.then(|| unwrap!(clocks.mpll_clk).value() / 1_000_000); + if let Some(mpll_mhz) = mpll_mhz { psram_phy_ldo_init(); + // Keep PLL_F25M and PLL_F50M at 25 and 50 MHz. HP_SYS_CLKRST::regs() .ref_25m_ctrl0() - .modify(|_, w| unsafe { w.clk_div_num().bits(19) }); + .modify(|_, w| unsafe { w.clk_div_num().bits((mpll_mhz / 25 - 1) as u8) }); HP_SYS_CLKRST::regs() .ref_50m_ctrl0() - .modify(|_, w| unsafe { w.clk_div_num().bits(9) }); + .modify(|_, w| unsafe { w.clk_div_num().bits((mpll_mhz / 50 - 1) as u8) }); // Clock source of 25/50MHz dividers. HP_SYS_CLKRST::regs() @@ -251,9 +282,59 @@ fn enable_mpll_clk_impl(_clocks: &mut ClockTree, en: bool) { w.hp_active_xpd_mpll().bit(en); w.hp_active_xpd_mpll_i2c().bit(en) }); + + if let Some(mpll_mhz) = mpll_mhz { + set_mpll_frequency(mpll_mhz); + } +} + +/// Programs the MPLL to `mpll_mhz` and waits for its calibration to end. +/// +/// MPLL = XTAL * (fb_div + 1) / (ref_div + 1), with ref_div 1. +/// +/// Ref: [IDF `clk_ll_mpll_set_config` (esp32s31)](https://github.com/espressif/esp-idf/blob/27506a49bc919926f546e325d5f5334ba23db316/components/esp_hal_clock/esp32s31/include/hal/clk_tree_ll.h#L527-L545) +fn set_mpll_frequency(mpll_mhz: u32) { + // Analog settings IDF writes before each calibration. + regi2c::I2C_MPLL_IR_CAL_EXT_CAP.write_field(3); + regi2c::I2C_MPLL_IR_CAL_ENX_CAP.write_field(1); + LP_AON_CLK_RST::regs() + .mspi_div() + .modify(|_, w| unsafe { w.mspi_fb_div().bits(9) }); + regi2c::I2C_MPLL_DHREF.write_field(3); + regi2c::I2C_MPLL_IR_CAL_ENX_CAP.write_field(0); + + // Calibration starts before the divider is written, and stops after the PLL reports that it + // ended. + HP_SYS_CLKRST::regs() + .ana_pll_ctrl0() + .modify(|_, w| w.mspi_cal_stop().clear_bit()); + let ref_div = 1; + let fb_div = mpll_mhz * (ref_div + 1) / (xtal_clk_frequency() / 1_000_000) - 1; + LP_AON_CLK_RST::regs() + .mspi_div() + .modify(|_, w| unsafe { w.mspi_fb_div().bits(fb_div as u8) }); + while HP_SYS_CLKRST::regs() + .ana_pll_ctrl0() + .read() + .mspi_cal_end() + .bit_is_clear() + { + core::hint::spin_loop(); + } + HP_SYS_CLKRST::regs() + .ana_pll_ctrl0() + .modify(|_, w| w.mspi_cal_stop().set_bit()); } -/// Program the PMU external LDO regulators for the MSPI PHY +fn configure_mpll_clk_impl( + _clocks: &mut ClockTree, + _old_config: Option, + _new_config: MpllClkConfig, +) { + // Configuration applied in enable_mpll_clk_impl +} + +/// Programs the PMU external LDO regulators for the MSPI PHY. fn psram_phy_ldo_init() { // Limit inrush current while the output cap charges; keep ripple // suppression (voltage detector) enabled. @@ -329,6 +410,7 @@ fn enable_rc_fast_clk_impl(_clocks: &mut ClockTree, en: bool) { } } +#[cfg(use_xtal32k)] fn enable_xtal32k_clk_impl(_clocks: &mut ClockTree, en: bool) { if en { LP_AON_CLK_RST::regs().xtal32k().modify(|_, w| unsafe { @@ -370,6 +452,10 @@ pll_gate!(enable_pll_f120m_impl, ref_120m_ctrl0); pll_gate!(enable_pll_f160m_impl, ref_160m_ctrl0); pll_gate!(enable_pll_f240m_impl, ref_240m_ctrl0); +fn enable_bbpll_d3_clock_impl(_clocks: &mut ClockTree, _en: bool) { + // Nothing to do here +} + fn enable_xtal_d2_clk_impl(_clocks: &mut ClockTree, _en: bool) { // Nothing to do here } @@ -420,11 +506,26 @@ fn configure_cpu_clk_impl(_clocks: &mut ClockTree, _old: Option, n } } -fn enable_ahb_clk_impl(_clocks: &mut ClockTree, _en: bool) { +// MEM_CLK + +fn enable_mem_clk_impl(_clocks: &mut ClockTree, _en: bool) { // Nothing to do here } -fn configure_ahb_clk_impl(_clocks: &mut ClockTree, _old: Option, new: AhbClkConfig) { +fn configure_mem_clk_impl(_clocks: &mut ClockTree, _old: Option, new: MemClkConfig) { + HP_SYS_CLKRST::regs() + .mem_freq_ctrl0() + .modify(|_, w| w.mem_clk_div_num().bit(new.divisor() == 1)); + update_bus_clocks(); +} + +// SYS_CLK + +fn enable_sys_clk_impl(_clocks: &mut ClockTree, _en: bool) { + // Nothing to do here +} + +fn configure_sys_clk_impl(_clocks: &mut ClockTree, _old: Option, new: SysClkConfig) { HP_SYS_CLKRST::regs() .sys_freq_ctrl0() .modify(|_, w| unsafe { @@ -483,6 +584,7 @@ fn configure_lp_slow_clk_impl( .modify(|_, w| unsafe { w.slow_clk_sel().bits(match new { LpSlowClkConfig::RcSlow => 0, + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => 1, }) }); @@ -502,6 +604,7 @@ fn configure_timg_calibration_clock_impl( let (source, divider): (u8, u16) = match new { TimgCalibrationClockConfig::RcFastDivClk => (7, 50), TimgCalibrationClockConfig::RcSlowClk => (8, 1), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => (10, 1), }; HP_SYS_CLKRST::regs() @@ -512,6 +615,29 @@ fn configure_timg_calibration_clock_impl( }); } +// CRYPTO_CLK + +fn enable_crypto_clk_impl(_clocks: &mut ClockTree, en: bool) { + HP_SYS_CLKRST::regs().crypto_ctrl0().modify(|_, w| { + w.crypto_sys_clk_en().bit(en); + w.crypto_sec_clk_en().bit(en) + }); +} + +fn configure_crypto_clk_impl( + _clocks: &mut ClockTree, + _old: Option, + new: CryptoClkConfig, +) { + HP_SYS_CLKRST::regs().crypto_ctrl0().modify(|_, w| unsafe { + w.crypto_clk_src_sel().bits(match new { + CryptoClkConfig::Xtal => 0, + CryptoClkConfig::RcFast => 1, + CryptoClkConfig::PllF240m => 2, + }) + }); +} + // IOMUX_FUNCTION_CLOCK fn configure_iomux_function_clock_impl( @@ -529,28 +655,74 @@ fn configure_iomux_function_clock_impl( } impl TimgInstance { - fn enable_function_clock_impl(self, _clocks: &mut ClockTree, _en: bool) { - // TODO: Control the selected timer's function-clock gate. + fn enable_function_clock_impl(self, _clocks: &mut ClockTree, en: bool) { + match self { + TimgInstance::Timg0 => HP_SYS_CLKRST::regs().timergrp0_ctrl0().modify(|_, w| { + w.t0_clk_en().bit(en); + w.t1_clk_en().bit(en) + }), + TimgInstance::Timg1 => HP_SYS_CLKRST::regs().timergrp1_ctrl0().modify(|_, w| { + w.t0_clk_en().bit(en); + w.t1_clk_en().bit(en) + }), + }; } fn configure_function_clock_impl( self, _clocks: &mut ClockTree, _old: Option, - _new: TimgFunctionClockConfig, + new: TimgFunctionClockConfig, ) { - // TODO: Configure the selected timer's function-clock source. + let bits = match new { + TimgFunctionClockConfig::XtalClk => 0, + TimgFunctionClockConfig::RcFastClk => 1, + TimgFunctionClockConfig::PllF80m => 2, + }; + match self { + TimgInstance::Timg0 => HP_SYS_CLKRST::regs() + .timergrp0_ctrl0() + .modify(|_, w| unsafe { + w.t0_src_sel().bits(bits); + w.t1_src_sel().bits(bits) + }), + TimgInstance::Timg1 => HP_SYS_CLKRST::regs() + .timergrp1_ctrl0() + .modify(|_, w| unsafe { + w.t0_src_sel().bits(bits); + w.t1_src_sel().bits(bits) + }), + }; } - fn enable_wdt_clock_impl(self, _clocks: &mut ClockTree, _en: bool) { - // TODO: Control the selected timer group's watchdog-clock gate. + fn enable_wdt_clock_impl(self, _clocks: &mut ClockTree, en: bool) { + match self { + TimgInstance::Timg0 => HP_SYS_CLKRST::regs() + .timergrp0_ctrl0() + .modify(|_, w| w.wdt_clk_en().bit(en)), + TimgInstance::Timg1 => HP_SYS_CLKRST::regs() + .timergrp1_ctrl0() + .modify(|_, w| w.wdt_clk_en().bit(en)), + }; } fn configure_wdt_clock_impl( self, _clocks: &mut ClockTree, _old: Option, - _new: TimgWdtClockConfig, + new: TimgWdtClockConfig, ) { - // TODO: Configure the selected timer group's watchdog-clock source. + let bits = match new { + TimgWdtClockConfig::XtalClk => 0, + TimgWdtClockConfig::RcFastClk => 1, + TimgWdtClockConfig::PllF80m => 2, + }; + match self { + TimgInstance::Timg0 => HP_SYS_CLKRST::regs() + .timergrp0_ctrl0() + .modify(|_, w| unsafe { w.wdt_src_sel().bits(bits) }), + TimgInstance::Timg1 => HP_SYS_CLKRST::regs() + .timergrp1_ctrl0() + .modify(|_, w| unsafe { w.wdt_src_sel().bits(bits) }), + }; } } @@ -620,3 +792,140 @@ impl SdmInstance { .modify(|_, w| w.sigmadelta_clk_en().bit(en)); } } + +impl LcdCamInstance { + fn enable_shared_core_clock(self, clocks: &ClockTree, en: bool) { + let idx = self as usize; + let sibling_held = clocks.lcd_cam_lcd_clock_refcount[idx] > 0 + || clocks.lcd_cam_cam_clock_refcount[idx] > 0; + if !en && sibling_held { + return; + } + + HP_SYS::regs().lcdcam_mem_lp_ctrl().modify(|_, w| { + w.lcdcam_mem_lp_force_ctrl().set_bit(); + w.lcdcam_mem_lp_en().bit(!en) + }); + // Shared LCD/CAM core clock. Source 0 = XTAL. Divider stores N - 1. + HP_SYS_CLKRST::regs() + .lcdcam_lcdcam_ctrl0() + .modify(|_, w| unsafe { + w.clk_en().bit(en); + w.clk_src_sel().bits(0); + w.clk_div_num().bits(0) + }); + } + + fn enable_lcd_clock_impl(self, clocks: &mut ClockTree, en: bool) { + self.enable_shared_core_clock(clocks, en); + HP_SYS_CLKRST::regs() + .lcdcam_lcd_ctrl0() + .modify(|_, w| w.clk_en().bit(en)); + } + + fn configure_lcd_clock_impl( + self, + _clocks: &mut ClockTree, + _old_config: Option, + new_config: LcdCamLcdClockConfig, + ) { + // Register stores N - 1. Source: 0 = XTAL, 1 = PLL_F160M, 2 = APLL. + let div_num = (new_config.div_num() - 1) as u8; + HP_SYS_CLKRST::regs() + .lcdcam_lcd_ctrl0() + .modify(|_, w| unsafe { + w.clk_src_sel().bits(match new_config.sclk() { + LcdCamLcdClockSclk::XtalClk => 0, + LcdCamLcdClockSclk::PllF160m => 1, + }); + w.clk_div_num().bits(div_num); + w.clk_div_denominator().bits(new_config.div_a() as u8); + w.clk_div_numerator().bits(new_config.div_b() as u8) + }); + } + + fn enable_cam_clock_impl(self, clocks: &mut ClockTree, en: bool) { + self.enable_shared_core_clock(clocks, en); + HP_SYS_CLKRST::regs() + .lcdcam_cam_ctrl0() + .modify(|_, w| w.clk_en().bit(en)); + } + + fn configure_cam_clock_impl( + self, + _clocks: &mut ClockTree, + _old_config: Option, + new_config: LcdCamCamClockConfig, + ) { + let div_num = (new_config.div_num() - 1) as u8; + HP_SYS_CLKRST::regs() + .lcdcam_cam_ctrl0() + .modify(|_, w| unsafe { + w.clk_src_sel().bits(match new_config.sclk() { + LcdCamCamClockSclk::XtalClk => 0, + LcdCamCamClockSclk::PllF160m => 1, + }); + w.clk_div_num().bits(div_num); + w.clk_div_denominator().bits(new_config.div_a() as u8); + w.clk_div_numerator().bits(new_config.div_b() as u8) + }); + } +} + +// BLE_LP_XTAL_CLK + +fn enable_ble_lp_xtal_clk_impl(_clocks: &mut ClockTree, _en: bool) { + // Nothing to do. +} + +// BLE_LP_CLK + +fn enable_ble_lp_clk_impl(_clocks: &mut ClockTree, en: bool) { + MODEM_LPCON::regs() + .clk_conf() + .modify(|_, w| w.clk_lp_timer_en().bit(en)); +} + +fn configure_ble_lp_clk_impl( + _clocks: &mut ClockTree, + _old_config: Option, + new_config: BleLpClkConfig, +) { + let divisor = match new_config { + BleLpClkConfig::Xtal => xtal_clk_frequency() / ble_lp_xtal_clk_frequency() - 1, + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => 0, + }; + let sel_xtal32k = cfg_select! { + use_xtal32k => new_config == BleLpClkConfig::Xtal32k, + _ => false, + }; + + MODEM_LPCON::regs() + .test_conf() + .modify(|_, w| w.clk_en().set_bit()); + + MODEM_LPCON::regs().lp_timer_conf().modify(|_, w| unsafe { + w.clk_lp_timer_sel_osc_slow().clear_bit(); + w.clk_lp_timer_sel_osc_fast().clear_bit(); + w.clk_lp_timer_sel_xtal() + .bit(new_config == BleLpClkConfig::Xtal); + w.clk_lp_timer_sel_xtal32k().bit(sel_xtal32k); + w.clk_lp_timer_div_num().bits(divisor as u16) + }); + + if sel_xtal32k { + // 0 routes XTAL32K to the modem 32 kHz input. + MODEM_LPCON::regs() + .modem_32k_clk_conf() + .modify(|_, w| unsafe { w.clk_modem_32k_sel().bits(0) }); + } + + // IDF `modem_lpcon_ll_reset_ble_rtc_timer`. + MODEM_LPCON::regs() + .rst_conf() + .modify(|_, w| w.rst_lp_timer().set_bit()); + MODEM_LPCON::regs() + .rst_conf() + .modify(|_, w| w.rst_lp_timer().clear_bit()); +} diff --git a/esp-hal/src/soc/esp32s31/cpu_control.rs b/esp-hal/src/soc/esp32s31/cpu_control.rs index 0cfe75209dd..ad3af7e4d52 100644 --- a/esp-hal/src/soc/esp32s31/cpu_control.rs +++ b/esp-hal/src/soc/esp32s31/cpu_control.rs @@ -1,5 +1,3 @@ -#[cfg(feature = "unstable")] -use crate::system::multi_core; use crate::{ peripherals::{HP_SYS, HP_SYS_CLKRST, LP_AON_CLK_RST, PMU}, system::Cpu, @@ -66,6 +64,28 @@ pub(crate) fn pre_system_reset() { crate::rom::ets_set_appcpu_boot_addr(0); } +/// Releases core 1 from reset after a CPU-domain power-down wake. +/// +/// esp-idf keys this on `core_id == 0` in both the initiator and the helper paths. +#[cfg(all( + cpu_retention = "software", + multi_core, + supports_cpu_power_down, + feature = "rt" +))] +#[crate::ram] +pub(crate) fn restart_core1_after_wake() { + if Cpu::current() != Cpu::ProCpu { + return; + } + HP_SYS_CLKRST::regs().hpcore1_ctrl0().modify(|_, w| { + w.core1_cpu_clk_en() + .set_bit() + .core1_global_rst_en() + .clear_bit() + }); +} + pub(crate) fn disable_core1() { // ESP-IDF single-core mode disables both Core 1 clocks and holds the core // in global reset. @@ -79,6 +99,59 @@ pub(crate) fn disable_core1() { }); } +macro_rules! read_csr { + ($csr:literal) => {{ + let value: u32; + unsafe { core::arch::asm!(concat!("csrr {0}, ", $csr), out(reg) value) }; + value + }}; +} + +macro_rules! write_csr { + ($csr:literal, $value:expr) => { + unsafe { core::arch::asm!(concat!("csrw ", $csr, ", {0}"), in(reg) $value) } + }; +} + +macro_rules! pma_entries { + ($($i:literal: $cfg:literal, $addr:literal;)*) => { + #[cfg(feature = "unstable")] + pub(crate) fn save_core0_pma(dst: &mut [u32; 32]) { + $( + dst[$i] = read_csr!($cfg); + dst[$i + 16] = read_csr!($addr); + )* + } + + #[cfg(feature = "unstable")] + pub(crate) fn set_core1_pma(src: &[u32; 32]) { + $( + write_csr!($addr, src[$i + 16]); + write_csr!($cfg, src[$i]); + )* + } + }; +} + +pma_entries! { + 0: "0xbc0", "0xbd0"; + 1: "0xbc1", "0xbd1"; + 2: "0xbc2", "0xbd2"; + 3: "0xbc3", "0xbd3"; + 4: "0xbc4", "0xbd4"; + 5: "0xbc5", "0xbd5"; + 6: "0xbc6", "0xbd6"; + 7: "0xbc7", "0xbd7"; + 8: "0xbc8", "0xbd8"; + 9: "0xbc9", "0xbd9"; + 10: "0xbca", "0xbda"; + 11: "0xbcb", "0xbdb"; + 12: "0xbcc", "0xbdc"; + 13: "0xbcd", "0xbdd"; + 14: "0xbce", "0xbde"; + 15: "0xbcf", "0xbdf"; +} + #[cfg(feature = "unstable")] pub(crate) fn start_core1(entry_point: *const u32) { // Enable both clocks and release Core 1 from global reset. @@ -94,60 +167,3 @@ pub(crate) fn start_core1(entry_point: *const u32) { // Core 1's ROM waits for this address before handing control to the app. crate::rom::ets_set_appcpu_boot_addr(entry_point as u32); } - -/// Core 1 entry point set as the boot address. -/// -/// ROM jumps here directly, bypassing `_start`, so initialize `gp` and the FPU -/// before entering regular Rust. -#[unsafe(naked)] -#[cfg(feature = "unstable")] -pub(crate) extern "C" fn start_core1_init() -> ! -where - F: FnOnce(), -{ - core::arch::naked_asm!( - ".option push", - ".option norelax", - "la gp, __global_pointer$", - ".option pop", - // Follow IDF's FPU initialization, enable it in Initial state, touch - // fcsr (which makes the state Dirty), then clear the dirty bit to - // leave mstatus.FS in Clean state (0b10). - "li t0, 0x2000", - "csrs mstatus, t0", - "li t0, 1", - "csrw fcsr, t0", - "li t0, 0x2000", - "csrc mstatus, t0", - "la t0, {stack_top}", - "lw sp, 0(t0)", - "j {init}", - stack_top = sym multi_core::APP_CORE_STACK_TOP, - init = sym start_core1_init_impl::, - ) -} - -#[cfg(feature = "unstable")] -fn start_core1_init_impl() -> ! -where - F: FnOnce(), -{ - crate::soc::enable_branch_predictor(); - crate::rom::ets_set_appcpu_boot_addr(0); - - unsafe { - #[cfg(all(feature = "rt", stack_guard_monitoring))] - { - let guard = - multi_core::APP_CORE_STACK_GUARD.load(core::sync::atomic::Ordering::Acquire); - guard.write_volatile(esp_config::esp_config_int!( - u32, - "ESP_HAL_CONFIG_STACK_GUARD_VALUE" - )); - crate::debugger::set_stack_watchpoint(guard as usize); - } - crate::interrupt::init_vectoring(); - } - - unsafe { multi_core::CpuControl::start_core1_run::() } -} diff --git a/esp-hal/src/soc/esp32s31/mod.rs b/esp-hal/src/soc/esp32s31/mod.rs index 4a36d8969ab..99787190025 100644 --- a/esp-hal/src/soc/esp32s31/mod.rs +++ b/esp-hal/src/soc/esp32s31/mod.rs @@ -7,32 +7,13 @@ crate::unstable_module! { pub mod clocks; + pub mod trng; } pub(crate) mod cpu_control; pub(crate) mod regi2c; pub(crate) use esp32s31 as pac; -#[cfg(i2s_driver_supported)] -#[cfg_attr(not(feature = "unstable"), allow(unused))] -pub(crate) fn i2s_sclk_frequency() -> u32 { - clocks::pll_f160m_frequency() -} - -pub(crate) fn enable_branch_predictor() { - // Enable branch predictor. - // Note that the branch predictor will start cache requests and needs to be - // disabled when the cache is disabled. - // MHCR: CSR 0x7c1 — sourced from SOC_BRANCH_PREDICTOR_SUPPORTED in - // esp-idf/components/soc/esp32s31/include/soc/soc_caps.h - const MHCR_RS: u32 = 1 << 4; // R/W, address return stack set bit - const MHCR_BFE: u32 = 1 << 5; // R/W, allow predictive jump set bit - const MHCR_BTB: u32 = 1 << 12; // R/W, branch target prediction enable bit - unsafe { - core::arch::asm!("csrrs x0, 0x7c1, {0}", in(reg) MHCR_RS | MHCR_BFE | MHCR_BTB); - } -} - #[cfg(feature = "rt")] pub(crate) fn riscv_preinit() {} @@ -71,6 +52,9 @@ pub(crate) fn pre_init() { systimer.modify(|_, w| w.rst_en().set_bit()); systimer.modify(|_, w| w.rst_en().clear_bit()); systimer.modify(|_, w| w.clk_en().set_bit()); + + // Mirrors ESP-IDF's `init_rng`, see + trng::rng_ll_enable(); } /// Opens LP/HP peripheral PMS regions for all security modes. @@ -97,7 +81,7 @@ fn write_pms_ctrl_range(base: usize, start: usize, end: usize) { const CACHE_MAP_L1_DCACHE: u32 = 1 << 4; -/// Write back a specific range of data in the cache. +/// Writes back a specific range of data in the cache. #[doc(hidden)] #[crate::ram] pub unsafe fn cache_writeback_addr(addr: u32, size: u32) { diff --git a/esp-hal/src/soc/esp32s31/regi2c.rs b/esp-hal/src/soc/esp32s31/regi2c.rs index ed74b944565..5b5e90e0c85 100644 --- a/esp-hal/src/soc/esp32s31/regi2c.rs +++ b/esp-hal/src/soc/esp32s31/regi2c.rs @@ -153,7 +153,15 @@ define_regi2c! { } } master: REGI2C_CPLL(0x0A, 0) {} - master: REGI2C_MPLL(0x0B, 0) {} + master: REGI2C_MPLL(0x0B, 0) { + reg: I2C_MPLL_IR_CAL(1) { + field: I2C_MPLL_IR_CAL_EXT_CAP(1..0), + field: I2C_MPLL_IR_CAL_ENX_CAP(2..2) + } + reg: I2C_MPLL_DHREF_REG(3) { + field: I2C_MPLL_DHREF(5..4) + } + } master: REGI2C_DIG_REG(0x6D, 0) { reg: I2C_DIG_REG4(4) { field: I2C_DIG_REG_EXT_RTC_DREG(4..0), diff --git a/esp-hal/src/soc/esp32s31/trng.rs b/esp-hal/src/soc/esp32s31/trng.rs new file mode 100644 index 00000000000..1bf5af70267 --- /dev/null +++ b/esp-hal/src/soc/esp32s31/trng.rs @@ -0,0 +1,46 @@ +use crate::peripherals::{LP_PERI, RNG}; + +// See +pub(crate) fn rng_ll_enable() { + let lp_peri = LP_PERI::regs(); + let rng = RNG::regs(); + lp_peri + .rng_ctrl() + .modify(|_, w| w.lp_rng_clk_en().set_bit()); + rng.date().modify(|_, w| w.clk_en().set_bit()); + lp_peri + .rng_ctrl() + .modify(|_, w| w.lp_rng_rst_en().set_bit()); + lp_peri + .rng_ctrl() + .modify(|_, w| w.lp_rng_rst_en().clear_bit()); + rng.conf().modify(|_, w| unsafe { + w.noise_source_sel().bits(1 << 4); + w.noise_pos_sel().bits(1 << 4); + w.repetition_value_c().bits(0x1f); + w.adpative_value_c().bits(0x12) + }); + rng.debug_conf().modify(|_, w| unsafe { + w.startup_test_limit().bits(1024); + w.health_test_bypass().clear_bit() + }); + rng.conf().modify(|_, w| { + w.random_output_mode().set_bit(); + w.noise_crc_en().set_bit(); + w.sample_enable().set_bit() + }); + rng.debug_conf() + .modify(|_, w| w.startup_test_start().set_bit()); +} + +/// Enables true randomness by enabling the entropy source. +// See +pub(crate) fn ensure_randomness() { + rng_ll_enable(); +} + +/// Disables true randomness. +// See +pub(crate) fn revert_trng() { + // `rng_ll_disable` is skipped: `Rng` keeps using the RNG. +} diff --git a/esp-hal/src/soc/mod.rs b/esp-hal/src/soc/mod.rs index 6a575834aa6..01811600507 100644 --- a/esp-hal/src/soc/mod.rs +++ b/esp-hal/src/soc/mod.rs @@ -14,12 +14,16 @@ use crate::efuse::ChipRevision; #[cfg_attr(esp32c6, path = "esp32c6/mod.rs")] #[cfg_attr(esp32c61, path = "esp32c61/mod.rs")] #[cfg_attr(esp32h2, path = "esp32h2/mod.rs")] +#[cfg_attr(esp32h4, path = "esp32h4/mod.rs")] #[cfg_attr(esp32p4, path = "esp32p4/mod.rs")] #[cfg_attr(esp32s2, path = "esp32s2/mod.rs")] #[cfg_attr(esp32s3, path = "esp32s3/mod.rs")] #[cfg_attr(esp32s31, path = "esp32s31/mod.rs")] mod implementation; +#[cfg(soc_cpu_has_branch_predictor)] +pub(crate) mod branch_predictor; + #[cfg(soc_has_xtal32k_pads)] pub(crate) mod xtal32k; @@ -56,15 +60,10 @@ pub(crate) fn is_slice_in_psram(slice: &[T]) -> bool { #[allow(unused)] pub(crate) fn is_valid_memory_address(address: usize) -> bool { - if is_valid_ram_address(address) { - return true; - } - #[cfg(soc_has_psram)] - if is_valid_psram_address(address) { - return true; + cfg_select! { + soc_has_psram => is_valid_ram_address(address) || is_valid_psram_address(address), + _ => is_valid_ram_address(address), } - - false } fn slice_in_range(slice: &[T], range: Range) -> bool { @@ -101,9 +100,8 @@ fn hal_main(a0: usize, a1: usize, a2: usize) -> ! { mod xtensa { use core::arch::{global_asm, naked_asm}; - /// The ESP32 has a first stage bootloader that handles loading program data - /// into the right place therefore we skip loading it again. This function - /// is called by xtensa-lx-rt in Reset. + /// The ESP32 has a first stage bootloader that handles loading program data into the right + /// place, so loading is skipped here. Called by xtensa-lx-rt in Reset. #[unsafe(export_name = "__init_data")] extern "C" fn __init_data() -> bool { false @@ -117,6 +115,8 @@ mod xtensa { } unsafe extern "C" { + static _dram2_uninit_bss_start: u32; + static _dram2_uninit_bss_end: u32; static _rtc_fast_bss_start: u32; static _rtc_fast_bss_end: u32; static _rtc_fast_persistent_end: u32; @@ -137,6 +137,9 @@ mod xtensa { .literal sym_init_persistent, {__init_persistent} .literal sym_xtensa_lx_rt_zero_fill, {_xtensa_lx_rt_zero_fill} + .literal sym_dram2_uninit_bss_start, {_dram2_uninit_bss_start} + .literal sym_dram2_uninit_bss_end, {_dram2_uninit_bss_end} + .literal sym_rtc_fast_bss_start, {_rtc_fast_bss_start} .literal sym_rtc_fast_bss_end, {_rtc_fast_bss_end} .literal sym_rtc_fast_persistent_end, {_rtc_fast_persistent_end} @@ -150,6 +153,9 @@ mod xtensa { __init_persistent = sym __init_persistent, _xtensa_lx_rt_zero_fill = sym _xtensa_lx_rt_zero_fill, + _dram2_uninit_bss_end = sym _dram2_uninit_bss_end, + _dram2_uninit_bss_start = sym _dram2_uninit_bss_start, + _rtc_fast_bss_end = sym _rtc_fast_bss_end, _rtc_fast_bss_start = sym _rtc_fast_bss_start, _rtc_fast_persistent_end = sym _rtc_fast_persistent_end, @@ -171,6 +177,10 @@ mod xtensa { l32r a2, sym_xtensa_lx_rt_zero_fill // Pre-load address of zero-fill function + l32r a6, sym_dram2_uninit_bss_start // Set input range to .dram2_uninit.bss + l32r a7, sym_dram2_uninit_bss_end // + callx4 a2 // Zero-fill + l32r a6, sym_rtc_fast_bss_start // Set input range to .rtc_fast.bss l32r a7, sym_rtc_fast_bss_end // callx4 a2 // Zero-fill @@ -197,13 +207,18 @@ mod xtensa { ) } - #[cfg(esp32s3)] - global_asm!(".section .rwtext,\"ax\",@progbits"); + // The section switch must stay in the same block as the literals: rustc does not emit + // separate `global_asm!` items in source order. global_asm!( + cfg_select! { + esp32s3 => ".pushsection .rwtext,\"ax\",@progbits", + _ => ".pushsection .text,\"ax\",@progbits", + }, " .literal sym_stack_chk_guard, {__stack_chk_guard} .literal stack_guard_value, {stack_guard_value} .literal sym_esp32_init, {__esp32_init} + .popsection ", __stack_chk_guard = sym __stack_chk_guard, stack_guard_value = const esp_config::esp_config_int!( @@ -360,6 +375,13 @@ pub(crate) fn enable_pmp() { end_addr: u32, permission: u8, ) -> Result<(), PmpError> { + // The CPU hardwires the address bits below the PMP granularity to zero, rounding both ends + // of the region down. Round the start up instead, so that the region cannot grow downwards + // over memory in front of it, such as the trap section and its interrupt handler table. + let granularity = property!("soc.cpu_pmp_granularity"); + let start_addr = start_addr.next_multiple_of(granularity); + let end_addr = end_addr & !(granularity - 1); + if start_addr >= end_addr { return Err(PmpError::InvalidRange); } @@ -406,7 +428,7 @@ pub(crate) fn enable_pmp() { Ok(()) } - /// Returns true if a PMP entry is unlocked and disabled (address matching OFF). + /// Returns whether a PMP entry is unlocked and disabled (address matching OFF). unsafe fn is_pmp_entry_free(idx: usize) -> bool { let cfg_reg = idx / 4; let byte_offset = idx % 4; @@ -594,13 +616,13 @@ fn chip_revision_in_range(range: Range) -> bool { range.start <= chip_revision && chip_revision < range.end } -/// Returns true if the chip revision is at least the given revision. +/// Returns whether the chip revision is at least the given revision. #[allow(dead_code)] pub(crate) fn chip_revision_above(revision: ChipRevision) -> bool { chip_revision_in_range(revision..MAX_REVISION) } -/// Returns true if the chip is at least the given revision, in the same major version. +/// Returns whether the chip is at least the given revision, in the same major version. #[allow(dead_code)] pub(crate) fn chip_minor_revision_above(revision: ChipRevision) -> bool { let next_major = ChipRevision { diff --git a/esp-hal/src/soc/xtal32k.rs b/esp-hal/src/soc/xtal32k.rs index d45f18db3fe..efb889b7cc5 100644 --- a/esp-hal/src/soc/xtal32k.rs +++ b/esp-hal/src/soc/xtal32k.rs @@ -17,6 +17,10 @@ /// Whether esp-hal should power and use the external 32 kHz crystal. #[inline(always)] +#[allow( + dead_code, + reason = "Sleep and RTC code uses this on chips that power-gate XTAL32K." +)] pub(crate) const fn use_xtal32k() -> bool { cfg!(use_xtal32k) } @@ -24,19 +28,17 @@ pub(crate) const fn use_xtal32k() -> bool { /// The LP slow clock source to select by default. #[cfg(soc_has_clock_node_lp_slow_clk)] pub(crate) const fn default_lp_slow_clk() -> crate::soc::clocks::LpSlowClkConfig { - if use_xtal32k() { - crate::soc::clocks::LpSlowClkConfig::Xtal32k - } else { - crate::soc::clocks::LpSlowClkConfig::RcSlow + cfg_select! { + use_xtal32k => crate::soc::clocks::LpSlowClkConfig::Xtal32k, + _ => crate::soc::clocks::LpSlowClkConfig::RcSlow, } } /// The RTC slow clock source to select by default. #[cfg(soc_has_clock_node_rtc_slow_clk)] pub(crate) const fn default_rtc_slow_clk() -> crate::soc::clocks::RtcSlowClkConfig { - if use_xtal32k() { - crate::soc::clocks::RtcSlowClkConfig::Xtal32k - } else { - crate::soc::clocks::RtcSlowClkConfig::RcSlow + cfg_select! { + use_xtal32k => crate::soc::clocks::RtcSlowClkConfig::Xtal32k, + _ => crate::soc::clocks::RtcSlowClkConfig::RcSlow, } } diff --git a/esp-hal/src/spi/clocks/esp32p4.rs b/esp-hal/src/spi/clocks/esp32p4.rs index 53a636f1219..7ff3ef4bdff 100644 --- a/esp-hal/src/spi/clocks/esp32p4.rs +++ b/esp-hal/src/spi/clocks/esp32p4.rs @@ -23,13 +23,34 @@ impl SpiInstance { // APLL SpiFunctionClockConfig::Spll => 4, }; - HP_SYS_CLKRST::regs() - .peri_clk_ctrl116() - .modify(|_, w| unsafe { - match self { - Self::Spi2 => w.gpspi2_clk_src_sel().bits(source), - Self::Spi3 => w.gpspi3_clk_src_sel().bits(source), - } - }); + + // Programs `gpspi*_hs_clk_div_num`. The register value is divisor - 1, so 2 means /3 + // (480 MHz SPLL -> 160 MHz). Reset the divider when the node is released so XTAL/RC_FAST + // are not divided. + let div_num = match new_config { + SpiFunctionClockConfig::Xtal => 0, + SpiFunctionClockConfig::RcFast => 0, + // SDIO_PLL0 + // APLL + SpiFunctionClockConfig::Spll => 2, + }; + match self { + Self::Spi2 => { + HP_SYS_CLKRST::regs() + .peri_clk_ctrl116() + .modify(|_, w| unsafe { + w.gpspi2_clk_src_sel().bits(source); + w.gpspi2_hs_clk_div_num().bits(div_num) + }); + } + Self::Spi3 => { + HP_SYS_CLKRST::regs() + .peri_clk_ctrl116() + .modify(|_, w| unsafe { w.gpspi3_clk_src_sel().bits(source) }); + HP_SYS_CLKRST::regs() + .peri_clk_ctrl117() + .modify(|_, w| unsafe { w.gpspi3_hs_clk_div_num().bits(div_num) }); + } + } } } diff --git a/esp-hal/src/spi/clocks/esp32s31.rs b/esp-hal/src/spi/clocks/esp32s31.rs index 7ede5b81760..4fbc1276738 100644 --- a/esp-hal/src/spi/clocks/esp32s31.rs +++ b/esp-hal/src/spi/clocks/esp32s31.rs @@ -21,16 +21,27 @@ impl SpiInstance { SpiFunctionClockConfig::RcFast => 1, SpiFunctionClockConfig::Bbpll => 2, }; + + // Programs `hs_clk_div_num`. The register value is divisor - 1, so 2 means /3 + // (480 MHz BBPLL -> 160 MHz). Reset the divider when the node is released so XTAL/RC_FAST + // are not divided. + let div_num = match new_config { + SpiFunctionClockConfig::Xtal => 0, + SpiFunctionClockConfig::RcFast => 0, + SpiFunctionClockConfig::Bbpll => 2, + }; match self { SpiInstance::Spi2 => { - HP_SYS_CLKRST::regs() - .gpspi2_ctrl0() - .modify(|_, w| unsafe { w.clk_src_sel().bits(source) }); + HP_SYS_CLKRST::regs().gpspi2_ctrl0().modify(|_, w| unsafe { + w.clk_src_sel().bits(source); + w.hs_clk_div_num().bits(div_num) + }); } SpiInstance::Spi3 => { - HP_SYS_CLKRST::regs() - .gpspi3_ctrl0() - .modify(|_, w| unsafe { w.clk_src_sel().bits(source) }); + HP_SYS_CLKRST::regs().gpspi3_ctrl0().modify(|_, w| unsafe { + w.clk_src_sel().bits(source); + w.hs_clk_div_num().bits(div_num) + }); } } } diff --git a/esp-hal/src/spi/clocks/v3_pcr.rs b/esp-hal/src/spi/clocks/v3_pcr.rs index c3c42c2b2de..99614500274 100644 --- a/esp-hal/src/spi/clocks/v3_pcr.rs +++ b/esp-hal/src/spi/clocks/v3_pcr.rs @@ -11,6 +11,10 @@ impl SpiInstance { SpiInstance::Spi2 => PCR::regs() .spi2_clkm_conf() .modify(|_, w| w.spi2_clkm_en().bit(en)), + #[cfg(soc_has_spi3)] + SpiInstance::Spi3 => PCR::regs() + .spi3_clkm_conf() + .modify(|_, w| w.spi3_clkm_en().bit(en)), }; } @@ -20,21 +24,27 @@ impl SpiInstance { _old_config: Option, new_config: SpiFunctionClockConfig, ) { + let sel = match new_config { + SpiFunctionClockConfig::Xtal => 0, + #[cfg(esp32c6)] + SpiFunctionClockConfig::PllF80m => 1, + #[cfg(any(esp32h2, esp32h4))] + SpiFunctionClockConfig::PllF48m => 1, + #[cfg(any(esp32c5, esp32c61))] + SpiFunctionClockConfig::PllF160m => 1, + SpiFunctionClockConfig::RcFast => 2, + #[cfg(esp32c5)] + SpiFunctionClockConfig::PllF120m => 3, + }; + match self { - SpiInstance::Spi2 => PCR::regs().spi2_clkm_conf().modify(|_, w| unsafe { - w.spi2_clkm_sel().bits(match new_config { - SpiFunctionClockConfig::Xtal => 0, - #[cfg(esp32c6)] - SpiFunctionClockConfig::PllF80m => 1, - #[cfg(esp32h2)] - SpiFunctionClockConfig::PllF48m => 1, - #[cfg(any(esp32c5, esp32c61))] - SpiFunctionClockConfig::PllF160m => 1, - SpiFunctionClockConfig::RcFast => 2, - #[cfg(esp32c5)] - SpiFunctionClockConfig::PllF120m => 3, - }) - }), + SpiInstance::Spi2 => PCR::regs() + .spi2_clkm_conf() + .modify(|_, w| unsafe { w.spi2_clkm_sel().bits(sel) }), + #[cfg(soc_has_spi3)] + SpiInstance::Spi3 => PCR::regs() + .spi3_clkm_conf() + .modify(|_, w| unsafe { w.spi3_clkm_sel().bits(sel) }), }; } } diff --git a/esp-hal/src/spi/master/dma.rs b/esp-hal/src/spi/master/dma.rs index ba2aa69ac83..577c36a522b 100644 --- a/esp-hal/src/spi/master/dma.rs +++ b/esp-hal/src/spi/master/dma.rs @@ -99,16 +99,16 @@ impl<'d> Spi<'d, Blocking> { /// passing them to [`with_buffers`](SpiDma::with_buffers) before the first transfer begins. For /// more details on when copying is necessary, see the documentation of the /// [`with_buffers`](SpiDma::with_buffers) method. -/// - The buffer API allows transferring externally managed buffers. In this mode, you provide the -/// buffers to be transferred. The buffer objects ensure that data is located in appropriate -/// memory regions. The buffers and the driver object are moved into transfer objects for the -/// duration of the transfer. These functions take [`DmaRxBuf`] and [`DmaTxBuf`] objects as -/// arguments as well as the number of bytes to transfer, and their names end with `_buffer`. +/// - The buffer API allows transferring externally managed buffers. In this mode, the buffers to be +/// transferred are provided by the caller. The buffer objects ensure that data is located in +/// appropriate memory regions. The buffers and the driver object are moved into transfer objects +/// for the duration of the transfer. These functions take [`DmaRxBuf`] and [`DmaTxBuf`] objects +/// as arguments as well as the number of bytes to transfer, and their names end with `_buffer` /// /// These approaches provide different trade-offs between memory usage / CPU overhead and ease of /// use. `embedded-hal` traits are implemented by the slice-based API's functions. /// -/// ## Examples +/// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -301,25 +301,25 @@ impl<'d> SpiDma<'d, Blocking> { Self::new_inner(spi, channel) } - /// Listen for the given interrupts + /// Listens for the given interrupts. #[instability::unstable] pub fn listen(&mut self, interrupts: impl Into>) { self.driver().enable_listen(interrupts.into(), true); } - /// Unlisten the given interrupts + /// Unlistens from the given interrupts. #[instability::unstable] pub fn unlisten(&mut self, interrupts: impl Into>) { self.driver().enable_listen(interrupts.into(), false); } - /// Gets asserted interrupts + /// Returns the asserted interrupts. #[instability::unstable] pub fn interrupts(&mut self) -> EnumSet { self.driver().interrupts() } - /// Resets asserted interrupts + /// Resets asserted interrupts. #[instability::unstable] pub fn clear_interrupts(&mut self, interrupts: impl Into>) { self.driver().clear_interrupts(interrupts.into()); @@ -334,10 +334,9 @@ impl<'d> SpiDma<'d, Blocking> { doc = "Registers an interrupt handler for the peripheral on the current core." )] #[doc = ""] - /// Note that this will replace any previously registered interrupt - /// handlers. + /// Replaces any previously registered interrupt handlers. /// - /// You can restore the default/unhandled interrupt handler by using + /// The default/unhandled interrupt handler can be restored with /// [crate::interrupt::DEFAULT_INTERRUPT_HANDLER] /// /// # Panics @@ -412,7 +411,7 @@ impl<'d> SpiDma<'d, Async> { } } - /// Fill the given buffer with data from the bus. + /// Fills the given buffer with data from the bus. #[instability::unstable] pub async fn read_async(&mut self, words: &mut [u8]) -> Result<(), Error> { if words.is_empty() { @@ -458,7 +457,7 @@ impl<'d> SpiDma<'d, Async> { Ok(()) } - /// Transmit the given buffer to the bus. + /// Transmits the given buffer to the bus. #[instability::unstable] pub async fn write_async(&mut self, words: &[u8]) -> Result<(), Error> { if words.is_empty() { @@ -498,7 +497,7 @@ impl<'d> SpiDma<'d, Async> { Ok(()) } - /// Transfer by writing out a buffer and reading the response from + /// Transfers by writing out a buffer and reading the response from /// the bus into another buffer. #[instability::unstable] pub async fn transfer_async(&mut self, read: &mut [u8], write: &[u8]) -> Result<(), Error> { @@ -579,7 +578,7 @@ impl<'d> SpiDma<'d, Async> { } } - /// Transfer by writing out a buffer and reading the response from + /// Transfers by writing out a buffer and reading the response from /// the bus into the same buffer. #[instability::unstable] pub async fn transfer_in_place_async(&mut self, words: &mut [u8]) -> Result<(), Error> { @@ -929,10 +928,10 @@ impl<'a> MaybeCopyRxBuf<'a> { #[derive(Clone, Copy)] enum DmaOperationKind { - /// The entire slice must be copied into the internal buffer first + /// The entire slice must be copied into the internal buffer first. Copied, - /// The slice can be transferred directly, with minimal copying done for alignment + /// The slice can be transferred directly, with minimal copying done for alignment. InPlace, } @@ -1045,7 +1044,7 @@ where fence(Ordering::Acquire); } - /// # Safety: + /// # Safety /// /// The caller must ensure to not access the buffer contents while the /// transfer is in progress. Moving the buffer itself is allowed. @@ -1082,7 +1081,7 @@ where } } - /// # Safety: + /// # Safety /// /// The caller must ensure that the buffers are not accessed while the /// transfer is in progress. Moving the buffers is allowed. @@ -1140,7 +1139,7 @@ where } } - /// # Safety: + /// # Safety /// /// The caller must ensure that the buffers are not accessed while the /// transfer is in progress. Moving the buffers is allowed. @@ -1191,9 +1190,9 @@ aligned, otherwise the driver requires copying the entire buffer." self } - /// Perform a DMA write. + /// Performs a DMA write. /// - /// This will return a [SpiDmaTransfer] owning the buffer and the + /// Returns a [`SpiDmaTransfer`] that owns the buffer and the /// SPI instance. The maximum amount of data to be sent is 32736 /// bytes. #[allow(clippy::type_complexity)] @@ -1215,7 +1214,7 @@ aligned, otherwise the driver requires copying the entire buffer." } } - /// # Safety: + /// # Safety /// /// The caller must ensure that the buffers are not accessed while the /// transfer is in progress. Moving the buffers is allowed. @@ -1230,9 +1229,9 @@ aligned, otherwise the driver requires copying the entire buffer." unsafe { self.start_dma_transfer(bytes_to_read, 0, buffer, tx_buffer) } } - /// Perform a DMA read. + /// Performs a DMA read. /// - /// This will return a [SpiDmaTransfer] owning the buffer and + /// Returns a [`SpiDmaTransfer`] that owns the buffer and /// the SPI instance. The maximum amount of data to be /// received is 32736 bytes. #[allow(clippy::type_complexity)] @@ -1254,7 +1253,7 @@ aligned, otherwise the driver requires copying the entire buffer." } } - /// # Safety: + /// # Safety /// /// The caller must ensure that the buffers are not accessed while the /// transfer is in progress. Moving the buffers is allowed. @@ -1271,9 +1270,9 @@ aligned, otherwise the driver requires copying the entire buffer." } } - /// Perform a DMA transfer + /// Performs a DMA transfer. /// - /// This will return a [SpiDmaTransfer] owning the buffers and + /// Returns a [`SpiDmaTransfer`] that owns the buffers and /// the SPI instance. The maximum amount of data to be /// sent/received is 32736 bytes. #[allow(clippy::type_complexity)] @@ -1304,7 +1303,7 @@ aligned, otherwise the driver requires copying the entire buffer." } } - /// # Safety: + /// # Safety /// /// The caller must ensure that the buffers are not accessed while the /// transfer is in progress. Moving the buffers is allowed. @@ -1333,7 +1332,7 @@ aligned, otherwise the driver requires copying the entire buffer." unsafe { self.start_transfer_dma(false, bytes_to_read, 0, buffer, tx_buffer) } } - /// Perform a half-duplex read operation using DMA. + /// Performs a half-duplex read operation using DMA. #[allow(clippy::type_complexity)] #[cfg_attr(place_spi_master_driver_in_ram, ram)] #[instability::unstable] @@ -1356,7 +1355,7 @@ aligned, otherwise the driver requires copying the entire buffer." } } - /// # Safety: + /// # Safety /// /// The caller must ensure that the buffers are not accessed while the /// transfer is in progress. Moving the buffers is allowed. @@ -1394,7 +1393,7 @@ aligned, otherwise the driver requires copying the entire buffer." unsafe { self.start_transfer_dma(false, 0, bytes_to_write, rx_buffer, buffer) } } - /// Perform a half-duplex write operation using DMA. + /// Performs a half-duplex write operation using DMA. #[allow(clippy::type_complexity)] #[cfg_attr(place_spi_master_driver_in_ram, ram)] #[instability::unstable] @@ -1430,12 +1429,12 @@ aligned, otherwise the driver requires copying the entire buffer." _ => "80MHz", } )] - /// Change the bus configuration. + /// Changes the bus configuration. /// /// # Errors /// - /// If frequency passed in config exceeds __max_frequency__ or is below 70kHz, - /// [`ConfigError::UnsupportedFrequency`] error will be returned. + /// [`ConfigError::FrequencyOutOfRange`] when frequency passed in config exceeds + /// __max_frequency__ or is below 70 kHz. #[instability::unstable] pub fn apply_config(&mut self, config: &Config) -> Result<(), ConfigError> { self.driver().apply_config(config) @@ -1724,8 +1723,7 @@ aligned, otherwise the driver requires copying the entire buffer." /// A structure representing a DMA transfer for SPI. /// -/// This structure holds references to the SPI instance, DMA buffers, and -/// transfer status. +/// Holds references to the SPI instance, DMA buffers, and transfer status. #[instability::unstable] pub struct SpiDmaTransfer<'d, Dm, Buf> where @@ -1739,7 +1737,7 @@ where impl SpiDmaTransfer<'_, Async, Buf> { /// Waits for the DMA transfer to complete asynchronously. /// - /// This method awaits the completion of both RX and TX operations. + /// Awaits the completion of both RX and TX operations. #[instability::unstable] pub async fn wait_for_done(&mut self) { self.spi_dma.wait_for_idle_async().await; @@ -1758,10 +1756,10 @@ where } } - /// Checks if the transfer is complete. + /// Returns whether the transfer is complete. /// - /// This method returns `true` if both RX and TX operations are done, - /// and the SPI instance is no longer busy. + /// Both RX and TX operations are done, and the SPI instance is no longer + /// busy. #[instability::unstable] pub fn is_done(&self) -> bool { self.spi_dma.is_done() @@ -1769,7 +1767,7 @@ where /// Waits for the DMA transfer to complete. /// - /// This method blocks until the transfer is finished and returns the + /// Blocks until the transfer is finished and returns the /// `SpiDma` instance and the associated buffer. #[instability::unstable] pub fn wait(mut self) -> (SpiDma<'d, Dm>, Buf) { @@ -1845,7 +1843,15 @@ impl DmaDriver { w.dma_rx_ena().clear_bit() }); - // PDMA: nothing to do + // PDMA has no enable bit: whether the peripheral takes its data from the + // descriptors or from the FIFO is decided by whether a link is armed, so + // a stale link keeps routing a CPU-driven transfer into DMA. This mirrors + // the clearing `start_transfer_dma` already does on the way *in*. + #[cfg(any(spi_master_version = "1", spi_master_version = "2"))] + { + self.regs().dma_out_link().write(|w| unsafe { w.bits(0) }); + self.regs().dma_in_link().write(|w| unsafe { w.bits(0) }); + } } fn regs(&self) -> &RegisterBlock { diff --git a/esp-hal/src/spi/master/low_level/mod.rs b/esp-hal/src/spi/master/low_level/mod.rs index 5d8acd70f76..8874ce1831f 100644 --- a/esp-hal/src/spi/master/low_level/mod.rs +++ b/esp-hal/src/spi/master/low_level/mod.rs @@ -151,7 +151,7 @@ pub trait QspiInstance: Instance {} pub struct Info { /// Pointer to the register block for this SPI instance. /// - /// Use [Self::register_block] to access the register block. + /// Used with [`Self::register_block`] to access the register block. pub register_block: *const RegisterBlock, /// The system peripheral marker. @@ -169,7 +169,7 @@ pub struct Info { pub sio_inputs: &'static [InputSignal], pub sio_outputs: &'static [OutputSignal], - /// Clock tree instance for this SPI peripheral. + /// Clocks tree instance for this SPI peripheral. pub clock_instance: crate::soc::clocks::SpiInstance, } @@ -212,7 +212,7 @@ impl Driver { self.update(); } - /// Initialize for full-duplex 1 bit mode + /// Initializes for full-duplex 1 bit mode. pub(super) fn init(&self) { version::enable_peripheral_clock(self); @@ -252,19 +252,19 @@ impl Driver { version::init_spi_data_mode(self, cmd_mode, address_mode, data_mode) } - /// Enable or disable listening for the given interrupts. + /// Enables or disables listening for the given interrupts. #[cfg_attr(not(feature = "unstable"), allow(dead_code))] pub(super) fn enable_listen(&self, interrupts: EnumSet, enable: bool) { version::enable_listen(self, interrupts, enable); } - /// Gets asserted interrupts + /// Returns the asserted interrupts. #[cfg_attr(not(feature = "unstable"), allow(dead_code))] pub(super) fn interrupts(&self) -> EnumSet { version::interrupts(self) } - /// Resets asserted interrupts + /// Resets asserted interrupts. pub(super) fn clear_interrupts(&self, interrupts: EnumSet) { version::clear_interrupts(self, interrupts); } @@ -357,7 +357,7 @@ impl Driver { } } - /// Write bytes to SPI. + /// Writes bytes to SPI. #[cfg_attr(place_spi_master_driver_in_ram, ram)] pub(super) fn write_one(&self, words: &[u8]) -> Result<(), Error> { if words.len() > FIFO_SIZE { @@ -369,7 +369,7 @@ impl Driver { Ok(()) } - /// Write bytes to SPI. + /// Writes bytes to SPI. #[cfg_attr(place_spi_master_driver_in_ram, ram)] pub(super) fn write(&self, words: &[u8]) -> Result<(), Error> { for chunk in words.chunks(FIFO_SIZE) { @@ -379,21 +379,21 @@ impl Driver { Ok(()) } - /// Write bytes to SPI. + /// Writes bytes to SPI. #[cfg_attr(place_spi_master_driver_in_ram, ram)] pub(super) async fn write_async(&self, words: &[u8]) -> Result<(), Error> { for chunk in words.chunks(FIFO_SIZE) { self.write_one(chunk)?; - self.flush_async().await; + self.flush_async_or_abort().await; } Ok(()) } - /// Read bytes from SPI. + /// Reads bytes from SPI. /// - /// Sends out a stuffing byte for every byte to read. This function doesn't - /// perform flushing. If you want to read the response to something you - /// have written before, consider using [`Self::transfer`] instead. + /// Sends out a stuffing byte for every byte to read. Does not perform + /// flushing. To read the response to a prior write, use [`Self::transfer`] + /// instead. #[cfg_attr(place_spi_master_driver_in_ram, ram)] pub(super) fn read(&self, words: &mut [u8]) -> Result<(), Error> { let empty_array = [EMPTY_WRITE_PAD; FIFO_SIZE]; @@ -406,29 +406,27 @@ impl Driver { Ok(()) } - /// Read bytes from SPI. + /// Reads bytes from SPI. /// - /// Sends out a stuffing byte for every byte to read. If you want to read - /// the response to something you have written before, consider using - /// [`Self::transfer`] instead. + /// Sends out a stuffing byte for every byte to read. To read the response to a + /// prior write, use [`Self::transfer`] instead #[cfg_attr(place_spi_master_driver_in_ram, ram)] pub(super) async fn read_async(&self, words: &mut [u8]) -> Result<(), Error> { let empty_array = [EMPTY_WRITE_PAD; FIFO_SIZE]; for chunk in words.chunks_mut(FIFO_SIZE) { self.write_one(&empty_array[0..chunk.len()])?; - self.flush_async().await; + self.flush_async_or_abort().await; self.read_from_fifo(chunk)?; } Ok(()) } - /// Read received bytes from SPI FIFO. + /// Reads received bytes from SPI FIFO. /// - /// Copies the contents of the SPI receive FIFO into `words`. This function - /// doesn't perform any data transfer. If you want to read the response to - /// something you have written before, consider using [`Self::transfer`] - /// instead. + /// Copies the contents of the SPI receive FIFO into `words`. Does not perform + /// any data transfer. To read the response to a prior write, use + /// [`Self::transfer`] instead #[cfg_attr(place_spi_master_driver_in_ram, ram)] pub(super) fn read_from_fifo(&self, words: &mut [u8]) -> Result<(), Error> { if words.len() > FIFO_SIZE { @@ -456,6 +454,28 @@ impl Driver { SpiFuture { driver: self } } + /// Waits for the current transfer to finish. + /// + /// If the future is dropped, the transfer is cut short, and the drop blocks for a short while + /// until the peripheral is idle. + /// + /// Await this directly after starting a CPU-driven chunk, with no `.await` in between. A + /// future can only be dropped while it is suspended, and the guard is created in the first + /// poll, before this future can first suspend. The chunk is therefore covered from the + /// moment it starts. + /// + /// Use [`Self::flush_async`] to wait for a transfer that the caller did not start, e.g. the + /// tail of an earlier operation. Cancelling that wait must not abort the other operation. + #[cfg_attr(place_spi_master_driver_in_ram, ram)] + async fn flush_async_or_abort(&self) { + let cancel_on_drop = DropGuard::new((), |_| { + self.abort_transfer(); + let _ = self.flush(); + }); + self.flush_async().await; + cancel_on_drop.defuse(); + } + // Check if the bus is busy and if it is wait for it to be idle #[cfg_attr(place_spi_master_driver_in_ram, ram)] pub(super) fn flush(&self) -> Result<(), Error> { @@ -678,14 +698,7 @@ impl Driver { self.prepare_half_duplex_chunk(first, last); self.configure_datalen(chunk.len(), 0); self.start_operation(); - - let cancel_on_drop = DropGuard::new((), |_| { - self.abort_transfer(); - let _ = self.flush(); - }); - self.flush_async().await; - cancel_on_drop.defuse(); - + self.flush_async_or_abort().await; self.read_from_fifo(chunk)?; first = false; } @@ -747,13 +760,7 @@ impl Driver { if buffer.is_empty() { self.prepare_half_duplex_chunk(true, true); self.start_operation(); - - let cancel_on_drop = DropGuard::new((), |_| { - self.abort_transfer(); - let _ = self.flush(); - }); - self.flush_async().await; - cancel_on_drop.defuse(); + self.flush_async_or_abort().await; } else { let mut first = true; let mut chunks = buffer.chunks(FIFO_SIZE).peekable(); @@ -763,14 +770,7 @@ impl Driver { self.configure_datalen(0, chunk.len()); self.fill_fifo(chunk); self.start_operation(); - - let cancel_on_drop = DropGuard::new((), |_| { - self.abort_transfer(); - let _ = self.flush(); - }); - self.flush_async().await; - cancel_on_drop.defuse(); - + self.flush_async_or_abort().await; first = false; } } @@ -780,17 +780,8 @@ impl Driver { #[cfg_attr(place_spi_master_driver_in_ram, ram)] pub(super) async fn transfer_in_place_async(&self, words: &mut [u8]) -> Result<(), Error> { for chunk in words.chunks_mut(FIFO_SIZE) { - // Cut the transfer short if the future is dropped. We'll block for a short - // while to ensure the peripheral is idle. - let cancel_on_drop = DropGuard::new((), |_| { - self.abort_transfer(); - let _ = self.flush(); - }); - let res = self.write_one(chunk); - self.flush_async().await; - cancel_on_drop.defuse(); - res?; - + self.write_one(chunk)?; + self.flush_async_or_abort().await; self.read_from_fifo(chunk)?; } @@ -823,7 +814,7 @@ impl Driver { self.write_one(&write[write_from..][..write_inc])?; } - self.flush_async().await; + self.flush_async_or_abort().await; if read_inc > 0 { self.read_from_fifo(&mut read[read_from..][..read_inc])?; diff --git a/esp-hal/src/spi/master/mod.rs b/esp-hal/src/spi/master/mod.rs index e742728e933..83aefa62744 100644 --- a/esp-hal/src/spi/master/mod.rs +++ b/esp-hal/src/spi/master/mod.rs @@ -94,7 +94,7 @@ pub enum SpiInterrupt { App1, } -/// The size of the FIFO buffer for SPI +/// The size of the FIFO buffer for SPI. const FIFO_SIZE: usize = property!("spi_master.fifo_size"); /// Padding byte for empty write transfers @@ -428,19 +428,19 @@ pub struct Config { /// Clock divider calculations are relatively expensive, and the SPI /// peripheral is commonly expected to be used in a shared bus /// configuration, where different devices may need different bus clock - /// frequencies. To reduce the time required to reconfigure the bus, we - /// cache clock register's value here, for each configuration. + /// frequencies. To reduce the time required to reconfigure the bus, the + /// clock register value is cached here for each configuration. /// - /// This field is not intended to be set by the user, and is only used + /// This field is not intended to be set from application code, and is only used /// internally. #[builder_lite(skip)] reg: Result, - /// The target frequency + /// The target frequency. #[builder_lite(skip_setter)] frequency: Rate, - /// The clock source + /// The clock source. #[builder_lite(unstable)] #[builder_lite(skip_setter)] clock_source: ClockSource, @@ -489,7 +489,7 @@ impl Default for Config { } impl Config { - /// Set the frequency of the SPI bus clock. + /// Sets the frequency of the SPI bus clock. /// /// The closest available frequency that does not exceed `frequency` is used, /// so the bus never runs faster than requested. @@ -500,7 +500,7 @@ impl Config { self } - /// Set the clock source of the SPI bus. + /// Sets the clock source of the SPI bus. #[instability::unstable] pub fn with_clock_source(mut self, clock_source: ClockSource) -> Self { self.clock_source = clock_source; @@ -549,8 +549,8 @@ impl Config { /// /// The peripheral divides the source clock by `pre * n`, so this is the /// smallest divider that does not overshoot. `n` also determines the duty - /// cycle resolution, so out of pairs forming that divider we want the one - /// with the largest `n`. + /// cycle resolution, so among pairs forming that divider the one with the + /// largest `n` is preferred. /// /// Out-of-range frequencies (see [`Config::validate`]) yield the slowest pair /// available rather than an error. @@ -673,7 +673,7 @@ impl core::fmt::Display for ConfigError { #[procmacros::doc_replace] /// SPI peripheral driver /// -/// ## Example +/// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -703,13 +703,9 @@ impl Sealed for Spi<'_, Dm> {} impl<'d> Spi<'d, Blocking> { #[procmacros::doc_replace] - /// Constructs an SPI instance in 8bit dataframe mode. + /// Creates a new SPI instance in 8-bit data-frame mode. /// - /// ## Errors - /// - /// See [`Spi::apply_config`]. - /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -723,6 +719,10 @@ impl<'d> Spi<'d, Blocking> { /// .with_miso(peripherals.GPIO2); /// # {after_snippet} /// ``` + /// + /// # Errors + /// + /// See [`Spi::apply_config`] pub fn new(spi: impl Instance + 'd, config: Config) -> Result { let mut this = Spi { _mode: PhantomData, @@ -764,12 +764,11 @@ impl<'d> Spi<'d, Blocking> { _ => "peripheral", } )] - /// # Registers an interrupt handler for the __peripheral_on__. + /// Registers an interrupt handler for the __peripheral_on__. /// - /// Note that this will replace any previously registered interrupt - /// handlers. + /// Replaces any previously registered interrupt handlers. /// - /// You can restore the default/unhandled interrupt handler by using + /// The default/unhandled interrupt handler can be restored with /// [crate::interrupt::DEFAULT_INTERRUPT_HANDLER] /// /// # Panics @@ -784,7 +783,7 @@ impl<'d> Spi<'d, Blocking> { #[instability::unstable] impl crate::interrupt::InterruptConfigurable for Spi<'_, Blocking> { - /// Sets the interrupt handler + /// Sets the interrupt handler. /// /// Interrupts are not enabled at the peripheral level here. fn set_interrupt_handler(&mut self, handler: InterruptHandler) { @@ -808,7 +807,7 @@ impl<'d> Spi<'d, Async> { #[procmacros::doc_replace] /// Waits for the completion of previous operations. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -835,12 +834,11 @@ impl<'d> Spi<'d, Async> { #[procmacros::doc_replace] /// Sends `words` to the slave. Returns the `words` received from the slave. /// - /// This function aborts the transfer when its Future is dropped. Some - /// amount of data may have been transferred before the Future is - /// dropped. Dropping the future may block for a short while to ensure - /// the transfer is aborted. + /// Aborts the transfer when its Future is dropped. Some amount of data may have + /// been transferred before the Future is dropped. Dropping the future may block + /// for a short while to ensure the transfer is aborted. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -876,15 +874,15 @@ impl<'d> Spi<'d, Async> { /// Transfers larger than the hardware FIFO are split into chunks. CS remains asserted across /// chunks, but the clock pauses while the CPU prepares each subsequent chunk. /// - /// This function aborts the transfer when its Future is dropped. Some amount of data may have - /// been transferred before the Future is dropped. Dropping the future may block for a short - /// while to ensure the transfer is aborted. + /// Aborts the transfer when its Future is dropped. Some amount of data may have + /// been transferred before the Future is dropped. Dropping the future may block + /// for a short while to ensure the transfer is aborted. /// /// # Errors /// - /// [`Error::Unsupported`] will be returned if the buffer is empty (currently unsupported). + /// [`Error::Unsupported`] when the buffer is empty (currently unsupported). /// `DataMode::Single` cannot be combined with any other [`DataMode`], otherwise - /// [`Error::Unsupported`] will be returned. + /// [`Error::Unsupported`]. #[instability::unstable] pub async fn half_duplex_read_async( &mut self, @@ -912,13 +910,13 @@ impl<'d> Spi<'d, Async> { /// Transfers larger than the hardware FIFO are split into chunks. CS remains asserted across /// chunks, but the clock pauses while the CPU prepares each subsequent chunk. /// - /// This function aborts the transfer when its Future is dropped. Some amount of data may have - /// been transferred before the Future is dropped. Dropping the future may block for a short - /// while to ensure the transfer is aborted. + /// Aborts the transfer when its Future is dropped. Some amount of data may have + /// been transferred before the Future is dropped. Dropping the future may block + /// for a short while to ensure the transfer is aborted. /// /// # Errors /// - /// [`Error::Unsupported`] will be returned for unsupported combinations of command, address, + /// [`Error::Unsupported`] for unsupported combinations of command, address, /// dummy, and data modes. #[cfg_attr( esp32, @@ -1024,14 +1022,14 @@ where } #[procmacros::doc_replace] - /// Assign the SCK (Serial Clock) pin for the SPI instance. + /// Assigns the SCK (Serial Clock) pin for the SPI instance. /// /// Configures the specified pin to push-pull output and connects it to the /// SPI clock signal. /// /// Disconnects the previous pin that was assigned with `with_sck`. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1051,16 +1049,16 @@ where } #[procmacros::doc_replace] - /// Assign the MOSI (Master Out Slave In) pin for the SPI instance. + /// Assigns the MOSI (Master Out Slave In) pin for the SPI instance. /// /// Enables output functionality for the pin, and connects it as the MOSI - /// signal. You want to use this for full-duplex SPI or - /// if you intend to use [DataMode::SingleTwoDataLines]. + /// signal. Use this for full-duplex SPI or + /// when using [DataMode::SingleTwoDataLines]. /// /// Disconnects the previous pin that was assigned with `with_mosi` or /// `with_sio0`. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1078,15 +1076,15 @@ where } #[procmacros::doc_replace] - /// Assign the MISO (Master In Slave Out) pin for the SPI instance. + /// Assigns the MISO (Master In Slave Out) pin for the SPI instance. /// /// Enables input functionality for the pin, and connects it to the MISO /// signal. /// - /// You want to use this for full-duplex SPI or + /// Use this for full-duplex SPI or /// [DataMode::SingleTwoDataLines] /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1109,7 +1107,7 @@ where self } - /// Assign the SIO0 pin for the SPI instance. + /// Assigns the SIO0 pin for the SPI instance. /// /// Enables both input and output functionality for the pin, and connects it /// to the MOSI output signal and SIO0 input signal. @@ -1119,7 +1117,7 @@ where /// /// Use this if any of the devices on the bus use half-duplex SPI. /// - /// See also [Self::with_mosi] when you only need a one-directional MOSI + /// See also [Self::with_mosi] for a one-directional MOSI /// signal. #[instability::unstable] pub fn with_sio0(mut self, mosi: impl PeripheralInput<'d> + PeripheralOutput<'d>) -> Self { @@ -1128,7 +1126,7 @@ where self } - /// Assign the SIO1/MISO pin for the SPI instance. + /// Assigns the SIO1/MISO pin for the SPI instance. /// /// Enables both input and output functionality for the pin, and connects it /// to the MISO input signal and SIO1 output signal. @@ -1137,7 +1135,7 @@ where /// /// Use this if any of the devices on the bus use half-duplex SPI. /// - /// See also [Self::with_miso] when you only need a one-directional MISO + /// See also [Self::with_miso] for a one-directional MISO /// signal. #[instability::unstable] pub fn with_sio1(mut self, sio1: impl PeripheralInput<'d> + PeripheralOutput<'d>) -> Self { @@ -1161,7 +1159,7 @@ where #[cfg(spi_master_has_octal)] def_with_sio_pin!(with_sio7, 7); - /// Assign the CS (Chip Select) pin for the SPI instance. + /// Assigns the CS (Chip Select) pin for the SPI instance. /// /// Configures the specified pin to push-pull output and connects it to the /// SPI CS signal. @@ -1186,14 +1184,9 @@ where _ => "80MHz", } )] - /// Change the bus configuration. + /// Changes the bus configuration. /// - /// # Errors - /// - /// If frequency passed in config exceeds __max_frequency__ or is below 70kHz, - /// [`ConfigError::FrequencyOutOfRange`] error will be returned. - /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1207,15 +1200,20 @@ where /// # /// # {after_snippet} /// ``` + /// + /// # Errors + /// + /// [`ConfigError::FrequencyOutOfRange`] when frequency passed in config exceeds + /// __max_frequency__ or is below 70 kHz. pub fn apply_config(&mut self, config: &Config) -> Result<(), ConfigError> { self.driver().apply_config(config) } #[procmacros::doc_replace] - /// Write bytes to SPI. After writing, flush is called to ensure all data + /// Writes bytes to SPI. After writing, flush is called to ensure all data /// has been transmitted. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1242,10 +1240,10 @@ where } #[procmacros::doc_replace] - /// Read bytes from SPI. The provided slice is filled with data received + /// Reads bytes from SPI. The provided slice is filled with data received /// from the slave. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1274,7 +1272,7 @@ where /// Sends `words` to the slave. The received data will be written to /// `words`, overwriting its contents. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1306,9 +1304,9 @@ where /// /// # Errors /// - /// [`Error::Unsupported`] will be returned if the buffer is empty (currently unsupported). + /// [`Error::Unsupported`] when the buffer is empty (currently unsupported). /// `DataMode::Single` cannot be combined with any other [`DataMode`], otherwise - /// [`Error::Unsupported`] will be returned. + /// [`Error::Unsupported`]. #[instability::unstable] pub fn half_duplex_read( &mut self, @@ -1330,7 +1328,7 @@ where /// /// # Errors /// - /// [`Error::Unsupported`] will be returned for unsupported combinations of command, address, + /// [`Error::Unsupported`] for unsupported combinations of command, address, /// dummy, and data modes. #[cfg_attr( esp32, @@ -1465,7 +1463,7 @@ impl SpiBusAsync for Spi<'_, Async> { } } -/// SPI data mode +/// SPI data mode. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[instability::unstable] diff --git a/esp-hal/src/spi/slave.rs b/esp-hal/src/spi/slave.rs index 348f431aaa3..2c64e4b11a1 100644 --- a/esp-hal/src/spi/slave.rs +++ b/esp-hal/src/spi/slave.rs @@ -95,7 +95,7 @@ pub struct Spi<'d, Dm: DriverMode> { _guard: PeripheralGuard, } impl<'d> Spi<'d, Blocking> { - /// Constructs an SPI instance in 8bit dataframe mode. + /// Creates a new SPI instance in 8-bit data-frame mode. #[instability::unstable] pub fn new(spi: impl Instance + 'd, mode: Mode) -> Spi<'d, Blocking> { let guard = PeripheralGuard::new(spi.info().peripheral); @@ -122,21 +122,21 @@ impl<'d> Spi<'d, Blocking> { signal.connect_to(&pin); } - /// Assign the SCK (Serial Clock) pin for the SPI instance. + /// Assigns the SCK (Serial Clock) pin for the SPI instance. #[instability::unstable] pub fn with_sck(self, sclk: impl PeripheralInput<'d>) -> Self { self.connect_input_pin(sclk, self.spi.info().sclk); self } - /// Assign the MOSI (Master Out Slave In) pin for the SPI instance. + /// Assigns the MOSI (Master Out Slave In) pin for the SPI instance. #[instability::unstable] pub fn with_mosi(self, mosi: impl PeripheralInput<'d>) -> Self { self.connect_input_pin(mosi, self.spi.info().mosi); self } - /// Assign the MISO (Master In Slave Out) pin for the SPI instance. + /// Assigns the MISO (Master In Slave Out) pin for the SPI instance. #[instability::unstable] pub fn with_miso(self, miso: impl PeripheralOutput<'d>) -> Self { let miso = miso.into(); @@ -148,7 +148,7 @@ impl<'d> Spi<'d, Blocking> { self } - /// Assign the CS (Chip Select) pin for the SPI instance. + /// Assigns the CS (Chip Select) pin for the SPI instance. #[instability::unstable] pub fn with_cs(self, cs: impl PeripheralInput<'d>) -> Self { self.connect_input_pin(cs, self.spi.info().cs); @@ -165,6 +165,8 @@ pub mod dma { use enumset::enum_set; use super::*; + #[cfg(not(spi_slave_dma_engine = "SPI_DMA"))] + use crate::RegisterToggle; use crate::{ DriverMode, dma::{Channel, DmaRxBuffer, DmaRxInterrupt, DmaTxBuffer, EmptyBuf}, @@ -233,10 +235,10 @@ pub mod dma { } } - /// Register a buffer for a DMA write. + /// Registers a buffer for a DMA write. /// - /// This will return a [SpiDmaTransfer]. The maximum amount of data to - /// be sent is 32736 bytes. + /// Returns a [`SpiDmaTransfer`] that can be used to wait for the transfer to complete. + /// The maximum amount of data to be sent is 32736 bytes. /// /// The write is driven by the SPI master's sclk signal and cs line. #[instability::unstable] @@ -268,10 +270,10 @@ pub mod dma { Ok(SpiDmaTransfer::new(self, buffer, false, true)) } - /// Register a buffer for a DMA read. + /// Registers a buffer for a DMA read. /// - /// This will return a [SpiDmaTransfer]. The maximum amount of data to - /// be received is 32736 bytes. + /// Returns a [`SpiDmaTransfer`] that can be used to wait for the transfer to complete. + /// The maximum amount of data to be received is 32736 bytes. /// /// The read is driven by the SPI master's sclk signal and cs line. #[instability::unstable] @@ -303,10 +305,10 @@ pub mod dma { Ok(SpiDmaTransfer::new(self, buffer, true, false)) } - /// Register buffers for a DMA transfer. + /// Registers buffers for a DMA transfer. /// - /// This will return a [SpiDmaTransfer]. The maximum amount of data to - /// be sent/received is 32736 bytes. + /// Returns a [`SpiDmaTransfer`] that can be used to wait for the transfer to complete. + /// The maximum amount of data to be sent/received is 32736 bytes. /// /// The data transfer is driven by the SPI master's sclk signal and cs /// line. @@ -356,8 +358,7 @@ pub mod dma { /// A structure representing a DMA transfer for SPI. /// - /// This structure holds references to the SPI instance, DMA buffers, and - /// transfer status. + /// Holds references to the SPI instance, DMA buffers, and transfer status. #[instability::unstable] pub struct SpiDmaTransfer<'d, Dm, Buf> where @@ -384,10 +385,10 @@ pub mod dma { } } - /// Checks if the transfer is complete. + /// Returns whether the transfer is complete. /// - /// This method returns `true` if both RX and TX operations are done, - /// and the SPI instance is no longer busy. + /// Both RX and TX operations are done, and the SPI instance is no longer + /// busy. #[instability::unstable] pub fn is_done(&self) -> bool { if self.has_rx { @@ -408,7 +409,7 @@ pub mod dma { /// Waits for the DMA transfer to complete. /// - /// This method blocks until the transfer is finished and returns the + /// Blocks until the transfer is finished and returns the /// `SpiDma` instance and the associated buffer. #[instability::unstable] pub fn wait(mut self) -> (SpiDma<'d, Dm>, Buf) { @@ -491,8 +492,6 @@ pub mod dma { self.info .prepare_length_and_lines(read_buffer_len, write_buffer_len); - self.reset_dma_before_usr_cmd(); - #[cfg(not(esp32))] self.regs() .dma_conf() @@ -500,26 +499,36 @@ pub mod dma { self.clear_dma_interrupts(); self.info.setup_for_flush(); - self.regs().cmd().modify(|_, w| w.usr().set_bit()); if read_buffer_len > 0 { + self.reset_dma_rx_fifo(); channel.rx.start_transfer()?; } if write_buffer_len > 0 { + self.reset_dma_tx_fifo(); channel.tx.start_transfer()?; } + // The SPI master owns SCLK and CS. Arm the peripheral only after + // both GDMA directions can service the first edge. + self.regs().cmd().modify(|_, w| w.usr().set_bit()); + Ok(()) } - fn reset_dma_before_usr_cmd(&self) { + fn reset_dma_rx_fifo(&self) { #[cfg(not(spi_slave_dma_engine = "SPI_DMA"))] - self.regs().dma_conf().modify(|_, w| { - w.rx_afifo_rst().set_bit(); - w.buf_afifo_rst().set_bit(); - w.dma_afifo_rst().set_bit() - }); + self.regs() + .dma_conf() + .toggle(|w, bit| w.rx_afifo_rst().bit(bit)); + } + + fn reset_dma_tx_fifo(&self) { + #[cfg(not(spi_slave_dma_engine = "SPI_DMA"))] + self.regs() + .dma_conf() + .toggle(|w, bit| w.dma_afifo_rst().bit(bit)); } fn enable_dma(&self) { @@ -620,7 +629,7 @@ pub trait Instance: crate::private::Sealed + any::Degrade { pub struct Info { /// Pointer to the register block for this SPI instance. /// - /// Use [Self::register_block] to access the register block. + /// Used with [`Self::register_block`] to access the register block. pub register_block: *const RegisterBlock, /// System peripheral marker. @@ -680,7 +689,7 @@ impl Info { }); } - /// Initialize for full-duplex 1 bit mode + /// Initializes for full-duplex 1 bit mode. fn init(&self) { #[cfg(soc_has_pcr)] crate::peripherals::PCR::regs() diff --git a/esp-hal/src/sync.rs b/esp-hal/src/sync.rs index 1ed26769536..e61c1c6042a 100644 --- a/esp-hal/src/sync.rs +++ b/esp-hal/src/sync.rs @@ -47,7 +47,7 @@ impl RawLock for PriorityLock { return unsafe { SingleCoreInterruptLock.exit(token) }; } assert!(Self::current_priority() <= self.0); - // Ensure no preceeding memory accesses are reordered to after interrupts are + // Ensure no preceding memory accesses are reordered to after interrupts are // enabled. compiler_fence(Ordering::SeqCst); @@ -65,7 +65,7 @@ pub struct RawPriorityLimitedMutex { } impl RawPriorityLimitedMutex { - /// Create a new lock that is accessible at or below the given `priority`. + /// Creates a new lock that is accessible at or below the given `priority`. pub const fn new(priority: Priority) -> Self { Self { inner: GenericRawMutex::new(PriorityLock(RunLevel::Interrupt( diff --git a/esp-hal/src/system.rs b/esp-hal/src/system.rs index e13ca7ab664..a9ac71ef740 100644 --- a/esp-hal/src/system.rs +++ b/esp-hal/src/system.rs @@ -1,6 +1,6 @@ //! # System Control -#![cfg_attr(esp32s31, allow(dead_code))] +#![allow(dead_code)] use esp_sync::NonReentrantMutex; @@ -40,7 +40,7 @@ impl RefCounts { static PERIPHERAL_REF_COUNT: NonReentrantMutex = NonReentrantMutex::new(RefCounts::new()); -/// Disable all peripherals. +/// Disables all peripherals. /// /// Peripherals listed in [KEEP_ENABLED] are NOT disabled. #[cfg_attr(not(feature = "rt"), expect(dead_code))] @@ -147,7 +147,7 @@ impl PeripheralClockControl { /// This keeps track of enabling a peripheral - i.e. a peripheral /// is only enabled with the first call attempt to enable it. /// - /// Returns `true` if it actually enabled the peripheral. + /// Returns whether it actually enabled the peripheral. pub(crate) fn enable(peripheral: Peripheral) -> bool { PERIPHERAL_REF_COUNT.with(|ref_counts| Self::enable_with_counts(peripheral, ref_counts)) } @@ -157,7 +157,7 @@ impl PeripheralClockControl { /// This keeps track of enabling a peripheral - i.e. a peripheral /// is only enabled with the first call attempt to enable it. /// - /// Returns `true` if it actually enabled the peripheral. + /// Returns whether it actually enabled the peripheral. fn enable_with_counts(peripheral: Peripheral, ref_counts: &mut RefCounts) -> bool { Self::enable_forced_with_counts(peripheral, true, false, ref_counts) } @@ -167,7 +167,7 @@ impl PeripheralClockControl { /// This keeps track of disabling a peripheral - i.e. it only /// gets disabled when the number of enable/disable attempts is balanced. /// - /// Returns `true` if it actually disabled the peripheral. + /// Returns whether it actually disabled the peripheral. pub(crate) fn disable(peripheral: Peripheral) -> bool { PERIPHERAL_REF_COUNT.with(|ref_counts| { Self::enable_forced_with_counts(peripheral, false, false, ref_counts) @@ -207,7 +207,7 @@ impl PeripheralClockControl { true } - /// Resets the given peripheral + /// Resets the given peripheral. pub(crate) unsafe fn reset_racey(peripheral: Peripheral) { debug!("Reset {:?}", peripheral); @@ -217,7 +217,7 @@ impl PeripheralClockControl { } } - /// Resets the given peripheral + /// Resets the given peripheral. pub(crate) fn reset(peripheral: Peripheral) { PERIPHERAL_REF_COUNT.with(|_| unsafe { Self::reset_racey(peripheral) }) } @@ -230,9 +230,9 @@ impl PeripheralClockControl { #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[repr(C)] pub enum Cpu { - /// The first core + /// The first core. ProCpu = 0, - /// The second core + /// The second core. #[cfg(multi_core)] AppCpu = 1, } @@ -242,7 +242,7 @@ impl Cpu { pub const COUNT: usize = 1 + cfg!(multi_core) as usize; #[procmacros::doc_replace] - /// Returns the core the application is currently executing on + /// Returns the core the application is currently executing on. /// /// ```rust, no_run /// # {before_snippet} @@ -303,7 +303,6 @@ impl Cpu { /// this bit to determine the core id. #[inline(always)] pub(crate) fn raw_core() -> usize { - // This method must never return UNUSED_THREAD_ID_VALUE cfg_select! { all(multi_core, riscv) => riscv::register::mhartid::read(), all(multi_core, xtensa) => (xtensa_lx::get_processor_id() & 0x2000) as usize, @@ -316,7 +315,7 @@ use crate::rtc_cntl::SocResetReason; #[procmacros::doc_replace] /// Performs a software reset on the chip. /// -/// # Example +/// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -327,7 +326,7 @@ use crate::rtc_cntl::SocResetReason; #[inline] pub fn software_reset() -> ! { let _uart0_sclk_guard = ensure_uart0_sclk_enabled(); - #[cfg(any(esp32p4, esp32s31))] + #[cfg(any(esp32h4, esp32p4, esp32s31))] crate::soc::cpu_control::pre_system_reset(); crate::rom::software_reset() } @@ -356,7 +355,7 @@ impl Drop for Uart0SclkGuard { } } -/// Ensure UART0's source clock stays enabled for boot ROM compatibility. +/// Ensures UART0's source clock stays enabled for boot ROM compatibility. /// /// On some chips, resetting or waking up while UART0's source clock is disabled /// can prevent the boot ROM from starting correctly. This only requests the @@ -397,6 +396,63 @@ fn release_uart0_sclk() { #[cfg(not(soc_has_clock_node_uart_function_clock))] fn release_uart0_sclk() {} +/// Guard for the clock shared by the crypto accelerators. +#[cfg(feature = "unstable")] +#[must_use = "dropping the guard releases the crypto clock"] +pub(crate) struct CryptoClockGuard; + +#[cfg(feature = "unstable")] +impl CryptoClockGuard { + /// Request the clock that drives the crypto accelerators. + /// + /// The clock is called `CRYPTO_CLK` on most chips, and `CRYPTO_PWM_CLK` on the ESP32-S3, where + /// the MCPWM peripherals share it. + #[inline(always)] + pub(crate) fn new() -> Self { + Self::request(); + Self + } + + fn request() { + cfg_select! { + soc_has_clock_node_crypto_clk => { + crate::soc::clocks::ClockTree::with(|clocks| { + crate::soc::clocks::request_crypto_clk(clocks); + }); + } + soc_has_clock_node_crypto_pwm_clk => { + crate::soc::clocks::ClockTree::with(|clocks| { + crate::soc::clocks::request_crypto_pwm_clk(clocks); + }); + } + _ => {} + } + } + + fn release() { + cfg_select! { + soc_has_clock_node_crypto_clk => { + crate::soc::clocks::ClockTree::with(|clocks| { + crate::soc::clocks::release_crypto_clk(clocks); + }); + } + soc_has_clock_node_crypto_pwm_clk => { + crate::soc::clocks::ClockTree::with(|clocks| { + crate::soc::clocks::release_crypto_pwm_clk(clocks); + }); + } + _ => {} + } + } +} + +#[cfg(feature = "unstable")] +impl Drop for CryptoClockGuard { + fn drop(&mut self) { + Self::release(); + } +} + /// Retrieves the reason for the last reset as a SocResetReason enum value. /// Returns `None` if the reset reason cannot be determined. #[instability::unstable] diff --git a/esp-hal/src/system/multi_core.rs b/esp-hal/src/system/multi_core.rs index 958269bdf7c..40ea06c7771 100644 --- a/esp-hal/src/system/multi_core.rs +++ b/esp-hal/src/system/multi_core.rs @@ -3,16 +3,12 @@ use core::{ marker::PhantomData, mem::{ManuallyDrop, MaybeUninit}, - sync::atomic::{AtomicPtr, Ordering}, + sync::atomic::{AtomicBool, AtomicPtr, Ordering}, }; #[instability::unstable] pub use crate::soc::cpu_control::is_running; -use crate::{ - peripherals::CPU_CTRL, - soc::cpu_control::{internal_park_core, start_core1_init}, - system::Cpu, -}; +use crate::{peripherals::CPU_CTRL, soc::cpu_control::internal_park_core, system::Cpu}; /// Data type for a properly aligned stack of N bytes // Xtensa ISA 10.5: [B]y default, the @@ -42,7 +38,7 @@ impl Default for Stack { #[allow(clippy::len_without_is_empty)] impl Stack { - /// Construct a stack of length SIZE, uninitialized + /// Creates a new stack of length SIZE, uninitialized. #[instability::unstable] pub const fn new() -> Stack { const { @@ -80,7 +76,7 @@ pub(crate) static START_CORE1_FUNCTION: AtomicPtr<()> = AtomicPtr::new(core::ptr pub(crate) static APP_CORE_STACK_TOP: AtomicPtr = AtomicPtr::new(core::ptr::null_mut()); pub(crate) static APP_CORE_STACK_GUARD: AtomicPtr = AtomicPtr::new(core::ptr::null_mut()); -/// Will park the APP (second) core when dropped +/// Will park the APP (second) core when dropped. #[must_use = "Dropping this guard will park the APP core"] #[instability::unstable] pub struct AppCoreGuard<'a> { @@ -105,7 +101,8 @@ pub enum Error { #[procmacros::doc_replace] /// Control CPU Cores /// -/// ## Examples +/// # Examples +/// /// ```rust, no_run /// # {before_snippet} /// # use esp_hal::delay::Delay; @@ -159,24 +156,24 @@ impl<'d> CpuControl<'d> { } } - /// Park the given core + /// Parks the given core. /// /// # Safety /// - /// The user must ensure that the core being parked is not the core which is - /// currently executing their code. + /// The caller must ensure that the core being parked is not the core which is + /// currently executing this code. #[instability::unstable] pub unsafe fn park_core(&mut self, core: Cpu) { unsafe { internal_park_core(core, true) }; } - /// Unpark the given core + /// Unparks the given core. #[instability::unstable] pub fn unpark_core(&mut self, core: Cpu) { unsafe { internal_park_core(core, false) }; } - /// Run the core1 closure. + /// Runs the core1 closure. #[inline(never)] pub(crate) unsafe fn start_core1_run() -> ! where @@ -194,10 +191,10 @@ impl<'d> CpuControl<'d> { } } - /// Start the APP (second) core. + /// Starts the APP (second) core. /// - /// The second core will start running the closure `entry`. Note that if the - /// closure exits, the core will be parked. + /// The second core starts running the closure `entry`. The core enables interrupts before + /// `entry` runs. If the closure exits, the core is parked. /// /// Dropping the returned guard will park the core. #[instability::unstable] @@ -225,10 +222,10 @@ impl<'d> CpuControl<'d> { self.start_app_core_with_stack_guard_offset(stack, stack_guard_offset, entry) } - /// Start the APP (second) core. + /// Starts the APP (second) core. /// - /// The second core will start running the closure `entry`. Note that if the - /// closure exits, the core will be parked. + /// The second core starts running the closure `entry`. The core enables interrupts before + /// `entry` runs. If the closure exits, the core is parked. /// /// Dropping the returned guard will park the core. #[instability::unstable] @@ -248,6 +245,7 @@ impl<'d> CpuControl<'d> { setup_second_core_stack(stack, stack_guard_offset, entry); + APP_CORE_TAKES_IPC.store(false, Ordering::Release); crate::soc::cpu_control::start_core1(start_core1_init:: as *const u32); self.unpark_core(Cpu::AppCpu); @@ -294,8 +292,166 @@ fn setup_second_core_stack<'a, F, const SIZE: usize>( entry_dst.write(entry); let entry_fn = entry_dst.cast::<()>(); + #[cfg(esp32s31)] + crate::soc::cpu_control::save_core0_pma(&mut *core0_pma_slot::(entry_fn)); START_CORE1_FUNCTION.store(entry_fn, Ordering::Release); APP_CORE_STACK_TOP.store(stack.top(), Ordering::Release); APP_CORE_STACK_GUARD.store(stack_guard.cast(), Ordering::Release); } } + +#[cfg(esp32s31)] +fn core0_pma_slot(entry: *mut ()) -> *mut [u32; 32] { + let end = entry.cast::().wrapping_add(core::mem::size_of::()); + end.wrapping_add(end.align_offset(core::mem::align_of::())) + .cast() +} + +/// Core 1 entry point, set as the boot address. +#[cfg(xtensa)] +pub(crate) fn start_core1_init() -> ! +where + F: FnOnce(), +{ + // disables interrupts + unsafe { + xtensa_lx::interrupt::set_mask(0); + } + + // reset cycle compare registers + xtensa_lx::timer::set_ccompare0(0); + xtensa_lx::timer::set_ccompare1(0); + xtensa_lx::timer::set_ccompare2(0); + + unsafe extern "C" { + static mut _init_start: u32; + } + + // set vector table and stack pointer + unsafe { + xtensa_lx::set_vecbase(&raw const _init_start); + xtensa_lx::set_stack_pointer(APP_CORE_STACK_TOP.load(Ordering::Acquire)); + + #[cfg(all(feature = "rt", stack_guard_monitoring))] + { + let stack_guard = APP_CORE_STACK_GUARD.load(Ordering::Acquire); + stack_guard.write_volatile(esp_config::esp_config_int!( + u32, + "ESP_HAL_CONFIG_STACK_GUARD_VALUE" + )); + // setting 0 effectively disables the functionality + crate::debugger::set_stack_watchpoint(stack_guard as usize); + } + } + + // The ROM has already handed off to us; clear the AppCpu boot address so a + // subsequent reset doesn't see a stale entry point. Matches IDF's + // `call_start_cpu1`. + cfg_select! { + esp32 => { + crate::peripherals::DPORT::regs() + .appcpu_ctrl_d() + .write(|w| unsafe { w.appcpu_boot_addr().bits(0) }); + } + _ => crate::rom::ets_set_appcpu_boot_addr(0), + } + + // Do not call setup_interrupts as that would disable peripheral interrupts, too. + unsafe { crate::interrupt::init_vectoring() }; + + enable_app_core_interrupts(); + + // Trampoline to run from the new stack. + // start_core1_run should _NEVER_ be inlined + // as we rely on the function call to use + // the new stack. + unsafe { CpuControl::start_core1_run::() } +} + +/// Core 1 entry point, set as the boot address. +/// +/// ROM jumps here directly, bypassing `_start`, so `gp`, the FPU and the stack pointer need to be +/// set up before entering regular Rust. +#[cfg(riscv)] +#[unsafe(naked)] +pub(crate) extern "C" fn start_core1_init() -> ! +where + F: FnOnce(), +{ + core::arch::naked_asm!( + ".option push", + ".option norelax", + "la gp, __global_pointer$", + "li ra, 0", // ensure probe-rs stops unwinding + ".option pop", + // Follow IDF's FPU initialization (rv_utils_enable_fpu, rv_utils_clear_fpu): enable the + // FPU in Initial state, touch fcsr (which makes the state Dirty), then clear the dirty + // bit to leave mstatus.FS in Clean state (0b10), which is what the interrupt handler + // expects. + "li t0, 0x2000", + "csrs mstatus, t0", + "li t0, 1", + "csrw fcsr, t0", + "li t0, 0x2000", + "csrc mstatus, t0", + // Switch to Core 1's stack (stored by Core 0 before releasing this core). + "la t0, {stack_top}", + "lw sp, 0(t0)", + "j {init}", + stack_top = sym APP_CORE_STACK_TOP, + init = sym start_core1_init_impl::, + ) +} + +#[cfg(riscv)] +fn start_core1_init_impl() -> ! +where + F: FnOnce(), +{ + #[cfg(esp32s31)] + crate::soc::cpu_control::set_core1_pma(unsafe { + &*core0_pma_slot::(START_CORE1_FUNCTION.load(Ordering::Acquire)) + }); + + crate::soc::branch_predictor::enable(); + + // The ROM has already handed off to us; clear the AppCpu boot address so a subsequent software + // reset doesn't re-enter this stale entry point. Matches IDF's `call_start_cpu1`. + crate::rom::ets_set_appcpu_boot_addr(0); + + unsafe { + #[cfg(all(feature = "rt", stack_guard_monitoring))] + { + let guard = APP_CORE_STACK_GUARD.load(Ordering::Acquire); + guard.write_volatile(esp_config::esp_config_int!( + u32, + "ESP_HAL_CONFIG_STACK_GUARD_VALUE" + )); + crate::debugger::set_stack_watchpoint(guard as usize); + } + crate::interrupt::init_vectoring(); + #[cfg(feature = "rt")] + crate::interrupt::ipc::install_app(); + } + + enable_app_core_interrupts(); + + unsafe { CpuControl::start_core1_run::() } +} + +fn enable_app_core_interrupts() { + unsafe { + crate::interrupt::RunLevel::change(crate::interrupt::RunLevel::ThreadMode); + #[cfg(riscv)] + core::arch::asm!("csrsi mstatus, 8", options(nomem, nostack)); + } + APP_CORE_TAKES_IPC.store(true, Ordering::Release); +} + +static APP_CORE_TAKES_IPC: AtomicBool = AtomicBool::new(false); + +/// Returns `true` if [`CpuControl`] started the APP core in this boot. That core takes IPC +/// interrupts unless it masks them. +pub(crate) fn app_core_takes_ipc() -> bool { + APP_CORE_TAKES_IPC.load(Ordering::Acquire) +} diff --git a/esp-hal/src/time.rs b/esp-hal/src/time.rs index 776ff6bf3eb..4ce1a54c5e4 100644 --- a/esp-hal/src/time.rs +++ b/esp-hal/src/time.rs @@ -45,9 +45,9 @@ impl defmt::Format for Rate { impl Rate { #[procmacros::doc_replace] - /// Shorthand for creating a rate which represents hertz. + /// Creates a new rate that represents hertz. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -61,9 +61,9 @@ impl Rate { } #[procmacros::doc_replace] - /// Shorthand for creating a rate which represents kilohertz. + /// Creates a new rate that represents kilohertz. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -77,9 +77,9 @@ impl Rate { } #[procmacros::doc_replace] - /// Shorthand for creating a rate which represents megahertz. + /// Creates a new rate that represents megahertz. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -93,9 +93,9 @@ impl Rate { } #[procmacros::doc_replace] - /// Convert the `Rate` to an integer number of Hz. + /// Converts the `Rate` to an integer number of Hz. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -110,9 +110,9 @@ impl Rate { } #[procmacros::doc_replace] - /// Convert the `Rate` to an integer number of kHz. + /// Converts the `Rate` to an integer number of kHz. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -127,9 +127,9 @@ impl Rate { } #[procmacros::doc_replace] - /// Convert the `Rate` to an integer number of MHz. + /// Converts the `Rate` to an integer number of MHz. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -144,9 +144,9 @@ impl Rate { } #[procmacros::doc_replace] - /// Convert the `Rate` to a `Duration`. + /// Converts the `Rate` to a `Duration`. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -246,15 +246,15 @@ impl Instant { )] /// Returns the current instant. /// - /// The counter won’t measure time in sleep-mode. + /// The counter does not measure time in sleep mode. /// - /// The timer has a 1 microsecond resolution and will wrap after __wrap_after__. + /// The timer has a 1 microsecond resolution and wraps after __wrap_after__. /// ///
- /// Note that this function returns an unreliable value before esp_hal::init() is - /// called.
+ /// Returns an unreliable value before esp_hal::init() is called. + /// /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -275,7 +275,7 @@ impl Instant { #[procmacros::doc_replace] /// Returns the elapsed `Duration` since boot. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -292,7 +292,7 @@ impl Instant { #[procmacros::doc_replace] /// Returns the elapsed `Duration` since this `Instant` was created. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -396,9 +396,9 @@ impl Duration { pub const MAX: Self = Self(InnerDuration::from_ticks(u64::MAX)); #[procmacros::doc_replace] - /// Creates a duration which represents microseconds. + /// Creates a new duration that represents microseconds. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -412,9 +412,9 @@ impl Duration { } #[procmacros::doc_replace] - /// Creates a duration which represents milliseconds. + /// Creates a new duration that represents milliseconds. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -428,9 +428,9 @@ impl Duration { } #[procmacros::doc_replace] - /// Creates a duration which represents seconds. + /// Creates a new duration that represents seconds. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -444,9 +444,9 @@ impl Duration { } #[procmacros::doc_replace] - /// Creates a duration which represents minutes. + /// Creates a new duration that represents minutes. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -460,9 +460,9 @@ impl Duration { } #[procmacros::doc_replace] - /// Creates a duration which represents hours. + /// Creates a new duration that represents hours. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -479,9 +479,9 @@ impl Duration { #[inline] to self.0 { #[procmacros::doc_replace] - /// Convert the `Duration` to an integer number of microseconds. + /// Converts the `Duration` to an integer number of microseconds. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -493,9 +493,9 @@ impl Duration { pub const fn as_micros(&self) -> u64; #[procmacros::doc_replace] - /// Convert the `Duration` to an integer number of milliseconds. + /// Converts the `Duration` to an integer number of milliseconds. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -507,9 +507,9 @@ impl Duration { pub const fn as_millis(&self) -> u64; #[procmacros::doc_replace] - /// Convert the `Duration` to an integer number of seconds. + /// Converts the `Duration` to an integer number of seconds. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -521,9 +521,9 @@ impl Duration { pub const fn as_secs(&self) -> u64; #[procmacros::doc_replace] - /// Convert the `Duration` to an integer number of minutes. + /// Converts the `Duration` to an integer number of minutes. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -535,9 +535,9 @@ impl Duration { pub const fn as_minutes(&self) -> u64; #[procmacros::doc_replace] - /// Convert the `Duration` to an integer number of hours. + /// Converts the `Duration` to an integer number of hours. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -551,9 +551,9 @@ impl Duration { } #[procmacros::doc_replace] - /// Add two durations while checking for overflow. + /// Adds two durations while checking for overflow. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -580,7 +580,7 @@ impl Duration { #[procmacros::doc_replace] /// Subtract two durations while checking for overflow. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -605,9 +605,9 @@ impl Duration { } #[procmacros::doc_replace] - /// Add two durations, returning the maximum value if overflow occurred. + /// Adds two durations, returning the maximum value if overflow occurred. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -631,7 +631,7 @@ impl Duration { /// Subtract two durations, returning the minimum value if the result would /// be negative. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -721,6 +721,8 @@ pub(crate) fn now() -> Instant { #[cfg(esp32)] pub(crate) mod implem { + use esp_sync::RawMutex; + use crate::peripherals::TIMG0; #[cfg(feature = "rt")] @@ -746,23 +748,30 @@ pub(crate) mod implem { #[inline] pub(crate) fn raw_counter() -> u64 { + // The latch is shared between cores, so we need additional locking + static LACT_LOCK: RawMutex = RawMutex::new(); + // on ESP32 use LACT let tg0 = TIMG0::regs(); - tg0.lactupdate().write(|w| unsafe { w.update().bits(1) }); - - // The peripheral doesn't have a bit to indicate that the update is done, so we - // poll the lower 32 bit part of the counter until it changes, or a timeout - // expires. - let lo_initial = tg0.lactlo().read().bits(); - let mut div = tg0.lactconfig().read().divider().bits(); - let lo = loop { - let lo = tg0.lactlo().read().bits(); - if lo != lo_initial || div == 0 { - break lo; - } - div -= 1; - }; - let hi = tg0.lacthi().read().bits(); + let (hi, lo) = LACT_LOCK.lock(|| { + tg0.lactupdate().write(|w| unsafe { w.update().bits(1) }); + + // The peripheral doesn't have a bit to indicate that the update is done, so we + // poll the lower 32 bit part of the counter until it changes, or a timeout + // expires. + let lo_initial = tg0.lactlo().read().bits(); + let mut div = tg0.lactconfig().read().divider().bits(); + let lo = loop { + let lo = tg0.lactlo().read().bits(); + if lo != lo_initial || div == 0 { + break lo; + } + div -= 1; + }; + let hi = tg0.lacthi().read().bits(); + + (hi, lo) + }); ((hi as u64) << 32u64) | lo as u64 } @@ -773,14 +782,14 @@ pub(crate) mod implem { } #[inline] - #[cfg(sleep_light_sleep)] + #[cfg(all(sleep_light_sleep, feature = "rt"))] pub(crate) fn us_to_ticks(counter: u64) -> u64 { counter * 16 } /// Callers must ensure this function is not called concurrently. #[inline] - #[cfg(sleep_light_sleep)] + #[cfg(all(sleep_light_sleep, feature = "rt"))] pub(crate) unsafe fn update_counter(counter: u64) { // On ESP32 the monotonic counter is the LACT timer of TIMG0. To set its // value we stage the new 64-bit count in the load registers and then @@ -834,14 +843,14 @@ pub(crate) mod implem { } #[inline] - #[cfg(sleep_light_sleep)] + #[cfg(all(sleep_light_sleep, feature = "rt"))] pub(crate) fn us_to_ticks(counter: u64) -> u64 { SystemTimer::us_to_ticks(counter) } /// Callers must ensure this function is not called concurrently. #[inline] - #[cfg(sleep_light_sleep)] + #[cfg(all(sleep_light_sleep, feature = "rt"))] pub(crate) unsafe fn update_counter(counter: u64) { unsafe { SystemTimer::set_unit_value(Unit::Unit0, counter); diff --git a/esp-hal/src/timer/mod.rs b/esp-hal/src/timer/mod.rs index b19ae633c9e..31901f25f95 100644 --- a/esp-hal/src/timer/mod.rs +++ b/esp-hal/src/timer/mod.rs @@ -82,15 +82,15 @@ pub enum Error { /// Functionality provided by any timer peripheral. pub trait Timer: crate::private::Sealed { - /// Start the timer. + /// Starts the timer. #[doc(hidden)] fn start(&self); - /// Stop the timer. + /// Stops the timer. #[doc(hidden)] fn stop(&self); - /// Reset the timer value to 0. + /// Resets the timer value to 0. #[doc(hidden)] fn reset(&self); @@ -102,29 +102,29 @@ pub trait Timer: crate::private::Sealed { #[doc(hidden)] fn now(&self) -> Instant; - /// Load a target value into the timer. + /// Loads a target value into the timer. #[doc(hidden)] fn load_value(&self, value: Duration) -> Result<(), Error>; - /// Enable auto reload of the loaded value. + /// Enables auto reload of the loaded value. #[doc(hidden)] fn enable_auto_reload(&self, auto_reload: bool); - /// Enable or disable the timer's interrupt. + /// Enables or disables the timer's interrupt. #[doc(hidden)] fn enable_interrupt(&self, state: bool); - /// Clear the timer's interrupt. + /// Clears the timer's interrupt. fn clear_interrupt(&self); - /// Has the timer triggered? + /// Returns whether the timer has triggered. fn is_interrupt_set(&self) -> bool; - /// Returns the HAL provided async interrupt handler + /// Returns the HAL provided async interrupt handler. #[doc(hidden)] fn async_interrupt_handler(&self) -> InterruptHandler; - /// Returns the interrupt source for the underlying timer + /// Returns the interrupt source for the underlying timer. fn peripheral_interrupt(&self) -> Interrupt; /// Configures the interrupt handler. @@ -142,7 +142,7 @@ pub struct OneShotTimer<'d, Dm: DriverMode> { } impl<'d> OneShotTimer<'d, Blocking> { - /// Construct a new instance of [`OneShotTimer`]. + /// Creates a new [`OneShotTimer`]. pub fn new(inner: impl Timer + Into>) -> OneShotTimer<'d, Blocking> { Self { inner: inner.into(), @@ -173,23 +173,23 @@ impl<'d> OneShotTimer<'d, Async> { } } - /// Delay for *at least* `ns` nanoseconds. + /// Delays for *at least* `ns` nanoseconds. pub async fn delay_nanos_async(&mut self, ns: u32) { self.delay_async(Duration::from_micros(ns.div_ceil(1000) as u64)) .await } - /// Delay for *at least* `ms` milliseconds. + /// Delays for *at least* `ms` milliseconds. pub async fn delay_millis_async(&mut self, ms: u32) { self.delay_async(Duration::from_millis(ms as u64)).await; } - /// Delay for *at least* `us` microseconds. + /// Delays for *at least* `us` microseconds. pub async fn delay_micros_async(&mut self, us: u32) { self.delay_async(Duration::from_micros(us as u64)).await; } - /// Wait for *at least* the time interval `timeout`. + /// Waits for *at least* the time interval `timeout`. /// /// Once the time period elapses, the underlying timer hardware does not automatically schedule /// the next timeout. The next timeout is scheduled only when `delay_async` is called again. @@ -248,17 +248,17 @@ impl OneShotTimer<'_, Dm> where Dm: DriverMode, { - /// Delay for *at least* `ms` milliseconds. + /// Delays for *at least* `ms` milliseconds. pub fn delay_millis(&mut self, ms: u32) { self.delay(Duration::from_millis(ms as u64)); } - /// Delay for *at least* `us` microseconds. + /// Delays for *at least* `us` microseconds. pub fn delay_micros(&mut self, us: u32) { self.delay(Duration::from_micros(us as u64)); } - /// Delay for *at least* `ns` nanoseconds. + /// Delays for *at least* `ns` nanoseconds. pub fn delay_nanos(&mut self, ns: u32) { self.delay(Duration::from_micros(ns.div_ceil(1000) as u64)) } @@ -274,7 +274,7 @@ where self.clear_interrupt(); } - /// Start counting until the given timeout and raise an interrupt + /// Starts counting until the given timeout and raise an interrupt. pub fn schedule(&mut self, timeout: Duration) -> Result<(), Error> { if self.inner.is_running() { self.inner.stop(); @@ -290,30 +290,30 @@ where Ok(()) } - /// Stop the timer + /// Stops the timer. pub fn stop(&mut self) { self.inner.stop(); } - /// Set the interrupt handler + /// Sets the interrupt handler. /// - /// Note that this will replace any previously set interrupt handler + /// Replaces any previously set interrupt handler. #[instability::unstable] pub fn set_interrupt_handler(&mut self, handler: InterruptHandler) { self.inner.set_interrupt_handler(handler); } - /// Listen for interrupt + /// Listens for interrupt. pub fn listen(&mut self) { self.inner.enable_interrupt(true); } - /// Unlisten for interrupt + /// Unlistens for interrupt. pub fn unlisten(&mut self) { self.inner.enable_interrupt(false); } - /// Clear the interrupt flag + /// Clears the interrupt flag. pub fn clear_interrupt(&mut self) { self.inner.clear_interrupt(); } @@ -349,7 +349,7 @@ pub struct PeriodicTimer<'d, Dm: DriverMode> { } impl<'d> PeriodicTimer<'d, Blocking> { - /// Construct a new instance of [`PeriodicTimer`]. + /// Creates a new instance of [`PeriodicTimer`]. pub fn new(inner: impl Timer + Into>) -> PeriodicTimer<'d, Blocking> { Self { inner: inner.into(), @@ -378,7 +378,7 @@ impl<'d> PeriodicTimer<'d, Async> { } } - /// Wait for *at least* the time interval loaded by [`PeriodicTimer::start`]. + /// Waits for *at least* the time interval loaded by [`PeriodicTimer::start`]. /// /// Once the time period elapses, the underlying timer hardware automatically schedules the /// next timeout. @@ -392,7 +392,7 @@ impl PeriodicTimer<'_, Dm> where Dm: DriverMode, { - /// Start a new count down. + /// Starts a new count down. pub fn start(&mut self, period: Duration) -> Result<(), Error> { if self.inner.is_running() { self.inner.stop(); @@ -425,25 +425,25 @@ where Ok(()) } - /// Set the interrupt handler + /// Sets the interrupt handler. /// - /// Note that this will replace any previously set interrupt handler + /// Replaces any previously set interrupt handler. #[instability::unstable] pub fn set_interrupt_handler(&mut self, handler: InterruptHandler) { self.inner.set_interrupt_handler(handler); } - /// Listen for interrupt + /// Listens for interrupt. pub fn listen(&mut self) { self.inner.enable_interrupt(true); } - /// Unlisten for interrupt + /// Unlistens for interrupt. pub fn unlisten(&mut self) { self.inner.enable_interrupt(false); } - /// Clear the interrupt flag + /// Clears the interrupt flag. pub fn clear_interrupt(&mut self) { self.inner.clear_interrupt(); } diff --git a/esp-hal/src/timer/systimer.rs b/esp-hal/src/timer/systimer.rs index 4f188fda91f..78e54ee5885 100644 --- a/esp-hal/src/timer/systimer.rs +++ b/esp-hal/src/timer/systimer.rs @@ -204,14 +204,14 @@ impl<'d> SystemTimer<'d> { _ => { cfg_select! { esp32s2 => crate::soc::clocks::apb_clk_frequency() as u64, - esp32h2 => (crate::soc::clocks::xtal_clk_frequency() / 2) as u64, + any(esp32h2, esp32h4) => (crate::soc::clocks::xtal_clk_frequency() / 2) as u64, _ => (crate::soc::clocks::xtal_clk_frequency() * 10 / 25) as u64, } } } } - /// Create a new instance. + /// Creates a new instance. pub fn new(_systimer: SYSTIMER<'d>) -> Self { // Don't reset Systimer as it will break `time::Instant::now`, only enable it if PeripheralClockControl::enable(PeripheralEnable::Systimer) { @@ -232,7 +232,7 @@ impl<'d> SystemTimer<'d> { } } - /// Get the current count of the given unit in the System Timer. + /// Returns the current count of the given unit in the System Timer. #[inline] pub fn unit_value(unit: Unit) -> u64 { // This should be safe to access from multiple contexts @@ -249,13 +249,13 @@ impl<'d> SystemTimer<'d> { /// /// # Safety /// - /// - Disabling a `Unit` whilst [`Alarm`]s are using it will affect the [`Alarm`]s operation. + /// - Disabling a `Unit` while [`Alarm`]s are using it will affect the [`Alarm`]s operation /// - Disabling Unit0 will affect [`Instant::now`]. pub unsafe fn configure_unit(unit: Unit, config: UnitConfig) { unit.configure(config) } - /// Set the value of the counter immediately. If the unit is at work, + /// Sets the value of the counter immediately. If the unit is at work, /// the counter will continue to count up from the new reloaded value. /// /// This can be used to load back the sleep time recorded by RTC timer @@ -263,7 +263,7 @@ impl<'d> SystemTimer<'d> { /// /// # Safety /// - /// - Modifying a unit's count whilst [`Alarm`]s are using it may cause unexpected behaviour + /// - Modifying a unit's count while [`Alarm`]s are using it may cause unexpected behavior /// - Any modification of the unit0 count will affect [`Instant::now`] pub unsafe fn set_unit_value(unit: Unit, value: u64) { unit.set_count(value) @@ -391,7 +391,7 @@ enum Comparator { Comparator2, } -/// An alarm unit +/// An alarm unit. #[derive(Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub struct Alarm<'d> { @@ -413,7 +413,7 @@ impl Alarm<'_> { /// /// # Safety /// - /// You must ensure that you're only using one instance of this type at a + /// The caller must ensure that only one instance of this type is used at a /// time. pub unsafe fn clone_unchecked(&self) -> Self { Self { @@ -425,8 +425,8 @@ impl Alarm<'_> { /// Creates a new peripheral reference with a shorter lifetime. /// - /// Use this method if you would like to keep working with the peripheral - /// after you dropped the driver that consumes this. + /// Use this method to keep working with the peripheral after dropping the + /// driver that consumes this. /// /// See [Peripheral singleton] section for more information. /// @@ -441,8 +441,8 @@ impl Alarm<'_> { self.comp as u8 } - /// Enables/disables the comparator. If enabled, this means - /// it will generate interrupt based on its configuration. + /// Enables or disables the comparator. If enabled, this means + /// it generates interrupts based on its configuration. fn set_enable(&self, enable: bool) { CONF_LOCK.lock(|| { #[cfg(not(esp32s2))] @@ -462,7 +462,7 @@ impl Alarm<'_> { .modify(|_r, w| w.work_en().bit(enable)); } - /// Returns true if the comparator has been enabled. This means + /// Returns whether the comparator has been enabled. This means /// it will generate interrupt based on its configuration. fn is_enabled(&self) -> bool { #[cfg(not(esp32s2))] @@ -489,7 +489,7 @@ impl Alarm<'_> { .modify(|_, w| w.timer_unit_sel().bit(matches!(unit, Unit::Unit1))); } - /// Set the mode of the comparator to be either target or periodic. + /// Sets the mode of the comparator to be either target or periodic. fn set_mode(&self, mode: ComparatorMode) { let is_period_mode = match mode { ComparatorMode::Period => true, @@ -500,7 +500,7 @@ impl Alarm<'_> { .modify(|_, w| w.period_mode().bit(is_period_mode)); } - /// Get the current mode of the comparator, which is either target or + /// Returns the current mode of the comparator, which is either target or /// periodic. fn mode(&self) -> ComparatorMode { if SYSTIMER::regs() @@ -515,7 +515,7 @@ impl Alarm<'_> { } } - /// Set how often the comparator should generate an interrupt when in + /// Sets how often the comparator should generate an interrupt when in /// periodic mode. fn set_period(&self, value: u32) { let systimer = SYSTIMER::regs(); @@ -528,7 +528,7 @@ impl Alarm<'_> { } } - /// Set when the comparator should generate an interrupt in target mode. + /// Sets when the comparator should generate an interrupt in target mode. fn set_target(&self, value: u64) { let systimer = SYSTIMER::regs(); let target = systimer.trgt(self.channel() as usize); @@ -543,7 +543,7 @@ impl Alarm<'_> { } } - /// Set the interrupt handler for this comparator. + /// Sets the interrupt handler for this comparator. fn set_interrupt_handler(&self, handler: InterruptHandler) { let interrupt = match self.channel() { 0 => Interrupt::SYSTIMER_TARGET0, @@ -845,13 +845,13 @@ pub mod etm { use super::*; - /// An ETM controlled SYSTIMER event + /// An ETM controlled SYSTIMER event. pub struct Event { id: u8, } impl Event { - /// Creates an ETM event from the given [Alarm] + /// Creates an ETM event from the given [Alarm]. pub fn new(alarm: &Alarm<'_>) -> Self { Self { id: 50 + alarm.channel(), diff --git a/esp-hal/src/timer/timg.rs b/esp-hal/src/timer/timg.rs index c4e2d87eb2a..4e471e971ac 100644 --- a/esp-hal/src/timer/timg.rs +++ b/esp-hal/src/timer/timg.rs @@ -184,7 +184,7 @@ impl<'d, T> TimerGroup<'d, T> where T: TimerGroupInstance + 'd, { - /// Construct a new instance of [`TimerGroup`] in blocking mode + /// Creates a new instance of [`TimerGroup`] in blocking mode. pub fn new(_timer_group: T) -> Self { // TODO: use PeripheralGuard if PeripheralClockControl::enable(T::peripheral()) { @@ -332,7 +332,7 @@ impl Timer<'_> { /// /// # Safety /// - /// You must ensure that you're only using one instance of this type at a + /// The caller must ensure that only one instance of this type is used at a /// time. pub unsafe fn clone_unchecked(&self) -> Self { Self { @@ -345,8 +345,8 @@ impl Timer<'_> { /// Creates a new peripheral reference with a shorter lifetime. /// - /// Use this method if you would like to keep working with the peripheral - /// after you dropped the driver that consumes this. + /// Use this method to keep working with the peripheral after dropping the + /// driver that consumes this. /// /// See [Peripheral singleton] section for more information. /// @@ -557,11 +557,11 @@ fn timeout_to_ticks(timeout: Duration, clock: Rate, divider: u32) -> Option pub enum MwdtStageAction { /// No effect on the system. Off = 0, - /// Trigger an interrupt. + /// Triggers an interrupt. Interrupt = 1, - /// Reset the CPU core. + /// Resets the CPU core. ResetCpu = 2, - /// Reset the main system, power management unit and RTC peripherals. + /// Resets the main system, power management unit and RTC peripherals. ResetSystem = 3, } @@ -591,7 +591,7 @@ impl Wdt where TG: TimerGroupInstance, { - /// Construct a new instance of [`Wdt`] + /// Creates a new instance of [`Wdt`]. pub fn new() -> Self { let mut this = Self { phantom: PhantomData, @@ -607,14 +607,14 @@ where this } - /// Enable the watchdog timer instance + /// Enables the watchdog timer instance. pub fn enable(&mut self) { // SAFETY: The `TG` instance being modified is owned by `self`, which is behind // a mutable reference. unsafe { self.set_wdt_enabled(true) }; } - /// Disable the watchdog timer instance + /// Disables the watchdog timer instance. pub fn disable(&mut self) { // SAFETY: The `TG` instance being modified is owned by `self`, which is behind // a mutable reference. @@ -651,13 +651,13 @@ where w.wdt_stg2().bits(MwdtStageAction::Off as u8); w.wdt_stg3().bits(MwdtStageAction::Off as u8) }); - - #[cfg(any(esp32c2, esp32c3, esp32c6))] - reg_block - .wdtconfig0() - .modify(|_, w| w.wdt_conf_update_en().set_bit()); } + #[cfg(timergroup_wdt_has_conf_update)] + reg_block + .wdtconfig0() + .modify(|_, w| w.wdt_conf_update_en().set_bit()); + #[cfg(soc_has_clock_node_timg_wdt_clock)] if !enabled { clocks::ClockTree::with(|clocks| TG::clock_instance().release_wdt_clock(clocks)); @@ -666,7 +666,7 @@ where self.set_write_protection(true); } - /// Feed the watchdog timer + /// Feeds the watchdog timer. pub fn feed(&mut self) { let reg_block = unsafe { &*TG::register_block() }; @@ -687,7 +687,7 @@ where .write(|w| unsafe { w.wdt_wkey().bits(wkey) }); } - /// Set the timeout, in microseconds, of the watchdog timer + /// Sets the timeout, in microseconds, of the watchdog timer. pub fn set_timeout(&mut self, stage: MwdtStage, timeout: Duration) { cfg_select! { soc_has_clock_node_timg_wdt_clock => { @@ -731,7 +731,7 @@ where config_register.write(|w| unsafe { w.hold().bits(timeout) }); - #[cfg(any(esp32c2, esp32c3, esp32c6))] + #[cfg(timergroup_wdt_has_conf_update)] reg_block .wdtconfig0() .modify(|_, w| w.wdt_conf_update_en().set_bit()); @@ -739,10 +739,10 @@ where self.set_write_protection(true); } - /// Set the stage action of the MWDT for a specific stage. + /// Sets the stage action of the MWDT for a specific stage. /// - /// This function modifies MWDT behavior only if a custom bootloader with - /// the following modifications is used: + /// Modifies MWDT behavior only if a custom bootloader with the following modifications is + /// used: /// - `ESP_TASK_WDT_EN` parameter **disabled** /// - `ESP_INT_WDT` parameter **disabled** pub fn set_stage_action(&mut self, stage: MwdtStage, action: MwdtStageAction) { @@ -759,6 +759,11 @@ where } }); + #[cfg(timergroup_wdt_has_conf_update)] + reg_block + .wdtconfig0() + .modify(|_, w| w.wdt_conf_update_en().set_bit()); + self.set_write_protection(true); } } diff --git a/esp-hal/src/touch.rs b/esp-hal/src/touch.rs index 2a0a5c49d51..fea319e97d8 100644 --- a/esp-hal/src/touch.rs +++ b/esp-hal/src/touch.rs @@ -83,7 +83,7 @@ pub struct TouchConfig { pub sleep_cycles: Option, } -/// This struct marks a successfully initialized touch peripheral +/// Marks a successfully initialized touch peripheral. pub struct Touch<'d, Tm: TouchMode, Dm: DriverMode> { _inner: TOUCH<'d>, _touch_mode: PhantomData, @@ -183,7 +183,7 @@ impl<'d> Touch<'d, OneShot, Blocking> { /// Initializes the touch peripheral and returns this marker struct. /// Optionally accepts configuration options. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -240,7 +240,7 @@ impl<'d> Touch<'d, Continuous, Blocking> { /// Initializes the touch peripheral in continuous mode and returns this /// marker struct. Optionally accepts configuration options. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -267,11 +267,9 @@ impl<'d> Touch<'d, Continuous, Async> { /// Initializes the touch peripheral in continuous async mode and returns /// this marker struct. /// - /// ## Warning: - /// - /// This uses [`RTC_CORE`](crate::peripherals::Interrupt::RTC_CORE) - /// interrupts under the hood. So the whole async part breaks if you install - /// an interrupt handler with [`Rtc::set_interrupt_handler()`][1]. + /// This uses [`RTC_CORE`](crate::peripherals::Interrupt::RTC_CORE) interrupts under the hood. + /// The async API stops working if an interrupt handler is installed with + /// [`Rtc::set_interrupt_handler()`][1] /// /// [1]: ../rtc_cntl/struct.Rtc.html#method.set_interrupt_handler /// @@ -280,7 +278,7 @@ impl<'d> Touch<'d, Continuous, Async> { /// - `rtc`: The RTC peripheral is needed to configure the required interrupts. /// - `config`: Optional configuration options. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -314,8 +312,9 @@ pub struct TouchPad { _mode: PhantomData, } impl TouchPad { - /// (Re-)Start a touch measurement on the pin. You can get the result by - /// calling [`read`](Self::read) once it is finished. + /// Starts a touch measurement on the pin. + /// + /// Call [`read`](Self::read) once the measurement is finished to get the result. pub fn start_measurement(&mut self) { crate::peripherals::RTC_IO::regs() .touch_pad2() @@ -344,7 +343,7 @@ impl TouchPad { } } impl TouchPad { - /// Construct a new instance of [`TouchPad`]. + /// Creates a new instance of [`TouchPad`]. /// /// ## Parameters: /// - `pin`: The pin that gets configured as touch pad @@ -360,14 +359,14 @@ impl TouchPad { } } - /// Read the current touch pad capacitance counter. + /// Reads the current touch pad capacitance counter. /// /// Usually a lower value means higher capacitance, thus indicating touch /// event. /// - /// Returns `None` if the value is not yet ready. (Note: Measurement must be + /// Returns `None` if the value is not yet ready. Measurement must be /// started manually with [`start_measurement`](Self::start_measurement) if - /// the touch peripheral is in [`OneShot`] mode). + /// the touch peripheral is in [`OneShot`] mode. pub fn try_read(&mut self) -> Option { if unsafe { &*crate::peripherals::SENS::ptr() } .sar_touch_ctrl2() @@ -387,13 +386,10 @@ impl TouchPad { /// Usually a lower value means higher capacitance, thus indicating touch /// event. /// - /// ## Note for [`OneShot`] mode: - /// - /// This function might block forever, if + /// In [`OneShot`] mode, may block indefinitely if /// [`start_measurement`](Self::start_measurement) was not called before. As - /// measurements are not cleared, the touch values might also be - /// outdated, if it has been some time since the last call to that - /// function. + /// measurements are not cleared, the touch values might also be outdated if + /// it has been some time since the last call to that function. pub fn read(&mut self) -> u16 { while unsafe { &*crate::peripherals::SENS::ptr() } .sar_touch_ctrl2() @@ -415,14 +411,12 @@ impl TouchPad { /// ## Parameters: /// - `threshold`: The threshold above/below which the pin is considered touched. Above/below /// depends on the configuration of `touch` in [`new`](Self::new) (defaults to below). - /// - /// ## Example pub fn listen(&mut self, threshold: u16) { self.pin.set_threshold(threshold, Internal); listen(self.pin.touch_nr(Internal)) } - /// Unlisten for the touch pad's interrupt. + /// Unlistens for the touch pad's interrupt. /// /// If no other touch pad interrupts are active, the touch interrupt is /// disabled completely. @@ -432,17 +426,15 @@ impl TouchPad { /// Clears a pending touch interrupt. /// - /// ## Note on interrupt clearing behaviour: - /// /// There is only a single interrupt for the touch pad. /// [`is_interrupt_set`](Self::is_interrupt_set) can be used to check - /// which pins are touchted. However, this function clears the interrupt + /// which pins are touched. However, this function clears the interrupt /// status for all pins. So only call it when all pins are handled. pub fn clear_interrupt(&mut self) { internal_clear_interrupt() } - /// Checks if the pad is touched, based on the configured threshold value. + /// Returns whether the pad is touched, based on the configured threshold value. pub fn is_interrupt_set(&mut self) -> bool { internal_is_interrupt_set(self.pin.touch_nr(Internal)) } @@ -569,7 +561,7 @@ mod asynch { } impl TouchPad { - /// Wait for the pad to be touched. + /// Waits for the pad to be touched. pub async fn wait_for_touch(&mut self, threshold: u16) { self.pin.set_threshold(threshold, Internal); let touch_nr = self.pin.touch_nr(Internal); diff --git a/esp-hal/src/trace.rs b/esp-hal/src/trace.rs index 811f3dcb4f1..ebf6ac9c391 100644 --- a/esp-hal/src/trace.rs +++ b/esp-hal/src/trace.rs @@ -46,7 +46,7 @@ pub enum Error { /// Returned by [Trace::stop_trace] #[derive(Debug, Clone, Copy)] pub struct TraceResult { - /// Start index of the valid data + /// Starts index of the valid data. pub valid_start_index: usize, /// Length of the valid data pub valid_length: usize, @@ -60,7 +60,7 @@ pub struct Trace<'d> { } impl<'d> Trace<'d> { - /// Construct a new instance + /// Creates a new instance. pub fn new(peripheral: TRACE0<'d>) -> Self { let guard = PeripheralGuard::new(peripheral.peripheral()); @@ -71,7 +71,7 @@ impl<'d> Trace<'d> { } } - /// Start tracing, writing data into the `buffer` + /// Starts tracing, writing data into the `buffer`. pub fn start_trace(&mut self, buffer: &'d mut [u8]) { let reg_block = self.peripheral.register_block(); @@ -107,9 +107,9 @@ impl<'d> Trace<'d> { reg_block.trigger().write(|w| w.on().set_bit()); } - /// Stop tracing + /// Stops tracing. /// - /// Be aware that valid data might not start at index 0 and you need to + /// Be aware that valid data might not start at index 0 and the reader must /// account for wrapping when reading the data. pub fn stop_trace(&mut self) -> Result { let reg_block = self.peripheral.register_block(); @@ -199,7 +199,7 @@ impl<'d> Trace<'d> { /// Trace peripheral instance #[doc(hidden)] pub trait Instance: crate::private::Sealed { - /// Get a reference to the peripheral's underlying register block + /// Returns a reference to the peripheral's underlying register block. fn register_block(&self) -> &RegisterBlock; /// Peripheral diff --git a/esp-hal/src/tsens.rs b/esp-hal/src/tsens.rs index 0a2eefe681f..62d3bf34654 100644 --- a/esp-hal/src/tsens.rs +++ b/esp-hal/src/tsens.rs @@ -29,10 +29,10 @@ //! //! let temperature_sensor = TemperatureSensor::new(peripherals.TSENS, Config::default())?; //! let delay = Delay::new(); -//! delay.delay_micros(200); +//! delay.delay_micros(300); //! loop { //! let temp = temperature_sensor.get_temperature(); -//! println!("Temperature: {:.2}°C", temp.to_celcius()); +//! println!("Temperature: {:.2}°C", temp.to_celsius()); //! delay.delay_millis(1_000); //! } //! # } @@ -43,71 +43,62 @@ //! - Temperature calibration range is not supported //! - Interrupts are not supported +mod clocks; + +/// Clock source for the temperature sensor. +pub use crate::soc::clocks::TsensSclkConfig as ClockSource; use crate::{ + clock::ll::{ClockTree, TsensInstance}, peripherals::{APB_SARADC, TSENS}, system::GenericPeripheralGuard, }; -/// Clock source for the temperature sensor -#[derive(Debug, Clone, Default, PartialEq, Eq, Copy, Hash)] -#[cfg_attr(feature = "defmt", derive(defmt::Format))] -#[non_exhaustive] -pub enum ClockSource { - /// Use RC_FAST clock source - RcFast, - /// Use XTAL clock source - #[default] - Xtal, -} - /// Temperature sensor configuration #[derive(Debug, Clone, Default, PartialEq, Eq, Copy, Hash, procmacros::BuilderLite)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[non_exhaustive] pub struct Config { - /// Clock source for the temperature sensor + /// Clock source for the temperature sensor. clock_source: ClockSource, } -/// Temperature sensor configuration error +/// Temperature sensor configuration error. #[derive(Debug, Clone, PartialEq, Eq, Copy, Hash)] #[non_exhaustive] pub enum ConfigError {} -/// Temperature value -/// This struct stores the raw ADC value, and can be used to calculate the -/// temperature in Celsius using the formula: -/// `(raw_value * 0.4386) - (offset * 27.88) - 20.52` +/// Stores the raw ADC value and can be used to calculate the temperature in Celsius using the +/// formula: `(raw_value * 0.4386) - (offset * 27.88) - 20.52`. #[derive(Debug)] pub struct Temperature { - /// Raw ADC value + /// Raw ADC value. pub raw_value: u8, - /// Offset value - depends on the temperature range configured + /// Offset value - depends on the temperature range configured. pub offset: i8, } impl Temperature { - /// Create a new temperature value + /// Creates a new temperature value. #[inline] pub fn new(raw_value: u8, offset: i8) -> Self { Self { raw_value, offset } } - /// Get the temperature in Celsius + /// Returns the temperature in Celsius. #[inline] pub fn to_celsius(&self) -> f32 { (self.raw_value as f32) * 0.4386 - (self.offset as f32) * 27.88 - 20.52 } - /// Get the temperature in Fahrenheit + /// Returns the temperature in Fahrenheit. #[inline] pub fn to_fahrenheit(&self) -> f32 { let celsius = self.to_celsius(); (celsius * 1.8) + 32.0 } - /// Get the temperature in Kelvin + /// Returns the temperature in Kelvin. #[inline] pub fn to_kelvin(&self) -> f32 { let celsius = self.to_celsius(); @@ -119,31 +110,35 @@ impl Temperature { #[derive(Debug)] pub struct TemperatureSensor<'d> { _peripheral: TSENS<'d>, + _clock_guard: TsensClockGuard, _tsens_guard: GenericPeripheralGuard<{ crate::system::Peripheral::Tsens as u8 }>, _abp_saradc_guard: GenericPeripheralGuard<{ crate::system::Peripheral::ApbSarAdc as u8 }>, } impl<'d> TemperatureSensor<'d> { - /// Create a new temperature sensor instance with configuration - /// The sensor will be automatically powered up + /// Creates a new temperature sensor instance with the given configuration. + /// + /// The sensor is automatically powered up. pub fn new(peripheral: TSENS<'d>, config: Config) -> Result { // NOTE: We need enable ApbSarAdc before enabling Tsens let apb_saradc_guard = GenericPeripheralGuard::new(); let tsens_guard = GenericPeripheralGuard::new(); - let mut tsens = Self { + let tsens = Self { _peripheral: peripheral, + _clock_guard: TsensClockGuard::new(config.clock_source), _tsens_guard: tsens_guard, _abp_saradc_guard: apb_saradc_guard, }; - tsens.apply_config(&config)?; tsens.power_up(); + // https://github.com/espressif/esp-idf/blob/ab95e70748f2eddac6f87217b0cf62533684a6ba/components/esp_hal_ana_conv/esp32c6/temperature_sensor_periph.c#L9-L16 + crate::soc::regi2c::I2C_SARADC_TSENS_DAC.write_field(7); // 20 °C to 100 °C, offset -1. Ok(tsens) } - /// Power up the temperature sensor + /// Powers up the temperature sensor. pub fn power_up(&self) { debug!("Power up"); APB_SARADC::regs() @@ -151,25 +146,23 @@ impl<'d> TemperatureSensor<'d> { .modify(|_, w| w.pu().set_bit()); } - /// Power down the temperature sensor - useful if you want to save power + /// Powers down the temperature sensor to save power. pub fn power_down(&self) { APB_SARADC::regs() .tsens_ctrl() .modify(|_, w| w.pu().clear_bit()); } - /// Change the temperature sensor configuration + /// Changes the temperature sensor configuration. pub fn apply_config(&mut self, config: &Config) -> Result<(), ConfigError> { - // Set clock source - APB_SARADC::regs().tsens_ctrl2().write(|w| { - w.clk_sel() - .bit(matches!(config.clock_source, ClockSource::Xtal)) + ClockTree::with(|clocks| { + TsensInstance::Tsens.configure_sclk(clocks, config.clock_source); }); Ok(()) } - /// Get the raw temperature value + /// Returns the raw temperature value. #[inline] pub fn get_temperature(&self) -> Temperature { let raw_value = APB_SARADC::regs().tsens_ctrl().read().out().bits(); @@ -180,3 +173,28 @@ impl<'d> TemperatureSensor<'d> { Temperature::new(raw_value, offset) } } + +impl Drop for TemperatureSensor<'_> { + fn drop(&mut self) { + self.power_down(); + } +} + +#[derive(Debug)] +struct TsensClockGuard; + +impl TsensClockGuard { + fn new(source: ClockSource) -> Self { + ClockTree::with(|clocks| { + TsensInstance::Tsens.configure_sclk(clocks, source); + TsensInstance::Tsens.request_sclk(clocks); + }); + Self + } +} + +impl Drop for TsensClockGuard { + fn drop(&mut self) { + ClockTree::with(|clocks| TsensInstance::Tsens.release_sclk(clocks)); + } +} diff --git a/esp-hal/src/tsens/clocks.rs b/esp-hal/src/tsens/clocks.rs new file mode 100644 index 00000000000..3ef317088e4 --- /dev/null +++ b/esp-hal/src/tsens/clocks.rs @@ -0,0 +1,29 @@ +use crate::clock::ll::{ClockTree, TsensInstance, TsensSclkConfig}; + +impl TsensInstance { + pub(crate) fn enable_sclk_impl(self, _clocks: &mut ClockTree, _en: bool) { + // The TSENS peripheral guard manages the clock gate. + } + + pub(crate) fn configure_sclk_impl( + self, + _clocks: &mut ClockTree, + _old_config: Option, + new_config: TsensSclkConfig, + ) { + let xtal = matches!(new_config, TsensSclkConfig::Xtal); + cfg_select! { + esp32c3 => { + crate::peripherals::APB_SARADC::regs() + .tsens_ctrl2() + .modify(|_, w| w.clk_sel().bit(xtal)); + } + esp32c6 => { + // https://github.com/espressif/esp-idf/blob/ab95e70748f2eddac6f87217b0cf62533684a6ba/components/esp_hal_ana_conv/esp32c6/include/hal/temperature_sensor_ll.h#L99-L114 + crate::peripherals::PCR::regs() + .tsens_clk_conf() + .modify(|_, w| w.tsens_clk_sel().bit(xtal)); + } + } + } +} diff --git a/esp-hal/src/twai/filter.rs b/esp-hal/src/twai/filter.rs index 1539d982fdd..40edaab0f4e 100644 --- a/esp-hal/src/twai/filter.rs +++ b/esp-hal/src/twai/filter.rs @@ -46,7 +46,7 @@ pub trait Filter { Self::FILTER_TYPE } - /// Get the register level representation of the filter. + /// Returns the register level representation of the filter. fn to_registers(&self) -> [u8; 8]; } @@ -103,7 +103,7 @@ pub struct SingleStandardFilter { impl SingleStandardFilter { #[procmacros::doc_replace] - /// Create a new filter that matches against a single 11-bit standard id. + /// Creates a new filter that matches against a single 11-bit standard id. /// The filter can match against the packet's id, RTR bit, and first two /// bytes of the payload. /// @@ -179,7 +179,6 @@ impl SingleStandardFilter { /// false, /// true, /// [0x00, 0x00], - /// [0x00, 0x00], /// ); /// ``` pub fn new_from_code_mask( @@ -230,7 +229,7 @@ pub struct SingleExtendedFilter { } impl SingleExtendedFilter { - /// Create a filter that matches against a single 29-bit extended id. + /// Creates a new filter that matches against a single 29-bit extended id. /// /// The filter can match against the packet's id and the RTR bit. /// @@ -318,7 +317,7 @@ pub struct DualStandardFilter { } impl DualStandardFilter { - /// Create a filter that matches against two standard 11-bit standard IDs. + /// Creates a new filter that matches against two standard 11-bit standard IDs. /// /// The first filter part can match a packet's id, RTR bit, and the first /// byte of the payload. The second filter part can match a packet's id @@ -467,7 +466,7 @@ pub struct DualExtendedFilter { } impl DualExtendedFilter { - /// Create a filter that matches the first 16 bits of two 29-bit extended + /// Creates a new filter that matches the first 16 bits of two 29-bit extended /// IDs. /// /// # Examples @@ -511,7 +510,7 @@ impl DualExtendedFilter { raw: code_mask_to_register_array(acceptance_code, acceptance_mask), } } - /// Create a new filter matching the first 16 bits of two 29-bit IDs. + /// Creates a new filter matching the first 16 bits of two 29-bit IDs. /// /// The masks indicate which bits of the code the filter should match /// against. Set bits in the mask indicate that the corresponding bit in diff --git a/esp-hal/src/twai/mod.rs b/esp-hal/src/twai/mod.rs index e875cc5763b..724d1178125 100644 --- a/esp-hal/src/twai/mod.rs +++ b/esp-hal/src/twai/mod.rs @@ -235,12 +235,12 @@ impl embedded_can::Error for ErrorKind { #[derive(Debug, Copy, Clone, Eq, PartialEq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum TwaiMode { - /// Normal operating mode + /// Normal operating mode. Normal, /// Self-test mode (no acknowledgement required for a successful message - /// transmission) + /// transmission). SelfTest, - /// Listen only operating mode + /// Listens only operating mode. ListenOnly, } @@ -258,7 +258,7 @@ impl StandardId { /// Tries to create a `StandardId` from a raw 16-bit integer. /// - /// This will return `None` if `raw` is out of range of an 11-bit integer + /// Returns `None` if `raw` is out of range of an 11-bit integer. /// (`> 0x7FF`). #[inline] pub fn new(raw: u16) -> Option { @@ -314,7 +314,7 @@ impl ExtendedId { /// Tries to create a `ExtendedId` from a raw 32-bit integer. /// - /// This will return `None` if `raw` is out of range of an 29-bit integer + /// Returns `None` if `raw` is out of range of an 29-bit integer. /// (`> 0x1FFF_FFFF`). #[inline] pub fn new(raw: u32) -> Option { @@ -459,7 +459,7 @@ impl EspTwaiFrame { /// Frame Format (FF): specifies whether content is Extended Frame Format (EFF) or Standard /// Frame Format (SFF). /// - /// This method is private: interested clients should deduce the frame format from + /// Private: interested clients should deduce the frame format from /// [`Self::id()`]. #[inline(always)] fn is_extended_format(&self) -> bool { @@ -469,7 +469,7 @@ impl EspTwaiFrame { /// Remote Transmission Request (RTR): specifies whether content is a data frame or a remote /// request frame (on-demand polling). /// - /// Note: Remote request frames do not have a data payload, no matter their DLC. + /// Remote request frames do not have a data payload, no matter their DLC. pub fn is_remote_request(&self) -> bool { self.info() & (0b1 << 6) != 0 } @@ -483,7 +483,7 @@ impl EspTwaiFrame { /// Data Length Code (DLC): specifies the number of data bytes for a data frame, or the number /// of data bytes requested by a remote frame. /// - /// Note: although no frame can have a payload longer than 8, the DLC can be greater than 8 in + /// Although no frame can have a payload longer than 8, the DLC can be greater than 8 in /// rare cases (payload length then is still 8). pub fn data_length_code(&self) -> usize { (self.info() & 0b1111) as usize @@ -559,7 +559,7 @@ impl EspTwaiFrame { &self.bytes[0..len] } - /// Make a new [`EspTwaiFrame`] from TWAI_DATA_x_REG registers. + /// Creates a new [`EspTwaiFrame`] from TWAI_DATA_x_REG registers. pub(super) fn new_from_registers(register_block: &RegisterBlock) -> Self { let mut bytes: [u8; 13] = [0; 13]; // SAFETY: Safe because it is a constant-size, read-only access to the 13 data registers @@ -569,7 +569,7 @@ impl EspTwaiFrame { Self { bytes } } - /// Make a new [`EspTwaiFrame`] from parameters. + /// Creates a new [`EspTwaiFrame`] from parameters. fn new_from_parameters( id: impl Into, remote_request: bool, @@ -625,18 +625,18 @@ impl EspTwaiFrame { Ok(Self { bytes }) } - /// Create a new `EspTwaiFrame` with the specified ID and data payload. + /// Creates a new `EspTwaiFrame` with the specified ID and data payload. pub fn new(id: impl Into, data: &[u8]) -> Option { Self::new_from_parameters(id.into(), false, false, data.len(), data).ok() } - /// Create a new `EspTwaiFrame` for a transmission request with the + /// Creates a new `EspTwaiFrame` for a transmission request with the /// specified ID and data length (DLC). pub fn new_remote(id: impl Into, dlc: usize) -> Option { Self::new_from_parameters(id.into(), true, false, dlc, &[]).ok() } - /// Create a new `EspTwaiFrame` ready for self-reception with the specified + /// Creates a new `EspTwaiFrame` ready for self-reception with the specified /// ID and data payload. pub fn new_self_reception(id: impl Into, data: &[u8]) -> Option { Self::new_from_parameters(id.into(), false, true, data.len(), data).ok() @@ -706,7 +706,7 @@ pub struct TimingConfig { /// A selection of pre-determined baudrates for the TWAI driver. /// Currently these timings are sourced from the ESP IDF C driver which assumes -/// an APB clock of 80MHz. +/// an APB clock of 80 MHz. #[derive(Debug, Copy, Clone, Eq, PartialEq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum BaudRate { @@ -718,15 +718,14 @@ pub enum BaudRate { B500K, /// A baud rate of 1 Mbps. B1000K, - /// A custom baud rate defined by the user. + /// A custom baud rate. /// - /// This variant allows users to specify their own timing configuration - /// using a `TimingConfig` struct. + /// Specifies a custom timing configuration using a `TimingConfig` struct. Custom(TimingConfig), } impl BaudRate { - /// Convert the BaudRate into the timings that the peripheral needs. + /// Converts the BaudRate into the timings that the peripheral needs. // See: https://github.com/espressif/esp-idf/tree/ab4200e/components/esp_hal_twai/include/hal/twai_types.h const fn timing(self) -> TimingConfig { #[cfg(not(esp32h2))] @@ -909,10 +908,13 @@ where crate::interrupt::bind_handler(self.twai.interrupt(), handler); } - /// Set the bitrate of the bus. + /// Sets the bitrate of the bus. Also usable on the configuration + /// [`Twai::stop`] returns, to change the bitrate of a driver that has + /// been running. /// - /// Note: The timings currently assume a APB_CLK of 80MHz. - fn set_baud_rate(&mut self, baud_rate: BaudRate) { + /// The timings currently assume an APB_CLK of 80 MHz. + #[instability::unstable] + pub fn set_baud_rate(&mut self, baud_rate: BaudRate) { // TWAI is clocked from the APB_CLK according to Table 6-4 [ESP32C3 Reference Manual](https://www.espressif.com/sites/default/files/documentation/esp32-c3_technical_reference_manual_en.pdf) // Included timings are all for 80MHz so assert that we are running at 80MHz. #[cfg(not(any(esp32h2, esp32c6)))] @@ -970,15 +972,15 @@ where .modify(|_, w| w.clock_off().set_bit()); } - /// Set up the acceptance filter on the device. + /// Sets up the acceptance filter on the device. /// - /// NOTE: On a bus with mixed 11-bit and 29-bit packet id's, you may - /// experience an 11-bit filter match against a 29-bit frame and vice - /// versa. Your application should check the id again once a frame has - /// been received to make sure it is the expected value. + /// NOTE: On a bus with mixed 11-bit and 29-bit packet id's, an 11-bit filter + /// match against a 29-bit frame and vice versa may occur. Applications should + /// verify the id again once a frame has been received to make sure it is the + /// expected value. /// - /// You may use a `const {}` block to ensure that the filter is parsed - /// during program compilation. + /// A `const {}` block can ensure that the filter is parsed during program + /// compilation. /// /// The filter is not applied to the peripheral until [`Self::start`] is /// called. @@ -1006,7 +1008,7 @@ where } } - /// Set the error warning threshold. + /// Sets the error warning threshold. /// /// In the case when any of an error counter value exceeds the threshold, or /// all the error counter values are below the threshold, an error @@ -1018,7 +1020,14 @@ where .write(|w| unsafe { w.err_warning_limit().bits(limit) }); } - /// Set the operating mode based on provided option + /// Sets the operating mode the driver starts in ([`Self::start`]). Also + /// usable on the configuration [`Twai::stop`] returns. + #[instability::unstable] + pub fn set_operating_mode(&mut self, mode: TwaiMode) { + self.mode = mode; + } + + /// Sets the operating mode based on provided option. fn set_mode(&self, mode: TwaiMode) { self.regs().mode().modify(|_, w| { // self-test mode turns off acknowledgement requirement @@ -1027,7 +1036,7 @@ where }); } - /// Put the peripheral into Operation Mode, allowing the transmission and + /// Puts the peripheral into Operation Mode, allowing the transmission and /// reception of packets using the new object. pub fn start(self) -> Twai<'d, Dm> { self.apply_filter(); @@ -1056,6 +1065,8 @@ where // Clear any interrupts by reading the status register let _ = self.regs().int_raw().read(); + self.twai.async_state().counts.reset(); + // Put the peripheral into operation mode by clearing the reset mode bit. self.regs().mode().modify(|_, w| w.reset_mode().clear_bit()); @@ -1077,9 +1088,9 @@ where } impl<'d> TwaiConfiguration<'d, Blocking> { - /// Create a new instance of [TwaiConfiguration] + /// Creates a new instance of [TwaiConfiguration]. /// - /// You will need to use a transceiver to connect to the TWAI bus + /// A transceiver is required to connect to the TWAI bus. pub fn new( peripheral: impl Instance + 'd, rx_pin: impl PeripheralInput<'d>, @@ -1090,11 +1101,11 @@ impl<'d> TwaiConfiguration<'d, Blocking> { Self::new_internal(peripheral.degrade(), rx_pin, tx_pin, baud_rate, false, mode) } - /// Create a new instance of [TwaiConfiguration] meant to connect two ESP32s - /// directly + /// Creates a new instance of [`TwaiConfiguration`] meant to connect two ESP32s + /// directly. /// - /// You don't need a transceiver by following the description in the - /// `twai.rs` example + /// A transceiver is not required when following the description in the + /// `twai.rs` example. pub fn new_no_transceiver( peripheral: impl Instance + 'd, rx_pin: impl PeripheralInput<'d>, @@ -1105,7 +1116,7 @@ impl<'d> TwaiConfiguration<'d, Blocking> { Self::new_internal(peripheral.degrade(), rx_pin, tx_pin, baud_rate, true, mode) } - /// Convert the configuration into an async configuration. + /// Converts the configuration into an async configuration. pub fn into_async(mut self) -> TwaiConfiguration<'d, Async> { self.set_interrupt_handler(self.twai.async_handler()); TwaiConfiguration { @@ -1119,8 +1130,7 @@ impl<'d> TwaiConfiguration<'d, Blocking> { /// Registers an interrupt handler for the TWAI peripheral. /// - /// Note that this will replace any previously registered interrupt - /// handlers. + /// Replaces any previously registered interrupt handlers. #[instability::unstable] pub fn set_interrupt_handler(&mut self, handler: crate::interrupt::InterruptHandler) { self.internal_set_interrupt_handler(handler); @@ -1128,7 +1138,7 @@ impl<'d> TwaiConfiguration<'d, Blocking> { } impl<'d> TwaiConfiguration<'d, Async> { - /// Convert the configuration into a blocking configuration. + /// Converts the configuration into a blocking configuration. pub fn into_blocking(self) -> TwaiConfiguration<'d, Blocking> { use crate::{interrupt, system::Cpu}; @@ -1185,7 +1195,7 @@ where } } - /// Stop the peripheral, putting it into reset mode and enabling + /// Stops the peripheral, putting it into reset mode and enabling /// reconfiguration. pub fn stop(self) -> TwaiConfiguration<'d, Dm> { // Put the peripheral into reset/configuration mode by setting the reset mode @@ -1214,7 +1224,14 @@ where self.regs().tx_err_cnt().read().tx_err_cnt().bits() } - /// Check if the controller is in a bus off state. + /// What the controller has reported since the driver was started (see + /// [`ErrorCounts`]) + #[instability::unstable] + pub fn error_counts(&self) -> ErrorCounts { + self.twai.async_state().counts.snapshot() + } + + /// Returns whether the controller is in a bus off state. pub fn is_bus_off(&self) -> bool { self.regs().status().read().bus_off_st().bit_is_set() } @@ -1237,11 +1254,11 @@ where } } - /// Get the number of messages that the peripheral has available in the + /// Returns the number of messages that the peripheral has available in the /// receive FIFO. /// - /// Note that this may not be the number of valid messages in the receive - /// FIFO due to fifo overflow/overrun. + /// May not be the number of valid messages in the receive FIFO due to fifo + /// overflow or overrun. pub fn num_available_messages(&self) -> u8 { self.regs() .rx_message_cnt() @@ -1250,7 +1267,7 @@ where .bits() } - /// Clear the receive FIFO, discarding any valid, partial, or invalid + /// Clears the receive FIFO, discarding any valid, partial, or invalid /// packets. /// /// This is typically used to clear an overrun receive FIFO. @@ -1273,6 +1290,14 @@ where self.rx.receive() } + /// Borrows the receiving and transmitting halves. Unlike [`Self::split`] + /// the driver stays whole, so it can still be stopped and reconfigured + /// ([`Self::stop`]) once they are no longer in use. + #[instability::unstable] + pub fn split_mut(&mut self) -> (&mut TwaiRx<'d, Dm>, &mut TwaiTx<'d, Dm>) { + (&mut self.rx, &mut self.tx) + } + /// Consumes this `Twai` instance and splits it into transmitting and /// receiving halves. pub fn split(self) -> (TwaiRx<'d, Dm>, TwaiTx<'d, Dm>) { @@ -1295,12 +1320,12 @@ where self.twai.register_block() } - /// Transmit a frame. + /// Transmits a frame. /// - /// Because of how the TWAI registers are set up, we have to do some - /// assembly of bytes. Note that these registers serve a filter - /// configuration role when the device is in configuration mode so - /// patching the svd files to improve this may be non-trivial. + /// Because of how the TWAI registers are set up, bytes must be assembled + /// manually. These registers serve a filter configuration role when the + /// device is in configuration mode, so patching the SVD files to improve + /// this may be non-trivial. /// /// [ESP32C3 Reference Manual](https://www.espressif.com/sites/default/files/documentation/esp32-c3_technical_reference_manual_en.pdf#subsubsection.29.4.4.2) /// @@ -1354,7 +1379,14 @@ where self.twai.register_block() } - /// Receive a frame + /// What the controller has reported since the driver was started (see + /// [`ErrorCounts`]) + #[instability::unstable] + pub fn error_counts(&self) -> ErrorCounts { + self.twai.async_state().counts.snapshot() + } + + /// Receives a frame. pub fn receive(&mut self) -> nb::Result { let status = self.regs().status().read(); @@ -1370,6 +1402,10 @@ where // Check if the packet in the receive buffer is valid or overrun. if status.miss_st().bit_is_set() { + // The FIFO entry is what is left of an overrun, not a frame: + // release it, or every later call would report it again. The + // async interrupt handler does the same. + release_receive_fifo(self.regs()); return nb::Result::Err(nb::Error::Other(EspTwaiError::EmbeddedHAL( ErrorKind::Overrun, ))); @@ -1403,9 +1439,37 @@ pub enum TwaiInterrupt { ErrorWarning, } -/// Represents errors that can occur in the TWAI driver. -/// This enum defines the possible errors that can be encountered when -/// interacting with the TWAI peripheral. +/// What the controller has reported since the driver was last started +/// ([`TwaiConfiguration::start`]), as counted by the async driver's interrupt +/// handler (a blocking driver counts nothing). +/// +/// Bus errors are classified from the error code capture register as +/// ESP-IDF does: bit, form and stuff errors by type, an acknowledgement +/// error by the ACK slot segment, anything else as `other`. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[non_exhaustive] +#[instability::unstable] +pub struct ErrorCounts { + /// Bit errors + pub bit: u32, + /// Form errors + pub form: u32, + /// Stuff errors + pub stuff: u32, + /// Acknowledgement errors: nobody acknowledged a transmitted frame + pub acknowledge: u32, + /// Other bus errors + pub other: u32, + /// Arbitration lost while transmitting (the controller retries) + pub arbitration_lost: u32, + /// Frames lost in the controller: its receive FIFO overran + pub overrun: u32, + /// Frames lost because the driver's receive queue was full + pub queue_full: u32, +} + +/// Errors that can occur when interacting with the TWAI peripheral. #[derive(Debug, Copy, Clone, Eq, PartialEq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum EspTwaiError { @@ -1434,14 +1498,14 @@ impl embedded_can::Error for EspTwaiError { } } -/// Copy data from multiple TWAI_DATA_x_REG registers, packing the source into +/// Copies data from multiple TWAI_DATA_x_REG registers, packing the source into /// the destination. /// /// # Safety -/// This function is marked unsafe because it reads arbitrarily from -/// memory-mapped registers. Specifically, this function is used with the -/// TWAI_DATA_x_REG registers which has different results based on the mode of -/// the peripheral. +/// +/// Reads arbitrarily from memory-mapped registers. Specifically, this function +/// is used with the TWAI_DATA_x_REG registers, which have different results +/// based on the mode of the peripheral. #[inline(always)] unsafe fn copy_from_data_register(dest: &mut [u8], src: *const u32) { for (i, dest) in dest.iter_mut().enumerate() { @@ -1452,14 +1516,14 @@ unsafe fn copy_from_data_register(dest: &mut [u8], src: *const u32) { } } -/// Copy data to multiple TWAI_DATA_x_REG registers, unpacking the source into +/// Copies data to multiple TWAI_DATA_x_REG registers, unpacking the source into /// the destination. /// /// # Safety -/// This function is marked unsafe because it writes arbitrarily to -/// memory-mapped registers. Specifically, this function is used with the -/// TWAI_DATA_x_REG registers which has different results based on the mode of -/// the peripheral. +/// +/// Writes arbitrarily to memory-mapped registers. Specifically, this function +/// is used with the TWAI_DATA_x_REG registers, which have different results +/// based on the mode of the peripheral. #[inline(always)] unsafe fn copy_to_data_register(dest: *mut u32, src: &[u8]) { for (i, src) in src.iter().enumerate() { @@ -1478,7 +1542,7 @@ where type Frame = EspTwaiFrame; type Error = EspTwaiError; - /// Transmit a frame. + /// Transmits a frame. fn transmit(&mut self, frame: &Self::Frame) -> nb::Result, Self::Error> { self.tx.transmit(frame)?; @@ -1488,7 +1552,7 @@ where nb::Result::Ok(None) } - /// Return a received frame if there are any available. + /// Returns the next received frame, or a would-block error when none is available. fn receive(&mut self) -> nb::Result { self.rx.receive() } @@ -1513,7 +1577,7 @@ pub trait PrivateInstance: crate::private::Sealed { /// Returns a reference to the register block for TWAI instance. fn register_block(&self) -> &RegisterBlock; - /// Enables/disables interrupts for the TWAI peripheral based on the `enable` flag. + /// Enables or disables interrupts for the TWAI peripheral based on the `enable` flag. fn enable_interrupts(&self, interrupts: EnumSet, enable: bool) { self.register_block().int_ena().modify(|_, w| { for interrupt in interrupts { @@ -1530,12 +1594,12 @@ pub trait PrivateInstance: crate::private::Sealed { }); } - /// Listen for given interrupts. + /// Listens for given interrupts. fn listen(&mut self, interrupts: impl Into>) { self.enable_interrupts(interrupts.into(), true); } - /// Unlisten the given interrupts. + /// Unlistens from the given interrupts. fn unlisten(&mut self, interrupts: impl Into>) { self.enable_interrupts(interrupts.into(), false); } @@ -1543,21 +1607,21 @@ pub trait PrivateInstance: crate::private::Sealed { fn async_state(&self) -> &asynch::TwaiAsyncState; } -/// Release the message in the buffer. This will decrement the received +/// Releases the message in the buffer. This will decrement the received /// message counter and prepare the next message in the FIFO for /// reading. fn release_receive_fifo(register_block: &RegisterBlock) { register_block.cmd().write(|w| w.release_buf().set_bit()); } -/// Check if the peripheral is in the error-passive state, i.e. one of the +/// Returns whether the peripheral is in the error-passive state, i.e. one of the /// error counters has reached 128. fn is_error_passive(register_block: &RegisterBlock) -> bool { register_block.tx_err_cnt().read().tx_err_cnt().bits() >= 128 || register_block.rx_err_cnt().read().rx_err_cnt().bits() >= 128 } -/// Write a frame to the peripheral. +/// Writes a frame to the peripheral. fn write_frame(register_block: &RegisterBlock, frame: &EspTwaiFrame) { // SAFETY: safe because there are 13 data registers and the slice is 13 bytes long max unsafe { @@ -1699,6 +1763,8 @@ mod asynch { use embassy_sync::{channel::Channel, waitqueue::AtomicWaker}; use esp_sync::RawMutex; + // `portable_atomic`: the ESP32-C3 has no atomic read-modify-write + use portable_atomic::{AtomicU32, Ordering}; use super::*; use crate::rtc_cntl::WakeLock; @@ -1707,6 +1773,83 @@ mod asynch { pub tx_waker: AtomicWaker, pub err_waker: AtomicWaker, pub rx_queue: Channel, 32>, + pub counts: Counts, + } + + /// [`ErrorCounts`], kept by the interrupt handler + pub struct Counts { + bit: AtomicU32, + form: AtomicU32, + stuff: AtomicU32, + acknowledge: AtomicU32, + other: AtomicU32, + arbitration_lost: AtomicU32, + overrun: AtomicU32, + queue_full: AtomicU32, + } + + /// ECC: the error type in bits 7-6, the segment in bits 4-0 + const ECC_TYPE_OTHER: u8 = 3; + const ECC_SEGMENT_ACK_SLOT: u8 = 25; + + impl Counts { + const fn new() -> Self { + Self { + bit: AtomicU32::new(0), + form: AtomicU32::new(0), + stuff: AtomicU32::new(0), + acknowledge: AtomicU32::new(0), + other: AtomicU32::new(0), + arbitration_lost: AtomicU32::new(0), + overrun: AtomicU32::new(0), + queue_full: AtomicU32::new(0), + } + } + + fn count(counter: &AtomicU32) { + counter.fetch_add(1, Ordering::Relaxed); + } + + /// A bus error, from the error code capture register + fn bus_error(&self, ecc: u8) { + let counter = match ecc >> 6 { + 0 => &self.bit, + 1 => &self.form, + 2 => &self.stuff, + ECC_TYPE_OTHER if ecc & 0x1F == ECC_SEGMENT_ACK_SLOT => &self.acknowledge, + _ => &self.other, + }; + Self::count(counter); + } + + pub fn reset(&self) { + for counter in [ + &self.bit, + &self.form, + &self.stuff, + &self.acknowledge, + &self.other, + &self.arbitration_lost, + &self.overrun, + &self.queue_full, + ] { + counter.store(0, Ordering::Relaxed); + } + } + + pub fn snapshot(&self) -> ErrorCounts { + let get = |c: &AtomicU32| c.load(Ordering::Relaxed); + ErrorCounts { + bit: get(&self.bit), + form: get(&self.form), + stuff: get(&self.stuff), + acknowledge: get(&self.acknowledge), + other: get(&self.other), + arbitration_lost: get(&self.arbitration_lost), + overrun: get(&self.overrun), + queue_full: get(&self.queue_full), + } + } } impl Default for TwaiAsyncState { @@ -1721,6 +1864,7 @@ mod asynch { tx_waker: AtomicWaker::new(), err_waker: AtomicWaker::new(), rx_queue: Channel::new(), + counts: Counts::new(), } } } @@ -1729,8 +1873,8 @@ mod asynch { /// Transmits an `EspTwaiFrame` asynchronously over the TWAI bus. /// /// The transmission is aborted if the future is dropped. The technical - /// reference manual does not specifiy if aborting the transmission also - /// stops it, in case it is activly transmitting. Therefor it could be + /// reference manual does not specify if aborting the transmission also + /// stops it, in case it is actively transmitting. Therefore it could be /// the case that even though the future is dropped, the frame was sent /// anyways. /// @@ -1827,8 +1971,8 @@ mod asynch { /// Transmits an `EspTwaiFrame` asynchronously over the TWAI bus. /// /// The transmission is aborted if the future is dropped. The technical - /// reference manual does not specifiy if aborting the transmission also - /// stops it, in case it is actively transmitting. Therefor it could be + /// reference manual does not specify if aborting the transmission also + /// stops it, in case it is actively transmitting. Therefore it could be /// the case that even though the future is dropped, the frame was sent /// anyways. /// @@ -1868,8 +2012,31 @@ mod asynch { pub(super) fn handle_interrupt(register_block: &RegisterBlock, async_state: &TwaiAsyncState) { let int_raw = register_block.int_raw().read(); - let int_ena_reg = register_block.int_ena(); - let int_ena = int_ena_reg.read(); + + // Disable the interrupts that fired (except the receive interrupt) + // before waking anyone: a woken task on a higher priority executor + // runs as soon as it is woken, before this handler returns. A + // transmit future polled then enables the transmit interrupt for its + // next frame, and clearing the bits afterwards from a copy read + // before the wake would disable it again - the next frame's + // completion would wake nobody. + let int_ena = register_block.int_ena().read(); + unsafe { + register_block + .int_ena() + .modify(|r, w| w.bits(r.bits() & (!int_raw.bits() | 1))); + } + // ... except the bus error and arbitration lost interrupts: they only + // feed `ErrorCounts`, and reading their capture registers below + // re-arms them. Masking them until the next future poll calls + // `listen` would drop every error in between. ESP-IDF keeps them + // enabled as well. + register_block.int_ena().modify(|_, w| { + w.bus_err_int_ena() + .bit(int_ena.bus_err_int_ena().bit()) + .arb_lost_int_ena() + .bit(int_ena.arb_lost_int_ena().bit()) + }); // The error warning interrupt fires on every change of the error or // bus status. Entering bus-off sets both the bus-off and the error @@ -1906,6 +2073,7 @@ mod asynch { let msg = if status_reg.read().miss_st().bit_is_set() { // Current frame is incomplete (Rx FIFO has overrun) release_receive_fifo(register_block); + Counts::count(&async_state.counts.overrun); Err(EspTwaiError::EmbeddedHAL(ErrorKind::Overrun)) } else { // Current frame is complete @@ -1913,8 +2081,10 @@ mod asynch { release_receive_fifo(register_block); Ok(frame) }; - // Rx queue is full? Stop consuming Rx frames + // Rx queue is full? Stop consuming Rx frames. The one just + // taken was released already: it is lost, and counted. if rx_queue.try_send(msg).is_err() { + Counts::count(&async_state.counts.queue_full); break; } } @@ -1924,13 +2094,29 @@ mod asynch { async_state.tx_waker.wake(); } + if int_raw.arb_lost_int_st().bit_is_set() { + // Reading the capture register re-arms the interrupt; nothing + // else did, so it fired once per driver lifetime + let _ = register_block.arb_lost_cap().read(); + Counts::count(&async_state.counts.arbitration_lost); + } + if int_raw.err_warn_int_st().bit_is_set() || int_raw.err_passive_int_st().bit_is_set() || int_raw.bus_err_int_st().bit_is_set() { - // We might want to use the error code to gather statistics in the - // future. - let _ = register_block.err_code_cap().read(); + // Reading the capture register also re-arms the bus error + // interrupt. The error that takes the controller bus-off raises + // no bus error interrupt of its own (ESP-IDF counts it from the + // error warning interrupt), so it is counted here too. + let ecc = register_block.err_code_cap().read().bits() as u8; + let status = register_block.status().read(); + let entered_bus_off = int_raw.err_warn_int_st().bit_is_set() + && status.bus_off_st().bit_is_set() + && status.err_st().bit_is_set(); + if int_raw.bus_err_int_st().bit_is_set() || entered_bus_off { + async_state.counts.bus_error(ecc); + } async_state.err_waker.wake(); // A frame that cannot be transmitted never raises the transmit // interrupt, so wake transmitters on errors to let them @@ -1938,10 +2124,5 @@ mod asynch { // reaches the error-passive or bus-off state. async_state.tx_waker.wake(); } - - // Clear interrupt request bits - unsafe { - int_ena_reg.modify(|_, w| w.bits(int_ena.bits() & (!int_raw.bits() | 1))); - } } } diff --git a/esp-hal/src/uart/clocks/v2_pcr.rs b/esp-hal/src/uart/clocks/v2_pcr.rs index 7ed7fe86afe..5acd35a3ac1 100644 --- a/esp-hal/src/uart/clocks/v2_pcr.rs +++ b/esp-hal/src/uart/clocks/v2_pcr.rs @@ -37,6 +37,11 @@ impl UartInstance { UartFunctionClockSclk::RcFast => 1, UartFunctionClockSclk::PllF80m => 2, }, + esp32h4 => match new_config.sclk() { + UartFunctionClockSclk::Xtal => 0, + UartFunctionClockSclk::RcFast => 1, + UartFunctionClockSclk::PllF48m => 2, + }, any(esp32c6, esp32h2) => match new_config.sclk() { #[cfg(esp32c6)] UartFunctionClockSclk::PllF80m => 1, diff --git a/esp-hal/src/uart/low_level/mod.rs b/esp-hal/src/uart/low_level/mod.rs index a876c86fdf8..088e26084df 100644 --- a/esp-hal/src/uart/low_level/mod.rs +++ b/esp-hal/src/uart/low_level/mod.rs @@ -41,10 +41,7 @@ use crate::{ #[cfg_attr(uart_version = "2", path = "v2.rs")] mod version; -#[inline(always)] -pub(super) fn sync_regs(register_block: &RegisterBlock) { - version::sync_regs(register_block); -} +pub(super) use version::{enable_register_sync, sync_regs}; #[derive(Debug, EnumSetType)] pub(super) enum TxEvent { @@ -255,7 +252,7 @@ pub trait Instance: crate::private::Sealed + any::Degrade { pub struct Info { /// Pointer to the register block for this UART instance. /// - /// Use [Self::register_block] to access the register block. + /// Used with [`Self::register_block`] to access the register block. pub register_block: *const RegisterBlock, /// The system peripheral marker. @@ -313,7 +310,7 @@ impl Info { unsafe { &*self.register_block } } - /// Listen for the given interrupts + /// Listens for the given interrupts. pub(super) fn enable_listen(&self, interrupts: EnumSet, enable: bool) { let reg_block = self.regs(); @@ -497,9 +494,9 @@ impl Info { }); } - /// Configures the RX-FIFO threshold + /// Configures the RX-FIFO threshold. /// - /// ## Errors + /// # Errors /// /// [`ConfigError::RxFifoThresholdNotSupported`] if the provided value is zero /// or exceeds [`Info::RX_FIFO_MAX_THRHD`]. @@ -515,15 +512,15 @@ impl Info { Ok(()) } - /// Reads the RX-FIFO threshold + /// Reads the RX-FIFO threshold. #[allow(clippy::useless_conversion)] pub(super) fn rx_fifo_full_threshold(&self) -> u16 { self.regs().conf1().read().rxfifo_full_thrhd().bits().into() } - /// Configures the TX-FIFO threshold + /// Configures the TX-FIFO threshold. /// - /// ## Errors + /// # Errors /// /// [`ConfigError::TxFifoThresholdNotSupported`] if the provided value exceeds /// [`Info::TX_FIFO_MAX_THRHD`]. @@ -552,14 +549,14 @@ impl Info { _ => "- The value you pass times the symbol size must be <= **0x3FF**.", } )] - /// Configures the Receive Timeout detection setting + /// Configures the Receive Timeout detection setting. /// /// ## Arguments /// /// `timeout` - the number of symbols ("bytes") to wait for before /// triggering a timeout. Pass None to disable the timeout. /// - /// ## Errors + /// # Errors /// /// [`ConfigError::TimeoutTooLong`] if the provided value exceeds /// the maximum value for SOC: @@ -711,6 +708,9 @@ impl Info { txfifo_rst(self.regs(), true); txfifo_rst(self.regs(), false); + + // The reset can drive the state machine. Wait for it to settle. + while !self.is_tx_idle() {} } pub(super) fn current_symbol_length(&self) -> u8 { diff --git a/esp-hal/src/uart/low_level/v1.rs b/esp-hal/src/uart/low_level/v1.rs index d13934264f3..ccffe37c8fe 100644 --- a/esp-hal/src/uart/low_level/v1.rs +++ b/esp-hal/src/uart/low_level/v1.rs @@ -10,12 +10,28 @@ use crate::uart::{ }; #[inline(always)] -pub(super) fn sync_regs(_register_block: &RegisterBlock) { +pub(crate) fn enable_register_sync(_register_block: &RegisterBlock) { + #[cfg(not(any(esp32, esp32s2)))] + { + // We need to clear "high_speed" (UART_UPDATE_CTRL) for UART_REG_UPDATE + // to actually do anything. It's unclear if we have to clear this bit + // separately from using `reg_update` but this is cheap and for sure works. + _register_block + .id() + .modify(|_, w| w.high_speed().clear_bit()); + } +} + +#[inline(always)] +pub(crate) fn sync_regs(_register_block: &RegisterBlock) { #[cfg(not(any(esp32, esp32s2)))] { let update_reg = _register_block.id(); - update_reg.modify(|_, w| w.reg_update().set_bit()); + update_reg.write(|w| { + w.high_speed().clear_bit(); + w.reg_update().set_bit() + }); while update_reg.read().reg_update().bit_is_set() { core::hint::spin_loop(); @@ -102,53 +118,41 @@ pub(super) fn change_flow_control( sw_flow_ctrl: SwFlowControl, hw_flow_ctrl: HwFlowControl, ) { - match sw_flow_ctrl { - SwFlowControl::Enabled { - xon_char, - xoff_char, - xon_threshold, - xoff_threshold, - } => { - info.regs().flow_conf().modify(|_, w| { - w.xonoff_del().set_bit(); - w.sw_flow_con_en().set_bit() - }); - - cfg_select! { - esp32 => { - info.regs().swfc_conf().modify(|_, w| unsafe { - w.xon_threshold() - .bits(xon_threshold) - .xoff_threshold() - .bits(xoff_threshold) - }); - info.regs().swfc_conf().modify(|_, w| unsafe { - w.xon_char().bits(xon_char).xoff_char().bits(xoff_char) - }); - } - _ => { - info.regs() - .swfc_conf1() - .modify(|_, w| unsafe { w.xon_threshold().bits(xon_threshold as u16) }); - info.regs() - .swfc_conf0() - .modify(|_, w| unsafe { w.xoff_threshold().bits(xoff_threshold as u16) }); - info.regs() - .swfc_conf1() - .modify(|_, w| unsafe { w.xon_char().bits(xon_char) }); - info.regs() - .swfc_conf0() - .modify(|_, w| unsafe { w.xoff_char().bits(xoff_char) }); - } + if let SwFlowControl::Enabled { + xon_char, + xoff_char, + xon_threshold, + xoff_threshold, + } = sw_flow_ctrl + { + cfg_select! { + esp32 => { + info.regs().swfc_conf().modify(|_, w| unsafe { + w.xon_threshold().bits(xon_threshold); + w.xoff_threshold().bits(xoff_threshold); + w.xon_char().bits(xon_char); + w.xoff_char().bits(xoff_char) + }); + } + _ => { + info.regs().swfc_conf1().modify(|_, w| unsafe { + w.xon_threshold().bits(xon_threshold as u16); + w.xon_char().bits(xon_char) + }); + info.regs().swfc_conf0().modify(|_, w| unsafe { + w.xoff_threshold().bits(xoff_threshold as u16); + w.xoff_char().bits(xoff_char) + }); } - } - SwFlowControl::Disabled => { - let reg = info.regs().flow_conf(); - reg.modify(|_, w| w.sw_flow_con_en().clear_bit()); - reg.modify(|_, w| w.xonoff_del().clear_bit()); } } + info.regs().flow_conf().modify(|_, w| { + w.xonoff_del() + .bit(matches!(sw_flow_ctrl, SwFlowControl::Enabled { .. })); + w.sw_flow_con_en() + .bit(matches!(sw_flow_ctrl, SwFlowControl::Enabled { .. })) + }); info.regs().conf0().modify(|_, w| { w.tx_flow_en() .bit(matches!(hw_flow_ctrl.cts, CtsConfig::Enabled)) diff --git a/esp-hal/src/uart/low_level/v2.rs b/esp-hal/src/uart/low_level/v2.rs index f7dc665e942..ea1da08984f 100644 --- a/esp-hal/src/uart/low_level/v2.rs +++ b/esp-hal/src/uart/low_level/v2.rs @@ -10,10 +10,13 @@ use crate::uart::{ }; #[inline(always)] -pub(super) fn sync_regs(register_block: &RegisterBlock) { +pub(crate) fn enable_register_sync(_register_block: &RegisterBlock) {} + +#[inline(always)] +pub(crate) fn sync_regs(register_block: &RegisterBlock) { let update_reg = register_block.reg_update(); - update_reg.modify(|_, w| w.reg_update().set_bit()); + update_reg.write(|w| w.reg_update().set_bit()); while update_reg.read().reg_update().bit_is_set() { core::hint::spin_loop(); diff --git a/esp-hal/src/uart/lp_uart.rs b/esp-hal/src/uart/lp_uart.rs index a7220e547d3..bd7c90bc168 100644 --- a/esp-hal/src/uart/lp_uart.rs +++ b/esp-hal/src/uart/lp_uart.rs @@ -119,7 +119,7 @@ pub struct LpUart { } impl LpUart { - /// Initialize the UART driver using the provided configuration + /// Initializes the UART driver using the provided configuration. // TODO: CTS and RTS pins pub fn new( uart: LP_UART<'static>, @@ -243,7 +243,7 @@ impl LpUart { self.update(); } - /// Modify UART baud rate and reset TX/RX fifo. + /// Modifies UART baud rate and reset TX/RX fifo. pub fn change_baud(&mut self, config: &Config) { self.change_baud_internal(config); self.txfifo_reset(); diff --git a/esp-hal/src/uart/mod.rs b/esp-hal/src/uart/mod.rs index d7f1dab7674..9c8d838ab14 100644 --- a/esp-hal/src/uart/mod.rs +++ b/esp-hal/src/uart/mod.rs @@ -71,6 +71,7 @@ use low_level::{ UartClockGuard, UartRxFuture, UartTxFuture, + enable_register_sync, rx_event_check_for_error, sync_regs, }; @@ -142,27 +143,26 @@ impl AnyUart<'_> { pub enum RxError { /// An RX FIFO overflow happened. /// - /// This error occurs when RX FIFO is full and a new byte is received. The - /// RX FIFO is then automatically reset by the driver. + /// Occurs when the RX FIFO is full and a new byte is received. The RX FIFO + /// is then automatically reset by the driver. FifoOverflowed, /// A glitch was detected on the RX line. /// - /// This error occurs when an unexpected or erroneous signal (glitch) is - /// detected on the UART RX line, which could lead to incorrect data - /// reception. + /// Occurs when an unexpected or erroneous signal (glitch) is detected on the + /// UART RX line, which could lead to incorrect data reception. GlitchOccurred, /// A framing error was detected on the RX line. /// - /// This error occurs when the received data does not conform to the - /// expected UART frame format. + /// Occurs when the received data does not conform to the expected UART frame + /// format. FrameFormatViolated, /// A parity error was detected on the RX line. /// - /// This error occurs when the parity bit in the received data does not - /// match the expected parity configuration. + /// Occurs when the parity bit in the received data does not match the + /// expected parity configuration. ParityMismatch, } @@ -170,9 +170,8 @@ impl core::error::Error for RxError {} /// UART RX error conditions that can be reported by read operations. /// -/// This enum can be used with [`RxConfig::with_reported_errors`] to choose -/// which hardware RX error conditions should make read operations return an -/// [`RxError`]. +/// Used with [`RxConfig::with_reported_errors`] to choose which hardware RX +/// error conditions should make read operations return an [`RxError`] #[derive(Debug, EnumSetType)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[instability::unstable] @@ -231,9 +230,9 @@ pub use crate::soc::clocks::UartFunctionClockSclk as ClockSource; /// Number of data bits /// -/// This enum represents the various configurations for the number of data -/// bits used in UART communication. The number of data bits defines the -/// length of each transmitted or received data frame. +/// Configurations for the number of data bits used in UART communication. The +/// number of data bits defines the length of each transmitted or received data +/// frame. #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum DataBits { @@ -271,8 +270,7 @@ pub enum Parity { /// Number of stop bits /// /// The stop bit(s) signal the end of a data packet in UART communication. -/// This enum defines the possible configurations for the number of stop -/// bits. +/// Possible configurations for the number of stop bits. #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum StopBits { @@ -293,7 +291,7 @@ pub enum SwFlowControl { #[default] /// Disables software flow control. Disabled, - /// Enables software flow control with configured parameters + /// Enables software flow control with configured parameters. Enabled { /// Xon flow control byte. xon_char: u8, @@ -313,10 +311,10 @@ pub enum SwFlowControl { #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[instability::unstable] pub enum CtsConfig { - /// Enable CTS flow control (TX). + /// Enables CTS flow control (TX). Enabled, #[default] - /// Disable CTS flow control (TX). + /// Disables CTS flow control (TX). Disabled, } @@ -325,10 +323,10 @@ pub enum CtsConfig { #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[instability::unstable] pub enum RtsConfig { - /// Enable RTS flow control with a FIFO threshold (RX). + /// Enables RTS flow control with a FIFO threshold (RX). Enabled(u8), #[default] - /// Disable RTS flow control. + /// Disables RTS flow control. Disabled, } @@ -348,13 +346,13 @@ pub struct HwFlowControl { #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[instability::unstable] pub enum BaudrateTolerance { - /// Accept the closest achievable baud rate without restriction. + /// Accepts the closest achievable baud rate without restriction. #[default] Closest, /// In this setting, the deviation of only 1% from the desired baud value is /// tolerated. Exact, - /// Allow a certain percentage of deviation. + /// Allows a certain percentage of deviation. ErrorPercent(u8), } @@ -662,7 +660,7 @@ where #[procmacros::doc_replace] /// UART (Full-duplex) /// -/// ## Example +/// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -715,13 +713,13 @@ pub enum ConfigError { /// The requested baud rate is not supported. /// - /// This error is returned if: + /// Returned when: /// * the baud rate exceeds 5MBaud or is equal to zero. - /// * the user has specified an exact baud rate or with some percentage of deviation to the - /// desired value, and the driver cannot reach this speed. + /// * an exact baud rate or a deviation tolerance is specified, and the driver cannot reach + /// that speed. BaudrateNotSupported, - /// The requested timeout exceeds the maximum value ( + /// The requested timeout exceeds the maximum value (. #[cfg_attr(esp32, doc = "127")] #[cfg_attr(not(esp32), doc = "1023")] /// ). @@ -764,16 +762,9 @@ impl<'d> UartTx<'d, Blocking> { _ => "" } )] - /// Create a new UART TX instance in [`Blocking`] mode. + /// Creates a new UART TX instance in [`Blocking`] mode. /// - /// __note__ - /// - /// ## Errors - /// - /// This function returns a [`ConfigError`] if the configuration is not - /// supported by the hardware. - /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -781,6 +772,10 @@ impl<'d> UartTx<'d, Blocking> { /// let tx = UartTx::new(peripherals.UART0, Config::default())?.with_tx(peripherals.GPIO1); /// # {after_snippet} /// ``` + /// + /// # Errors + /// + /// [`ConfigError`] when the configuration is not supported by the hardware #[instability::unstable] pub fn new(uart: impl Instance + 'd, config: Config) -> Result { let (_, uart_tx) = UartBuilder::new(uart).init(config)?.split(); @@ -832,21 +827,21 @@ impl<'d> UartTx<'d, Async> { } } - /// Write data into the TX buffer. + /// Writes data into the TX buffer. /// - /// This function writes the provided buffer `bytes` into the UART transmit - /// buffer. If the buffer is full, the function waits asynchronously for - /// space in the buffer to become available. + /// Writes the provided buffer `bytes` into the UART transmit buffer. If the + /// buffer is full, waits asynchronously for space in the buffer to become + /// available. /// - /// The function returns the number of bytes written into the buffer. This - /// may be less than the length of the buffer. + /// Returns the number of bytes written into the buffer. This may be less + /// than the length of the buffer. /// - /// Upon an error, the function returns immediately and the contents of the - /// internal FIFO are not modified. + /// Upon an error, returns immediately and the contents of the internal FIFO + /// are not modified. /// - /// ## Cancellation + /// # Cancellation Safety /// - /// This function is cancellation safe. + /// Cancellation safe. pub async fn write_async(&mut self, bytes: &[u8]) -> Result { // We need to loop in case the TX empty interrupt was fired but not cleared // before, but the FIFO itself was filled up by a previous write. @@ -874,13 +869,13 @@ impl<'d> UartTx<'d, Async> { /// Asynchronously flushes the UART transmit buffer. /// - /// This function ensures that all pending data in the transmit FIFO has - /// been sent over the UART. If the FIFO contains data, it waits for the - /// transmission to complete before returning. + /// Ensures that all pending data in the transmit FIFO has been sent over the + /// UART. If the FIFO contains data, waits for the transmission to complete + /// before returning. /// - /// ## Cancellation + /// # Cancellation Safety /// - /// This function is cancellation safe. + /// Cancellation safe. pub async fn flush_async(&mut self) -> Result<(), TxError> { // Nothing is guaranteed to clear the Done status, so let's loop here in case Tx // was Done before the last write operation that pushed data into the @@ -899,7 +894,7 @@ impl<'d> UartTx<'d, Async> { /// Duration is in bits, the time it takes to transfer one bit at the /// current baud rate. /// - /// This function restores the original TX line state after the break signal is sent, even if + /// Restores the original TX line state after the break signal is sent, even if /// the future is cancelled. #[instability::unstable] pub async fn send_break_async(&mut self, delay: &mut D, bits: u32) { @@ -919,7 +914,7 @@ impl<'d, Dm> UartTx<'d, Dm> where Dm: DriverMode, { - /// Configure RTS pin + /// Configures RTS pin. #[instability::unstable] pub fn with_rts(mut self, rts: impl PeripheralOutput<'d>) -> Self { let rts = rts.into(); @@ -932,7 +927,7 @@ where self } - /// Assign the TX pin for UART instance. + /// Assigns the TX pin for UART instance. /// /// Sets the specified pin to push-pull output and connects it to the UART /// TX signal. @@ -952,12 +947,16 @@ where self } - /// Change the configuration. + /// Changes the configuration. + /// + /// Do not call this function while a transmission is in progress. The function discards + /// the data that the transmitter did not send yet, and the TX line goes low for a short + /// time. A receiver reports that pulse as an error. Call [`Self::flush`] first, to let + /// the transmitter send the remaining data. /// - /// ## Errors + /// # Errors /// - /// This function returns a [`ConfigError`] if the configuration is not - /// supported by the hardware. + /// [`ConfigError`] when the configuration is not supported by the hardware #[instability::unstable] pub fn apply_config(&mut self, config: &Config) -> Result<(), ConfigError> { self.uart @@ -975,19 +974,17 @@ where self.uart.info().tx_fifo_count() < Info::UART_FIFO_SIZE } - /// Write bytes. + /// Writes bytes. /// - /// This function writes data to the internal TX FIFO of the UART - /// peripheral. The data is then transmitted over the UART TX line. + /// Writes data to the internal TX FIFO of the UART peripheral. The data is + /// then transmitted over the UART TX line. /// - /// The function returns the number of bytes written to the FIFO. This may - /// be less than the length of the provided data. The function may only - /// return 0 if the provided data is empty. + /// Returns the number of bytes written to the FIFO. This may be less than the + /// length of the provided data. Returns 0 only if the provided data is empty. /// - /// ## Errors + /// # Errors /// - /// This function returns a [`TxError`] if an error occurred during the - /// write operation. + /// [`TxError`] when an error occurred during the write operation #[instability::unstable] pub fn write(&mut self, data: &[u8]) -> Result { self.uart.info().write(data) @@ -1001,10 +998,9 @@ where Ok(()) } - /// Flush the transmit buffer. + /// Flushes the transmit buffer. /// - /// This function blocks until all data in the TX FIFO has been - /// transmitted. + /// Blocks until all data in the TX FIFO has been transmitted. #[instability::unstable] pub fn flush(&mut self) -> Result<(), TxError> { while self.uart.info().tx_fifo_count() > 0 {} @@ -1064,19 +1060,17 @@ where }) } - /// Checks if the TX line is idle for this UART instance. + /// Returns whether the TX line is idle for this UART instance. /// - /// Returns `true` if the transmit line is idle, meaning no data is - /// currently being transmitted. + /// The transmit line is idle when no data is currently being transmitted. fn is_tx_idle(&self) -> bool { self.uart.info().is_tx_idle() } /// Disables all TX-related interrupts for this UART instance. /// - /// This function clears and disables the `transmit FIFO empty` interrupt, - /// `transmit break done`, `transmit break idle done`, and `transmit done` - /// interrupts. + /// Clears and disables the `transmit FIFO empty` interrupt, `transmit break + /// done`, `transmit break idle done`, and `transmit done` interrupts fn disable_tx_interrupts(&self) { self.regs().int_clr().write(|w| { w.txfifo_empty().clear_bit_by_one(); @@ -1105,14 +1099,9 @@ impl<'d> UartRx<'d, Blocking> { _ => "" } )] - /// Create a new UART RX instance in [`Blocking`] mode. - /// - /// __note__ - /// - /// ## Errors + /// Creates a new UART RX instance in [`Blocking`] mode. /// - /// This function returns a [`ConfigError`] if the configuration is not - /// supported by the hardware. + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1120,6 +1109,10 @@ impl<'d> UartRx<'d, Blocking> { /// let rx = UartRx::new(peripherals.UART0, Config::default())?.with_rx(peripherals.GPIO2); /// # {after_snippet} /// ``` + /// + /// # Errors + /// + /// [`ConfigError`] when the configuration is not supported by the hardware #[instability::unstable] pub fn new(uart: impl Instance + 'd, config: Config) -> Result { let (uart_rx, _) = UartBuilder::new(uart).init(config)?.split(); @@ -1129,9 +1122,9 @@ impl<'d> UartRx<'d, Blocking> { /// Waits for a break condition to be detected. /// - /// This function polls the break-detection interrupt status and returns once - /// the receiver has detected a break condition. After detection, the break - /// status is automatically cleared. + /// Polls the break-detection interrupt status and returns once the receiver + /// has detected a break condition. After detection, the break status is + /// automatically cleared. #[instability::unstable] pub fn wait_for_break(&mut self) { while !self.is_break_detected() { @@ -1143,10 +1136,10 @@ impl<'d> UartRx<'d, Blocking> { /// Waits for a break condition to be detected with a timeout. /// - /// This function polls the break-detection interrupt status until a break is - /// detected or the specified timeout expires. Returns `true` if a break was - /// detected, `false` if the timeout elapsed. After successful detection, the - /// break status is automatically cleared. + /// Polls the break-detection interrupt status until a break is detected or + /// the specified timeout expires. Returns whether a break was detected + /// before the timeout expired. After successful detection, the break + /// status is automatically cleared. /// /// ## Arguments /// * `timeout` - Maximum time to wait for a break condition @@ -1259,24 +1252,24 @@ impl<'d> UartRx<'d, Async> { Ok(()) } - /// Read data asynchronously. + /// Reads data asynchronously. /// - /// This function reads data from the UART receive buffer into the - /// provided buffer. If the buffer is empty, the function waits - /// asynchronously for data to become available, or for an error to occur. + /// Reads data from the UART receive buffer into the provided buffer. If the + /// buffer is empty, waits asynchronously for data to become available, or for + /// an error to occur. /// - /// The function returns the number of bytes read into the buffer. This may - /// be less than the length of the buffer. + /// Returns the number of bytes read into the buffer. This may be less than + /// the length of the buffer. /// - /// Note that this function may ignore the `rx_fifo_full_threshold` setting - /// to ensure that it does not wait for more data than the buffer can hold. + /// May ignore the `rx_fifo_full_threshold` setting to ensure that it does not + /// wait for more data than the buffer can hold. /// - /// Upon an error, the function returns immediately and the contents of the - /// internal FIFO are not modified. + /// Upon an error, returns immediately and the contents of the internal FIFO + /// are not modified. /// - /// ## Cancellation + /// # Cancellation Safety /// - /// This function is cancellation safe. + /// Cancellation safe. pub async fn read_async(&mut self, buf: &mut [u8]) -> Result { if buf.is_empty() { return Ok(0); @@ -1287,20 +1280,20 @@ impl<'d> UartRx<'d, Async> { self.read_buffered(buf) } - /// Fill buffer asynchronously. + /// Fills buffer asynchronously. /// - /// This function reads data into the provided buffer. If the internal FIFO - /// does not contain enough data, the function waits asynchronously for data - /// to become available, or for an error to occur. + /// Reads data into the provided buffer. If the internal FIFO does not contain + /// enough data, waits asynchronously for data to become available, or for an + /// error to occur. /// - /// Note that this function may ignore the `rx_fifo_full_threshold` setting - /// to ensure that it does not wait for more data than the buffer can hold. + /// May ignore the `rx_fifo_full_threshold` setting to ensure that it does not + /// wait for more data than the buffer can hold. /// - /// ## Cancellation + /// # Cancellation Safety /// - /// This function is **not** cancellation safe. If the future is dropped - /// before it resolves, or if an error occurs during the read operation, - /// previously read data may be lost. + /// **Not** cancellation safe. If the future is dropped before it resolves, or + /// if an error occurs during the read operation, previously read data may be + /// lost. pub async fn read_exact_async(&mut self, mut buf: &mut [u8]) -> Result<(), RxError> { if buf.is_empty() { return Ok(()); @@ -1343,7 +1336,7 @@ where self.uart.info().regs() } - /// Assign the CTS pin for UART instance. + /// Assigns the CTS pin for UART instance. /// /// Sets the specified pin to input and connects it to the UART CTS signal. #[instability::unstable] @@ -1358,14 +1351,13 @@ where self } - /// Assign the RX pin for UART instance. + /// Assigns the RX pin for UART instance. /// /// Sets the specified pin to input and connects it to the UART RX signal. /// - /// Note: when you listen for the output of the UART peripheral, you should - /// configure the driver side (i.e. the TX pin), or ensure that the line is - /// initially high, to avoid receiving a non-data byte caused by an - /// initial low signal level. + /// When listening for the output of the UART peripheral, configure the driver + /// side (the TX pin), or ensure that the line is initially high, to avoid + /// receiving a non-data byte caused by an initial low signal level. #[instability::unstable] pub fn with_rx(self, rx: impl PeripheralInput<'d>) -> Self { let rx = rx.into(); @@ -1394,12 +1386,11 @@ where self.uart.info().clear_rx_break_detected(); } - /// Change the configuration. + /// Changes the configuration. /// - /// ## Errors + /// # Errors /// - /// This function returns a [`ConfigError`] if the configuration is not - /// supported by the hardware. + /// [`ConfigError`] when the configuration is not supported by the hardware #[instability::unstable] pub fn apply_config(&mut self, config: &Config) -> Result<(), ConfigError> { self.uart @@ -1437,8 +1428,8 @@ where /// /// # Errors /// - /// Returns [`WakeConfigError::NotAWakeupSource`] if this UART instance cannot wake the chip, - /// and [`WakeConfigError::EdgeCountUnsupported`] if the hardware cannot count the requested + /// [`WakeConfigError::NotAWakeupSource`] when this UART instance cannot wake the chip, + /// and [`WakeConfigError::EdgeCountUnsupported`] when the hardware cannot count the requested /// number of edges. #[cfg(sleep_driver_supported)] #[instability::unstable] @@ -1472,21 +1463,20 @@ where self.uart.info().rx_fifo_count() > 0 } - /// Read bytes. + /// Reads bytes. /// /// The UART hardware continuously receives bytes and stores them in the RX - /// FIFO. This function reads the bytes from the RX FIFO and returns - /// them in the provided buffer. If the hardware buffer is empty, this - /// function will block until data is available. The [`Self::read_ready`] - /// function can be used to check if data is available without blocking. + /// FIFO. Reads the bytes from the RX FIFO and returns them in the provided + /// buffer. If the hardware buffer is empty, blocks until data is available. + /// [`Self::read_ready`] can be used to check if data is available without + /// blocking. /// - /// The function returns the number of bytes read into the buffer. This may - /// be less than the length of the buffer. This function only returns 0 - /// if the provided buffer is empty. + /// Returns the number of bytes read into the buffer. This may be less than + /// the length of the buffer. Returns 0 only if the provided buffer is empty. /// - /// ## Errors + /// # Errors /// - /// This function returns an [`RxError`] if a reported error occurred since + /// [`RxError`] when a reported error occurred since /// the last call to [`Self::check_for_errors`], [`Self::read_buffered`], or /// this function. /// @@ -1497,18 +1487,17 @@ where self.uart.info().read(buf, self.reported_errors) } - /// Read already received bytes. + /// Reads already received bytes. /// - /// This function reads the already received bytes from the FIFO into the - /// provided buffer. The function does not wait for the FIFO to actually - /// contain any bytes. + /// Reads the already received bytes from the FIFO into the provided buffer. + /// Does not wait for the FIFO to actually contain any bytes. /// - /// The function returns the number of bytes read into the buffer. This may - /// be less than the length of the buffer, and it may also be 0. + /// Returns the number of bytes read into the buffer. This may be less than + /// the length of the buffer, and it may also be 0. /// - /// ## Errors + /// # Errors /// - /// This function returns an [`RxError`] if a reported error occurred since + /// [`RxError`] when a reported error occurred since /// the last call to [`Self::check_for_errors`], [`Self::read`], or this /// function. /// @@ -1521,9 +1510,9 @@ where /// Disables all RX-related interrupts for this UART instance. /// - /// This function clears and disables the `receive FIFO full` interrupt, - /// `receive FIFO overflow`, `receive FIFO timeout`, and `AT command - /// byte detection` interrupts. + /// Clears and disables the `receive FIFO full` interrupt, `receive FIFO + /// overflow`, `receive FIFO timeout`, and `AT command byte detection` + /// interrupts. fn disable_rx_interrupts(&self) { self.regs().int_clr().write(|w| { w.rxfifo_full().clear_bit_by_one(); @@ -1548,16 +1537,9 @@ impl<'d> Uart<'d, Blocking> { _ => "" } )] - /// Create a new UART instance in [`Blocking`] mode. - /// - /// __note__ - /// - /// ## Errors + /// Creates a new UART instance in [`Blocking`] mode. /// - /// This function returns a [`ConfigError`] if the configuration is not - /// supported by the hardware. - /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1567,6 +1549,10 @@ impl<'d> Uart<'d, Blocking> { /// .with_tx(peripherals.GPIO2); /// # {after_snippet} /// ``` + /// + /// # Errors + /// + /// [`ConfigError`] when the configuration is not supported by the hardware pub fn new(uart: impl Instance + 'd, config: Config) -> Result { UartBuilder::new(uart).init(config) } @@ -1591,10 +1577,9 @@ impl<'d> Uart<'d, Blocking> { doc = "Registers an interrupt handler for the peripheral on the current core." )] #[doc = ""] - /// Note that this will replace any previously registered interrupt - /// handlers. + /// Replaces any previously registered interrupt handlers. /// - /// You can restore the default/unhandled interrupt handler by using + /// The default/unhandled interrupt handler can be restored with /// [crate::interrupt::DEFAULT_INTERRUPT_HANDLER] #[instability::unstable] pub fn set_interrupt_handler(&mut self, handler: InterruptHandler) { @@ -1603,12 +1588,12 @@ impl<'d> Uart<'d, Blocking> { } #[procmacros::doc_replace] - /// Listen for the given interrupts + /// Listens for the given interrupts. /// - /// ## Example + /// # Examples /// /// **Note**: In practice a proper serial terminal should be used - /// to connect to the board (espflash won't work) + /// to connect to the board (espflash will not work) /// /// ```rust, no_run /// # {before_snippet} @@ -1674,19 +1659,19 @@ impl<'d> Uart<'d, Blocking> { self.tx.uart.info().enable_listen(interrupts.into(), true) } - /// Unlisten the given interrupts + /// Unlistens from the given interrupts. #[instability::unstable] pub fn unlisten(&mut self, interrupts: impl Into>) { self.tx.uart.info().enable_listen(interrupts.into(), false) } - /// Gets asserted interrupts + /// Returns the asserted interrupts. #[instability::unstable] pub fn interrupts(&mut self) -> EnumSet { self.tx.uart.info().interrupts() } - /// Resets asserted interrupts + /// Resets asserted interrupts. #[instability::unstable] pub fn clear_interrupts(&mut self, interrupts: EnumSet) { self.tx.uart.info().clear_interrupts(interrupts) @@ -1704,8 +1689,8 @@ impl<'d> Uart<'d, Blocking> { /// Waits for a break condition to be detected with a timeout. /// /// This is a blocking function that will check for a break condition up to - /// the specified timeout. Returns `true` if a break was detected, `false` if - /// the timeout elapsed. After successful detection, the break interrupt flag + /// the specified timeout. Returns whether a break was detected before the + /// timeout expired. After successful detection, the break interrupt flag /// is automatically cleared. /// /// ## Arguments @@ -1729,23 +1714,19 @@ impl<'d> Uart<'d, Async> { } #[procmacros::doc_replace] - /// Write data into the TX buffer. + /// Writes data into the TX buffer. /// - /// This function writes the provided buffer `bytes` into the UART transmit - /// buffer. If the buffer is full, the function waits asynchronously for - /// space in the buffer to become available. + /// Writes the provided buffer `bytes` into the UART transmit buffer. If the + /// buffer is full, waits asynchronously for space in the buffer to become + /// available. /// - /// The function returns the number of bytes written into the buffer. This - /// may be less than the length of the buffer. + /// Returns the number of bytes written into the buffer. This may be less + /// than the length of the buffer. /// - /// Upon an error, the function returns immediately and the contents of the - /// internal FIFO are not modified. + /// Upon an error, returns immediately and the contents of the internal FIFO + /// are not modified. /// - /// ## Cancellation - /// - /// This function is cancellation safe. - /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1759,6 +1740,10 @@ impl<'d> Uart<'d, Async> { /// uart.write_async(&MESSAGE).await?; /// # {after_snippet} /// ``` + /// + /// # Cancellation Safety + /// + /// Cancellation safe. pub async fn write_async(&mut self, words: &[u8]) -> Result { self.tx.write_async(words).await } @@ -1766,15 +1751,11 @@ impl<'d> Uart<'d, Async> { #[procmacros::doc_replace] /// Asynchronously flushes the UART transmit buffer. /// - /// This function ensures that all pending data in the transmit FIFO has - /// been sent over the UART. If the FIFO contains data, it waits for the - /// transmission to complete before returning. + /// Ensures that all pending data in the transmit FIFO has been sent over the + /// UART. If the FIFO contains data, waits for the transmission to complete + /// before returning. /// - /// ## Cancellation - /// - /// This function is cancellation safe. - /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1789,31 +1770,31 @@ impl<'d> Uart<'d, Async> { /// uart.flush_async().await?; /// # {after_snippet} /// ``` + /// + /// # Cancellation Safety + /// + /// Cancellation safe. pub async fn flush_async(&mut self) -> Result<(), TxError> { self.tx.flush_async().await } #[procmacros::doc_replace] - /// Read data asynchronously. + /// Reads data asynchronously. /// - /// This function reads data from the UART receive buffer into the - /// provided buffer. If the buffer is empty, the function waits - /// asynchronously for data to become available, or for an error to occur. + /// Reads data from the UART receive buffer into the provided buffer. If the + /// buffer is empty, waits asynchronously for data to become available, or for + /// an error to occur. /// - /// The function returns the number of bytes read into the buffer. This may - /// be less than the length of the buffer. + /// Returns the number of bytes read into the buffer. This may be less than + /// the length of the buffer. /// - /// Note that this function may ignore the `rx_fifo_full_threshold` setting - /// to ensure that it does not wait for more data than the buffer can hold. + /// May ignore the `rx_fifo_full_threshold` setting to ensure that it does not + /// wait for more data than the buffer can hold. /// - /// Upon an error, the function returns immediately and the contents of the - /// internal FIFO are not modified. + /// Upon an error, returns immediately and the contents of the internal FIFO + /// are not modified. /// - /// ## Cancellation - /// - /// This function is cancellation safe. - /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1831,24 +1812,28 @@ impl<'d> Uart<'d, Async> { /// uart.read_async(&mut buf[..]).await?; /// # {after_snippet} /// ``` + /// + /// # Cancellation Safety + /// + /// Cancellation safe. pub async fn read_async(&mut self, buf: &mut [u8]) -> Result { self.rx.read_async(buf).await } - /// Fill buffer asynchronously. + /// Fills buffer asynchronously. /// - /// This function reads data from the UART receive buffer into the - /// provided buffer. If the buffer is empty, the function waits - /// asynchronously for data to become available, or for an error to occur. + /// Reads data from the UART receive buffer into the provided buffer. If the + /// buffer is empty, waits asynchronously for data to become available, or for + /// an error to occur. /// - /// Note that this function may ignore the `rx_fifo_full_threshold` setting - /// to ensure that it does not wait for more data than the buffer can hold. + /// May ignore the `rx_fifo_full_threshold` setting to ensure that it does not + /// wait for more data than the buffer can hold. /// - /// ## Cancellation + /// # Cancellation Safety /// - /// This function is **not** cancellation safe. If the future is dropped - /// before it resolves, or if an error occurs during the read operation, - /// previously read data may be lost. + /// **Not** cancellation safe. If the future is dropped before it resolves, or + /// if an error occurs during the read operation, previously read data may be + /// lost. #[instability::unstable] pub async fn read_exact_async(&mut self, buf: &mut [u8]) -> Result<(), RxError> { self.rx.read_exact_async(buf).await @@ -1869,7 +1854,7 @@ impl<'d> Uart<'d, Async> { /// Duration is in bits, the time it takes to transfer one bit at the /// current baud rate. /// - /// This function restores the original TX line state after the break signal is sent, even if + /// Restores the original TX line state after the break signal is sent, even if /// the future is cancelled. #[instability::unstable] pub async fn send_break_async(&mut self, delay: &mut D, bits: u32) { @@ -1909,16 +1894,15 @@ where Dm: DriverMode, { #[procmacros::doc_replace] - /// Assign the RX pin for UART instance. + /// Assigns the RX pin for UART instance. /// /// Sets the specified pin to input and connects it to the UART RX signal. /// - /// Note: when you listen for the output of the UART peripheral, you should - /// configure the driver side (i.e. the TX pin), or ensure that the line is - /// initially high, to avoid receiving a non-data byte caused by an - /// initial low signal level. + /// When listening for the output of the UART peripheral, configure the driver + /// side (the TX pin), or ensure that the line is initially high, to avoid + /// receiving a non-data byte caused by an initial low signal level. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1933,12 +1917,12 @@ where } #[procmacros::doc_replace] - /// Assign the TX pin for UART instance. + /// Assigns the TX pin for UART instance. /// /// Sets the specified pin to push-pull output and connects it to the UART /// TX signal. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1953,9 +1937,9 @@ where } #[procmacros::doc_replace] - /// Configure CTS pin + /// Configures CTS pin. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -1972,9 +1956,9 @@ where } #[procmacros::doc_replace] - /// Configure RTS pin + /// Configures RTS pin. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -2002,7 +1986,7 @@ where /// will not block. Otherwise, the functions will not return until the buffer is /// ready. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -2027,19 +2011,13 @@ where #[procmacros::doc_replace] /// Writes bytes. /// - /// This function writes data to the internal TX FIFO of the UART - /// peripheral. The data is then transmitted over the UART TX line. + /// Writes data to the internal TX FIFO of the UART peripheral. The data is + /// then transmitted over the UART TX line. /// - /// The function returns the number of bytes written to the FIFO. This may - /// be less than the length of the provided data. The function may only - /// return 0 if the provided data is empty. + /// Returns the number of bytes written to the FIFO. This may be less than the + /// length of the provided data. Returns 0 only if the provided data is empty. /// - /// ## Errors - /// - /// This function returns a [`TxError`] if an error occurred during the - /// write operation. - /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -2050,14 +2028,18 @@ where /// uart.write(&MESSAGE)?; /// # {after_snippet} /// ``` + /// + /// # Errors + /// + /// [`TxError`] when an error occurred during the write operation pub fn write(&mut self, data: &[u8]) -> Result { self.tx.write(data) } #[procmacros::doc_replace] - /// Flush the transmit buffer of the UART + /// Flushes the transmit buffer of the UART. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -2073,7 +2055,7 @@ where self.tx.flush() } - /// Sends a break signal for a specified duration + /// Sends a break signal for a specified duration. #[instability::unstable] pub fn send_break(&mut self, bits: u32) { self.tx.send_break(bits) @@ -2088,7 +2070,7 @@ where /// Data that does not get stored due to an error will be lost and does not count /// towards the number of bytes in the receive buffer. // TODO: once we add support for UART_ERR_WR_MASK it needs to be documented here. - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -2125,27 +2107,18 @@ where } #[procmacros::doc_replace] - /// Read received bytes. + /// Reads received bytes. /// /// The UART hardware continuously receives bytes and stores them in the RX - /// FIFO. This function reads the bytes from the RX FIFO and returns - /// them in the provided buffer. If the hardware buffer is empty, this - /// function will block until data is available. The [`Self::read_ready`] - /// function can be used to check if data is available without blocking. - /// - /// The function returns the number of bytes read into the buffer. This may - /// be less than the length of the buffer. This function only returns 0 - /// if the provided buffer is empty. - /// - /// ## Errors - /// - /// This function returns an [`RxError`] if a reported error occurred since - /// the last check for errors. + /// FIFO. Reads the bytes from the RX FIFO and returns them in the provided + /// buffer. If the hardware buffer is empty, blocks until data is available. + /// [`Self::read_ready`] can be used to check if data is available without + /// blocking. /// - /// If the error occurred before this function was called, the contents of - /// the FIFO are not modified. + /// Returns the number of bytes read into the buffer. This may be less than + /// the length of the buffer. Returns 0 only if the provided buffer is empty. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -2161,19 +2134,27 @@ where /// /// # {after_snippet} /// ``` + /// + /// # Errors + /// + /// [`RxError`] when a reported error occurred since + /// the last check for errors. + /// + /// If the error occurred before this function was called, the contents of + /// the FIFO are not modified. pub fn read(&mut self, buf: &mut [u8]) -> Result { self.rx.read(buf) } #[procmacros::doc_replace] - /// Change the configuration. + /// Changes the configuration. /// - /// ## Errors + /// Do not call this function while a transmission is in progress. The function discards + /// the data that the transmitter did not send yet, and the TX line goes low for a short + /// time. A receiver reports that pulse as an error. Call [`Self::flush`] first, to let + /// the transmitter send the remaining data. /// - /// This function returns a [`ConfigError`] if the configuration is not - /// supported by the hardware. - /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -2183,6 +2164,10 @@ where /// uart.apply_config(&Config::default().with_baudrate(19_200))?; /// # {after_snippet} /// ``` + /// + /// # Errors + /// + /// [`ConfigError`] when the configuration is not supported by the hardware pub fn apply_config(&mut self, config: &Config) -> Result<(), ConfigError> { // Must apply the common settings first, as `rx.apply_config` reads back symbol // size. @@ -2199,8 +2184,8 @@ where /// /// # Errors /// - /// Returns [`WakeConfigError::NotAWakeupSource`] if this UART instance cannot wake the chip, - /// and [`WakeConfigError::EdgeCountUnsupported`] if the hardware cannot count the requested + /// [`WakeConfigError::NotAWakeupSource`] when this UART instance cannot wake the chip, + /// and [`WakeConfigError::EdgeCountUnsupported`] when the hardware cannot count the requested /// number of edges. #[cfg(sleep_driver_supported)] #[instability::unstable] @@ -2216,12 +2201,12 @@ where } #[procmacros::doc_replace] - /// Split the UART into a transmitter and receiver + /// Splits the UART into a transmitter and receiver. /// /// This is particularly useful when having two tasks correlating to /// transmitting and receiving. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -2254,7 +2239,7 @@ where /// This is particularly useful when running separate transmit and receive /// futures concurrently. /// - /// ## Example + /// # Examples /// /// ```rust, no_run /// # {before_snippet} @@ -2288,18 +2273,17 @@ where self.rx.check_for_errors() } - /// Read already received bytes. + /// Reads already received bytes. /// - /// This function reads the already received bytes from the FIFO into the - /// provided buffer. The function does not wait for the FIFO to actually - /// contain any bytes. + /// Reads the already received bytes from the FIFO into the provided buffer. + /// Does not wait for the FIFO to actually contain any bytes. /// - /// The function returns the number of bytes read into the buffer. This may - /// be less than the length of the buffer, and it may also be 0. + /// Returns the number of bytes read into the buffer. This may be less than + /// the length of the buffer, and it may also be 0. /// - /// ## Errors + /// # Errors /// - /// This function returns an [`RxError`] if a reported error occurred since + /// [`RxError`] when a reported error occurred since /// the last check for errors. /// /// If the error occurred before this function was called, the contents of @@ -2309,7 +2293,7 @@ where self.rx.read_buffered(buf) } - /// Configures the AT-CMD detection settings + /// Configures the AT-CMD detection settings. #[instability::unstable] pub fn set_at_cmd(&mut self, config: AtCmdConfig) { #[cfg(uart_has_sclk_enable)] @@ -2349,6 +2333,8 @@ where self.rx.disable_rx_interrupts(); self.tx.disable_tx_interrupts(); + enable_register_sync(self.regs()); + // Applying config also resets Tx/Rx FIFOs self.apply_config(&config)?; @@ -2370,15 +2356,15 @@ where } } -/// UART Tx or Rx Error +/// UART Tx or Rx Error. #[instability::unstable] #[derive(Debug, Clone, Copy, PartialEq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[non_exhaustive] pub enum IoError { - /// UART TX error + /// UART TX error. Tx(TxError), - /// UART RX error + /// UART RX error. Rx(RxError), } diff --git a/esp-hal/src/uart/uhci.rs b/esp-hal/src/uart/uhci.rs index d07b258e9df..b18974016fd 100644 --- a/esp-hal/src/uart/uhci.rs +++ b/esp-hal/src/uart/uhci.rs @@ -143,7 +143,7 @@ crate::any_peripheral! { } impl AnyUhci<'_> { - /// Opens the enum into the peripheral below + /// Returns a reference to the UHCI register block. fn register_block(&self) -> &uhci0::RegisterBlock { any::delegate!(self, uhci => { uhci.register_block() }) } @@ -343,12 +343,12 @@ where } } - /// Sets the config the the consumed UART + /// Sets the configuration of the consumed UART. pub fn set_uart_config(&mut self, uart_config: &uart::Config) -> Result<(), uart::ConfigError> { self.uart.set_config(uart_config) } - /// Split the Uhci into UhciRx and UhciTx + /// Splits the Uhci into UhciRx and UhciTx. pub fn split(self) -> (UhciRx<'d, Dm>, UhciTx<'d, Dm>) { let (uart_rx, uart_tx) = self.uart.split(); ( @@ -367,13 +367,13 @@ where ) } - /// Sets the config to the UHCI peripheral, Rx part + /// Sets the config to the UHCI peripheral, Rx part. pub fn apply_rx_config(&mut self, config: &RxConfig) -> Result<(), ConfigError> { let reg = self.uhci_per.register_block(); config.apply_config(reg) } - /// Sets the config to the UHCI peripheral, Tx part + /// Sets the config to the UHCI peripheral, Tx part. pub fn apply_tx_config(&mut self, config: &TxConfig) -> Result<(), ConfigError> { let reg = self.uhci_per.register_block(); config.apply_config(reg) @@ -381,7 +381,7 @@ where } impl<'d> Uhci<'d, Blocking> { - /// Creates a new instance of UHCI + /// Creates a new instance of UHCI. pub fn new( uart: Uart<'d, Blocking>, uhci: peripherals::UHCI0<'static>, @@ -403,7 +403,7 @@ impl<'d> Uhci<'d, Blocking> { uhci } - /// Create a new instance in [crate::Async] mode. + /// Reconfigures the driver to operate in [`Async`] mode. pub fn into_async(self) -> Uhci<'d, Async> { Uhci { uart: self.uart.into_async(), @@ -415,7 +415,7 @@ impl<'d> Uhci<'d, Blocking> { } impl<'d> Uhci<'d, Async> { - /// Create a new instance in [crate::Blocking] mode. + /// Reconfigures the driver to operate in [`Blocking`] mode. pub fn into_blocking(self) -> Uhci<'d, Blocking> { Uhci { uart: self.uart.into_blocking(), @@ -426,14 +426,14 @@ impl<'d> Uhci<'d, Async> { } } -/// Splitted Uhci structs, Tx part for sending data +/// Split Uhci structs, Tx part for sending data pub struct UhciTx<'d, Dm> where Dm: DriverMode, { - /// Internal UHCI struct. Use it to configure the UHCI peripheral + /// Internal UHCI driver used to configure the UHCI peripheral. uhci_per: AnyUhci<'static>, - /// Tx of the used uart. You can configure it by accessing the value + /// UART TX handle used by this UHCI instance. pub uart_tx: UartTx<'d, Dm>, channel_tx: ChannelTx>, // TODO: devices with UHCI1 need the non-generic guard @@ -444,7 +444,7 @@ impl<'d, Dm> UhciTx<'d, Dm> where Dm: DriverMode, { - /// Starts the write DMA transfer and returns the instance of UhciDmaTxTransfer + /// Starts the write DMA transfer and returns the instance of UhciDmaTxTransfer. pub fn write( mut self, mut tx_buffer: Buf, @@ -465,21 +465,21 @@ where Ok(UhciDmaTxTransfer::new(self, tx_buffer)) } - /// Sets the config to the UHCI peripheral + /// Sets the config to the UHCI peripheral. pub fn apply_config(&mut self, config: &TxConfig) -> Result<(), ConfigError> { let reg = self.uhci_per.register_block(); config.apply_config(reg) } } -/// Splitted Uhci structs, Rx part for receiving data +/// Split Uhci structs, Rx part for receiving data pub struct UhciRx<'d, Dm> where Dm: DriverMode, { - /// Internal UHCI struct. Use it to configure the UHCI peripheral + /// Internal UHCI driver used to configure the UHCI peripheral. uhci_per: AnyUhci<'static>, - /// Rx of the used uart. You can configure it by accessing the value + /// UART RX handle used by this UHCI instance. pub uart_rx: UartRx<'d, Dm>, channel_rx: ChannelRx>, _guard: GenericPeripheralGuard<{ Peripheral::Uhci0 as u8 }>, @@ -489,7 +489,7 @@ impl<'d, Dm> UhciRx<'d, Dm> where Dm: DriverMode, { - /// Starts the read DMA transfer and returns the instance of UhciDmaRxTransfer + /// Starts the read DMA transfer and returns the instance of UhciDmaRxTransfer. pub fn read( mut self, mut rx_buffer: Buf, @@ -512,17 +512,16 @@ where } } - /// Sets the config to the UHCI peripheral + /// Sets the config to the UHCI peripheral. pub fn apply_config(&mut self, config: &RxConfig) -> Result<(), ConfigError> { let reg = self.uhci_per.register_block(); config.apply_config(reg) } } -/// A structure representing a DMA transfer for UHCI/UART. +/// A structure representing a DMA transfer for UHCI or UART. /// -/// This structure holds references to the UHCI instance, DMA buffers, and -/// transfer status. +/// Holds references to the UHCI instance, DMA buffers, and transfer status. pub struct UhciDmaTxTransfer<'d, Dm, Buf> where Dm: DriverMode, @@ -544,7 +543,7 @@ impl<'d, Buf: DmaTxBuffer, Dm: DriverMode> UhciDmaTxTransfer<'d, Dm, Buf> { } } - /// Returns true when [Self::wait] will not block. + /// Returns whether [`Self::wait`] will not block. pub fn is_done(&self) -> bool { self.uhci.channel_tx.is_done() } @@ -565,7 +564,7 @@ impl<'d, Buf: DmaTxBuffer, Dm: DriverMode> UhciDmaTxTransfer<'d, Dm, Buf> { /// Waits for the DMA transfer to complete. /// - /// This method blocks until the transfer is finished and returns the + /// Blocks until the transfer is finished and returns the /// `Uhci` instance and the associated buffer. pub fn wait(mut self) -> (Result<(), Error>, UhciTx<'d, Dm>, Buf::Final) { if let Err(err) = self.saved_err { @@ -603,7 +602,8 @@ impl<'d, Buf: DmaTxBuffer, Dm: DriverMode> UhciDmaTxTransfer<'d, Dm, Buf> { } impl<'d, Buf: DmaTxBuffer> UhciDmaTxTransfer<'d, Async, Buf> { - /// Waits for the DMA transfer to complete, but async. After that, you still need to wait() + /// Waits for the DMA transfer to complete asynchronously. After that, + /// [`Self::wait`] must still be called. pub async fn wait_for_done(&mut self) { // Workaround for an issue when it doesn't actually wait for the transfer to complete. I'm // lost at this point, this is the only thing that worked @@ -652,10 +652,9 @@ where } } -/// A structure representing a DMA transfer for UHCI/UART. +/// A structure representing a DMA transfer for UHCI or UART. /// -/// This structure holds references to the UHCI instance, DMA buffers, and -/// transfer status. +/// Holds references to the UHCI instance, DMA buffers, and transfer status. pub struct UhciDmaRxTransfer<'d, Dm, Buf> where Dm: DriverMode, @@ -677,7 +676,7 @@ impl<'d, Buf: DmaRxBuffer, Dm: DriverMode> UhciDmaRxTransfer<'d, Dm, Buf> { } } - /// Returns true when [Self::wait] will not block. + /// Returns whether [`Self::wait`] will not block. pub fn is_done(&self) -> bool { self.uhci.channel_rx.is_done() } @@ -698,7 +697,7 @@ impl<'d, Buf: DmaRxBuffer, Dm: DriverMode> UhciDmaRxTransfer<'d, Dm, Buf> { /// Waits for the DMA transfer to complete. /// - /// This method blocks until the transfer is finished and returns the + /// Blocks until the transfer is finished and returns the /// `Uhci` instance and the associated buffer. pub fn wait(mut self) -> (Result<(), Error>, UhciRx<'d, Dm>, Buf::Final) { if let Err(err) = self.saved_err { @@ -727,7 +726,8 @@ impl<'d, Buf: DmaRxBuffer, Dm: DriverMode> UhciDmaRxTransfer<'d, Dm, Buf> { } impl<'d, Buf: DmaRxBuffer> UhciDmaRxTransfer<'d, Async, Buf> { - /// Waits for the DMA transfer to complete, but async. After that, you still need to wait() + /// Waits for the DMA transfer to complete asynchronously. After that, + /// [`Self::wait`] must still be called. pub async fn wait_for_done(&mut self) { let res = DmaRxFuture::new(&mut self.uhci.channel_rx).await; if let Err(err) = res { diff --git a/esp-hal/src/usb/usb_serial_jtag.rs b/esp-hal/src/usb/usb_serial_jtag.rs index e8a23b34333..4e89f7569d4 100644 --- a/esp-hal/src/usb/usb_serial_jtag.rs +++ b/esp-hal/src/usb/usb_serial_jtag.rs @@ -174,7 +174,7 @@ where self.peripheral.register_block() } - /// Write data to the serial output in chunks of up to 64 bytes + /// Writes data to the serial output in chunks of up to 64 bytes. pub fn write(&mut self, data: &[u8]) -> Result<(), Error> { for chunk in data.chunks(64) { for byte in chunk { @@ -193,8 +193,8 @@ where Ok(()) } - /// Write data to the serial output in a non-blocking manner - /// Requires manual flushing (automatically flushed every 64 bytes) + /// Writes data to the serial output in a non-blocking manner. + /// Requires manual flushing (automatically flushed every 64 bytes). pub fn write_byte_nb(&mut self, word: u8) -> nb::Result<(), Error> { if self .regs() @@ -212,7 +212,7 @@ where } } - /// Flush the output FIFO and block until it has been sent + /// Flushes the output FIFO and blocks until it has been sent. pub fn flush_tx(&mut self) -> Result<(), Error> { self.regs().ep1_conf().modify(|_, w| w.wr_done().set_bit()); @@ -224,7 +224,7 @@ where Ok(()) } - /// Flush the output FIFO but don't block if it isn't ready immediately + /// Flushes the output FIFO but does not block if it is not ready immediately. pub fn flush_tx_nb(&mut self) -> nb::Result<(), Error> { self.regs().ep1_conf().modify(|_, w| w.wr_done().set_bit()); @@ -253,7 +253,7 @@ where self.peripheral.register_block() } - /// Read a byte from the UART in a non-blocking manner + /// Reads a byte from USB Serial/JTAG in a non-blocking manner. pub fn read_byte(&mut self) -> nb::Result { // Check if there are any bytes to read if self @@ -271,7 +271,7 @@ where } } - /// Read all available bytes from the RX FIFO into the provided buffer and + /// Reads all available bytes from the RX FIFO into the provided buffer and /// returns the number of read bytes. Never blocks. May stop early if the /// number of bytes in the FIFO is larger than `buf`. pub fn drain_rx_fifo(&mut self, buf: &mut [u8]) -> usize { @@ -286,21 +286,21 @@ where count } - /// Listen for RX-PACKET-RECV interrupts + /// Listens for RX-PACKET-RECV interrupts. pub fn listen_rx_packet_recv_interrupt(&mut self) { self.regs() .int_ena() .modify(|_, w| w.serial_out_recv_pkt().set_bit()); } - /// Stop listening for RX-PACKET-RECV interrupts + /// Stops listening for RX-PACKET-RECV interrupts. pub fn unlisten_rx_packet_recv_interrupt(&mut self) { self.regs() .int_ena() .modify(|_, w| w.serial_out_recv_pkt().clear_bit()); } - /// Checks if RX-PACKET-RECV interrupt is set + /// Returns whether RX-PACKET-RECV interrupt is set. pub fn rx_packet_recv_interrupt_set(&mut self) -> bool { self.regs() .int_st() @@ -309,7 +309,7 @@ where .bit_is_set() } - /// Reset RX-PACKET-RECV interrupt + /// Resets RX-PACKET-RECV interrupt. pub fn reset_rx_packet_recv_interrupt(&mut self) { self.regs() .int_clr() @@ -318,12 +318,12 @@ where } impl<'d> UsbSerialJtag<'d, Blocking> { - /// Create a new USB serial/JTAG instance with defaults + /// Creates a new USB serial/JTAG instance with defaults. pub fn new(usb_device: USB_DEVICE<'d>) -> Self { Self::new_inner(usb_device) } - /// Reconfigure the USB Serial JTAG peripheral to operate in asynchronous + /// Reconfigures the USB Serial JTAG peripheral to operate in asynchronous /// mode. pub fn into_async(mut self) -> UsbSerialJtag<'d, Async> { self.set_interrupt_handler(async_interrupt_handler); @@ -390,63 +390,62 @@ where tx: UsbSerialJtagTx::new_inner(usb_device), } } - /// Split the USB Serial JTAG peripheral into a transmitter and receiver, + /// Splits the USB Serial JTAG peripheral into a transmitter and receiver, /// which is particularly useful when having two tasks correlating to /// transmitting and receiving. pub fn split(self) -> (UsbSerialJtagRx<'d, Dm>, UsbSerialJtagTx<'d, Dm>) { (self.rx, self.tx) } - /// Write data to the serial output in chunks of up to 64 bytes + /// Writes data to the serial output in chunks of up to 64 bytes. pub fn write(&mut self, data: &[u8]) -> Result<(), Error> { self.tx.write(data) } - /// Write data to the serial output in a non-blocking manner - /// Requires manual flushing (automatically flushed every 64 bytes) + /// Writes data to the serial output in a non-blocking manner. + /// Requires manual flushing (automatically flushed every 64 bytes). pub fn write_byte_nb(&mut self, word: u8) -> nb::Result<(), Error> { self.tx.write_byte_nb(word) } - /// Flush the output FIFO and block until it has been sent + /// Flushes the output FIFO and blocks until it has been sent. pub fn flush_tx(&mut self) -> Result<(), Error> { self.tx.flush_tx() } - /// Flush the output FIFO but don't block if it isn't ready immediately + /// Flushes the output FIFO but does not block if it is not ready immediately. pub fn flush_tx_nb(&mut self) -> nb::Result<(), Error> { self.tx.flush_tx_nb() } - /// Read a single byte but don't block if it isn't ready immediately + /// Reads a single byte but does not block if it is not ready immediately. pub fn read_byte(&mut self) -> nb::Result { self.rx.read_byte() } - /// Listen for RX-PACKET-RECV interrupts + /// Listens for RX-PACKET-RECV interrupts. pub fn listen_rx_packet_recv_interrupt(&mut self) { self.rx.listen_rx_packet_recv_interrupt() } - /// Stop listening for RX-PACKET-RECV interrupts + /// Stops listening for RX-PACKET-RECV interrupts. pub fn unlisten_rx_packet_recv_interrupt(&mut self) { self.rx.unlisten_rx_packet_recv_interrupt() } - /// Checks if RX-PACKET-RECV interrupt is set + /// Returns whether RX-PACKET-RECV interrupt is set. pub fn rx_packet_recv_interrupt_set(&mut self) -> bool { self.rx.rx_packet_recv_interrupt_set() } - /// Reset RX-PACKET-RECV interrupt + /// Resets RX-PACKET-RECV interrupt. pub fn reset_rx_packet_recv_interrupt(&mut self) { self.rx.reset_rx_packet_recv_interrupt() } /// Registers an interrupt handler for the USB Serial JTAG peripheral. /// - /// Note that this will replace any previously registered interrupt - /// handlers. + /// Replaces any previously registered interrupt handlers. #[instability::unstable] pub fn set_interrupt_handler(&mut self, handler: crate::interrupt::InterruptHandler) { self.rx.peripheral.disable_peri_interrupt_on_all_cores(); @@ -457,10 +456,10 @@ where /// USB Serial/JTAG peripheral instance #[doc(hidden)] pub trait Instance: crate::private::Sealed { - /// Get a reference to the peripheral's underlying register block + /// Returns a reference to the peripheral's underlying register block. fn register_block(&self) -> &RegisterBlock; - /// Disable all transmit interrupts for the peripheral + /// Disables all transmit interrupts for the peripheral. fn disable_tx_interrupts(&self) { self.register_block() .int_ena() @@ -471,7 +470,7 @@ pub trait Instance: crate::private::Sealed { .write(|w| w.serial_in_empty().clear_bit_by_one()); } - /// Disable all receive interrupts for the peripheral + /// Disables all receive interrupts for the peripheral. fn disable_rx_interrupts(&self) { self.register_block() .int_ena() @@ -806,7 +805,7 @@ impl core::future::Future for UsbSerialJtagReadFuture<'_> { } impl<'d> UsbSerialJtag<'d, Async> { - /// Reconfigure the USB Serial JTAG peripheral to operate in blocking + /// Reconfigures the USB Serial JTAG peripheral to operate in blocking /// mode. pub fn into_blocking(self) -> UsbSerialJtag<'d, Blocking> { self.rx.peripheral.disable_peri_interrupt_on_all_cores(); diff --git a/esp-hal/src/work_queue.rs b/esp-hal/src/work_queue.rs index d353b1d34c0..350cb161492 100644 --- a/esp-hal/src/work_queue.rs +++ b/esp-hal/src/work_queue.rs @@ -17,7 +17,7 @@ use core::{future::poll_fn, marker::PhantomData, ptr::NonNull, task::Context}; use embassy_sync::waitqueue::WakerRegistration; use esp_sync::NonReentrantMutex; -/// Queue driver operations. +/// Queues driver operations. /// /// Functions in this VTable are provided by drivers that consume work items. /// These functions may be called both in the context of the queue frontends and drivers. @@ -28,7 +28,7 @@ pub(crate) struct VTable { /// accepted. If there is no driver currently processing the queue, this function will /// return None to prevent removing the work item from the queue. /// - /// This function should be as short as possible. + /// Should be as short as possible. pub(crate) post: fn(NonNull<()>, &mut T) -> Option, /// Polls the status of the current work item. @@ -36,17 +36,17 @@ pub(crate) struct VTable { /// The work queue ensures that the item passed here has been first passed to the driver by /// `post`. /// - /// This function should be as short as possible. + /// Should be as short as possible. pub(crate) poll: fn(NonNull<()>, &mut T) -> Poll, /// Attempts to abort processing a work item. /// - /// This function should be as short as possible. + /// Should be as short as possible. pub(crate) cancel: fn(NonNull<()>, &mut T), /// Called when the driver may be stopped. /// - /// This function should be as short as possible. + /// Should be as short as possible. pub(crate) stop: fn(NonNull<()>), } @@ -112,7 +112,7 @@ impl Inner { /// Runs one processing iteration. /// - /// This function enqueues a new work item or polls the status of the currently processed one. + /// Enqueues a new work item or polls the status of the currently processed one. /// Returns whether the function should be re-called by the caller. fn process(&mut self) -> bool { if let Some(mut current) = self.current { @@ -142,7 +142,7 @@ impl Inner { /// Retrieves the next work queue item and sends it to the driver. /// - /// Returns true if the queue needs to be polled again. + /// Returns whether the queue needs to be polled again. // Note: even if the queue itself may be implemented lock-free, dequeuing and posting to the // driver must be done atomically to ensure that the queue can be processed fully by any of // the frontends polling it. @@ -202,10 +202,10 @@ impl Inner { /// If the work item is currently being processed, this function notifies the driver. Otherwise, /// it tries to remove the pointer from the work queue. /// - /// The function returns true when the item was immediately cancelled. + /// Returns whether the item was immediately cancelled. /// - /// This function is not `unsafe` because it only dereferences `work_item` if the function has - /// determined that the item belongs to this queue. + /// Not `unsafe` because it only dereferences `work_item` if the item belongs + /// to this queue. fn cancel(&mut self, mut work_item: NonNull>) -> bool { if self.current == Some(work_item) { // Cancelling an in-progress item is more complicated than plucking it from the @@ -241,11 +241,12 @@ impl Inner { /// Removes the item from the queue. /// - /// Returns `true` if the work item was successfully removed, `false` if the work item was not - /// found in the queue. + /// Returns whether the work item was successfully removed. /// - /// This function is not `unsafe` because it does not dereference `ptr`, so it does not matter - /// that `ptr` may belong to a different work queue. + /// Returns `false` if the work item was not found in the queue. + /// + /// Not `unsafe` because it does not dereference `ptr`, so it does not matter + /// that `ptr` may belong to a different work queue fn remove(&mut self, ptr: NonNull>) -> bool { // Walk the queue to find `ptr`. let mut prev = None; @@ -298,7 +299,7 @@ impl Inner { /// Decreases the suspend counter. /// /// When it reaches 0, this function wakes async tasks that poll the queue. They need to be - /// waken to ensure that their items don't end up stuck. Blocking pollers will eventually end up + /// waken to ensure that their items do not end up stuck. Blocking pollers eventually end up /// looping when their turn comes. fn resume(&mut self) { self.suspend_count -= 1; @@ -397,7 +398,7 @@ impl WorkQueue { /// Polls the queue once. /// - /// Returns true if the queue needs to be polled again. + /// Returns whether the queue needs to be polled again. #[allow(unused)] pub fn process(&self) -> bool { self.inner.with(|inner| inner.process()) @@ -405,7 +406,7 @@ impl WorkQueue { /// Polls the queue once and returns the status of the given work item. /// - /// ## Safety + /// # Safety /// /// The caller must ensure that `item` belongs to the polled queue. An item belongs to the /// **last queue it was enqueued in**, even if the item is no longer in the queue's linked @@ -424,7 +425,7 @@ impl WorkQueue { /// Schedules the work item to be cancelled. /// - /// The function returns true when the item was immediately cancelled. If the function returns + /// Returns whether the item was immediately cancelled. If it returns /// `false`, the item will need to be polled until its status becomes [`Poll::Ready`]. /// /// The work item should not be assumed to be immediately cancelled. Polling its handle @@ -468,7 +469,7 @@ impl Clone for WorkItem { impl WorkItem { /// Completes the work item. /// - /// This function is intended to be called from the underlying drivers. + /// Intended to be called from the underlying drivers. pub fn complete(&mut self, status: Status) { self.status = Poll::Ready(status); self.waker.wake(); @@ -476,7 +477,7 @@ impl WorkItem { /// Prepares a work item to be enqueued. /// - /// # Safety: + /// # Safety /// /// The caller must ensure the reference is not used again while the pointer returned by this /// function is in use. @@ -515,7 +516,7 @@ impl Poll { /// A reference to a posted [`WorkItem`]. /// -/// This struct ensures that the work item is valid until the item is processed or is removed from +/// Ensures that the work item is valid until the item is processed or is removed from /// the work queue. /// /// Dropping the handle cancels the work item, but may block for some time if the work item is @@ -555,7 +556,7 @@ impl<'t, T: Sync + Send> Handle<'t, T> { /// Polls the work item to completion, by busy-looping. /// - /// This function returns immediately if `poll` returns `true`. + /// Returns immediately if `poll` returns `true`. #[inline] pub fn wait_blocking(mut self) -> Status { loop { @@ -738,7 +739,7 @@ impl WorkQueueFrontend { queue.post_work(&mut self.work_item) } - /// Creates a Handle for a work item that does not need to be put into the queue. + /// Creates a new [`Handle`] for a work item that does not need to be put into the queue. #[cfg(sha_driver_supported)] pub fn post_completed<'t>(&'t mut self, queue: &'t WorkQueue) -> Handle<'t, T> { Handle::from_completed_work_item(queue, &mut self.work_item) diff --git a/esp-lp-hal/Cargo.toml b/esp-lp-hal/Cargo.toml index 754d03ab0f9..c436e7d4e21 100644 --- a/esp-lp-hal/Cargo.toml +++ b/esp-lp-hal/Cargo.toml @@ -46,7 +46,7 @@ embedded-io-07 = { package = "embedded-io", version = "0.7", optional = true nb = { version = "1.1.0", optional = true } procmacros = { version = "0.23.0", package = "esp-hal-procmacros", path = "../esp-hal-procmacros" } riscv = { version = "0.15", features = ["critical-section-single-hart"] } -esp-metadata-generated = { version = "0.5.0", path = "../esp-metadata-generated" } +esp-metadata-generated = { version = "0.6.0", path = "../esp-metadata-generated" } esp32c6-lp = { version = "0.3.0", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs", rev = "fc3e6d4" } esp32s2-ulp = { version = "0.3.0", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs", rev = "fc3e6d4" } esp32s3-ulp = { version = "0.3.0", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs", rev = "fc3e6d4" } @@ -55,7 +55,7 @@ esp32s3-ulp = { version = "0.3.0", features = ["critical-section"], option panic-halt = "0.2.0" [build-dependencies] -esp-metadata-generated = { version = "0.5.0", path = "../esp-metadata-generated", features = ["build-script"] } +esp-metadata-generated = { version = "0.6.0", path = "../esp-metadata-generated", features = ["build-script"] } [features] default = ["embedded-hal"] diff --git a/esp-lp-hal/examples/uart.rs b/esp-lp-hal/examples/uart.rs index 6b6f940d5a4..219d7fd629c 100644 --- a/esp-lp-hal/examples/uart.rs +++ b/esp-lp-hal/examples/uart.rs @@ -2,7 +2,7 @@ //! //! Uses GPIO4 for RX and GPIO5 for TX. GPIOs can't be changed. //! -//! It is neccessary to use Serial-Uart bridge connected to TX and RX to see +//! It is necessary to use Serial-Uart bridge connected to TX and RX to see //! logs from LP_UART. Make sure the LP RAM is cleared before loading the code. //% CHIP_FILTER: ulp_riscv_driver_supported && soc_has_lp_uart diff --git a/esp-lp-hal/src/gpio.rs b/esp-lp-hal/src/gpio.rs index 61a91da2a91..b15622807a1 100644 --- a/esp-lp-hal/src/gpio.rs +++ b/esp-lp-hal/src/gpio.rs @@ -106,9 +106,12 @@ impl Flex { pub fn level(&self) -> Level { cfg_select! { esp32c6 => ((unsafe { &*LpIo::PTR }.in_().read().bits() >> PIN) & 0x1 != 0).into(), - esp32s2 => ((unsafe { &*LpIo::PTR }.in_().read().gpio_in_next().bits() >> PIN) & 0x1 != 0) + esp32s2 => ((unsafe { &*LpIo::PTR }.in_().read().gpio_in_next().bits() >> PIN) & 0x1 + != 0) .into(), - esp32s3 => ((unsafe { &*LpIo::PTR }.in_().read().next().bits() >> PIN) & 0x1 != 0).into(), + esp32s3 => { + ((unsafe { &*LpIo::PTR }.in_().read().next().bits() >> PIN) & 0x1 != 0).into() + } _ => {} } } @@ -135,7 +138,9 @@ impl Flex { esp32s2 => ((unsafe { &*LpIo::PTR }.out().read().gpio_out_data().bits() >> PIN) & 0x1 != 0) .into(), - esp32s3 => ((unsafe { &*LpIo::PTR }.out().read().data().bits() >> PIN) & 0x1 != 0).into(), + esp32s3 => { + ((unsafe { &*LpIo::PTR }.out().read().data().bits() >> PIN) & 0x1 != 0).into() + } _ => {} } } diff --git a/esp-metadata-generated/Cargo.toml b/esp-metadata-generated/Cargo.toml index db64c39d05a..63c3d4d58b3 100644 --- a/esp-metadata-generated/Cargo.toml +++ b/esp-metadata-generated/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "esp-metadata-generated" -version = "0.5.0" +version = "0.6.0" edition = "2024" rust-version = "1.95.0" description = "Generated metadata for Espressif devices" @@ -11,6 +11,7 @@ license = "MIT OR Apache-2.0" [package.metadata.espressif] changelog-exempt = true chip-features-matter = true +host-features = ["build-script"] check-configs = [ { features = [] }, { features = ["build-script"] }, @@ -29,6 +30,7 @@ esp32c5 = ["_device-selected"] esp32c6 = ["_device-selected"] esp32c61 = ["_device-selected"] esp32h2 = ["_device-selected"] +esp32h4 = ["_device-selected"] esp32p4 = ["_device-selected"] esp32s2 = ["_device-selected"] esp32s3 = ["_device-selected"] diff --git a/esp-metadata-generated/src/_build_script_utils.rs b/esp-metadata-generated/src/_build_script_utils.rs index aa7d78978fb..7577e889c41 100644 --- a/esp-metadata-generated/src/_build_script_utils.rs +++ b/esp-metadata-generated/src/_build_script_utils.rs @@ -43,6 +43,7 @@ pub enum Chip { Esp32c6, Esp32c61, Esp32h2, + Esp32h4, Esp32p4, Esp32s2, Esp32s3, @@ -59,13 +60,14 @@ impl core::str::FromStr for Chip { "esp32c6" => Ok(Self::Esp32c6), "esp32c61" => Ok(Self::Esp32c61), "esp32h2" => Ok(Self::Esp32h2), + "esp32h4" => Ok(Self::Esp32h4), "esp32p4" => Ok(Self::Esp32p4), "esp32s2" => Ok(Self::Esp32s2), "esp32s3" => Ok(Self::Esp32s3), "esp32s31" => Ok(Self::Esp32s31), _ => Err(alloc::format!( "Unknown chip {s}. Possible options: esp32, esp32c2, esp32c3, esp32c5, esp32c6, \ - esp32c61, esp32h2, esp32p4, esp32s2, esp32s3, esp32s31" + esp32c61, esp32h2, esp32h4, esp32p4, esp32s2, esp32s3, esp32s31" )), } } @@ -83,6 +85,7 @@ impl Chip { ("CARGO_FEATURE_ESP32C6", Self::Esp32c6), ("CARGO_FEATURE_ESP32C61", Self::Esp32c61), ("CARGO_FEATURE_ESP32H2", Self::Esp32h2), + ("CARGO_FEATURE_ESP32H4", Self::Esp32h4), ("CARGO_FEATURE_ESP32P4", Self::Esp32p4), ("CARGO_FEATURE_ESP32S2", Self::Esp32s2), ("CARGO_FEATURE_ESP32S3", Self::Esp32s3), @@ -94,8 +97,8 @@ impl Chip { if chip.is_some() { return Err( "Expected exactly one of the following features to be enabled: esp32, \ - esp32c2, esp32c3, esp32c5, esp32c6, esp32c61, esp32h2, esp32p4, esp32s2, \ - esp32s3, esp32s31", + esp32c2, esp32c3, esp32c5, esp32c6, esp32c61, esp32h2, esp32h4, esp32p4, \ + esp32s2, esp32s3, esp32s31", ); } chip = Some(c); @@ -105,7 +108,8 @@ impl Chip { Some(chip) => Ok(chip), None => Err( "Expected exactly one of the following features to be enabled: esp32, esp32c2, \ - esp32c3, esp32c5, esp32c6, esp32c61, esp32h2, esp32p4, esp32s2, esp32s3, esp32s31", + esp32c3, esp32c5, esp32c6, esp32c61, esp32h2, esp32h4, esp32p4, esp32s2, \ + esp32s3, esp32s31", ), } } @@ -133,6 +137,7 @@ impl Chip { Self::Esp32c6 => "esp32c6", Self::Esp32c61 => "esp32c61", Self::Esp32h2 => "esp32h2", + Self::Esp32h4 => "esp32h4", Self::Esp32p4 => "esp32p4", Self::Esp32s2 => "esp32s2", Self::Esp32s3 => "esp32s3", @@ -189,6 +194,7 @@ impl Chip { Self::Esp32c6, Self::Esp32c61, Self::Esp32h2, + Self::Esp32h4, Self::Esp32p4, Self::Esp32s2, Self::Esp32s3, @@ -265,6 +271,7 @@ impl Chip { "soc_has_flash", "soc_has_psram", "soc_has_touch", + "soc_has_ipc", "soc_has_from_cpu_intr0", "soc_has_from_cpu_intr1", "soc_has_from_cpu_intr2", @@ -287,7 +294,6 @@ impl Chip { "rgb_display_driver_supported", "adc_driver_supported", "dac_driver_supported", - "temp_sensor_driver_supported", "touch_driver_supported", "ledc_driver_supported", "mcpwm_driver_supported", @@ -303,6 +309,7 @@ impl Chip { "dma_driver_supported", "interrupts_driver_supported", "mmu_driver_supported", + "flash_driver_supported", "psram_driver_supported", "rom_driver_supported", "soc_driver_supported", @@ -321,6 +328,7 @@ impl Chip { "adc_adc2", "dac_dac1", "dac_dac2", + "pcnt_PCNT", "timergroup_timg0", "timergroup_timg1", "gpio_version=\"1\"", @@ -348,8 +356,6 @@ impl Chip { "spi_master_bit_order_is_bool", "i2s_version=\"1\"", "i2s_version_is_set", - "i2s_default_clock_source=\"2\"", - "i2s_default_clock_source_is_set", "i2s_mclk_divider_bit_width=\"6\"", "i2s_mclk_divider_bit_width_is_set", "i2s_max_ws_width=\"128\"", @@ -365,7 +371,12 @@ impl Chip { "bt_controller=\"btdm\"", "wifi_mac_version=\"1\"", "wifi_csi_supported", + "wifi_has_nan", + "ethernet_rx_store_and_forward", + "ethernet_dma_burst_len=\"32\"", "phy_combo_module", + "rgb_display_output_lines=\"24\"", + "adc_line_calibration", "ledc_version=\"1\"", "ledc_channel_count=\"8\"", "soc_has_sdm_ch0", @@ -378,12 +389,17 @@ impl Chip { "soc_has_sdm_ch7", "timergroup_timg_has_timer1", "timergroup_rc_fast_calibration_is_set", + "timergroup_rc_slow_calibration_is_set", "aes_endianness_configurable", "rng_apb_cycle_wait_num=\"16\"", "rng_trng_supported", "rsa_version=\"1\"", "rsa_size_increment=\"512\"", "rsa_memory_size_bytes=\"512\"", + "sha_has_sha1", + "sha_has_sha256", + "sha_has_sha384", + "sha_has_sha512", "sleep_light_sleep", "sleep_deep_sleep", "sleep_has_wakeup_source_ext0", @@ -413,6 +429,7 @@ impl Chip { "i2s_dma_engine=\"I2S_DMA\"", "interrupts_status_registers=\"3\"", "interrupt_controller=\"xtensa\"", + "context_switch_source=\"ipc\"", "mmu_page_size=\"65536\"", "mmu_entry_num=\"256\"", "psram_extmem_origin=\"1065353216\"", @@ -421,6 +438,8 @@ impl Chip { "rom_has_md5_bsd", "soc_multi_core_enabled", "soc_cpu_mcause_mask=\"0\"", + "soc_cpu_pmp_granularity=\"4\"", + "soc_cpu_pmp_granularity_is_set", "soc_has_clock_node_xtal_clk", "soc_clock_node_xtal_clk_is_configurable", "soc_has_clock_node_pll_clk", @@ -429,6 +448,7 @@ impl Chip { "soc_clock_node_apll_clk_is_configurable", "soc_has_clock_node_rc_fast_clk", "soc_has_clock_node_pll_f160m_clk", + "soc_has_clock_node_pll_d2_clk", "soc_has_clock_node_cpu_pll_div_in", "soc_clock_node_cpu_pll_div_in_is_configurable", "soc_has_clock_node_cpu_pll_div", @@ -459,6 +479,9 @@ impl Chip { "soc_has_clock_node_xtal_div_clk", "soc_has_clock_node_rtc_slow_clk", "soc_clock_node_rtc_slow_clk_is_configurable", + "soc_has_clock_node_ble_lp_xtal_clk", + "soc_has_clock_node_ble_lp_clk", + "soc_clock_node_ble_lp_clk_is_configurable", "soc_has_clock_node_rtc_fast_clk", "soc_clock_node_rtc_fast_clk_is_configurable", "soc_has_clock_node_uart_mem_clk", @@ -476,6 +499,8 @@ impl Chip { "soc_has_clock_node_rmt_sclk", "soc_clock_node_rmt_sclk_is_configurable", "soc_has_clock_node_spi_function_clock", + "soc_has_clock_node_i2s_mclk", + "soc_clock_node_i2s_mclk_is_configurable", "has_dram_region", "has_dram2_uninit_region", "has_irom_region", @@ -545,6 +570,7 @@ impl Chip { "cargo:rustc-cfg=soc_has_flash", "cargo:rustc-cfg=soc_has_psram", "cargo:rustc-cfg=soc_has_touch", + "cargo:rustc-cfg=soc_has_ipc", "cargo:rustc-cfg=soc_has_from_cpu_intr0", "cargo:rustc-cfg=soc_has_from_cpu_intr1", "cargo:rustc-cfg=soc_has_from_cpu_intr2", @@ -567,7 +593,6 @@ impl Chip { "cargo:rustc-cfg=rgb_display_driver_supported", "cargo:rustc-cfg=adc_driver_supported", "cargo:rustc-cfg=dac_driver_supported", - "cargo:rustc-cfg=temp_sensor_driver_supported", "cargo:rustc-cfg=touch_driver_supported", "cargo:rustc-cfg=ledc_driver_supported", "cargo:rustc-cfg=mcpwm_driver_supported", @@ -583,6 +608,7 @@ impl Chip { "cargo:rustc-cfg=dma_driver_supported", "cargo:rustc-cfg=interrupts_driver_supported", "cargo:rustc-cfg=mmu_driver_supported", + "cargo:rustc-cfg=flash_driver_supported", "cargo:rustc-cfg=psram_driver_supported", "cargo:rustc-cfg=rom_driver_supported", "cargo:rustc-cfg=soc_driver_supported", @@ -601,6 +627,7 @@ impl Chip { "cargo:rustc-cfg=adc_adc2", "cargo:rustc-cfg=dac_dac1", "cargo:rustc-cfg=dac_dac2", + "cargo:rustc-cfg=pcnt_PCNT", "cargo:rustc-cfg=timergroup_timg0", "cargo:rustc-cfg=timergroup_timg1", "cargo:rustc-cfg=gpio_version=\"1\"", @@ -628,8 +655,6 @@ impl Chip { "cargo:rustc-cfg=spi_master_bit_order_is_bool", "cargo:rustc-cfg=i2s_version=\"1\"", "cargo:rustc-cfg=i2s_version_is_set", - "cargo:rustc-cfg=i2s_default_clock_source=\"2\"", - "cargo:rustc-cfg=i2s_default_clock_source_is_set", "cargo:rustc-cfg=i2s_mclk_divider_bit_width=\"6\"", "cargo:rustc-cfg=i2s_mclk_divider_bit_width_is_set", "cargo:rustc-cfg=i2s_max_ws_width=\"128\"", @@ -645,7 +670,12 @@ impl Chip { "cargo:rustc-cfg=bt_controller=\"btdm\"", "cargo:rustc-cfg=wifi_mac_version=\"1\"", "cargo:rustc-cfg=wifi_csi_supported", + "cargo:rustc-cfg=wifi_has_nan", + "cargo:rustc-cfg=ethernet_rx_store_and_forward", + "cargo:rustc-cfg=ethernet_dma_burst_len=\"32\"", "cargo:rustc-cfg=phy_combo_module", + "cargo:rustc-cfg=rgb_display_output_lines=\"24\"", + "cargo:rustc-cfg=adc_line_calibration", "cargo:rustc-cfg=ledc_version=\"1\"", "cargo:rustc-cfg=ledc_channel_count=\"8\"", "cargo:rustc-cfg=soc_has_sdm_ch0", @@ -658,12 +688,17 @@ impl Chip { "cargo:rustc-cfg=soc_has_sdm_ch7", "cargo:rustc-cfg=timergroup_timg_has_timer1", "cargo:rustc-cfg=timergroup_rc_fast_calibration_is_set", + "cargo:rustc-cfg=timergroup_rc_slow_calibration_is_set", "cargo:rustc-cfg=aes_endianness_configurable", "cargo:rustc-cfg=rng_apb_cycle_wait_num=\"16\"", "cargo:rustc-cfg=rng_trng_supported", "cargo:rustc-cfg=rsa_version=\"1\"", "cargo:rustc-cfg=rsa_size_increment=\"512\"", "cargo:rustc-cfg=rsa_memory_size_bytes=\"512\"", + "cargo:rustc-cfg=sha_has_sha1", + "cargo:rustc-cfg=sha_has_sha256", + "cargo:rustc-cfg=sha_has_sha384", + "cargo:rustc-cfg=sha_has_sha512", "cargo:rustc-cfg=sleep_light_sleep", "cargo:rustc-cfg=sleep_deep_sleep", "cargo:rustc-cfg=sleep_has_wakeup_source_ext0", @@ -693,6 +728,7 @@ impl Chip { "cargo:rustc-cfg=i2s_dma_engine=\"I2S_DMA\"", "cargo:rustc-cfg=interrupts_status_registers=\"3\"", "cargo:rustc-cfg=interrupt_controller=\"xtensa\"", + "cargo:rustc-cfg=context_switch_source=\"ipc\"", "cargo:rustc-cfg=mmu_page_size=\"65536\"", "cargo:rustc-cfg=mmu_entry_num=\"256\"", "cargo:rustc-cfg=psram_extmem_origin=\"1065353216\"", @@ -701,6 +737,8 @@ impl Chip { "cargo:rustc-cfg=rom_has_md5_bsd", "cargo:rustc-cfg=soc_multi_core_enabled", "cargo:rustc-cfg=soc_cpu_mcause_mask=\"0\"", + "cargo:rustc-cfg=soc_cpu_pmp_granularity=\"4\"", + "cargo:rustc-cfg=soc_cpu_pmp_granularity_is_set", "cargo:rustc-cfg=soc_has_clock_node_xtal_clk", "cargo:rustc-cfg=soc_clock_node_xtal_clk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_pll_clk", @@ -709,6 +747,7 @@ impl Chip { "cargo:rustc-cfg=soc_clock_node_apll_clk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_rc_fast_clk", "cargo:rustc-cfg=soc_has_clock_node_pll_f160m_clk", + "cargo:rustc-cfg=soc_has_clock_node_pll_d2_clk", "cargo:rustc-cfg=soc_has_clock_node_cpu_pll_div_in", "cargo:rustc-cfg=soc_clock_node_cpu_pll_div_in_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_cpu_pll_div", @@ -739,6 +778,9 @@ impl Chip { "cargo:rustc-cfg=soc_has_clock_node_xtal_div_clk", "cargo:rustc-cfg=soc_has_clock_node_rtc_slow_clk", "cargo:rustc-cfg=soc_clock_node_rtc_slow_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_ble_lp_xtal_clk", + "cargo:rustc-cfg=soc_has_clock_node_ble_lp_clk", + "cargo:rustc-cfg=soc_clock_node_ble_lp_clk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_rtc_fast_clk", "cargo:rustc-cfg=soc_clock_node_rtc_fast_clk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_uart_mem_clk", @@ -756,6 +798,8 @@ impl Chip { "cargo:rustc-cfg=soc_has_clock_node_rmt_sclk", "cargo:rustc-cfg=soc_clock_node_rmt_sclk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_spi_function_clock", + "cargo:rustc-cfg=soc_has_clock_node_i2s_mclk", + "cargo:rustc-cfg=soc_clock_node_i2s_mclk_is_configurable", "cargo:rustc-cfg=has_dram_region", "cargo:rustc-cfg=has_dram2_uninit_region", "cargo:rustc-cfg=has_irom_region", @@ -990,7 +1034,6 @@ impl Chip { "wifi_driver_supported", "phy_driver_supported", "adc_driver_supported", - "temp_sensor_driver_supported", "ledc_driver_supported", "lp_timer_driver_supported", "systimer_driver_supported", @@ -1003,6 +1046,7 @@ impl Chip { "dma_driver_supported", "interrupts_driver_supported", "mmu_driver_supported", + "flash_driver_supported", "rom_driver_supported", "soc_driver_supported", "uart_uart0", @@ -1044,17 +1088,30 @@ impl Chip { "spi_master_has_dma_segmented_transfer", "bt_controller=\"npl\"", "wifi_mac_version=\"1\"", + "wifi_has_ftm", "phy_combo_module", + "adc_controller=\"digital\"", + "adc_controller_is_set", + "adc_channel_count=\"5\"", + "adc_channel_count_is_set", + "adc_line_calibration", + "adc_basic_calibration", + "adc_calibration_v1_scheme_supported", "ledc_version=\"2\"", "ledc_channel_count=\"6\"", "timergroup_timg_has_divcnt_rst", + "timergroup_wdt_has_conf_update", "timergroup_rc_fast_calibration_is_set", + "timergroup_rc_slow_calibration_is_set", "ecc_zero_extend_writes", "ecc_has_finite_field_division", "ecc_has_curve_p192", "ecc_has_curve_p256", "rng_apb_cycle_wait_num=\"16\"", "rng_trng_supported", + "sha_has_sha1", + "sha_has_sha224", + "sha_has_sha256", "sleep_light_sleep", "sleep_deep_sleep", "sleep_has_wakeup_source_gpio", @@ -1083,6 +1140,7 @@ impl Chip { "dma_max_priority_is_set", "interrupts_status_registers=\"2\"", "interrupt_controller=\"riscv_basic\"", + "context_switch_source=\"from_cpu\"", "mmu_page_size=\"65536\"", "mmu_entry_num=\"64\"", "rom_has_crc_le", @@ -1091,6 +1149,8 @@ impl Chip { "soc_cpu_has_csr_pc", "soc_has_swd_watchdog", "soc_cpu_mcause_mask=\"31\"", + "soc_cpu_pmp_granularity=\"4\"", + "soc_cpu_pmp_granularity_is_set", "soc_has_clock_node_xtal_clk", "soc_clock_node_xtal_clk_is_configurable", "soc_has_clock_node_pll_clk", @@ -1121,6 +1181,10 @@ impl Chip { "soc_has_clock_node_xtal_div_clk", "soc_has_clock_node_rtc_slow_clk", "soc_clock_node_rtc_slow_clk_is_configurable", + "soc_has_clock_node_ble_lp_xtal_clk", + "soc_has_clock_node_ble_lp_rc_slow_clk", + "soc_has_clock_node_ble_lp_clk", + "soc_clock_node_ble_lp_clk_is_configurable", "soc_has_clock_node_rtc_fast_clk", "soc_clock_node_rtc_fast_clk_is_configurable", "soc_has_clock_node_low_power_clk", @@ -1141,6 +1205,7 @@ impl Chip { "soc_clock_node_i2c_function_clock_is_configurable", "soc_has_clock_node_spi_function_clock", "soc_clock_node_spi_function_clock_is_configurable", + "soc_has_clock_node_adc_function_clock", "has_dram_region", "has_dram2_uninit_region", "has_irom_region", @@ -1201,7 +1266,6 @@ impl Chip { "cargo:rustc-cfg=wifi_driver_supported", "cargo:rustc-cfg=phy_driver_supported", "cargo:rustc-cfg=adc_driver_supported", - "cargo:rustc-cfg=temp_sensor_driver_supported", "cargo:rustc-cfg=ledc_driver_supported", "cargo:rustc-cfg=lp_timer_driver_supported", "cargo:rustc-cfg=systimer_driver_supported", @@ -1214,6 +1278,7 @@ impl Chip { "cargo:rustc-cfg=dma_driver_supported", "cargo:rustc-cfg=interrupts_driver_supported", "cargo:rustc-cfg=mmu_driver_supported", + "cargo:rustc-cfg=flash_driver_supported", "cargo:rustc-cfg=rom_driver_supported", "cargo:rustc-cfg=soc_driver_supported", "cargo:rustc-cfg=uart_uart0", @@ -1255,17 +1320,30 @@ impl Chip { "cargo:rustc-cfg=spi_master_has_dma_segmented_transfer", "cargo:rustc-cfg=bt_controller=\"npl\"", "cargo:rustc-cfg=wifi_mac_version=\"1\"", + "cargo:rustc-cfg=wifi_has_ftm", "cargo:rustc-cfg=phy_combo_module", + "cargo:rustc-cfg=adc_controller=\"digital\"", + "cargo:rustc-cfg=adc_controller_is_set", + "cargo:rustc-cfg=adc_channel_count=\"5\"", + "cargo:rustc-cfg=adc_channel_count_is_set", + "cargo:rustc-cfg=adc_line_calibration", + "cargo:rustc-cfg=adc_basic_calibration", + "cargo:rustc-cfg=adc_calibration_v1_scheme_supported", "cargo:rustc-cfg=ledc_version=\"2\"", "cargo:rustc-cfg=ledc_channel_count=\"6\"", "cargo:rustc-cfg=timergroup_timg_has_divcnt_rst", + "cargo:rustc-cfg=timergroup_wdt_has_conf_update", "cargo:rustc-cfg=timergroup_rc_fast_calibration_is_set", + "cargo:rustc-cfg=timergroup_rc_slow_calibration_is_set", "cargo:rustc-cfg=ecc_zero_extend_writes", "cargo:rustc-cfg=ecc_has_finite_field_division", "cargo:rustc-cfg=ecc_has_curve_p192", "cargo:rustc-cfg=ecc_has_curve_p256", "cargo:rustc-cfg=rng_apb_cycle_wait_num=\"16\"", "cargo:rustc-cfg=rng_trng_supported", + "cargo:rustc-cfg=sha_has_sha1", + "cargo:rustc-cfg=sha_has_sha224", + "cargo:rustc-cfg=sha_has_sha256", "cargo:rustc-cfg=sleep_light_sleep", "cargo:rustc-cfg=sleep_deep_sleep", "cargo:rustc-cfg=sleep_has_wakeup_source_gpio", @@ -1294,6 +1372,7 @@ impl Chip { "cargo:rustc-cfg=dma_max_priority_is_set", "cargo:rustc-cfg=interrupts_status_registers=\"2\"", "cargo:rustc-cfg=interrupt_controller=\"riscv_basic\"", + "cargo:rustc-cfg=context_switch_source=\"from_cpu\"", "cargo:rustc-cfg=mmu_page_size=\"65536\"", "cargo:rustc-cfg=mmu_entry_num=\"64\"", "cargo:rustc-cfg=rom_has_crc_le", @@ -1302,6 +1381,8 @@ impl Chip { "cargo:rustc-cfg=soc_cpu_has_csr_pc", "cargo:rustc-cfg=soc_has_swd_watchdog", "cargo:rustc-cfg=soc_cpu_mcause_mask=\"31\"", + "cargo:rustc-cfg=soc_cpu_pmp_granularity=\"4\"", + "cargo:rustc-cfg=soc_cpu_pmp_granularity_is_set", "cargo:rustc-cfg=soc_has_clock_node_xtal_clk", "cargo:rustc-cfg=soc_clock_node_xtal_clk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_pll_clk", @@ -1332,6 +1413,10 @@ impl Chip { "cargo:rustc-cfg=soc_has_clock_node_xtal_div_clk", "cargo:rustc-cfg=soc_has_clock_node_rtc_slow_clk", "cargo:rustc-cfg=soc_clock_node_rtc_slow_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_ble_lp_xtal_clk", + "cargo:rustc-cfg=soc_has_clock_node_ble_lp_rc_slow_clk", + "cargo:rustc-cfg=soc_has_clock_node_ble_lp_clk", + "cargo:rustc-cfg=soc_clock_node_ble_lp_clk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_rtc_fast_clk", "cargo:rustc-cfg=soc_clock_node_rtc_fast_clk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_low_power_clk", @@ -1352,6 +1437,7 @@ impl Chip { "cargo:rustc-cfg=soc_clock_node_i2c_function_clock_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_spi_function_clock", "cargo:rustc-cfg=soc_clock_node_spi_function_clock_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_adc_function_clock", "cargo:rustc-cfg=has_dram_region", "cargo:rustc-cfg=has_dram2_uninit_region", "cargo:rustc-cfg=has_irom_region", @@ -1522,7 +1608,6 @@ impl Chip { "soc_has_usb_device", "soc_has_xts_aes", "soc_has_adc1", - "soc_has_adc2", "soc_has_bt", "soc_has_flash", "soc_has_gpio_dedicated", @@ -1566,6 +1651,7 @@ impl Chip { "dma_driver_supported", "interrupts_driver_supported", "mmu_driver_supported", + "flash_driver_supported", "rom_driver_supported", "soc_driver_supported", "uart_uart0", @@ -1576,7 +1662,6 @@ impl Chip { "spi_slave_spi2", "i2s_i2s0", "adc_adc1", - "adc_adc2", "timergroup_timg0", "timergroup_timg1", "gpio_version=\"2\"", @@ -1612,8 +1697,6 @@ impl Chip { "spi_master_has_dma_segmented_transfer", "i2s_version=\"2\"", "i2s_version_is_set", - "i2s_default_clock_source=\"2\"", - "i2s_default_clock_source_is_set", "i2s_mclk_divider_bit_width=\"9\"", "i2s_mclk_divider_bit_width_is_set", "i2s_max_ws_width=\"128\"", @@ -1632,9 +1715,18 @@ impl Chip { "bt_controller=\"btdm\"", "wifi_mac_version=\"1\"", "wifi_csi_supported", + "wifi_has_ftm", "phy_combo_module", "phy_backed_up_digital_register_count=\"21\"", "phy_backed_up_digital_register_count_is_set", + "adc_controller=\"digital\"", + "adc_controller_is_set", + "adc_channel_count=\"5\"", + "adc_channel_count_is_set", + "adc_line_calibration", + "adc_curve_calibration", + "adc_basic_calibration", + "adc_calibration_v1_scheme_supported", "ledc_version=\"2\"", "ledc_channel_count=\"6\"", "soc_has_sdm_ch0", @@ -1642,7 +1734,9 @@ impl Chip { "soc_has_sdm_ch2", "soc_has_sdm_ch3", "timergroup_timg_has_divcnt_rst", + "timergroup_wdt_has_conf_update", "timergroup_rc_fast_calibration_is_set", + "timergroup_rc_slow_calibration_is_set", "aes_dma_mode_ecb", "aes_dma_mode_cbc", "aes_dma_mode_ofb", @@ -1655,6 +1749,9 @@ impl Chip { "rsa_version=\"3\"", "rsa_size_increment=\"32\"", "rsa_memory_size_bytes=\"384\"", + "sha_has_sha1", + "sha_has_sha224", + "sha_has_sha256", "sleep_light_sleep", "sleep_deep_sleep", "sleep_has_wakeup_source_gpio", @@ -1668,6 +1765,8 @@ impl Chip { "sleep_pin_wakeup_version=\"2\"", "sleep_pin_wakeup_version_is_set", "sleep_deep_sleep_needs_gpio_isolation", + "cpu_retention=\"rtc_cntl\"", + "supports_cpu_power_down", "assist_debug_has_sp_monitor", "assist_debug_has_region_monitor", "dma_mem2mem_requires_peripheral", @@ -1693,6 +1792,7 @@ impl Chip { "dma_max_priority_is_set", "interrupts_status_registers=\"2\"", "interrupt_controller=\"riscv_basic\"", + "context_switch_source=\"from_cpu\"", "mmu_page_size=\"65536\"", "mmu_entry_num=\"128\"", "rom_has_crc_le", @@ -1701,6 +1801,8 @@ impl Chip { "soc_cpu_has_csr_pc", "soc_has_swd_watchdog", "soc_cpu_mcause_mask=\"31\"", + "soc_cpu_pmp_granularity=\"4\"", + "soc_cpu_pmp_granularity_is_set", "soc_has_clock_node_xtal_clk", "soc_clock_node_xtal_clk_is_configurable", "soc_has_clock_node_pll_clk", @@ -1728,6 +1830,9 @@ impl Chip { "soc_has_clock_node_xtal_div_clk", "soc_has_clock_node_rtc_slow_clk", "soc_clock_node_rtc_slow_clk_is_configurable", + "soc_has_clock_node_ble_lp_xtal_clk", + "soc_has_clock_node_ble_lp_clk", + "soc_clock_node_ble_lp_clk_is_configurable", "soc_has_clock_node_rtc_fast_clk", "soc_clock_node_rtc_fast_clk_is_configurable", "soc_has_clock_node_low_power_clk", @@ -1749,8 +1854,17 @@ impl Chip { "soc_clock_node_uart_baud_rate_generator_is_configurable", "soc_has_clock_node_i2c_function_clock", "soc_clock_node_i2c_function_clock_is_configurable", + "soc_has_clock_node_tsens_sclk", + "soc_clock_node_tsens_sclk_is_configurable", "soc_has_clock_node_spi_function_clock", "soc_clock_node_spi_function_clock_is_configurable", + "soc_has_clock_node_adc_function_clock", + "soc_has_clock_node_i2s_tx_clk", + "soc_clock_node_i2s_tx_clk_is_configurable", + "soc_has_clock_node_i2s_rx_clk", + "soc_clock_node_i2s_rx_clk_is_configurable", + "soc_has_clock_node_i2s_mclk_out", + "soc_clock_node_i2s_mclk_out_is_configurable", "has_dram_region", "has_dram2_uninit_region", "has_irom_region", @@ -1803,7 +1917,6 @@ impl Chip { "cargo:rustc-cfg=soc_has_usb_device", "cargo:rustc-cfg=soc_has_xts_aes", "cargo:rustc-cfg=soc_has_adc1", - "cargo:rustc-cfg=soc_has_adc2", "cargo:rustc-cfg=soc_has_bt", "cargo:rustc-cfg=soc_has_flash", "cargo:rustc-cfg=soc_has_gpio_dedicated", @@ -1847,6 +1960,7 @@ impl Chip { "cargo:rustc-cfg=dma_driver_supported", "cargo:rustc-cfg=interrupts_driver_supported", "cargo:rustc-cfg=mmu_driver_supported", + "cargo:rustc-cfg=flash_driver_supported", "cargo:rustc-cfg=rom_driver_supported", "cargo:rustc-cfg=soc_driver_supported", "cargo:rustc-cfg=uart_uart0", @@ -1857,7 +1971,6 @@ impl Chip { "cargo:rustc-cfg=spi_slave_spi2", "cargo:rustc-cfg=i2s_i2s0", "cargo:rustc-cfg=adc_adc1", - "cargo:rustc-cfg=adc_adc2", "cargo:rustc-cfg=timergroup_timg0", "cargo:rustc-cfg=timergroup_timg1", "cargo:rustc-cfg=gpio_version=\"2\"", @@ -1893,8 +2006,6 @@ impl Chip { "cargo:rustc-cfg=spi_master_has_dma_segmented_transfer", "cargo:rustc-cfg=i2s_version=\"2\"", "cargo:rustc-cfg=i2s_version_is_set", - "cargo:rustc-cfg=i2s_default_clock_source=\"2\"", - "cargo:rustc-cfg=i2s_default_clock_source_is_set", "cargo:rustc-cfg=i2s_mclk_divider_bit_width=\"9\"", "cargo:rustc-cfg=i2s_mclk_divider_bit_width_is_set", "cargo:rustc-cfg=i2s_max_ws_width=\"128\"", @@ -1913,9 +2024,18 @@ impl Chip { "cargo:rustc-cfg=bt_controller=\"btdm\"", "cargo:rustc-cfg=wifi_mac_version=\"1\"", "cargo:rustc-cfg=wifi_csi_supported", + "cargo:rustc-cfg=wifi_has_ftm", "cargo:rustc-cfg=phy_combo_module", "cargo:rustc-cfg=phy_backed_up_digital_register_count=\"21\"", "cargo:rustc-cfg=phy_backed_up_digital_register_count_is_set", + "cargo:rustc-cfg=adc_controller=\"digital\"", + "cargo:rustc-cfg=adc_controller_is_set", + "cargo:rustc-cfg=adc_channel_count=\"5\"", + "cargo:rustc-cfg=adc_channel_count_is_set", + "cargo:rustc-cfg=adc_line_calibration", + "cargo:rustc-cfg=adc_curve_calibration", + "cargo:rustc-cfg=adc_basic_calibration", + "cargo:rustc-cfg=adc_calibration_v1_scheme_supported", "cargo:rustc-cfg=ledc_version=\"2\"", "cargo:rustc-cfg=ledc_channel_count=\"6\"", "cargo:rustc-cfg=soc_has_sdm_ch0", @@ -1923,7 +2043,9 @@ impl Chip { "cargo:rustc-cfg=soc_has_sdm_ch2", "cargo:rustc-cfg=soc_has_sdm_ch3", "cargo:rustc-cfg=timergroup_timg_has_divcnt_rst", + "cargo:rustc-cfg=timergroup_wdt_has_conf_update", "cargo:rustc-cfg=timergroup_rc_fast_calibration_is_set", + "cargo:rustc-cfg=timergroup_rc_slow_calibration_is_set", "cargo:rustc-cfg=aes_dma_mode_ecb", "cargo:rustc-cfg=aes_dma_mode_cbc", "cargo:rustc-cfg=aes_dma_mode_ofb", @@ -1936,6 +2058,9 @@ impl Chip { "cargo:rustc-cfg=rsa_version=\"3\"", "cargo:rustc-cfg=rsa_size_increment=\"32\"", "cargo:rustc-cfg=rsa_memory_size_bytes=\"384\"", + "cargo:rustc-cfg=sha_has_sha1", + "cargo:rustc-cfg=sha_has_sha224", + "cargo:rustc-cfg=sha_has_sha256", "cargo:rustc-cfg=sleep_light_sleep", "cargo:rustc-cfg=sleep_deep_sleep", "cargo:rustc-cfg=sleep_has_wakeup_source_gpio", @@ -1949,6 +2074,8 @@ impl Chip { "cargo:rustc-cfg=sleep_pin_wakeup_version=\"2\"", "cargo:rustc-cfg=sleep_pin_wakeup_version_is_set", "cargo:rustc-cfg=sleep_deep_sleep_needs_gpio_isolation", + "cargo:rustc-cfg=cpu_retention=\"rtc_cntl\"", + "cargo:rustc-cfg=supports_cpu_power_down", "cargo:rustc-cfg=assist_debug_has_sp_monitor", "cargo:rustc-cfg=assist_debug_has_region_monitor", "cargo:rustc-cfg=dma_mem2mem_requires_peripheral", @@ -1974,6 +2101,7 @@ impl Chip { "cargo:rustc-cfg=dma_max_priority_is_set", "cargo:rustc-cfg=interrupts_status_registers=\"2\"", "cargo:rustc-cfg=interrupt_controller=\"riscv_basic\"", + "cargo:rustc-cfg=context_switch_source=\"from_cpu\"", "cargo:rustc-cfg=mmu_page_size=\"65536\"", "cargo:rustc-cfg=mmu_entry_num=\"128\"", "cargo:rustc-cfg=rom_has_crc_le", @@ -1982,6 +2110,8 @@ impl Chip { "cargo:rustc-cfg=soc_cpu_has_csr_pc", "cargo:rustc-cfg=soc_has_swd_watchdog", "cargo:rustc-cfg=soc_cpu_mcause_mask=\"31\"", + "cargo:rustc-cfg=soc_cpu_pmp_granularity=\"4\"", + "cargo:rustc-cfg=soc_cpu_pmp_granularity_is_set", "cargo:rustc-cfg=soc_has_clock_node_xtal_clk", "cargo:rustc-cfg=soc_clock_node_xtal_clk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_pll_clk", @@ -2009,6 +2139,9 @@ impl Chip { "cargo:rustc-cfg=soc_has_clock_node_xtal_div_clk", "cargo:rustc-cfg=soc_has_clock_node_rtc_slow_clk", "cargo:rustc-cfg=soc_clock_node_rtc_slow_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_ble_lp_xtal_clk", + "cargo:rustc-cfg=soc_has_clock_node_ble_lp_clk", + "cargo:rustc-cfg=soc_clock_node_ble_lp_clk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_rtc_fast_clk", "cargo:rustc-cfg=soc_clock_node_rtc_fast_clk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_low_power_clk", @@ -2030,8 +2163,17 @@ impl Chip { "cargo:rustc-cfg=soc_clock_node_uart_baud_rate_generator_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_i2c_function_clock", "cargo:rustc-cfg=soc_clock_node_i2c_function_clock_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_tsens_sclk", + "cargo:rustc-cfg=soc_clock_node_tsens_sclk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_spi_function_clock", "cargo:rustc-cfg=soc_clock_node_spi_function_clock_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_adc_function_clock", + "cargo:rustc-cfg=soc_has_clock_node_i2s_tx_clk", + "cargo:rustc-cfg=soc_clock_node_i2s_tx_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_i2s_rx_clk", + "cargo:rustc-cfg=soc_clock_node_i2s_rx_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_i2s_mclk_out", + "cargo:rustc-cfg=soc_clock_node_i2s_mclk_out_is_configurable", "cargo:rustc-cfg=has_dram_region", "cargo:rustc-cfg=has_dram2_uninit_region", "cargo:rustc-cfg=has_irom_region", @@ -2167,6 +2309,7 @@ impl Chip { "soc_has_assist_debug", "soc_has_apb_saradc", "soc_has_cache", + "soc_has_clic", "soc_has_clint", "soc_has_dma", "soc_has_ds", @@ -2225,6 +2368,8 @@ impl Chip { "soc_has_tee", "soc_has_timg0", "soc_has_timg1", + "soc_has_twai0", + "soc_has_twai1", "soc_has_uart0", "soc_has_uart1", "soc_has_uhci0", @@ -2253,6 +2398,7 @@ impl Chip { "i2s_driver_supported", "parl_io_driver_supported", "rmt_driver_supported", + "canfd_driver_supported", "usb_serial_jtag_driver_supported", "bt_driver_supported", "wifi_driver_supported", @@ -2274,6 +2420,7 @@ impl Chip { "dma_driver_supported", "interrupts_driver_supported", "mmu_driver_supported", + "flash_driver_supported", "psram_driver_supported", "rom_driver_supported", "soc_driver_supported", @@ -2283,7 +2430,10 @@ impl Chip { "spi_master_spi2", "spi_slave_spi2", "i2s_i2s0", + "canfd_twai0", + "canfd_twai1", "adc_adc1", + "pcnt_PCNT", "timergroup_timg0", "timergroup_timg1", "gpio_version=\"2\"", @@ -2327,8 +2477,6 @@ impl Chip { "spi_master_dma_can_access_flash", "i2s_version=\"3\"", "i2s_version_is_set", - "i2s_default_clock_source=\"2\"", - "i2s_default_clock_source_is_set", "i2s_mclk_divider_bit_width=\"9\"", "i2s_mclk_divider_bit_width_is_set", "i2s_max_ws_width=\"512\"", @@ -2338,6 +2486,8 @@ impl Chip { "i2s_supports_pdm_rx", "i2s_supports_pcm2pdm", "parl_io_version=\"2\"", + "parl_io_max_data_width=\"8\"", + "parl_io_has_tx_cs", "rmt_ram_start=\"1610638336\"", "rmt_channel_ram_size=\"48\"", "rmt_has_tx_immediate_stop", @@ -2348,17 +2498,33 @@ impl Chip { "rmt_has_rx_wrap", "rmt_has_rx_demodulation", "bt_controller=\"npl\"", + "wifi_has_wifi6", "wifi_mac_version=\"3\"", "wifi_has_5g", "wifi_csi_supported", - "phy_combo_module", + "wifi_has_nan", + "wifi_has_ftm", + "adc_controller=\"digital\"", + "adc_controller_is_set", + "adc_channel_count=\"6\"", + "adc_channel_count_is_set", + "adc_line_calibration", + "adc_curve_calibration", + "adc_basic_calibration", + "adc_calibration_v1_scheme_supported", + "adc_channel_compensation", + "adc_pcr_clock", + "adc_pcr_sar_clk_div", + "adc_sar_power_override", "soc_has_sdm_ch0", "soc_has_sdm_ch1", "soc_has_sdm_ch2", "soc_has_sdm_ch3", "timergroup_timg_has_divcnt_rst", + "timergroup_wdt_has_conf_update", "timergroup_rc_fast_calibration_divider", "timergroup_rc_fast_calibration_is_set", + "timergroup_rc_slow_calibration_is_set", "aes_dma_mode_ecb", "aes_dma_mode_cbc", "aes_dma_mode_ofb", @@ -2375,10 +2541,14 @@ impl Chip { "ecc_has_curve_p256", "ecc_has_curve_p384", "rng_apb_cycle_wait_num=\"16\"", + "rng_trng_supported", "rng_is_lp_sys", "rsa_version=\"3\"", "rsa_size_increment=\"32\"", "rsa_memory_size_bytes=\"384\"", + "sha_has_sha1", + "sha_has_sha224", + "sha_has_sha256", "sleep_light_sleep", "sleep_deep_sleep", "sleep_has_wakeup_source_ext1", @@ -2394,6 +2564,10 @@ impl Chip { "sleep_ext1_version_is_set", "sleep_pin_wakeup_version=\"3\"", "sleep_pin_wakeup_version_is_set", + "cpu_retention=\"software\"", + "cpu_retention_frame=\"clic\"", + "supports_cpu_power_down", + "supports_top_power_down", "assist_debug_has_sp_monitor", "assist_debug_has_region_monitor", "dma_separate_in_out_interrupts", @@ -2422,6 +2596,7 @@ impl Chip { "dma_max_priority_is_set", "interrupts_status_registers=\"3\"", "interrupt_controller=\"clic\"", + "context_switch_source=\"clint\"", "mmu_page_size=\"65536\"", "mmu_entry_num=\"512\"", "psram_extmem_origin=\"1107296256\"", @@ -2433,6 +2608,8 @@ impl Chip { "soc_cpu_csr_prv_mode_is_set", "soc_has_swd_watchdog", "soc_cpu_mcause_mask=\"31\"", + "soc_cpu_pmp_granularity=\"128\"", + "soc_cpu_pmp_granularity_is_set", "soc_has_clock_node_xtal_clk", "soc_clock_node_xtal_clk_is_configurable", "soc_has_clock_node_pll_clk", @@ -2462,6 +2639,11 @@ impl Chip { "soc_clock_node_lp_fast_clk_is_configurable", "soc_has_clock_node_lp_slow_clk", "soc_clock_node_lp_slow_clk_is_configurable", + "soc_has_clock_node_ble_lp_xtal_clk", + "soc_has_clock_node_ble_lp_rc_slow_clk", + "soc_has_clock_node_ble_lp_clk", + "soc_clock_node_ble_lp_clk_is_configurable", + "soc_has_clock_node_crypto_pll_div", "soc_has_clock_node_crypto_clk", "soc_clock_node_crypto_clk_is_configurable", "soc_has_clock_node_iomux_function_clock", @@ -2483,10 +2665,20 @@ impl Chip { "soc_clock_node_parl_io_rx_clock_is_configurable", "soc_has_clock_node_parl_io_tx_clock", "soc_clock_node_parl_io_tx_clock_is_configurable", + "soc_has_clock_node_i2s_tx_clk", + "soc_clock_node_i2s_tx_clk_is_configurable", + "soc_has_clock_node_i2s_rx_clk", + "soc_clock_node_i2s_rx_clk_is_configurable", + "soc_has_clock_node_i2s_mclk_out", + "soc_clock_node_i2s_mclk_out_is_configurable", "soc_has_clock_node_i2c_function_clock", "soc_clock_node_i2c_function_clock_is_configurable", "soc_has_clock_node_spi_function_clock", "soc_clock_node_spi_function_clock_is_configurable", + "soc_has_clock_node_twai_function_clock", + "soc_clock_node_twai_function_clock_is_configurable", + "soc_has_clock_node_adc_function_clock", + "soc_clock_node_adc_function_clock_is_configurable", "has_dram_region", "has_dram2_uninit_region", "has_irom_region", @@ -2500,6 +2692,7 @@ impl Chip { "cargo:rustc-cfg=soc_has_assist_debug", "cargo:rustc-cfg=soc_has_apb_saradc", "cargo:rustc-cfg=soc_has_cache", + "cargo:rustc-cfg=soc_has_clic", "cargo:rustc-cfg=soc_has_clint", "cargo:rustc-cfg=soc_has_dma", "cargo:rustc-cfg=soc_has_ds", @@ -2558,6 +2751,8 @@ impl Chip { "cargo:rustc-cfg=soc_has_tee", "cargo:rustc-cfg=soc_has_timg0", "cargo:rustc-cfg=soc_has_timg1", + "cargo:rustc-cfg=soc_has_twai0", + "cargo:rustc-cfg=soc_has_twai1", "cargo:rustc-cfg=soc_has_uart0", "cargo:rustc-cfg=soc_has_uart1", "cargo:rustc-cfg=soc_has_uhci0", @@ -2586,6 +2781,7 @@ impl Chip { "cargo:rustc-cfg=i2s_driver_supported", "cargo:rustc-cfg=parl_io_driver_supported", "cargo:rustc-cfg=rmt_driver_supported", + "cargo:rustc-cfg=canfd_driver_supported", "cargo:rustc-cfg=usb_serial_jtag_driver_supported", "cargo:rustc-cfg=bt_driver_supported", "cargo:rustc-cfg=wifi_driver_supported", @@ -2607,6 +2803,7 @@ impl Chip { "cargo:rustc-cfg=dma_driver_supported", "cargo:rustc-cfg=interrupts_driver_supported", "cargo:rustc-cfg=mmu_driver_supported", + "cargo:rustc-cfg=flash_driver_supported", "cargo:rustc-cfg=psram_driver_supported", "cargo:rustc-cfg=rom_driver_supported", "cargo:rustc-cfg=soc_driver_supported", @@ -2616,7 +2813,10 @@ impl Chip { "cargo:rustc-cfg=spi_master_spi2", "cargo:rustc-cfg=spi_slave_spi2", "cargo:rustc-cfg=i2s_i2s0", + "cargo:rustc-cfg=canfd_twai0", + "cargo:rustc-cfg=canfd_twai1", "cargo:rustc-cfg=adc_adc1", + "cargo:rustc-cfg=pcnt_PCNT", "cargo:rustc-cfg=timergroup_timg0", "cargo:rustc-cfg=timergroup_timg1", "cargo:rustc-cfg=gpio_version=\"2\"", @@ -2660,8 +2860,6 @@ impl Chip { "cargo:rustc-cfg=spi_master_dma_can_access_flash", "cargo:rustc-cfg=i2s_version=\"3\"", "cargo:rustc-cfg=i2s_version_is_set", - "cargo:rustc-cfg=i2s_default_clock_source=\"2\"", - "cargo:rustc-cfg=i2s_default_clock_source_is_set", "cargo:rustc-cfg=i2s_mclk_divider_bit_width=\"9\"", "cargo:rustc-cfg=i2s_mclk_divider_bit_width_is_set", "cargo:rustc-cfg=i2s_max_ws_width=\"512\"", @@ -2671,6 +2869,8 @@ impl Chip { "cargo:rustc-cfg=i2s_supports_pdm_rx", "cargo:rustc-cfg=i2s_supports_pcm2pdm", "cargo:rustc-cfg=parl_io_version=\"2\"", + "cargo:rustc-cfg=parl_io_max_data_width=\"8\"", + "cargo:rustc-cfg=parl_io_has_tx_cs", "cargo:rustc-cfg=rmt_ram_start=\"1610638336\"", "cargo:rustc-cfg=rmt_channel_ram_size=\"48\"", "cargo:rustc-cfg=rmt_has_tx_immediate_stop", @@ -2681,17 +2881,33 @@ impl Chip { "cargo:rustc-cfg=rmt_has_rx_wrap", "cargo:rustc-cfg=rmt_has_rx_demodulation", "cargo:rustc-cfg=bt_controller=\"npl\"", + "cargo:rustc-cfg=wifi_has_wifi6", "cargo:rustc-cfg=wifi_mac_version=\"3\"", "cargo:rustc-cfg=wifi_has_5g", "cargo:rustc-cfg=wifi_csi_supported", - "cargo:rustc-cfg=phy_combo_module", + "cargo:rustc-cfg=wifi_has_nan", + "cargo:rustc-cfg=wifi_has_ftm", + "cargo:rustc-cfg=adc_controller=\"digital\"", + "cargo:rustc-cfg=adc_controller_is_set", + "cargo:rustc-cfg=adc_channel_count=\"6\"", + "cargo:rustc-cfg=adc_channel_count_is_set", + "cargo:rustc-cfg=adc_line_calibration", + "cargo:rustc-cfg=adc_curve_calibration", + "cargo:rustc-cfg=adc_basic_calibration", + "cargo:rustc-cfg=adc_calibration_v1_scheme_supported", + "cargo:rustc-cfg=adc_channel_compensation", + "cargo:rustc-cfg=adc_pcr_clock", + "cargo:rustc-cfg=adc_pcr_sar_clk_div", + "cargo:rustc-cfg=adc_sar_power_override", "cargo:rustc-cfg=soc_has_sdm_ch0", "cargo:rustc-cfg=soc_has_sdm_ch1", "cargo:rustc-cfg=soc_has_sdm_ch2", "cargo:rustc-cfg=soc_has_sdm_ch3", "cargo:rustc-cfg=timergroup_timg_has_divcnt_rst", + "cargo:rustc-cfg=timergroup_wdt_has_conf_update", "cargo:rustc-cfg=timergroup_rc_fast_calibration_divider", "cargo:rustc-cfg=timergroup_rc_fast_calibration_is_set", + "cargo:rustc-cfg=timergroup_rc_slow_calibration_is_set", "cargo:rustc-cfg=aes_dma_mode_ecb", "cargo:rustc-cfg=aes_dma_mode_cbc", "cargo:rustc-cfg=aes_dma_mode_ofb", @@ -2708,10 +2924,14 @@ impl Chip { "cargo:rustc-cfg=ecc_has_curve_p256", "cargo:rustc-cfg=ecc_has_curve_p384", "cargo:rustc-cfg=rng_apb_cycle_wait_num=\"16\"", + "cargo:rustc-cfg=rng_trng_supported", "cargo:rustc-cfg=rng_is_lp_sys", "cargo:rustc-cfg=rsa_version=\"3\"", "cargo:rustc-cfg=rsa_size_increment=\"32\"", "cargo:rustc-cfg=rsa_memory_size_bytes=\"384\"", + "cargo:rustc-cfg=sha_has_sha1", + "cargo:rustc-cfg=sha_has_sha224", + "cargo:rustc-cfg=sha_has_sha256", "cargo:rustc-cfg=sleep_light_sleep", "cargo:rustc-cfg=sleep_deep_sleep", "cargo:rustc-cfg=sleep_has_wakeup_source_ext1", @@ -2727,6 +2947,10 @@ impl Chip { "cargo:rustc-cfg=sleep_ext1_version_is_set", "cargo:rustc-cfg=sleep_pin_wakeup_version=\"3\"", "cargo:rustc-cfg=sleep_pin_wakeup_version_is_set", + "cargo:rustc-cfg=cpu_retention=\"software\"", + "cargo:rustc-cfg=cpu_retention_frame=\"clic\"", + "cargo:rustc-cfg=supports_cpu_power_down", + "cargo:rustc-cfg=supports_top_power_down", "cargo:rustc-cfg=assist_debug_has_sp_monitor", "cargo:rustc-cfg=assist_debug_has_region_monitor", "cargo:rustc-cfg=dma_separate_in_out_interrupts", @@ -2755,6 +2979,7 @@ impl Chip { "cargo:rustc-cfg=dma_max_priority_is_set", "cargo:rustc-cfg=interrupts_status_registers=\"3\"", "cargo:rustc-cfg=interrupt_controller=\"clic\"", + "cargo:rustc-cfg=context_switch_source=\"clint\"", "cargo:rustc-cfg=mmu_page_size=\"65536\"", "cargo:rustc-cfg=mmu_entry_num=\"512\"", "cargo:rustc-cfg=psram_extmem_origin=\"1107296256\"", @@ -2766,6 +2991,8 @@ impl Chip { "cargo:rustc-cfg=soc_cpu_csr_prv_mode_is_set", "cargo:rustc-cfg=soc_has_swd_watchdog", "cargo:rustc-cfg=soc_cpu_mcause_mask=\"31\"", + "cargo:rustc-cfg=soc_cpu_pmp_granularity=\"128\"", + "cargo:rustc-cfg=soc_cpu_pmp_granularity_is_set", "cargo:rustc-cfg=soc_has_clock_node_xtal_clk", "cargo:rustc-cfg=soc_clock_node_xtal_clk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_pll_clk", @@ -2795,6 +3022,11 @@ impl Chip { "cargo:rustc-cfg=soc_clock_node_lp_fast_clk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_lp_slow_clk", "cargo:rustc-cfg=soc_clock_node_lp_slow_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_ble_lp_xtal_clk", + "cargo:rustc-cfg=soc_has_clock_node_ble_lp_rc_slow_clk", + "cargo:rustc-cfg=soc_has_clock_node_ble_lp_clk", + "cargo:rustc-cfg=soc_clock_node_ble_lp_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_crypto_pll_div", "cargo:rustc-cfg=soc_has_clock_node_crypto_clk", "cargo:rustc-cfg=soc_clock_node_crypto_clk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_iomux_function_clock", @@ -2816,10 +3048,20 @@ impl Chip { "cargo:rustc-cfg=soc_clock_node_parl_io_rx_clock_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_parl_io_tx_clock", "cargo:rustc-cfg=soc_clock_node_parl_io_tx_clock_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_i2s_tx_clk", + "cargo:rustc-cfg=soc_clock_node_i2s_tx_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_i2s_rx_clk", + "cargo:rustc-cfg=soc_clock_node_i2s_rx_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_i2s_mclk_out", + "cargo:rustc-cfg=soc_clock_node_i2s_mclk_out_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_i2c_function_clock", "cargo:rustc-cfg=soc_clock_node_i2c_function_clock_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_spi_function_clock", "cargo:rustc-cfg=soc_clock_node_spi_function_clock_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_twai_function_clock", + "cargo:rustc-cfg=soc_clock_node_twai_function_clock_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_adc_function_clock", + "cargo:rustc-cfg=soc_clock_node_adc_function_clock_is_configurable", "cargo:rustc-cfg=has_dram_region", "cargo:rustc-cfg=has_dram2_uninit_region", "cargo:rustc-cfg=has_irom_region", @@ -2983,6 +3225,7 @@ impl Chip { "soc_has_apb_saradc", "soc_has_assist_debug", "soc_has_atomic", + "soc_has_clint", "soc_has_dma", "soc_has_ds", "soc_has_ecc", @@ -3026,6 +3269,7 @@ impl Chip { "soc_has_pcnt", "soc_has_pcr", "soc_has_plic_mx", + "soc_has_plic_ux", "soc_has_pmu", "soc_has_rmt", "soc_has_rng", @@ -3102,6 +3346,7 @@ impl Chip { "etm_driver_supported", "interrupts_driver_supported", "mmu_driver_supported", + "flash_driver_supported", "rom_driver_supported", "soc_driver_supported", "uart_uart0", @@ -3112,6 +3357,7 @@ impl Chip { "spi_slave_spi2", "i2s_i2s0", "adc_adc1", + "pcnt_PCNT", "timergroup_timg0", "timergroup_timg1", "gpio_version=\"2\"", @@ -3153,8 +3399,6 @@ impl Chip { "spi_master_has_dma_segmented_transfer", "i2s_version=\"2\"", "i2s_version_is_set", - "i2s_default_clock_source=\"2\"", - "i2s_default_clock_source_is_set", "i2s_mclk_divider_bit_width=\"9\"", "i2s_mclk_divider_bit_width_is_set", "i2s_max_ws_width=\"128\"", @@ -3164,6 +3408,7 @@ impl Chip { "i2s_supports_pdm_rx", "i2s_supports_pcm2pdm", "parl_io_version=\"1\"", + "parl_io_max_data_width=\"16\"", "rmt_ram_start=\"1610638336\"", "rmt_channel_ram_size=\"48\"", "rmt_has_tx_immediate_stop", @@ -3177,7 +3422,19 @@ impl Chip { "wifi_has_wifi6", "wifi_mac_version=\"2\"", "wifi_csi_supported", + "wifi_has_ftm", "phy_combo_module", + "adc_controller=\"digital\"", + "adc_controller_is_set", + "adc_channel_count=\"7\"", + "adc_channel_count_is_set", + "adc_line_calibration", + "adc_curve_calibration", + "adc_basic_calibration", + "adc_calibration_v1_scheme_supported", + "adc_channel_compensation", + "adc_pcr_clock", + "adc_sar_power_override", "ledc_version=\"3\"", "ledc_channel_count=\"6\"", "soc_has_sdm_ch0", @@ -3185,8 +3442,10 @@ impl Chip { "soc_has_sdm_ch2", "soc_has_sdm_ch3", "timergroup_timg_has_divcnt_rst", + "timergroup_wdt_has_conf_update", "timergroup_rc_fast_calibration_divider", "timergroup_rc_fast_calibration_is_set", + "timergroup_rc_slow_calibration_is_set", "aes_dma_mode_ecb", "aes_dma_mode_cbc", "aes_dma_mode_ofb", @@ -3204,6 +3463,9 @@ impl Chip { "rsa_version=\"3\"", "rsa_size_increment=\"32\"", "rsa_memory_size_bytes=\"384\"", + "sha_has_sha1", + "sha_has_sha224", + "sha_has_sha256", "sleep_light_sleep", "sleep_deep_sleep", "sleep_has_wakeup_source_ext1", @@ -3219,6 +3481,10 @@ impl Chip { "sleep_ext1_version_is_set", "sleep_pin_wakeup_version=\"3\"", "sleep_pin_wakeup_version_is_set", + "cpu_retention=\"software\"", + "cpu_retention_frame=\"c6_h2\"", + "supports_cpu_power_down", + "supports_top_power_down", "assist_debug_has_sp_monitor", "assist_debug_has_region_monitor", "dma_separate_in_out_interrupts", @@ -3246,6 +3512,7 @@ impl Chip { "dma_max_priority_is_set", "interrupts_status_registers=\"3\"", "interrupt_controller=\"plic\"", + "context_switch_source=\"clint\"", "mmu_page_size=\"65536\"", "mmu_entry_num=\"256\"", "rom_has_crc_le", @@ -3256,6 +3523,8 @@ impl Chip { "soc_cpu_csr_prv_mode_is_set", "soc_has_swd_watchdog", "soc_cpu_mcause_mask=\"31\"", + "soc_cpu_pmp_granularity=\"4\"", + "soc_cpu_pmp_granularity_is_set", "soc_has_clock_node_xtal_clk", "soc_clock_node_xtal_clk_is_configurable", "soc_has_clock_node_pll_clk", @@ -3300,6 +3569,10 @@ impl Chip { "soc_clock_node_lp_fast_clk_is_configurable", "soc_has_clock_node_lp_slow_clk", "soc_clock_node_lp_slow_clk_is_configurable", + "soc_has_clock_node_ble_lp_xtal_clk", + "soc_has_clock_node_ble_lp_rc_slow_clk", + "soc_has_clock_node_ble_lp_clk", + "soc_clock_node_ble_lp_clk_is_configurable", "soc_has_clock_node_timg_calibration_clock", "soc_clock_node_timg_calibration_clock_is_configurable", "soc_has_clock_node_uart_function_clock", @@ -3319,10 +3592,20 @@ impl Chip { "soc_clock_node_parl_io_rx_clock_is_configurable", "soc_has_clock_node_parl_io_tx_clock", "soc_clock_node_parl_io_tx_clock_is_configurable", + "soc_has_clock_node_i2s_tx_clk", + "soc_clock_node_i2s_tx_clk_is_configurable", + "soc_has_clock_node_i2s_rx_clk", + "soc_clock_node_i2s_rx_clk_is_configurable", + "soc_has_clock_node_i2s_mclk_out", + "soc_clock_node_i2s_mclk_out_is_configurable", "soc_has_clock_node_i2c_function_clock", "soc_clock_node_i2c_function_clock_is_configurable", + "soc_has_clock_node_tsens_sclk", + "soc_clock_node_tsens_sclk_is_configurable", "soc_has_clock_node_spi_function_clock", "soc_clock_node_spi_function_clock_is_configurable", + "soc_has_clock_node_adc_function_clock", + "soc_clock_node_adc_function_clock_is_configurable", "has_dram_region", "has_dram2_uninit_region", "has_irom_region", @@ -3336,6 +3619,7 @@ impl Chip { "cargo:rustc-cfg=soc_has_apb_saradc", "cargo:rustc-cfg=soc_has_assist_debug", "cargo:rustc-cfg=soc_has_atomic", + "cargo:rustc-cfg=soc_has_clint", "cargo:rustc-cfg=soc_has_dma", "cargo:rustc-cfg=soc_has_ds", "cargo:rustc-cfg=soc_has_ecc", @@ -3379,6 +3663,7 @@ impl Chip { "cargo:rustc-cfg=soc_has_pcnt", "cargo:rustc-cfg=soc_has_pcr", "cargo:rustc-cfg=soc_has_plic_mx", + "cargo:rustc-cfg=soc_has_plic_ux", "cargo:rustc-cfg=soc_has_pmu", "cargo:rustc-cfg=soc_has_rmt", "cargo:rustc-cfg=soc_has_rng", @@ -3455,6 +3740,7 @@ impl Chip { "cargo:rustc-cfg=etm_driver_supported", "cargo:rustc-cfg=interrupts_driver_supported", "cargo:rustc-cfg=mmu_driver_supported", + "cargo:rustc-cfg=flash_driver_supported", "cargo:rustc-cfg=rom_driver_supported", "cargo:rustc-cfg=soc_driver_supported", "cargo:rustc-cfg=uart_uart0", @@ -3465,6 +3751,7 @@ impl Chip { "cargo:rustc-cfg=spi_slave_spi2", "cargo:rustc-cfg=i2s_i2s0", "cargo:rustc-cfg=adc_adc1", + "cargo:rustc-cfg=pcnt_PCNT", "cargo:rustc-cfg=timergroup_timg0", "cargo:rustc-cfg=timergroup_timg1", "cargo:rustc-cfg=gpio_version=\"2\"", @@ -3506,8 +3793,6 @@ impl Chip { "cargo:rustc-cfg=spi_master_has_dma_segmented_transfer", "cargo:rustc-cfg=i2s_version=\"2\"", "cargo:rustc-cfg=i2s_version_is_set", - "cargo:rustc-cfg=i2s_default_clock_source=\"2\"", - "cargo:rustc-cfg=i2s_default_clock_source_is_set", "cargo:rustc-cfg=i2s_mclk_divider_bit_width=\"9\"", "cargo:rustc-cfg=i2s_mclk_divider_bit_width_is_set", "cargo:rustc-cfg=i2s_max_ws_width=\"128\"", @@ -3517,6 +3802,7 @@ impl Chip { "cargo:rustc-cfg=i2s_supports_pdm_rx", "cargo:rustc-cfg=i2s_supports_pcm2pdm", "cargo:rustc-cfg=parl_io_version=\"1\"", + "cargo:rustc-cfg=parl_io_max_data_width=\"16\"", "cargo:rustc-cfg=rmt_ram_start=\"1610638336\"", "cargo:rustc-cfg=rmt_channel_ram_size=\"48\"", "cargo:rustc-cfg=rmt_has_tx_immediate_stop", @@ -3530,7 +3816,19 @@ impl Chip { "cargo:rustc-cfg=wifi_has_wifi6", "cargo:rustc-cfg=wifi_mac_version=\"2\"", "cargo:rustc-cfg=wifi_csi_supported", + "cargo:rustc-cfg=wifi_has_ftm", "cargo:rustc-cfg=phy_combo_module", + "cargo:rustc-cfg=adc_controller=\"digital\"", + "cargo:rustc-cfg=adc_controller_is_set", + "cargo:rustc-cfg=adc_channel_count=\"7\"", + "cargo:rustc-cfg=adc_channel_count_is_set", + "cargo:rustc-cfg=adc_line_calibration", + "cargo:rustc-cfg=adc_curve_calibration", + "cargo:rustc-cfg=adc_basic_calibration", + "cargo:rustc-cfg=adc_calibration_v1_scheme_supported", + "cargo:rustc-cfg=adc_channel_compensation", + "cargo:rustc-cfg=adc_pcr_clock", + "cargo:rustc-cfg=adc_sar_power_override", "cargo:rustc-cfg=ledc_version=\"3\"", "cargo:rustc-cfg=ledc_channel_count=\"6\"", "cargo:rustc-cfg=soc_has_sdm_ch0", @@ -3538,8 +3836,10 @@ impl Chip { "cargo:rustc-cfg=soc_has_sdm_ch2", "cargo:rustc-cfg=soc_has_sdm_ch3", "cargo:rustc-cfg=timergroup_timg_has_divcnt_rst", + "cargo:rustc-cfg=timergroup_wdt_has_conf_update", "cargo:rustc-cfg=timergroup_rc_fast_calibration_divider", "cargo:rustc-cfg=timergroup_rc_fast_calibration_is_set", + "cargo:rustc-cfg=timergroup_rc_slow_calibration_is_set", "cargo:rustc-cfg=aes_dma_mode_ecb", "cargo:rustc-cfg=aes_dma_mode_cbc", "cargo:rustc-cfg=aes_dma_mode_ofb", @@ -3557,6 +3857,9 @@ impl Chip { "cargo:rustc-cfg=rsa_version=\"3\"", "cargo:rustc-cfg=rsa_size_increment=\"32\"", "cargo:rustc-cfg=rsa_memory_size_bytes=\"384\"", + "cargo:rustc-cfg=sha_has_sha1", + "cargo:rustc-cfg=sha_has_sha224", + "cargo:rustc-cfg=sha_has_sha256", "cargo:rustc-cfg=sleep_light_sleep", "cargo:rustc-cfg=sleep_deep_sleep", "cargo:rustc-cfg=sleep_has_wakeup_source_ext1", @@ -3572,6 +3875,10 @@ impl Chip { "cargo:rustc-cfg=sleep_ext1_version_is_set", "cargo:rustc-cfg=sleep_pin_wakeup_version=\"3\"", "cargo:rustc-cfg=sleep_pin_wakeup_version_is_set", + "cargo:rustc-cfg=cpu_retention=\"software\"", + "cargo:rustc-cfg=cpu_retention_frame=\"c6_h2\"", + "cargo:rustc-cfg=supports_cpu_power_down", + "cargo:rustc-cfg=supports_top_power_down", "cargo:rustc-cfg=assist_debug_has_sp_monitor", "cargo:rustc-cfg=assist_debug_has_region_monitor", "cargo:rustc-cfg=dma_separate_in_out_interrupts", @@ -3599,6 +3906,7 @@ impl Chip { "cargo:rustc-cfg=dma_max_priority_is_set", "cargo:rustc-cfg=interrupts_status_registers=\"3\"", "cargo:rustc-cfg=interrupt_controller=\"plic\"", + "cargo:rustc-cfg=context_switch_source=\"clint\"", "cargo:rustc-cfg=mmu_page_size=\"65536\"", "cargo:rustc-cfg=mmu_entry_num=\"256\"", "cargo:rustc-cfg=rom_has_crc_le", @@ -3609,6 +3917,8 @@ impl Chip { "cargo:rustc-cfg=soc_cpu_csr_prv_mode_is_set", "cargo:rustc-cfg=soc_has_swd_watchdog", "cargo:rustc-cfg=soc_cpu_mcause_mask=\"31\"", + "cargo:rustc-cfg=soc_cpu_pmp_granularity=\"4\"", + "cargo:rustc-cfg=soc_cpu_pmp_granularity_is_set", "cargo:rustc-cfg=soc_has_clock_node_xtal_clk", "cargo:rustc-cfg=soc_clock_node_xtal_clk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_pll_clk", @@ -3653,6 +3963,10 @@ impl Chip { "cargo:rustc-cfg=soc_clock_node_lp_fast_clk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_lp_slow_clk", "cargo:rustc-cfg=soc_clock_node_lp_slow_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_ble_lp_xtal_clk", + "cargo:rustc-cfg=soc_has_clock_node_ble_lp_rc_slow_clk", + "cargo:rustc-cfg=soc_has_clock_node_ble_lp_clk", + "cargo:rustc-cfg=soc_clock_node_ble_lp_clk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_timg_calibration_clock", "cargo:rustc-cfg=soc_clock_node_timg_calibration_clock_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_uart_function_clock", @@ -3672,10 +3986,20 @@ impl Chip { "cargo:rustc-cfg=soc_clock_node_parl_io_rx_clock_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_parl_io_tx_clock", "cargo:rustc-cfg=soc_clock_node_parl_io_tx_clock_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_i2s_tx_clk", + "cargo:rustc-cfg=soc_clock_node_i2s_tx_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_i2s_rx_clk", + "cargo:rustc-cfg=soc_clock_node_i2s_rx_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_i2s_mclk_out", + "cargo:rustc-cfg=soc_clock_node_i2s_mclk_out_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_i2c_function_clock", "cargo:rustc-cfg=soc_clock_node_i2c_function_clock_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_tsens_sclk", + "cargo:rustc-cfg=soc_clock_node_tsens_sclk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_spi_function_clock", "cargo:rustc-cfg=soc_clock_node_spi_function_clock_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_adc_function_clock", + "cargo:rustc-cfg=soc_clock_node_adc_function_clock_is_configurable", "cargo:rustc-cfg=has_dram_region", "cargo:rustc-cfg=has_dram2_uninit_region", "cargo:rustc-cfg=has_irom_region", @@ -3845,8 +4169,9 @@ impl Chip { "single_core", "soc_has_apb_saradc", "soc_has_assist_debug", - "soc_has_clint", "soc_has_cache", + "soc_has_clic", + "soc_has_clint", "soc_has_dma", "soc_has_ecc", "soc_has_ecdsa", @@ -3929,6 +4254,7 @@ impl Chip { "dma_driver_supported", "interrupts_driver_supported", "mmu_driver_supported", + "flash_driver_supported", "psram_driver_supported", "rom_driver_supported", "soc_driver_supported", @@ -3979,8 +4305,6 @@ impl Chip { "spi_master_dma_can_access_flash", "i2s_version=\"3\"", "i2s_version_is_set", - "i2s_default_clock_source=\"2\"", - "i2s_default_clock_source_is_set", "i2s_mclk_divider_bit_width=\"9\"", "i2s_mclk_divider_bit_width_is_set", "i2s_max_ws_width=\"512\"", @@ -3993,10 +4317,26 @@ impl Chip { "wifi_has_wifi6", "wifi_mac_version=\"3\"", "wifi_csi_supported", + "wifi_has_nan", + "wifi_has_ftm", "phy_combo_module", + "adc_controller=\"digital\"", + "adc_controller_is_set", + "adc_channel_count=\"4\"", + "adc_channel_count_is_set", + "adc_line_calibration", + "adc_curve_calibration", + "adc_basic_calibration", + "adc_calibration_v1_scheme_supported", + "adc_channel_compensation", + "adc_pcr_clock", + "adc_pcr_sar_clk_div", + "adc_sar_power_override", "timergroup_timg_has_divcnt_rst", + "timergroup_wdt_has_conf_update", "timergroup_rc_fast_calibration_divider", "timergroup_rc_fast_calibration_is_set", + "timergroup_rc_slow_calibration_is_set", "ecc_zero_extend_writes", "ecc_separate_jacobian_point_memory", "ecc_has_memory_clock_gate", @@ -4006,7 +4346,11 @@ impl Chip { "ecc_has_curve_p192", "ecc_has_curve_p256", "rng_apb_cycle_wait_num=\"16\"", + "rng_trng_supported", "rng_is_lp_sys", + "sha_has_sha1", + "sha_has_sha224", + "sha_has_sha256", "sleep_light_sleep", "sleep_deep_sleep", "sleep_has_wakeup_source_ext1", @@ -4022,6 +4366,10 @@ impl Chip { "sleep_ext1_version_is_set", "sleep_pin_wakeup_version=\"3\"", "sleep_pin_wakeup_version_is_set", + "cpu_retention=\"software\"", + "cpu_retention_frame=\"clic\"", + "supports_cpu_power_down", + "supports_top_power_down", "assist_debug_has_sp_monitor", "assist_debug_has_region_monitor", "dma_separate_in_out_interrupts", @@ -4043,6 +4391,7 @@ impl Chip { "dma_max_priority_is_set", "interrupts_status_registers=\"3\"", "interrupt_controller=\"clic\"", + "context_switch_source=\"clint\"", "mmu_page_size=\"65536\"", "mmu_entry_num=\"512\"", "psram_extmem_origin=\"1107296256\"", @@ -4054,6 +4403,8 @@ impl Chip { "soc_cpu_csr_prv_mode_is_set", "soc_has_swd_watchdog", "soc_cpu_mcause_mask=\"31\"", + "soc_cpu_pmp_granularity=\"128\"", + "soc_cpu_pmp_granularity_is_set", "soc_has_clock_node_xtal_clk", "soc_clock_node_xtal_clk_is_configurable", "soc_has_clock_node_rc_fast_clk", @@ -4081,6 +4432,13 @@ impl Chip { "soc_clock_node_lp_fast_clk_is_configurable", "soc_has_clock_node_lp_slow_clk", "soc_clock_node_lp_slow_clk_is_configurable", + "soc_has_clock_node_ble_lp_xtal_clk", + "soc_has_clock_node_ble_lp_rc_slow_clk", + "soc_has_clock_node_ble_lp_clk", + "soc_clock_node_ble_lp_clk_is_configurable", + "soc_has_clock_node_crypto_pll_div", + "soc_has_clock_node_crypto_clk", + "soc_clock_node_crypto_clk_is_configurable", "soc_has_clock_node_timg_calibration_clock", "soc_clock_node_timg_calibration_clock_is_configurable", "soc_has_clock_node_uart_function_clock", @@ -4095,6 +4453,14 @@ impl Chip { "soc_clock_node_i2c_function_clock_is_configurable", "soc_has_clock_node_spi_function_clock", "soc_clock_node_spi_function_clock_is_configurable", + "soc_has_clock_node_adc_function_clock", + "soc_clock_node_adc_function_clock_is_configurable", + "soc_has_clock_node_i2s_tx_clk", + "soc_clock_node_i2s_tx_clk_is_configurable", + "soc_has_clock_node_i2s_rx_clk", + "soc_clock_node_i2s_rx_clk_is_configurable", + "soc_has_clock_node_i2s_mclk_out", + "soc_clock_node_i2s_mclk_out_is_configurable", "has_dram_region", "has_dram2_uninit_region", "has_irom_region", @@ -4106,8 +4472,9 @@ impl Chip { "cargo:rustc-cfg=single_core", "cargo:rustc-cfg=soc_has_apb_saradc", "cargo:rustc-cfg=soc_has_assist_debug", - "cargo:rustc-cfg=soc_has_clint", "cargo:rustc-cfg=soc_has_cache", + "cargo:rustc-cfg=soc_has_clic", + "cargo:rustc-cfg=soc_has_clint", "cargo:rustc-cfg=soc_has_dma", "cargo:rustc-cfg=soc_has_ecc", "cargo:rustc-cfg=soc_has_ecdsa", @@ -4190,6 +4557,7 @@ impl Chip { "cargo:rustc-cfg=dma_driver_supported", "cargo:rustc-cfg=interrupts_driver_supported", "cargo:rustc-cfg=mmu_driver_supported", + "cargo:rustc-cfg=flash_driver_supported", "cargo:rustc-cfg=psram_driver_supported", "cargo:rustc-cfg=rom_driver_supported", "cargo:rustc-cfg=soc_driver_supported", @@ -4240,8 +4608,6 @@ impl Chip { "cargo:rustc-cfg=spi_master_dma_can_access_flash", "cargo:rustc-cfg=i2s_version=\"3\"", "cargo:rustc-cfg=i2s_version_is_set", - "cargo:rustc-cfg=i2s_default_clock_source=\"2\"", - "cargo:rustc-cfg=i2s_default_clock_source_is_set", "cargo:rustc-cfg=i2s_mclk_divider_bit_width=\"9\"", "cargo:rustc-cfg=i2s_mclk_divider_bit_width_is_set", "cargo:rustc-cfg=i2s_max_ws_width=\"512\"", @@ -4254,10 +4620,26 @@ impl Chip { "cargo:rustc-cfg=wifi_has_wifi6", "cargo:rustc-cfg=wifi_mac_version=\"3\"", "cargo:rustc-cfg=wifi_csi_supported", + "cargo:rustc-cfg=wifi_has_nan", + "cargo:rustc-cfg=wifi_has_ftm", "cargo:rustc-cfg=phy_combo_module", + "cargo:rustc-cfg=adc_controller=\"digital\"", + "cargo:rustc-cfg=adc_controller_is_set", + "cargo:rustc-cfg=adc_channel_count=\"4\"", + "cargo:rustc-cfg=adc_channel_count_is_set", + "cargo:rustc-cfg=adc_line_calibration", + "cargo:rustc-cfg=adc_curve_calibration", + "cargo:rustc-cfg=adc_basic_calibration", + "cargo:rustc-cfg=adc_calibration_v1_scheme_supported", + "cargo:rustc-cfg=adc_channel_compensation", + "cargo:rustc-cfg=adc_pcr_clock", + "cargo:rustc-cfg=adc_pcr_sar_clk_div", + "cargo:rustc-cfg=adc_sar_power_override", "cargo:rustc-cfg=timergroup_timg_has_divcnt_rst", + "cargo:rustc-cfg=timergroup_wdt_has_conf_update", "cargo:rustc-cfg=timergroup_rc_fast_calibration_divider", "cargo:rustc-cfg=timergroup_rc_fast_calibration_is_set", + "cargo:rustc-cfg=timergroup_rc_slow_calibration_is_set", "cargo:rustc-cfg=ecc_zero_extend_writes", "cargo:rustc-cfg=ecc_separate_jacobian_point_memory", "cargo:rustc-cfg=ecc_has_memory_clock_gate", @@ -4267,7 +4649,11 @@ impl Chip { "cargo:rustc-cfg=ecc_has_curve_p192", "cargo:rustc-cfg=ecc_has_curve_p256", "cargo:rustc-cfg=rng_apb_cycle_wait_num=\"16\"", + "cargo:rustc-cfg=rng_trng_supported", "cargo:rustc-cfg=rng_is_lp_sys", + "cargo:rustc-cfg=sha_has_sha1", + "cargo:rustc-cfg=sha_has_sha224", + "cargo:rustc-cfg=sha_has_sha256", "cargo:rustc-cfg=sleep_light_sleep", "cargo:rustc-cfg=sleep_deep_sleep", "cargo:rustc-cfg=sleep_has_wakeup_source_ext1", @@ -4283,6 +4669,10 @@ impl Chip { "cargo:rustc-cfg=sleep_ext1_version_is_set", "cargo:rustc-cfg=sleep_pin_wakeup_version=\"3\"", "cargo:rustc-cfg=sleep_pin_wakeup_version_is_set", + "cargo:rustc-cfg=cpu_retention=\"software\"", + "cargo:rustc-cfg=cpu_retention_frame=\"clic\"", + "cargo:rustc-cfg=supports_cpu_power_down", + "cargo:rustc-cfg=supports_top_power_down", "cargo:rustc-cfg=assist_debug_has_sp_monitor", "cargo:rustc-cfg=assist_debug_has_region_monitor", "cargo:rustc-cfg=dma_separate_in_out_interrupts", @@ -4304,6 +4694,7 @@ impl Chip { "cargo:rustc-cfg=dma_max_priority_is_set", "cargo:rustc-cfg=interrupts_status_registers=\"3\"", "cargo:rustc-cfg=interrupt_controller=\"clic\"", + "cargo:rustc-cfg=context_switch_source=\"clint\"", "cargo:rustc-cfg=mmu_page_size=\"65536\"", "cargo:rustc-cfg=mmu_entry_num=\"512\"", "cargo:rustc-cfg=psram_extmem_origin=\"1107296256\"", @@ -4315,6 +4706,8 @@ impl Chip { "cargo:rustc-cfg=soc_cpu_csr_prv_mode_is_set", "cargo:rustc-cfg=soc_has_swd_watchdog", "cargo:rustc-cfg=soc_cpu_mcause_mask=\"31\"", + "cargo:rustc-cfg=soc_cpu_pmp_granularity=\"128\"", + "cargo:rustc-cfg=soc_cpu_pmp_granularity_is_set", "cargo:rustc-cfg=soc_has_clock_node_xtal_clk", "cargo:rustc-cfg=soc_clock_node_xtal_clk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_rc_fast_clk", @@ -4342,6 +4735,13 @@ impl Chip { "cargo:rustc-cfg=soc_clock_node_lp_fast_clk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_lp_slow_clk", "cargo:rustc-cfg=soc_clock_node_lp_slow_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_ble_lp_xtal_clk", + "cargo:rustc-cfg=soc_has_clock_node_ble_lp_rc_slow_clk", + "cargo:rustc-cfg=soc_has_clock_node_ble_lp_clk", + "cargo:rustc-cfg=soc_clock_node_ble_lp_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_crypto_pll_div", + "cargo:rustc-cfg=soc_has_clock_node_crypto_clk", + "cargo:rustc-cfg=soc_clock_node_crypto_clk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_timg_calibration_clock", "cargo:rustc-cfg=soc_clock_node_timg_calibration_clock_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_uart_function_clock", @@ -4356,6 +4756,14 @@ impl Chip { "cargo:rustc-cfg=soc_clock_node_i2c_function_clock_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_spi_function_clock", "cargo:rustc-cfg=soc_clock_node_spi_function_clock_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_adc_function_clock", + "cargo:rustc-cfg=soc_clock_node_adc_function_clock_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_i2s_tx_clk", + "cargo:rustc-cfg=soc_clock_node_i2s_tx_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_i2s_rx_clk", + "cargo:rustc-cfg=soc_clock_node_i2s_rx_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_i2s_mclk_out", + "cargo:rustc-cfg=soc_clock_node_i2s_mclk_out_is_configurable", "cargo:rustc-cfg=has_dram_region", "cargo:rustc-cfg=has_dram2_uninit_region", "cargo:rustc-cfg=has_irom_region", @@ -4522,10 +4930,12 @@ impl Chip { "soc_has_aes", "soc_has_apb_saradc", "soc_has_assist_debug", + "soc_has_clint", "soc_has_dma", "soc_has_ds", "soc_has_ecc", "soc_has_efuse", + "soc_has_extmem", "soc_has_gpio", "soc_has_gpio_sd", "soc_has_hmac", @@ -4559,6 +4969,7 @@ impl Chip { "soc_has_pcnt", "soc_has_pcr", "soc_has_plic_mx", + "soc_has_plic_ux", "soc_has_pmu", "soc_has_rmt", "soc_has_rng", @@ -4605,7 +5016,6 @@ impl Chip { "ieee802154_driver_supported", "phy_driver_supported", "adc_driver_supported", - "temp_sensor_driver_supported", "ledc_driver_supported", "mcpwm_driver_supported", "pcnt_driver_supported", @@ -4625,6 +5035,7 @@ impl Chip { "etm_driver_supported", "interrupts_driver_supported", "mmu_driver_supported", + "flash_driver_supported", "rom_driver_supported", "soc_driver_supported", "uart_uart0", @@ -4635,6 +5046,7 @@ impl Chip { "spi_slave_spi2", "i2s_i2s0", "adc_adc1", + "pcnt_PCNT", "timergroup_timg0", "timergroup_timg1", "gpio_version=\"2\"", @@ -4672,8 +5084,6 @@ impl Chip { "spi_master_has_dma_segmented_transfer", "i2s_version=\"3\"", "i2s_version_is_set", - "i2s_default_clock_source=\"1\"", - "i2s_default_clock_source_is_set", "i2s_mclk_divider_bit_width=\"9\"", "i2s_mclk_divider_bit_width_is_set", "i2s_max_ws_width=\"512\"", @@ -4683,6 +5093,7 @@ impl Chip { "i2s_supports_pdm_rx", "i2s_supports_pcm2pdm", "parl_io_version=\"2\"", + "parl_io_max_data_width=\"8\"", "rmt_ram_start=\"1610642432\"", "rmt_channel_ram_size=\"48\"", "rmt_has_tx_immediate_stop", @@ -4693,6 +5104,18 @@ impl Chip { "rmt_has_rx_wrap", "rmt_has_rx_demodulation", "bt_controller=\"npl\"", + "adc_controller=\"digital\"", + "adc_controller_is_set", + "adc_channel_count=\"5\"", + "adc_channel_count_is_set", + "adc_line_calibration", + "adc_curve_calibration", + "adc_basic_calibration", + "adc_calibration_v1_scheme_supported", + "adc_channel_compensation", + "adc_pcr_clock", + "adc_pcr_sar_clk_div", + "adc_sar_power_override", "ledc_version=\"3\"", "ledc_channel_count=\"6\"", "soc_has_sdm_ch0", @@ -4700,9 +5123,11 @@ impl Chip { "soc_has_sdm_ch2", "soc_has_sdm_ch3", "timergroup_timg_has_divcnt_rst", + "timergroup_wdt_has_conf_update", "timergroup_rc_fast_calibration_divider", "timergroup_rc_fast_calibration_tick_enable", "timergroup_rc_fast_calibration_is_set", + "timergroup_rc_slow_calibration_is_set", "aes_dma_mode_ecb", "aes_dma_mode_cbc", "aes_dma_mode_ofb", @@ -4723,6 +5148,9 @@ impl Chip { "rsa_version=\"3\"", "rsa_size_increment=\"32\"", "rsa_memory_size_bytes=\"384\"", + "sha_has_sha1", + "sha_has_sha224", + "sha_has_sha256", "sleep_light_sleep", "sleep_deep_sleep", "sleep_has_wakeup_source_ext1", @@ -4736,6 +5164,10 @@ impl Chip { "sleep_has_wakeup_source_lp_core", "sleep_ext1_version=\"2\"", "sleep_ext1_version_is_set", + "cpu_retention=\"software\"", + "cpu_retention_frame=\"c6_h2\"", + "supports_cpu_power_down", + "supports_top_power_down", "assist_debug_has_sp_monitor", "assist_debug_has_region_monitor", "dma_separate_in_out_interrupts", @@ -4763,6 +5195,7 @@ impl Chip { "dma_max_priority_is_set", "interrupts_status_registers=\"2\"", "interrupt_controller=\"plic\"", + "context_switch_source=\"clint\"", "mmu_page_size=\"65536\"", "mmu_entry_num=\"256\"", "rom_has_crc_le", @@ -4773,6 +5206,8 @@ impl Chip { "soc_cpu_csr_prv_mode_is_set", "soc_has_swd_watchdog", "soc_cpu_mcause_mask=\"31\"", + "soc_cpu_pmp_granularity=\"4\"", + "soc_cpu_pmp_granularity_is_set", "soc_has_clock_node_xtal_clk", "soc_clock_node_xtal_clk_is_configurable", "soc_has_clock_node_pll_f96m_clk", @@ -4798,6 +5233,12 @@ impl Chip { "soc_clock_node_lp_fast_clk_is_configurable", "soc_has_clock_node_lp_slow_clk", "soc_clock_node_lp_slow_clk_is_configurable", + "soc_has_clock_node_ble_lp_xtal_clk", + "soc_has_clock_node_ble_lp_rc_slow_clk", + "soc_has_clock_node_ble_lp_clk", + "soc_clock_node_ble_lp_clk_is_configurable", + "soc_has_clock_node_crypto_clk", + "soc_clock_node_crypto_clk_is_configurable", "soc_has_clock_node_timg_calibration_clock", "soc_clock_node_timg_calibration_clock_is_configurable", "soc_has_clock_node_uart_function_clock", @@ -4817,10 +5258,18 @@ impl Chip { "soc_clock_node_parl_io_rx_clock_is_configurable", "soc_has_clock_node_parl_io_tx_clock", "soc_clock_node_parl_io_tx_clock_is_configurable", + "soc_has_clock_node_i2s_tx_clk", + "soc_clock_node_i2s_tx_clk_is_configurable", + "soc_has_clock_node_i2s_rx_clk", + "soc_clock_node_i2s_rx_clk_is_configurable", + "soc_has_clock_node_i2s_mclk_out", + "soc_clock_node_i2s_mclk_out_is_configurable", "soc_has_clock_node_i2c_function_clock", "soc_clock_node_i2c_function_clock_is_configurable", "soc_has_clock_node_spi_function_clock", "soc_clock_node_spi_function_clock_is_configurable", + "soc_has_clock_node_adc_function_clock", + "soc_clock_node_adc_function_clock_is_configurable", "has_dram_region", "has_dram2_uninit_region", "has_irom_region", @@ -4833,10 +5282,12 @@ impl Chip { "cargo:rustc-cfg=soc_has_aes", "cargo:rustc-cfg=soc_has_apb_saradc", "cargo:rustc-cfg=soc_has_assist_debug", + "cargo:rustc-cfg=soc_has_clint", "cargo:rustc-cfg=soc_has_dma", "cargo:rustc-cfg=soc_has_ds", "cargo:rustc-cfg=soc_has_ecc", "cargo:rustc-cfg=soc_has_efuse", + "cargo:rustc-cfg=soc_has_extmem", "cargo:rustc-cfg=soc_has_gpio", "cargo:rustc-cfg=soc_has_gpio_sd", "cargo:rustc-cfg=soc_has_hmac", @@ -4870,6 +5321,7 @@ impl Chip { "cargo:rustc-cfg=soc_has_pcnt", "cargo:rustc-cfg=soc_has_pcr", "cargo:rustc-cfg=soc_has_plic_mx", + "cargo:rustc-cfg=soc_has_plic_ux", "cargo:rustc-cfg=soc_has_pmu", "cargo:rustc-cfg=soc_has_rmt", "cargo:rustc-cfg=soc_has_rng", @@ -4916,7 +5368,6 @@ impl Chip { "cargo:rustc-cfg=ieee802154_driver_supported", "cargo:rustc-cfg=phy_driver_supported", "cargo:rustc-cfg=adc_driver_supported", - "cargo:rustc-cfg=temp_sensor_driver_supported", "cargo:rustc-cfg=ledc_driver_supported", "cargo:rustc-cfg=mcpwm_driver_supported", "cargo:rustc-cfg=pcnt_driver_supported", @@ -4936,6 +5387,7 @@ impl Chip { "cargo:rustc-cfg=etm_driver_supported", "cargo:rustc-cfg=interrupts_driver_supported", "cargo:rustc-cfg=mmu_driver_supported", + "cargo:rustc-cfg=flash_driver_supported", "cargo:rustc-cfg=rom_driver_supported", "cargo:rustc-cfg=soc_driver_supported", "cargo:rustc-cfg=uart_uart0", @@ -4946,6 +5398,7 @@ impl Chip { "cargo:rustc-cfg=spi_slave_spi2", "cargo:rustc-cfg=i2s_i2s0", "cargo:rustc-cfg=adc_adc1", + "cargo:rustc-cfg=pcnt_PCNT", "cargo:rustc-cfg=timergroup_timg0", "cargo:rustc-cfg=timergroup_timg1", "cargo:rustc-cfg=gpio_version=\"2\"", @@ -4983,8 +5436,6 @@ impl Chip { "cargo:rustc-cfg=spi_master_has_dma_segmented_transfer", "cargo:rustc-cfg=i2s_version=\"3\"", "cargo:rustc-cfg=i2s_version_is_set", - "cargo:rustc-cfg=i2s_default_clock_source=\"1\"", - "cargo:rustc-cfg=i2s_default_clock_source_is_set", "cargo:rustc-cfg=i2s_mclk_divider_bit_width=\"9\"", "cargo:rustc-cfg=i2s_mclk_divider_bit_width_is_set", "cargo:rustc-cfg=i2s_max_ws_width=\"512\"", @@ -4994,6 +5445,7 @@ impl Chip { "cargo:rustc-cfg=i2s_supports_pdm_rx", "cargo:rustc-cfg=i2s_supports_pcm2pdm", "cargo:rustc-cfg=parl_io_version=\"2\"", + "cargo:rustc-cfg=parl_io_max_data_width=\"8\"", "cargo:rustc-cfg=rmt_ram_start=\"1610642432\"", "cargo:rustc-cfg=rmt_channel_ram_size=\"48\"", "cargo:rustc-cfg=rmt_has_tx_immediate_stop", @@ -5004,6 +5456,18 @@ impl Chip { "cargo:rustc-cfg=rmt_has_rx_wrap", "cargo:rustc-cfg=rmt_has_rx_demodulation", "cargo:rustc-cfg=bt_controller=\"npl\"", + "cargo:rustc-cfg=adc_controller=\"digital\"", + "cargo:rustc-cfg=adc_controller_is_set", + "cargo:rustc-cfg=adc_channel_count=\"5\"", + "cargo:rustc-cfg=adc_channel_count_is_set", + "cargo:rustc-cfg=adc_line_calibration", + "cargo:rustc-cfg=adc_curve_calibration", + "cargo:rustc-cfg=adc_basic_calibration", + "cargo:rustc-cfg=adc_calibration_v1_scheme_supported", + "cargo:rustc-cfg=adc_channel_compensation", + "cargo:rustc-cfg=adc_pcr_clock", + "cargo:rustc-cfg=adc_pcr_sar_clk_div", + "cargo:rustc-cfg=adc_sar_power_override", "cargo:rustc-cfg=ledc_version=\"3\"", "cargo:rustc-cfg=ledc_channel_count=\"6\"", "cargo:rustc-cfg=soc_has_sdm_ch0", @@ -5011,9 +5475,11 @@ impl Chip { "cargo:rustc-cfg=soc_has_sdm_ch2", "cargo:rustc-cfg=soc_has_sdm_ch3", "cargo:rustc-cfg=timergroup_timg_has_divcnt_rst", + "cargo:rustc-cfg=timergroup_wdt_has_conf_update", "cargo:rustc-cfg=timergroup_rc_fast_calibration_divider", "cargo:rustc-cfg=timergroup_rc_fast_calibration_tick_enable", "cargo:rustc-cfg=timergroup_rc_fast_calibration_is_set", + "cargo:rustc-cfg=timergroup_rc_slow_calibration_is_set", "cargo:rustc-cfg=aes_dma_mode_ecb", "cargo:rustc-cfg=aes_dma_mode_cbc", "cargo:rustc-cfg=aes_dma_mode_ofb", @@ -5034,6 +5500,9 @@ impl Chip { "cargo:rustc-cfg=rsa_version=\"3\"", "cargo:rustc-cfg=rsa_size_increment=\"32\"", "cargo:rustc-cfg=rsa_memory_size_bytes=\"384\"", + "cargo:rustc-cfg=sha_has_sha1", + "cargo:rustc-cfg=sha_has_sha224", + "cargo:rustc-cfg=sha_has_sha256", "cargo:rustc-cfg=sleep_light_sleep", "cargo:rustc-cfg=sleep_deep_sleep", "cargo:rustc-cfg=sleep_has_wakeup_source_ext1", @@ -5047,6 +5516,10 @@ impl Chip { "cargo:rustc-cfg=sleep_has_wakeup_source_lp_core", "cargo:rustc-cfg=sleep_ext1_version=\"2\"", "cargo:rustc-cfg=sleep_ext1_version_is_set", + "cargo:rustc-cfg=cpu_retention=\"software\"", + "cargo:rustc-cfg=cpu_retention_frame=\"c6_h2\"", + "cargo:rustc-cfg=supports_cpu_power_down", + "cargo:rustc-cfg=supports_top_power_down", "cargo:rustc-cfg=assist_debug_has_sp_monitor", "cargo:rustc-cfg=assist_debug_has_region_monitor", "cargo:rustc-cfg=dma_separate_in_out_interrupts", @@ -5074,6 +5547,7 @@ impl Chip { "cargo:rustc-cfg=dma_max_priority_is_set", "cargo:rustc-cfg=interrupts_status_registers=\"2\"", "cargo:rustc-cfg=interrupt_controller=\"plic\"", + "cargo:rustc-cfg=context_switch_source=\"clint\"", "cargo:rustc-cfg=mmu_page_size=\"65536\"", "cargo:rustc-cfg=mmu_entry_num=\"256\"", "cargo:rustc-cfg=rom_has_crc_le", @@ -5084,6 +5558,8 @@ impl Chip { "cargo:rustc-cfg=soc_cpu_csr_prv_mode_is_set", "cargo:rustc-cfg=soc_has_swd_watchdog", "cargo:rustc-cfg=soc_cpu_mcause_mask=\"31\"", + "cargo:rustc-cfg=soc_cpu_pmp_granularity=\"4\"", + "cargo:rustc-cfg=soc_cpu_pmp_granularity_is_set", "cargo:rustc-cfg=soc_has_clock_node_xtal_clk", "cargo:rustc-cfg=soc_clock_node_xtal_clk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_pll_f96m_clk", @@ -5109,6 +5585,12 @@ impl Chip { "cargo:rustc-cfg=soc_clock_node_lp_fast_clk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_lp_slow_clk", "cargo:rustc-cfg=soc_clock_node_lp_slow_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_ble_lp_xtal_clk", + "cargo:rustc-cfg=soc_has_clock_node_ble_lp_rc_slow_clk", + "cargo:rustc-cfg=soc_has_clock_node_ble_lp_clk", + "cargo:rustc-cfg=soc_clock_node_ble_lp_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_crypto_clk", + "cargo:rustc-cfg=soc_clock_node_crypto_clk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_timg_calibration_clock", "cargo:rustc-cfg=soc_clock_node_timg_calibration_clock_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_uart_function_clock", @@ -5128,10 +5610,18 @@ impl Chip { "cargo:rustc-cfg=soc_clock_node_parl_io_rx_clock_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_parl_io_tx_clock", "cargo:rustc-cfg=soc_clock_node_parl_io_tx_clock_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_i2s_tx_clk", + "cargo:rustc-cfg=soc_clock_node_i2s_tx_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_i2s_rx_clk", + "cargo:rustc-cfg=soc_clock_node_i2s_rx_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_i2s_mclk_out", + "cargo:rustc-cfg=soc_clock_node_i2s_mclk_out_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_i2c_function_clock", "cargo:rustc-cfg=soc_clock_node_i2c_function_clock_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_spi_function_clock", "cargo:rustc-cfg=soc_clock_node_spi_function_clock_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_adc_function_clock", + "cargo:rustc-cfg=soc_clock_node_adc_function_clock_is_configurable", "cargo:rustc-cfg=has_dram_region", "cargo:rustc-cfg=has_dram2_uninit_region", "cargo:rustc-cfg=has_irom_region", @@ -5252,91 +5742,93 @@ impl Chip { }, ], }, - Self::Esp32p4 => Config { + Self::Esp32h4 => Config { architecture: "riscv", target: "riscv32imafc-unknown-none-elf", symbols: &[ - "esp32p4", + "esp32h4", "riscv", "multi_core", + "soc_has_aes", + "soc_has_apb_saradc", + "soc_has_asrc", + "soc_has_bus_monitor", + "soc_has_cache", + "soc_has_clic", + "soc_has_clint", + "soc_has_clint_other_core", + "soc_has_cpu_apm", + "soc_has_dma", + "soc_has_ecc", + "soc_has_ecdsa", "soc_has_efuse", + "soc_has_etm", "soc_has_gpio", + "soc_has_gpio_dedicated", "soc_has_gpio_sd", - "soc_has_system", + "soc_has_hmac", + "soc_has_hp_apm", "soc_has_hp_sys", - "soc_has_hp_sys_clkrst", - "soc_has_rng", + "soc_has_huk", + "soc_has_i2c_ana_mst", + "soc_has_i2s0", + "soc_has_i2c0", + "soc_has_i2c1", + "soc_has_ieee802154", "soc_has_interrupt_core0", "soc_has_interrupt_core1", - "soc_has_lp_i2c_ana_mst", - "soc_has_clic", + "soc_has_intpri", "soc_has_io_mux", - "soc_has_iomux_mspi_pin", - "soc_has_lp_i2c0", + "soc_has_keymng", + "soc_has_ledc", + "soc_has_lpwr", + "soc_has_lp_ana", "soc_has_lp_aon", - "soc_has_lp_aon_clkrst", - "soc_has_lp_sys", + "soc_has_lp_clkrst", "soc_has_lp_gpio", "soc_has_lp_io_mux", "soc_has_lp_peri", - "soc_has_rtc_timer", + "soc_has_lp_tee", "soc_has_lp_wdt", - "soc_has_lpwr", + "soc_has_mcpwm0", + "soc_has_mcpwm1", + "soc_has_mem_monitor", + "soc_has_modem_lpcon", + "soc_has_modem_syscon", + "soc_has_parl_io", + "soc_has_pau", + "soc_has_pcnt", + "soc_has_pcr", "soc_has_pmu", + "soc_has_pvt", + "soc_has_rmt", + "soc_has_rng", + "soc_has_sha", + "soc_has_rtc_timer", + "soc_has_spi0", + "soc_has_spi1", + "soc_has_spi2", + "soc_has_spi3", + "soc_has_system", "soc_has_systimer", + "soc_has_tee", "soc_has_timg0", "soc_has_timg1", + "soc_has_touch", + "soc_has_touch_aon", + "soc_has_twai0", "soc_has_uart0", "soc_has_uart1", - "soc_has_uart2", - "soc_has_uart3", - "soc_has_uart4", "soc_has_uhci0", - "soc_has_spi0", - "soc_has_spi1", - "soc_has_memspi2", - "soc_has_memspi3", - "soc_has_spi2", - "soc_has_spi3", - "soc_has_i2c0", - "soc_has_i2c1", - "soc_has_i2s0", - "soc_has_i2s1", - "soc_has_i2s2", - "soc_has_twai0", - "soc_has_twai1", - "soc_has_twai2", - "soc_has_dma", - "soc_has_axi_gdma", - "soc_has_eth", - "soc_has_emac_dma", - "soc_has_emac_mac", - "soc_has_mipi_dsi", - "soc_has_vdma", - "soc_has_mipi_dsi_host", - "soc_has_mipi_dsi_bridge", "soc_has_usb_device", - "soc_has_sdhost", - "soc_has_ledc", - "soc_has_mcpwm0", - "soc_has_mcpwm1", - "soc_has_pcnt", - "soc_has_apb_saradc", - "soc_has_lp_adc", - "soc_has_rmt", - "soc_has_aes", - "soc_has_sha", - "soc_has_rsa", - "soc_has_ecc", "soc_has_usb_fs", - "soc_has_usb_hs", "soc_has_usb_wrap", + "soc_has_zero_det", "soc_has_adc1", - "soc_has_adc2", - "soc_has_flash", - "soc_has_psram", - "soc_has_gpio_dedicated", + "soc_has_bt", "soc_has_cpu_ctrl", + "soc_has_ipc", + "soc_has_flash", "soc_has_from_cpu_intr0", "soc_has_from_cpu_intr1", "soc_has_from_cpu_intr2", @@ -5346,151 +5838,901 @@ impl Chip { "io_mux_driver_supported", "lp_io_driver_supported", "uart_driver_supported", - "uhci_driver_supported", "i2c_master_driver_supported", - "lp_i2c_master_driver_supported", "spi_master_driver_supported", - "spi_slave_driver_supported", "i2s_driver_supported", - "rmt_driver_supported", - "sdmmc_driver_supported", - "usb_otg_driver_supported", - "usb_otg_hs_driver_supported", "usb_serial_jtag_driver_supported", - "ethernet_driver_supported", - "mipi_dsi_driver_supported", - "adc_driver_supported", + "bt_driver_supported", + "ieee802154_driver_supported", + "phy_driver_supported", "lp_timer_driver_supported", - "sdm_driver_supported", "systimer_driver_supported", "timergroup_driver_supported", - "aes_driver_supported", - "ecc_driver_supported", "rng_driver_supported", - "rsa_driver_supported", - "sha_driver_supported", "sleep_driver_supported", "dma_driver_supported", "interrupts_driver_supported", "mmu_driver_supported", - "psram_driver_supported", + "flash_driver_supported", "rom_driver_supported", "soc_driver_supported", "uart_uart0", "uart_uart1", - "uart_uart2", - "uart_uart3", - "uart_uart4", "i2c_master_i2c0", "i2c_master_i2c1", "spi_master_spi2", "spi_master_spi3", - "spi_slave_spi2", - "spi_slave_spi3", "i2s_i2s0", - "i2s_i2s1", - "i2s_i2s2", - "adc_adc1", - "adc_adc2", "timergroup_timg0", "timergroup_timg1", "gpio_version=\"3\"", "gpio_has_input_sync", "gpio_gpio_function=\"1\"", - "gpio_constant_0_input=\"62\"", - "gpio_constant_1_input=\"63\"", - "gpio_func_in_sel_offset=\"1\"", + "gpio_constant_0_input=\"96\"", + "gpio_constant_1_input=\"64\"", + "gpio_func_in_sel_offset=\"0\"", + "soc_has_xtal32k_pads", "gpio_has_bank_1", - "gpio_input_signal_max=\"249\"", + "gpio_input_signal_max=\"189\"", "gpio_output_signal_max=\"256\"", - "dedicated_gpio_version=\"riscv_v2\"", - "lp_io_version=\"esp32p4\"", - "lp_io_has_gpio_matrix", + "dedicated_gpio_version=\"riscv_v1\"", + "lp_io_version=\"v4\"", "uart_ram_size=\"128\"", "uart_version=\"2\"", - "uhci_combined_uart_selector_field", + "uart_peripheral_controls_mem_clk", + "uart_has_sclk_enable", "i2c_master_version=\"4\"", "i2c_master_has_fsm_timeouts", "i2c_master_has_hw_bus_clear", "i2c_master_has_bus_timeout_enable", "i2c_master_can_estimate_nack_reason", "i2c_master_has_conf_update", + "i2c_master_has_reliable_fsm_reset", "i2c_master_has_arbitration_en", + "i2c_master_has_tx_fifo_watermark", + "i2c_master_bus_timeout_is_exponential", "i2c_master_has_pd_en", "i2c_master_max_bus_timeout=\"31\"", "i2c_master_ll_intr_mask=\"262143\"", "i2c_master_fifo_size=\"32\"", - "lp_i2c_master_version=\"lp_i2c\"", - "lp_i2c_master_fifo_size=\"16\"", - "lp_i2c_master_fifo_size_is_set", "spi_master_version=\"3\"", "spi_master_fifo_size=\"64\"", + "spi_master_has_app_interrupts", + "spi_master_has_dma_segmented_transfer", "i2s_version=\"3\"", "i2s_version_is_set", - "i2s_default_clock_source=\"3\"", - "i2s_default_clock_source_is_set", - "i2s_mclk_divider_bit_width=\"6\"", + "i2s_mclk_divider_bit_width=\"9\"", "i2s_mclk_divider_bit_width_is_set", - "i2s_max_ws_width=\"128\"", + "i2s_max_ws_width=\"512\"", "i2s_max_ws_width_is_set", - "i2s_clock_configured_by_hp_sys_clkrst", - "i2s_supports_pdm_rx_hp_filter", + "i2s_clock_configured_by_pcr", "i2s_supports_pdm_tx", "i2s_supports_pdm_rx", "i2s_supports_pcm2pdm", - "i2s_supports_pdm2pcm", - "rmt_ram_start=\"1342842880\"", - "rmt_channel_ram_size=\"48\"", - "rmt_has_tx_immediate_stop", - "rmt_has_tx_loop_count", - "rmt_has_tx_loop_auto_stop", - "rmt_has_tx_carrier_data_only", - "rmt_has_tx_sync", - "rmt_has_rx_wrap", - "rmt_has_rx_demodulation", - "sdmmc_delay_phase_num=\"8\"", - "sdmmc_delay_phase_num_is_set", - "sdmmc_has_iomux", - "sdmmc_has_gpio_matrix", - "sdmmc_psram_dma", - "usb_otg_fifo_depth_words=\"200\"", - "usb_otg_hs_fifo_depth_words=\"896\"", - "ethernet_mii_via_gpio_matrix", - "soc_has_sdm_ch0", - "soc_has_sdm_ch1", - "soc_has_sdm_ch2", - "soc_has_sdm_ch3", - "soc_has_sdm_ch4", - "soc_has_sdm_ch5", - "soc_has_sdm_ch6", - "soc_has_sdm_ch7", - "timergroup_timg_has_timer1", + "bt_controller=\"btdm2\"", "timergroup_timg_has_divcnt_rst", + "timergroup_wdt_has_conf_update", + "timergroup_rc_fast_calibration_divider", "timergroup_rc_fast_calibration_is_set", - "aes_dma_mode_ecb", - "aes_dma_mode_cbc", - "aes_dma_mode_ofb", - "aes_dma_mode_ctr", - "aes_dma_mode_cfb8", - "aes_dma_mode_cfb128", - "aes_dma_mode_gcm", - "aes_has_split_text_registers", - "ecc_separate_jacobian_point_memory", - "ecc_has_memory_clock_gate", - "ecc_supports_enhanced_security", - "ecc_has_modular_arithmetic", - "ecc_has_point_addition", - "ecc_has_curve_p192", - "ecc_has_curve_p256", - "ecc_has_curve_p384", + "timergroup_rc_slow_calibration_multiplier", + "timergroup_rc_slow_calibration_is_set", "rng_apb_cycle_wait_num=\"16\"", - "rng_is_lp_sys", - "rsa_version=\"3\"", - "rsa_size_increment=\"32\"", - "rsa_memory_size_bytes=\"512\"", "sleep_light_sleep", "sleep_deep_sleep", - "sleep_has_wakeup_source_sdio", + "sleep_has_wakeup_source_ext1", + "sleep_has_wakeup_source_gpio", + "sleep_has_wakeup_source_timer", + "sleep_has_wakeup_source_uart", + "sleep_has_wakeup_source_bt", + "sleep_has_wakeup_source_usb", + "sleep_ext1_version=\"2\"", + "sleep_ext1_version_is_set", + "sleep_pin_wakeup_version=\"3\"", + "sleep_pin_wakeup_version_is_set", + "dma_separate_in_out_interrupts", + "dma_gdma_version=\"3\"", + "dma_gdma_version_is_set", + "soc_has_dma_ch0", + "soc_has_dma_ch1", + "soc_has_dma_ch2", + "soc_has_dma_ch3", + "soc_has_dma_ch4", + "dma_supports_mem2mem", + "i2s_supports_dma", + "i2s_dma_engine=\"AHB_GDMA\"", + "spi_master_supports_dma", + "spi_master_dma_engine=\"AHB_GDMA\"", + "dma_max_priority=\"5\"", + "dma_max_priority_is_set", + "interrupts_status_registers=\"4\"", + "interrupt_controller=\"clic\"", + "context_switch_source=\"ipc\"", + "mmu_page_size=\"65536\"", + "mmu_entry_num=\"512\"", + "rom_has_crc_le", + "rom_has_crc_be", + "rom_has_md5_bsd", + "soc_cpu_has_branch_predictor", + "soc_cpu_has_zcmp_workaround", + "soc_multi_core_enabled", + "soc_cpu_csr_prv_mode=\"2064\"", + "soc_cpu_csr_prv_mode_is_set", + "soc_has_swd_watchdog", + "soc_cpu_mcause_mask=\"63\"", + "soc_cpu_pmp_granularity=\"128\"", + "soc_cpu_pmp_granularity_is_set", + "soc_has_clock_node_xtal_clk", + "soc_has_clock_node_pll_f96m_clk", + "soc_has_clock_node_pll_f48m_clk", + "soc_has_clock_node_iomux_function_clock", + "soc_clock_node_iomux_function_clock_is_configurable", + "soc_has_clock_node_xtal_x2_clk", + "soc_has_clock_node_rc_fast_clk", + "soc_has_clock_node_xtal32k_clk", + "soc_has_clock_node_osc_slow_clk", + "soc_has_clock_node_rc_slow_clk", + "soc_has_clock_node_rc_slow_d4_clk", + "soc_has_clock_node_hp_root_clk", + "soc_clock_node_hp_root_clk_is_configurable", + "soc_has_clock_node_cpu_clk", + "soc_clock_node_cpu_clk_is_configurable", + "soc_has_clock_node_ahb_clk", + "soc_clock_node_ahb_clk_is_configurable", + "soc_has_clock_node_apb_clk", + "soc_clock_node_apb_clk_is_configurable", + "soc_has_clock_node_xtal_d2_clk", + "soc_has_clock_node_lp_fast_clk", + "soc_clock_node_lp_fast_clk_is_configurable", + "soc_has_clock_node_lp_slow_clk", + "soc_clock_node_lp_slow_clk_is_configurable", + "soc_has_clock_node_ble_lp_xtal_clk", + "soc_has_clock_node_ble_lp_clk", + "soc_clock_node_ble_lp_clk_is_configurable", + "soc_has_clock_node_timg_calibration_clock", + "soc_clock_node_timg_calibration_clock_is_configurable", + "soc_has_clock_node_uart_function_clock", + "soc_clock_node_uart_function_clock_is_configurable", + "soc_has_clock_node_uart_baud_rate_generator", + "soc_clock_node_uart_baud_rate_generator_is_configurable", + "soc_has_clock_node_spi_function_clock", + "soc_clock_node_spi_function_clock_is_configurable", + "soc_has_clock_node_i2s_tx_clk", + "soc_clock_node_i2s_tx_clk_is_configurable", + "soc_has_clock_node_i2s_rx_clk", + "soc_clock_node_i2s_rx_clk_is_configurable", + "soc_has_clock_node_i2s_mclk_out", + "soc_clock_node_i2s_mclk_out_is_configurable", + "soc_has_clock_node_i2c_function_clock", + "soc_clock_node_i2c_function_clock_is_configurable", + "soc_has_clock_node_timg_function_clock", + "soc_clock_node_timg_function_clock_is_configurable", + "soc_has_clock_node_timg_wdt_clock", + "soc_clock_node_timg_wdt_clock_is_configurable", + "has_dram_region", + "has_dram2_uninit_region", + "has_irom_region", + "has_drom_region", + ], + cfgs: &[ + "cargo:rustc-cfg=esp32h4", + "cargo:rustc-cfg=riscv", + "cargo:rustc-cfg=multi_core", + "cargo:rustc-cfg=soc_has_aes", + "cargo:rustc-cfg=soc_has_apb_saradc", + "cargo:rustc-cfg=soc_has_asrc", + "cargo:rustc-cfg=soc_has_bus_monitor", + "cargo:rustc-cfg=soc_has_cache", + "cargo:rustc-cfg=soc_has_clic", + "cargo:rustc-cfg=soc_has_clint", + "cargo:rustc-cfg=soc_has_clint_other_core", + "cargo:rustc-cfg=soc_has_cpu_apm", + "cargo:rustc-cfg=soc_has_dma", + "cargo:rustc-cfg=soc_has_ecc", + "cargo:rustc-cfg=soc_has_ecdsa", + "cargo:rustc-cfg=soc_has_efuse", + "cargo:rustc-cfg=soc_has_etm", + "cargo:rustc-cfg=soc_has_gpio", + "cargo:rustc-cfg=soc_has_gpio_dedicated", + "cargo:rustc-cfg=soc_has_gpio_sd", + "cargo:rustc-cfg=soc_has_hmac", + "cargo:rustc-cfg=soc_has_hp_apm", + "cargo:rustc-cfg=soc_has_hp_sys", + "cargo:rustc-cfg=soc_has_huk", + "cargo:rustc-cfg=soc_has_i2c_ana_mst", + "cargo:rustc-cfg=soc_has_i2s0", + "cargo:rustc-cfg=soc_has_i2c0", + "cargo:rustc-cfg=soc_has_i2c1", + "cargo:rustc-cfg=soc_has_ieee802154", + "cargo:rustc-cfg=soc_has_interrupt_core0", + "cargo:rustc-cfg=soc_has_interrupt_core1", + "cargo:rustc-cfg=soc_has_intpri", + "cargo:rustc-cfg=soc_has_io_mux", + "cargo:rustc-cfg=soc_has_keymng", + "cargo:rustc-cfg=soc_has_ledc", + "cargo:rustc-cfg=soc_has_lpwr", + "cargo:rustc-cfg=soc_has_lp_ana", + "cargo:rustc-cfg=soc_has_lp_aon", + "cargo:rustc-cfg=soc_has_lp_clkrst", + "cargo:rustc-cfg=soc_has_lp_gpio", + "cargo:rustc-cfg=soc_has_lp_io_mux", + "cargo:rustc-cfg=soc_has_lp_peri", + "cargo:rustc-cfg=soc_has_lp_tee", + "cargo:rustc-cfg=soc_has_lp_wdt", + "cargo:rustc-cfg=soc_has_mcpwm0", + "cargo:rustc-cfg=soc_has_mcpwm1", + "cargo:rustc-cfg=soc_has_mem_monitor", + "cargo:rustc-cfg=soc_has_modem_lpcon", + "cargo:rustc-cfg=soc_has_modem_syscon", + "cargo:rustc-cfg=soc_has_parl_io", + "cargo:rustc-cfg=soc_has_pau", + "cargo:rustc-cfg=soc_has_pcnt", + "cargo:rustc-cfg=soc_has_pcr", + "cargo:rustc-cfg=soc_has_pmu", + "cargo:rustc-cfg=soc_has_pvt", + "cargo:rustc-cfg=soc_has_rmt", + "cargo:rustc-cfg=soc_has_rng", + "cargo:rustc-cfg=soc_has_sha", + "cargo:rustc-cfg=soc_has_rtc_timer", + "cargo:rustc-cfg=soc_has_spi0", + "cargo:rustc-cfg=soc_has_spi1", + "cargo:rustc-cfg=soc_has_spi2", + "cargo:rustc-cfg=soc_has_spi3", + "cargo:rustc-cfg=soc_has_system", + "cargo:rustc-cfg=soc_has_systimer", + "cargo:rustc-cfg=soc_has_tee", + "cargo:rustc-cfg=soc_has_timg0", + "cargo:rustc-cfg=soc_has_timg1", + "cargo:rustc-cfg=soc_has_touch", + "cargo:rustc-cfg=soc_has_touch_aon", + "cargo:rustc-cfg=soc_has_twai0", + "cargo:rustc-cfg=soc_has_uart0", + "cargo:rustc-cfg=soc_has_uart1", + "cargo:rustc-cfg=soc_has_uhci0", + "cargo:rustc-cfg=soc_has_usb_device", + "cargo:rustc-cfg=soc_has_usb_fs", + "cargo:rustc-cfg=soc_has_usb_wrap", + "cargo:rustc-cfg=soc_has_zero_det", + "cargo:rustc-cfg=soc_has_adc1", + "cargo:rustc-cfg=soc_has_bt", + "cargo:rustc-cfg=soc_has_cpu_ctrl", + "cargo:rustc-cfg=soc_has_ipc", + "cargo:rustc-cfg=soc_has_flash", + "cargo:rustc-cfg=soc_has_from_cpu_intr0", + "cargo:rustc-cfg=soc_has_from_cpu_intr1", + "cargo:rustc-cfg=soc_has_from_cpu_intr2", + "cargo:rustc-cfg=soc_has_from_cpu_intr3", + "cargo:rustc-cfg=gpio_driver_supported", + "cargo:rustc-cfg=dedicated_gpio_driver_supported", + "cargo:rustc-cfg=io_mux_driver_supported", + "cargo:rustc-cfg=lp_io_driver_supported", + "cargo:rustc-cfg=uart_driver_supported", + "cargo:rustc-cfg=i2c_master_driver_supported", + "cargo:rustc-cfg=spi_master_driver_supported", + "cargo:rustc-cfg=i2s_driver_supported", + "cargo:rustc-cfg=usb_serial_jtag_driver_supported", + "cargo:rustc-cfg=bt_driver_supported", + "cargo:rustc-cfg=ieee802154_driver_supported", + "cargo:rustc-cfg=phy_driver_supported", + "cargo:rustc-cfg=lp_timer_driver_supported", + "cargo:rustc-cfg=systimer_driver_supported", + "cargo:rustc-cfg=timergroup_driver_supported", + "cargo:rustc-cfg=rng_driver_supported", + "cargo:rustc-cfg=sleep_driver_supported", + "cargo:rustc-cfg=dma_driver_supported", + "cargo:rustc-cfg=interrupts_driver_supported", + "cargo:rustc-cfg=mmu_driver_supported", + "cargo:rustc-cfg=flash_driver_supported", + "cargo:rustc-cfg=rom_driver_supported", + "cargo:rustc-cfg=soc_driver_supported", + "cargo:rustc-cfg=uart_uart0", + "cargo:rustc-cfg=uart_uart1", + "cargo:rustc-cfg=i2c_master_i2c0", + "cargo:rustc-cfg=i2c_master_i2c1", + "cargo:rustc-cfg=spi_master_spi2", + "cargo:rustc-cfg=spi_master_spi3", + "cargo:rustc-cfg=i2s_i2s0", + "cargo:rustc-cfg=timergroup_timg0", + "cargo:rustc-cfg=timergroup_timg1", + "cargo:rustc-cfg=gpio_version=\"3\"", + "cargo:rustc-cfg=gpio_has_input_sync", + "cargo:rustc-cfg=gpio_gpio_function=\"1\"", + "cargo:rustc-cfg=gpio_constant_0_input=\"96\"", + "cargo:rustc-cfg=gpio_constant_1_input=\"64\"", + "cargo:rustc-cfg=gpio_func_in_sel_offset=\"0\"", + "cargo:rustc-cfg=soc_has_xtal32k_pads", + "cargo:rustc-cfg=gpio_has_bank_1", + "cargo:rustc-cfg=gpio_input_signal_max=\"189\"", + "cargo:rustc-cfg=gpio_output_signal_max=\"256\"", + "cargo:rustc-cfg=dedicated_gpio_version=\"riscv_v1\"", + "cargo:rustc-cfg=lp_io_version=\"v4\"", + "cargo:rustc-cfg=uart_ram_size=\"128\"", + "cargo:rustc-cfg=uart_version=\"2\"", + "cargo:rustc-cfg=uart_peripheral_controls_mem_clk", + "cargo:rustc-cfg=uart_has_sclk_enable", + "cargo:rustc-cfg=i2c_master_version=\"4\"", + "cargo:rustc-cfg=i2c_master_has_fsm_timeouts", + "cargo:rustc-cfg=i2c_master_has_hw_bus_clear", + "cargo:rustc-cfg=i2c_master_has_bus_timeout_enable", + "cargo:rustc-cfg=i2c_master_can_estimate_nack_reason", + "cargo:rustc-cfg=i2c_master_has_conf_update", + "cargo:rustc-cfg=i2c_master_has_reliable_fsm_reset", + "cargo:rustc-cfg=i2c_master_has_arbitration_en", + "cargo:rustc-cfg=i2c_master_has_tx_fifo_watermark", + "cargo:rustc-cfg=i2c_master_bus_timeout_is_exponential", + "cargo:rustc-cfg=i2c_master_has_pd_en", + "cargo:rustc-cfg=i2c_master_max_bus_timeout=\"31\"", + "cargo:rustc-cfg=i2c_master_ll_intr_mask=\"262143\"", + "cargo:rustc-cfg=i2c_master_fifo_size=\"32\"", + "cargo:rustc-cfg=spi_master_version=\"3\"", + "cargo:rustc-cfg=spi_master_fifo_size=\"64\"", + "cargo:rustc-cfg=spi_master_has_app_interrupts", + "cargo:rustc-cfg=spi_master_has_dma_segmented_transfer", + "cargo:rustc-cfg=i2s_version=\"3\"", + "cargo:rustc-cfg=i2s_version_is_set", + "cargo:rustc-cfg=i2s_mclk_divider_bit_width=\"9\"", + "cargo:rustc-cfg=i2s_mclk_divider_bit_width_is_set", + "cargo:rustc-cfg=i2s_max_ws_width=\"512\"", + "cargo:rustc-cfg=i2s_max_ws_width_is_set", + "cargo:rustc-cfg=i2s_clock_configured_by_pcr", + "cargo:rustc-cfg=i2s_supports_pdm_tx", + "cargo:rustc-cfg=i2s_supports_pdm_rx", + "cargo:rustc-cfg=i2s_supports_pcm2pdm", + "cargo:rustc-cfg=bt_controller=\"btdm2\"", + "cargo:rustc-cfg=timergroup_timg_has_divcnt_rst", + "cargo:rustc-cfg=timergroup_wdt_has_conf_update", + "cargo:rustc-cfg=timergroup_rc_fast_calibration_divider", + "cargo:rustc-cfg=timergroup_rc_fast_calibration_is_set", + "cargo:rustc-cfg=timergroup_rc_slow_calibration_multiplier", + "cargo:rustc-cfg=timergroup_rc_slow_calibration_is_set", + "cargo:rustc-cfg=rng_apb_cycle_wait_num=\"16\"", + "cargo:rustc-cfg=sleep_light_sleep", + "cargo:rustc-cfg=sleep_deep_sleep", + "cargo:rustc-cfg=sleep_has_wakeup_source_ext1", + "cargo:rustc-cfg=sleep_has_wakeup_source_gpio", + "cargo:rustc-cfg=sleep_has_wakeup_source_timer", + "cargo:rustc-cfg=sleep_has_wakeup_source_uart", + "cargo:rustc-cfg=sleep_has_wakeup_source_bt", + "cargo:rustc-cfg=sleep_has_wakeup_source_usb", + "cargo:rustc-cfg=sleep_ext1_version=\"2\"", + "cargo:rustc-cfg=sleep_ext1_version_is_set", + "cargo:rustc-cfg=sleep_pin_wakeup_version=\"3\"", + "cargo:rustc-cfg=sleep_pin_wakeup_version_is_set", + "cargo:rustc-cfg=dma_separate_in_out_interrupts", + "cargo:rustc-cfg=dma_gdma_version=\"3\"", + "cargo:rustc-cfg=dma_gdma_version_is_set", + "cargo:rustc-cfg=soc_has_dma_ch0", + "cargo:rustc-cfg=soc_has_dma_ch1", + "cargo:rustc-cfg=soc_has_dma_ch2", + "cargo:rustc-cfg=soc_has_dma_ch3", + "cargo:rustc-cfg=soc_has_dma_ch4", + "cargo:rustc-cfg=dma_supports_mem2mem", + "cargo:rustc-cfg=i2s_supports_dma", + "cargo:rustc-cfg=i2s_dma_engine=\"AHB_GDMA\"", + "cargo:rustc-cfg=spi_master_supports_dma", + "cargo:rustc-cfg=spi_master_dma_engine=\"AHB_GDMA\"", + "cargo:rustc-cfg=dma_max_priority=\"5\"", + "cargo:rustc-cfg=dma_max_priority_is_set", + "cargo:rustc-cfg=interrupts_status_registers=\"4\"", + "cargo:rustc-cfg=interrupt_controller=\"clic\"", + "cargo:rustc-cfg=context_switch_source=\"ipc\"", + "cargo:rustc-cfg=mmu_page_size=\"65536\"", + "cargo:rustc-cfg=mmu_entry_num=\"512\"", + "cargo:rustc-cfg=rom_has_crc_le", + "cargo:rustc-cfg=rom_has_crc_be", + "cargo:rustc-cfg=rom_has_md5_bsd", + "cargo:rustc-cfg=soc_cpu_has_branch_predictor", + "cargo:rustc-cfg=soc_cpu_has_zcmp_workaround", + "cargo:rustc-cfg=soc_multi_core_enabled", + "cargo:rustc-cfg=soc_cpu_csr_prv_mode=\"2064\"", + "cargo:rustc-cfg=soc_cpu_csr_prv_mode_is_set", + "cargo:rustc-cfg=soc_has_swd_watchdog", + "cargo:rustc-cfg=soc_cpu_mcause_mask=\"63\"", + "cargo:rustc-cfg=soc_cpu_pmp_granularity=\"128\"", + "cargo:rustc-cfg=soc_cpu_pmp_granularity_is_set", + "cargo:rustc-cfg=soc_has_clock_node_xtal_clk", + "cargo:rustc-cfg=soc_has_clock_node_pll_f96m_clk", + "cargo:rustc-cfg=soc_has_clock_node_pll_f48m_clk", + "cargo:rustc-cfg=soc_has_clock_node_iomux_function_clock", + "cargo:rustc-cfg=soc_clock_node_iomux_function_clock_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_xtal_x2_clk", + "cargo:rustc-cfg=soc_has_clock_node_rc_fast_clk", + "cargo:rustc-cfg=soc_has_clock_node_xtal32k_clk", + "cargo:rustc-cfg=soc_has_clock_node_osc_slow_clk", + "cargo:rustc-cfg=soc_has_clock_node_rc_slow_clk", + "cargo:rustc-cfg=soc_has_clock_node_rc_slow_d4_clk", + "cargo:rustc-cfg=soc_has_clock_node_hp_root_clk", + "cargo:rustc-cfg=soc_clock_node_hp_root_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_cpu_clk", + "cargo:rustc-cfg=soc_clock_node_cpu_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_ahb_clk", + "cargo:rustc-cfg=soc_clock_node_ahb_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_apb_clk", + "cargo:rustc-cfg=soc_clock_node_apb_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_xtal_d2_clk", + "cargo:rustc-cfg=soc_has_clock_node_lp_fast_clk", + "cargo:rustc-cfg=soc_clock_node_lp_fast_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_lp_slow_clk", + "cargo:rustc-cfg=soc_clock_node_lp_slow_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_ble_lp_xtal_clk", + "cargo:rustc-cfg=soc_has_clock_node_ble_lp_clk", + "cargo:rustc-cfg=soc_clock_node_ble_lp_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_timg_calibration_clock", + "cargo:rustc-cfg=soc_clock_node_timg_calibration_clock_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_uart_function_clock", + "cargo:rustc-cfg=soc_clock_node_uart_function_clock_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_uart_baud_rate_generator", + "cargo:rustc-cfg=soc_clock_node_uart_baud_rate_generator_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_spi_function_clock", + "cargo:rustc-cfg=soc_clock_node_spi_function_clock_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_i2s_tx_clk", + "cargo:rustc-cfg=soc_clock_node_i2s_tx_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_i2s_rx_clk", + "cargo:rustc-cfg=soc_clock_node_i2s_rx_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_i2s_mclk_out", + "cargo:rustc-cfg=soc_clock_node_i2s_mclk_out_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_i2c_function_clock", + "cargo:rustc-cfg=soc_clock_node_i2c_function_clock_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_timg_function_clock", + "cargo:rustc-cfg=soc_clock_node_timg_function_clock_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_timg_wdt_clock", + "cargo:rustc-cfg=soc_clock_node_timg_wdt_clock_is_configurable", + "cargo:rustc-cfg=has_dram_region", + "cargo:rustc-cfg=has_dram2_uninit_region", + "cargo:rustc-cfg=has_irom_region", + "cargo:rustc-cfg=has_drom_region", + ], + memory_layout: &MemoryLayout { + regions: &[ + ( + "dram", + MemoryRegion { + address_range: 0x40810000..0x4084F350, + }, + ), + ( + "dram2_uninit", + MemoryRegion { + address_range: 0x4084F350..0x4085D350, + }, + ), + ( + "irom", + MemoryRegion { + address_range: 0x42000000..0x44000000, + }, + ), + ( + "drom", + MemoryRegion { + address_range: 0x42000000..0x44000000, + }, + ), + ], + }, + pins: &[ + PinInfo { + pin: 0, + limitations: &[], + }, + PinInfo { + pin: 1, + limitations: &[], + }, + PinInfo { + pin: 2, + limitations: &[], + }, + PinInfo { + pin: 3, + limitations: &[], + }, + PinInfo { + pin: 4, + limitations: &[], + }, + PinInfo { + pin: 5, + limitations: &[], + }, + PinInfo { + pin: 6, + limitations: &["spi_flash"], + }, + PinInfo { + pin: 7, + limitations: &["spi_flash"], + }, + PinInfo { + pin: 8, + limitations: &["spi_flash"], + }, + PinInfo { + pin: 9, + limitations: &["spi_flash"], + }, + PinInfo { + pin: 10, + limitations: &["spi_flash"], + }, + PinInfo { + pin: 11, + limitations: &["spi_flash"], + }, + PinInfo { + pin: 12, + limitations: &["spi_flash"], + }, + PinInfo { + pin: 13, + limitations: &["usb_jtag"], + }, + PinInfo { + pin: 14, + limitations: &["usb_jtag"], + }, + PinInfo { + pin: 15, + limitations: &[], + }, + PinInfo { + pin: 16, + limitations: &[], + }, + PinInfo { + pin: 17, + limitations: &[], + }, + PinInfo { + pin: 18, + limitations: &[], + }, + PinInfo { + pin: 19, + limitations: &[], + }, + PinInfo { + pin: 20, + limitations: &[], + }, + PinInfo { + pin: 21, + limitations: &[], + }, + PinInfo { + pin: 22, + limitations: &[], + }, + PinInfo { + pin: 23, + limitations: &["bootloader_uart"], + }, + PinInfo { + pin: 24, + limitations: &["bootloader_uart"], + }, + PinInfo { + pin: 25, + limitations: &["strapping"], + }, + PinInfo { + pin: 26, + limitations: &[], + }, + PinInfo { + pin: 27, + limitations: &[], + }, + PinInfo { + pin: 28, + limitations: &["jtag"], + }, + PinInfo { + pin: 29, + limitations: &["jtag"], + }, + PinInfo { + pin: 30, + limitations: &["jtag"], + }, + PinInfo { + pin: 31, + limitations: &["jtag"], + }, + PinInfo { + pin: 32, + limitations: &[], + }, + PinInfo { + pin: 33, + limitations: &[], + }, + PinInfo { + pin: 34, + limitations: &[], + }, + PinInfo { + pin: 35, + limitations: &[], + }, + PinInfo { + pin: 36, + limitations: &["strapping"], + }, + PinInfo { + pin: 37, + limitations: &[], + }, + PinInfo { + pin: 38, + limitations: &[], + }, + PinInfo { + pin: 39, + limitations: &[], + }, + ], + }, + Self::Esp32p4 => Config { + architecture: "riscv", + target: "riscv32imafc-unknown-none-elf", + symbols: &[ + "esp32p4", + "riscv", + "multi_core", + "soc_has_efuse", + "soc_has_gpio", + "soc_has_gpio_sd", + "soc_has_system", + "soc_has_hp_sys", + "soc_has_hp_sys_clkrst", + "soc_has_rng", + "soc_has_interrupt_core0", + "soc_has_interrupt_core1", + "soc_has_lp_i2c_ana_mst", + "soc_has_cache", + "soc_has_clic", + "soc_has_clint", + "soc_has_clint_other_core", + "soc_has_io_mux", + "soc_has_iomux_mspi_pin", + "soc_has_lp_i2c0", + "soc_has_lp_aon", + "soc_has_lp_aon_clkrst", + "soc_has_lp_sys", + "soc_has_lp_gpio", + "soc_has_lp_io_mux", + "soc_has_lp_peri", + "soc_has_rtc_timer", + "soc_has_lp_wdt", + "soc_has_lpwr", + "soc_has_pmu", + "soc_has_pau", + "soc_has_systimer", + "soc_has_timg0", + "soc_has_timg1", + "soc_has_uart0", + "soc_has_uart1", + "soc_has_uart2", + "soc_has_uart3", + "soc_has_uart4", + "soc_has_uhci0", + "soc_has_spi0", + "soc_has_spi1", + "soc_has_memspi2", + "soc_has_memspi3", + "soc_has_spi2", + "soc_has_spi3", + "soc_has_i2c0", + "soc_has_i2c1", + "soc_has_i2s0", + "soc_has_i2s1", + "soc_has_i2s2", + "soc_has_twai0", + "soc_has_twai1", + "soc_has_twai2", + "soc_has_dma", + "soc_has_axi_gdma", + "soc_has_eth", + "soc_has_emac_dma", + "soc_has_emac_mac", + "soc_has_mipi_dsi", + "soc_has_vdma", + "soc_has_mipi_dsi_host", + "soc_has_mipi_dsi_bridge", + "soc_has_usb_device", + "soc_has_sdhost", + "soc_has_ledc", + "soc_has_mcpwm0", + "soc_has_mcpwm1", + "soc_has_pcnt", + "soc_has_apb_saradc", + "soc_has_lp_adc", + "soc_has_rmt", + "soc_has_aes", + "soc_has_sha", + "soc_has_rsa", + "soc_has_ecc", + "soc_has_usb_fs", + "soc_has_usb_hs", + "soc_has_usb_wrap", + "soc_has_adc1", + "soc_has_adc2", + "soc_has_flash", + "soc_has_psram", + "soc_has_gpio_dedicated", + "soc_has_cpu_ctrl", + "soc_has_ipc", + "soc_has_from_cpu_intr0", + "soc_has_from_cpu_intr1", + "soc_has_from_cpu_intr2", + "soc_has_from_cpu_intr3", + "gpio_driver_supported", + "dedicated_gpio_driver_supported", + "io_mux_driver_supported", + "lp_io_driver_supported", + "uart_driver_supported", + "uhci_driver_supported", + "i2c_master_driver_supported", + "lp_i2c_master_driver_supported", + "spi_master_driver_supported", + "spi_slave_driver_supported", + "i2s_driver_supported", + "rmt_driver_supported", + "sdmmc_driver_supported", + "usb_otg_driver_supported", + "usb_otg_hs_driver_supported", + "usb_serial_jtag_driver_supported", + "ethernet_driver_supported", + "mipi_dsi_driver_supported", + "adc_driver_supported", + "pcnt_driver_supported", + "lp_timer_driver_supported", + "sdm_driver_supported", + "systimer_driver_supported", + "timergroup_driver_supported", + "aes_driver_supported", + "ecc_driver_supported", + "rng_driver_supported", + "rsa_driver_supported", + "sha_driver_supported", + "sleep_driver_supported", + "dma_driver_supported", + "interrupts_driver_supported", + "mmu_driver_supported", + "flash_driver_supported", + "psram_driver_supported", + "rom_driver_supported", + "soc_driver_supported", + "uart_uart0", + "uart_uart1", + "uart_uart2", + "uart_uart3", + "uart_uart4", + "i2c_master_i2c0", + "i2c_master_i2c1", + "spi_master_spi2", + "spi_master_spi3", + "spi_slave_spi2", + "spi_slave_spi3", + "i2s_i2s0", + "i2s_i2s1", + "i2s_i2s2", + "adc_adc1", + "adc_adc2", + "pcnt_PCNT", + "timergroup_timg0", + "timergroup_timg1", + "gpio_version=\"3\"", + "gpio_has_input_sync", + "gpio_gpio_function=\"1\"", + "gpio_constant_0_input=\"62\"", + "gpio_constant_1_input=\"63\"", + "gpio_func_in_sel_offset=\"1\"", + "gpio_has_bank_1", + "gpio_input_signal_max=\"249\"", + "gpio_output_signal_max=\"256\"", + "dedicated_gpio_version=\"riscv_v2\"", + "lp_io_version=\"esp32p4\"", + "lp_io_has_gpio_matrix", + "uart_ram_size=\"128\"", + "uart_version=\"2\"", + "uhci_combined_uart_selector_field", + "i2c_master_version=\"4\"", + "i2c_master_has_fsm_timeouts", + "i2c_master_has_hw_bus_clear", + "i2c_master_has_bus_timeout_enable", + "i2c_master_can_estimate_nack_reason", + "i2c_master_has_conf_update", + "i2c_master_has_arbitration_en", + "i2c_master_has_pd_en", + "i2c_master_max_bus_timeout=\"31\"", + "i2c_master_ll_intr_mask=\"262143\"", + "i2c_master_fifo_size=\"32\"", + "lp_i2c_master_version=\"lp_i2c\"", + "lp_i2c_master_fifo_size=\"16\"", + "lp_i2c_master_fifo_size_is_set", + "spi_master_version=\"3\"", + "spi_master_fifo_size=\"64\"", + "i2s_version=\"3\"", + "i2s_version_is_set", + "i2s_mclk_divider_bit_width=\"9\"", + "i2s_mclk_divider_bit_width_is_set", + "i2s_max_ws_width=\"128\"", + "i2s_max_ws_width_is_set", + "i2s_clock_configured_by_hp_sys_clkrst", + "i2s_supports_pdm_rx_hp_filter", + "i2s_supports_pdm_tx", + "i2s_supports_pdm_rx", + "i2s_supports_pcm2pdm", + "i2s_supports_pdm2pcm", + "rmt_ram_start=\"1342842880\"", + "rmt_channel_ram_size=\"48\"", + "rmt_has_tx_immediate_stop", + "rmt_has_tx_loop_count", + "rmt_has_tx_loop_auto_stop", + "rmt_has_tx_carrier_data_only", + "rmt_has_tx_sync", + "rmt_has_rx_wrap", + "rmt_has_rx_demodulation", + "sdmmc_delay_phase_num=\"8\"", + "sdmmc_delay_phase_num_is_set", + "sdmmc_has_iomux", + "sdmmc_has_gpio_matrix", + "sdmmc_psram_dma", + "usb_otg_fifo_depth_words=\"200\"", + "usb_otg_hs_fifo_depth_words=\"896\"", + "ethernet_mii_via_gpio_matrix", + "ethernet_rx_checksum_offload", + "ethernet_dma_burst_len=\"32\"", + "adc_line_calibration", + "adc_curve_calibration", + "adc_basic_calibration", + "adc_calibration_v1_scheme_supported", + "adc_channel_compensation", + "soc_has_sdm_ch0", + "soc_has_sdm_ch1", + "soc_has_sdm_ch2", + "soc_has_sdm_ch3", + "soc_has_sdm_ch4", + "soc_has_sdm_ch5", + "soc_has_sdm_ch6", + "soc_has_sdm_ch7", + "timergroup_timg_has_timer1", + "timergroup_timg_has_divcnt_rst", + "timergroup_wdt_has_conf_update", + "timergroup_rc_fast_calibration_is_set", + "timergroup_rc_slow_calibration_is_set", + "aes_dma_mode_ecb", + "aes_dma_mode_cbc", + "aes_dma_mode_ofb", + "aes_dma_mode_ctr", + "aes_dma_mode_cfb8", + "aes_dma_mode_cfb128", + "aes_dma_mode_gcm", + "aes_has_split_text_registers", + "ecc_separate_jacobian_point_memory", + "ecc_has_memory_clock_gate", + "ecc_supports_enhanced_security", + "ecc_has_modular_arithmetic", + "ecc_has_point_addition", + "ecc_has_curve_p192", + "ecc_has_curve_p256", + "ecc_has_curve_p384", + "rng_apb_cycle_wait_num=\"16\"", + "rng_trng_supported", + "rsa_version=\"3\"", + "rsa_size_increment=\"32\"", + "rsa_memory_size_bytes=\"512\"", + "sha_has_sha1", + "sha_has_sha224", + "sha_has_sha256", + "sha_has_sha384", + "sha_has_sha512", + "sha_has_sha512_224", + "sha_has_sha512_256", + "sleep_light_sleep", + "sleep_deep_sleep", + "sleep_has_wakeup_source_sdio", "sleep_has_wakeup_source_gpio", "sleep_has_wakeup_source_usb", "sleep_has_wakeup_source_uart", @@ -5501,6 +6743,10 @@ impl Chip { "sleep_ext1_version_is_set", "sleep_pin_wakeup_version=\"3\"", "sleep_pin_wakeup_version_is_set", + "cpu_retention=\"software\"", + "cpu_retention_frame=\"p4\"", + "supports_cpu_power_down", + "supports_top_power_down", "dma_separate_in_out_interrupts", "dma_gdma_version=\"2\"", "dma_gdma_version_is_set", @@ -5534,8 +6780,9 @@ impl Chip { "dma_max_priority_is_set", "interrupts_status_registers=\"5\"", "interrupt_controller=\"clic\"", + "context_switch_source=\"ipc\"", "mmu_page_size=\"65536\"", - "mmu_entry_num=\"512\"", + "mmu_entry_num=\"1024\"", "psram_octal_spi", "psram_hex_spi", "psram_extmem_origin=\"1207959552\"", @@ -5543,10 +6790,13 @@ impl Chip { "rom_has_crc_be", "rom_has_md5_bsd", "soc_cpu_has_branch_predictor", + "soc_cpu_has_zcmp_workaround", "soc_multi_core_enabled", "soc_internal_memory_cached", "soc_has_swd_watchdog", "soc_cpu_mcause_mask=\"63\"", + "soc_cpu_pmp_granularity=\"128\"", + "soc_cpu_pmp_granularity_is_set", "soc_has_clock_node_xtal_clk", "soc_has_clock_node_cpll_clk", "soc_clock_node_cpll_clk_is_configurable", @@ -5563,6 +6813,7 @@ impl Chip { "soc_has_clock_node_pll_f120m", "soc_has_clock_node_pll_f160m", "soc_has_clock_node_pll_f240m", + "soc_has_clock_node_spll_d3_clock", "soc_has_clock_node_iomux_function_clock", "soc_clock_node_iomux_function_clock_is_configurable", "soc_has_clock_node_pll_f25m", @@ -5582,6 +6833,8 @@ impl Chip { "soc_clock_node_lp_fast_clk_is_configurable", "soc_has_clock_node_lp_slow_clk", "soc_clock_node_lp_slow_clk_is_configurable", + "soc_has_clock_node_crypto_clk", + "soc_clock_node_crypto_clk_is_configurable", "soc_has_clock_node_timg_calibration_clock", "soc_clock_node_timg_calibration_clock_is_configurable", "soc_has_clock_node_psram_function_clock", @@ -5601,6 +6854,12 @@ impl Chip { "soc_clock_node_rmt_sclk_is_configurable", "soc_has_clock_node_spi_function_clock", "soc_clock_node_spi_function_clock_is_configurable", + "soc_has_clock_node_i2s_tx_clk", + "soc_clock_node_i2s_tx_clk_is_configurable", + "soc_has_clock_node_i2s_rx_clk", + "soc_clock_node_i2s_rx_clk_is_configurable", + "soc_has_clock_node_i2s_mclk_out", + "soc_clock_node_i2s_mclk_out_is_configurable", "soc_has_clock_node_mipi_dsi_dpi_clk", "soc_clock_node_mipi_dsi_dpi_clk_is_configurable", "soc_has_clock_node_mipi_dsi_phy_pll_refclk", @@ -5626,7 +6885,10 @@ impl Chip { "cargo:rustc-cfg=soc_has_interrupt_core0", "cargo:rustc-cfg=soc_has_interrupt_core1", "cargo:rustc-cfg=soc_has_lp_i2c_ana_mst", + "cargo:rustc-cfg=soc_has_cache", "cargo:rustc-cfg=soc_has_clic", + "cargo:rustc-cfg=soc_has_clint", + "cargo:rustc-cfg=soc_has_clint_other_core", "cargo:rustc-cfg=soc_has_io_mux", "cargo:rustc-cfg=soc_has_iomux_mspi_pin", "cargo:rustc-cfg=soc_has_lp_i2c0", @@ -5640,6 +6902,7 @@ impl Chip { "cargo:rustc-cfg=soc_has_lp_wdt", "cargo:rustc-cfg=soc_has_lpwr", "cargo:rustc-cfg=soc_has_pmu", + "cargo:rustc-cfg=soc_has_pau", "cargo:rustc-cfg=soc_has_systimer", "cargo:rustc-cfg=soc_has_timg0", "cargo:rustc-cfg=soc_has_timg1", @@ -5694,6 +6957,7 @@ impl Chip { "cargo:rustc-cfg=soc_has_psram", "cargo:rustc-cfg=soc_has_gpio_dedicated", "cargo:rustc-cfg=soc_has_cpu_ctrl", + "cargo:rustc-cfg=soc_has_ipc", "cargo:rustc-cfg=soc_has_from_cpu_intr0", "cargo:rustc-cfg=soc_has_from_cpu_intr1", "cargo:rustc-cfg=soc_has_from_cpu_intr2", @@ -5717,6 +6981,7 @@ impl Chip { "cargo:rustc-cfg=ethernet_driver_supported", "cargo:rustc-cfg=mipi_dsi_driver_supported", "cargo:rustc-cfg=adc_driver_supported", + "cargo:rustc-cfg=pcnt_driver_supported", "cargo:rustc-cfg=lp_timer_driver_supported", "cargo:rustc-cfg=sdm_driver_supported", "cargo:rustc-cfg=systimer_driver_supported", @@ -5730,6 +6995,7 @@ impl Chip { "cargo:rustc-cfg=dma_driver_supported", "cargo:rustc-cfg=interrupts_driver_supported", "cargo:rustc-cfg=mmu_driver_supported", + "cargo:rustc-cfg=flash_driver_supported", "cargo:rustc-cfg=psram_driver_supported", "cargo:rustc-cfg=rom_driver_supported", "cargo:rustc-cfg=soc_driver_supported", @@ -5749,6 +7015,7 @@ impl Chip { "cargo:rustc-cfg=i2s_i2s2", "cargo:rustc-cfg=adc_adc1", "cargo:rustc-cfg=adc_adc2", + "cargo:rustc-cfg=pcnt_PCNT", "cargo:rustc-cfg=timergroup_timg0", "cargo:rustc-cfg=timergroup_timg1", "cargo:rustc-cfg=gpio_version=\"3\"", @@ -5784,9 +7051,7 @@ impl Chip { "cargo:rustc-cfg=spi_master_fifo_size=\"64\"", "cargo:rustc-cfg=i2s_version=\"3\"", "cargo:rustc-cfg=i2s_version_is_set", - "cargo:rustc-cfg=i2s_default_clock_source=\"3\"", - "cargo:rustc-cfg=i2s_default_clock_source_is_set", - "cargo:rustc-cfg=i2s_mclk_divider_bit_width=\"6\"", + "cargo:rustc-cfg=i2s_mclk_divider_bit_width=\"9\"", "cargo:rustc-cfg=i2s_mclk_divider_bit_width_is_set", "cargo:rustc-cfg=i2s_max_ws_width=\"128\"", "cargo:rustc-cfg=i2s_max_ws_width_is_set", @@ -5813,6 +7078,13 @@ impl Chip { "cargo:rustc-cfg=usb_otg_fifo_depth_words=\"200\"", "cargo:rustc-cfg=usb_otg_hs_fifo_depth_words=\"896\"", "cargo:rustc-cfg=ethernet_mii_via_gpio_matrix", + "cargo:rustc-cfg=ethernet_rx_checksum_offload", + "cargo:rustc-cfg=ethernet_dma_burst_len=\"32\"", + "cargo:rustc-cfg=adc_line_calibration", + "cargo:rustc-cfg=adc_curve_calibration", + "cargo:rustc-cfg=adc_basic_calibration", + "cargo:rustc-cfg=adc_calibration_v1_scheme_supported", + "cargo:rustc-cfg=adc_channel_compensation", "cargo:rustc-cfg=soc_has_sdm_ch0", "cargo:rustc-cfg=soc_has_sdm_ch1", "cargo:rustc-cfg=soc_has_sdm_ch2", @@ -5823,7 +7095,9 @@ impl Chip { "cargo:rustc-cfg=soc_has_sdm_ch7", "cargo:rustc-cfg=timergroup_timg_has_timer1", "cargo:rustc-cfg=timergroup_timg_has_divcnt_rst", + "cargo:rustc-cfg=timergroup_wdt_has_conf_update", "cargo:rustc-cfg=timergroup_rc_fast_calibration_is_set", + "cargo:rustc-cfg=timergroup_rc_slow_calibration_is_set", "cargo:rustc-cfg=aes_dma_mode_ecb", "cargo:rustc-cfg=aes_dma_mode_cbc", "cargo:rustc-cfg=aes_dma_mode_ofb", @@ -5841,10 +7115,17 @@ impl Chip { "cargo:rustc-cfg=ecc_has_curve_p256", "cargo:rustc-cfg=ecc_has_curve_p384", "cargo:rustc-cfg=rng_apb_cycle_wait_num=\"16\"", - "cargo:rustc-cfg=rng_is_lp_sys", + "cargo:rustc-cfg=rng_trng_supported", "cargo:rustc-cfg=rsa_version=\"3\"", "cargo:rustc-cfg=rsa_size_increment=\"32\"", "cargo:rustc-cfg=rsa_memory_size_bytes=\"512\"", + "cargo:rustc-cfg=sha_has_sha1", + "cargo:rustc-cfg=sha_has_sha224", + "cargo:rustc-cfg=sha_has_sha256", + "cargo:rustc-cfg=sha_has_sha384", + "cargo:rustc-cfg=sha_has_sha512", + "cargo:rustc-cfg=sha_has_sha512_224", + "cargo:rustc-cfg=sha_has_sha512_256", "cargo:rustc-cfg=sleep_light_sleep", "cargo:rustc-cfg=sleep_deep_sleep", "cargo:rustc-cfg=sleep_has_wakeup_source_sdio", @@ -5858,6 +7139,10 @@ impl Chip { "cargo:rustc-cfg=sleep_ext1_version_is_set", "cargo:rustc-cfg=sleep_pin_wakeup_version=\"3\"", "cargo:rustc-cfg=sleep_pin_wakeup_version_is_set", + "cargo:rustc-cfg=cpu_retention=\"software\"", + "cargo:rustc-cfg=cpu_retention_frame=\"p4\"", + "cargo:rustc-cfg=supports_cpu_power_down", + "cargo:rustc-cfg=supports_top_power_down", "cargo:rustc-cfg=dma_separate_in_out_interrupts", "cargo:rustc-cfg=dma_gdma_version=\"2\"", "cargo:rustc-cfg=dma_gdma_version_is_set", @@ -5891,8 +7176,9 @@ impl Chip { "cargo:rustc-cfg=dma_max_priority_is_set", "cargo:rustc-cfg=interrupts_status_registers=\"5\"", "cargo:rustc-cfg=interrupt_controller=\"clic\"", + "cargo:rustc-cfg=context_switch_source=\"ipc\"", "cargo:rustc-cfg=mmu_page_size=\"65536\"", - "cargo:rustc-cfg=mmu_entry_num=\"512\"", + "cargo:rustc-cfg=mmu_entry_num=\"1024\"", "cargo:rustc-cfg=psram_octal_spi", "cargo:rustc-cfg=psram_hex_spi", "cargo:rustc-cfg=psram_extmem_origin=\"1207959552\"", @@ -5900,10 +7186,13 @@ impl Chip { "cargo:rustc-cfg=rom_has_crc_be", "cargo:rustc-cfg=rom_has_md5_bsd", "cargo:rustc-cfg=soc_cpu_has_branch_predictor", + "cargo:rustc-cfg=soc_cpu_has_zcmp_workaround", "cargo:rustc-cfg=soc_multi_core_enabled", "cargo:rustc-cfg=soc_internal_memory_cached", "cargo:rustc-cfg=soc_has_swd_watchdog", "cargo:rustc-cfg=soc_cpu_mcause_mask=\"63\"", + "cargo:rustc-cfg=soc_cpu_pmp_granularity=\"128\"", + "cargo:rustc-cfg=soc_cpu_pmp_granularity_is_set", "cargo:rustc-cfg=soc_has_clock_node_xtal_clk", "cargo:rustc-cfg=soc_has_clock_node_cpll_clk", "cargo:rustc-cfg=soc_clock_node_cpll_clk_is_configurable", @@ -5920,6 +7209,7 @@ impl Chip { "cargo:rustc-cfg=soc_has_clock_node_pll_f120m", "cargo:rustc-cfg=soc_has_clock_node_pll_f160m", "cargo:rustc-cfg=soc_has_clock_node_pll_f240m", + "cargo:rustc-cfg=soc_has_clock_node_spll_d3_clock", "cargo:rustc-cfg=soc_has_clock_node_iomux_function_clock", "cargo:rustc-cfg=soc_clock_node_iomux_function_clock_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_pll_f25m", @@ -5939,6 +7229,8 @@ impl Chip { "cargo:rustc-cfg=soc_clock_node_lp_fast_clk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_lp_slow_clk", "cargo:rustc-cfg=soc_clock_node_lp_slow_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_crypto_clk", + "cargo:rustc-cfg=soc_clock_node_crypto_clk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_timg_calibration_clock", "cargo:rustc-cfg=soc_clock_node_timg_calibration_clock_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_psram_function_clock", @@ -5958,6 +7250,12 @@ impl Chip { "cargo:rustc-cfg=soc_clock_node_rmt_sclk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_spi_function_clock", "cargo:rustc-cfg=soc_clock_node_spi_function_clock_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_i2s_tx_clk", + "cargo:rustc-cfg=soc_clock_node_i2s_tx_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_i2s_rx_clk", + "cargo:rustc-cfg=soc_clock_node_i2s_rx_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_i2s_mclk_out", + "cargo:rustc-cfg=soc_clock_node_i2s_mclk_out_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_mipi_dsi_dpi_clk", "cargo:rustc-cfg=soc_clock_node_mipi_dsi_dpi_clk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_mipi_dsi_phy_pll_refclk", @@ -5974,13 +7272,13 @@ impl Chip { ( "dram", MemoryRegion { - address_range: 0x4FF40000..0x4FFC0000, + address_range: 0x4FF40000..0x4FFADFC0, }, ), ( "dram2_uninit", MemoryRegion { - address_range: 0x4FF00000..0x4FF40000, + address_range: 0x4FFADFC0..0x4FFBEFC0, }, ), ( @@ -6302,7 +7600,6 @@ impl Chip { "phy_driver_supported", "adc_driver_supported", "dac_driver_supported", - "temp_sensor_driver_supported", "ledc_driver_supported", "pcnt_driver_supported", "lp_timer_driver_supported", @@ -6319,6 +7616,7 @@ impl Chip { "dma_driver_supported", "interrupts_driver_supported", "mmu_driver_supported", + "flash_driver_supported", "psram_driver_supported", "rom_driver_supported", "soc_driver_supported", @@ -6335,6 +7633,7 @@ impl Chip { "adc_adc2", "dac_dac1", "dac_dac2", + "pcnt_PCNT", "timergroup_timg0", "timergroup_timg1", "gpio_version=\"2\"", @@ -6369,8 +7668,6 @@ impl Chip { "spi_master_has_dma_segmented_transfer", "i2s_version=\"1\"", "i2s_version_is_set", - "i2s_default_clock_source=\"2\"", - "i2s_default_clock_source_is_set", "i2s_mclk_divider_bit_width=\"6\"", "i2s_mclk_divider_bit_width_is_set", "i2s_max_ws_width=\"128\"", @@ -6386,6 +7683,13 @@ impl Chip { "usb_otg_fifo_depth_words=\"256\"", "wifi_mac_version=\"1\"", "wifi_csi_supported", + "wifi_has_nan", + "wifi_has_ftm", + "adc_controller=\"rtc\"", + "adc_controller_is_set", + "adc_line_calibration", + "adc_basic_calibration", + "adc_calibration_v1_scheme_supported", "ledc_version=\"2\"", "ledc_channel_count=\"8\"", "soc_has_sdm_ch0", @@ -6398,6 +7702,7 @@ impl Chip { "soc_has_sdm_ch7", "timergroup_timg_has_timer1", "timergroup_rc_fast_calibration_is_set", + "timergroup_rc_slow_calibration_is_set", "aes_dma_mode_ecb", "aes_dma_mode_cbc", "aes_dma_mode_ofb", @@ -6412,6 +7717,13 @@ impl Chip { "rsa_version=\"2\"", "rsa_size_increment=\"32\"", "rsa_memory_size_bytes=\"512\"", + "sha_has_sha1", + "sha_has_sha224", + "sha_has_sha256", + "sha_has_sha384", + "sha_has_sha512", + "sha_has_sha512_224", + "sha_has_sha512_256", "sleep_light_sleep", "sleep_deep_sleep", "sleep_has_wakeup_source_ext0", @@ -6448,6 +7760,7 @@ impl Chip { "dma_can_access_psram", "interrupts_status_registers=\"3\"", "interrupt_controller=\"xtensa\"", + "context_switch_source=\"software0\"", "mmu_page_size=\"65536\"", "mmu_entry_num=\"256\"", "psram_extmem_origin=\"1062207488\"", @@ -6455,12 +7768,15 @@ impl Chip { "rom_has_md5_bsd", "soc_has_swd_watchdog", "soc_cpu_mcause_mask=\"0\"", + "soc_cpu_pmp_granularity=\"4\"", + "soc_cpu_pmp_granularity_is_set", "soc_has_clock_node_xtal_clk", "soc_clock_node_xtal_clk_is_configurable", "soc_has_clock_node_pll_clk", "soc_clock_node_pll_clk_is_configurable", "soc_has_clock_node_apll_clk", "soc_clock_node_apll_clk_is_configurable", + "soc_has_clock_node_pll_f160m_clk", "soc_has_clock_node_rc_fast_clk", "soc_has_clock_node_cpu_pll_div_in", "soc_clock_node_cpu_pll_div_in_is_configurable", @@ -6506,6 +7822,8 @@ impl Chip { "soc_has_clock_node_i2c_function_clock", "soc_clock_node_i2c_function_clock_is_configurable", "soc_has_clock_node_spi_function_clock", + "soc_has_clock_node_i2s_mclk", + "soc_clock_node_i2s_mclk_is_configurable", "has_dram_region", "has_dram2_uninit_region", "has_irom_region", @@ -6590,7 +7908,6 @@ impl Chip { "cargo:rustc-cfg=phy_driver_supported", "cargo:rustc-cfg=adc_driver_supported", "cargo:rustc-cfg=dac_driver_supported", - "cargo:rustc-cfg=temp_sensor_driver_supported", "cargo:rustc-cfg=ledc_driver_supported", "cargo:rustc-cfg=pcnt_driver_supported", "cargo:rustc-cfg=lp_timer_driver_supported", @@ -6607,6 +7924,7 @@ impl Chip { "cargo:rustc-cfg=dma_driver_supported", "cargo:rustc-cfg=interrupts_driver_supported", "cargo:rustc-cfg=mmu_driver_supported", + "cargo:rustc-cfg=flash_driver_supported", "cargo:rustc-cfg=psram_driver_supported", "cargo:rustc-cfg=rom_driver_supported", "cargo:rustc-cfg=soc_driver_supported", @@ -6623,6 +7941,7 @@ impl Chip { "cargo:rustc-cfg=adc_adc2", "cargo:rustc-cfg=dac_dac1", "cargo:rustc-cfg=dac_dac2", + "cargo:rustc-cfg=pcnt_PCNT", "cargo:rustc-cfg=timergroup_timg0", "cargo:rustc-cfg=timergroup_timg1", "cargo:rustc-cfg=gpio_version=\"2\"", @@ -6657,8 +7976,6 @@ impl Chip { "cargo:rustc-cfg=spi_master_has_dma_segmented_transfer", "cargo:rustc-cfg=i2s_version=\"1\"", "cargo:rustc-cfg=i2s_version_is_set", - "cargo:rustc-cfg=i2s_default_clock_source=\"2\"", - "cargo:rustc-cfg=i2s_default_clock_source_is_set", "cargo:rustc-cfg=i2s_mclk_divider_bit_width=\"6\"", "cargo:rustc-cfg=i2s_mclk_divider_bit_width_is_set", "cargo:rustc-cfg=i2s_max_ws_width=\"128\"", @@ -6674,6 +7991,13 @@ impl Chip { "cargo:rustc-cfg=usb_otg_fifo_depth_words=\"256\"", "cargo:rustc-cfg=wifi_mac_version=\"1\"", "cargo:rustc-cfg=wifi_csi_supported", + "cargo:rustc-cfg=wifi_has_nan", + "cargo:rustc-cfg=wifi_has_ftm", + "cargo:rustc-cfg=adc_controller=\"rtc\"", + "cargo:rustc-cfg=adc_controller_is_set", + "cargo:rustc-cfg=adc_line_calibration", + "cargo:rustc-cfg=adc_basic_calibration", + "cargo:rustc-cfg=adc_calibration_v1_scheme_supported", "cargo:rustc-cfg=ledc_version=\"2\"", "cargo:rustc-cfg=ledc_channel_count=\"8\"", "cargo:rustc-cfg=soc_has_sdm_ch0", @@ -6686,6 +8010,7 @@ impl Chip { "cargo:rustc-cfg=soc_has_sdm_ch7", "cargo:rustc-cfg=timergroup_timg_has_timer1", "cargo:rustc-cfg=timergroup_rc_fast_calibration_is_set", + "cargo:rustc-cfg=timergroup_rc_slow_calibration_is_set", "cargo:rustc-cfg=aes_dma_mode_ecb", "cargo:rustc-cfg=aes_dma_mode_cbc", "cargo:rustc-cfg=aes_dma_mode_ofb", @@ -6700,6 +8025,13 @@ impl Chip { "cargo:rustc-cfg=rsa_version=\"2\"", "cargo:rustc-cfg=rsa_size_increment=\"32\"", "cargo:rustc-cfg=rsa_memory_size_bytes=\"512\"", + "cargo:rustc-cfg=sha_has_sha1", + "cargo:rustc-cfg=sha_has_sha224", + "cargo:rustc-cfg=sha_has_sha256", + "cargo:rustc-cfg=sha_has_sha384", + "cargo:rustc-cfg=sha_has_sha512", + "cargo:rustc-cfg=sha_has_sha512_224", + "cargo:rustc-cfg=sha_has_sha512_256", "cargo:rustc-cfg=sleep_light_sleep", "cargo:rustc-cfg=sleep_deep_sleep", "cargo:rustc-cfg=sleep_has_wakeup_source_ext0", @@ -6736,6 +8068,7 @@ impl Chip { "cargo:rustc-cfg=dma_can_access_psram", "cargo:rustc-cfg=interrupts_status_registers=\"3\"", "cargo:rustc-cfg=interrupt_controller=\"xtensa\"", + "cargo:rustc-cfg=context_switch_source=\"software0\"", "cargo:rustc-cfg=mmu_page_size=\"65536\"", "cargo:rustc-cfg=mmu_entry_num=\"256\"", "cargo:rustc-cfg=psram_extmem_origin=\"1062207488\"", @@ -6743,12 +8076,15 @@ impl Chip { "cargo:rustc-cfg=rom_has_md5_bsd", "cargo:rustc-cfg=soc_has_swd_watchdog", "cargo:rustc-cfg=soc_cpu_mcause_mask=\"0\"", + "cargo:rustc-cfg=soc_cpu_pmp_granularity=\"4\"", + "cargo:rustc-cfg=soc_cpu_pmp_granularity_is_set", "cargo:rustc-cfg=soc_has_clock_node_xtal_clk", "cargo:rustc-cfg=soc_clock_node_xtal_clk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_pll_clk", "cargo:rustc-cfg=soc_clock_node_pll_clk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_apll_clk", "cargo:rustc-cfg=soc_clock_node_apll_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_pll_f160m_clk", "cargo:rustc-cfg=soc_has_clock_node_rc_fast_clk", "cargo:rustc-cfg=soc_has_clock_node_cpu_pll_div_in", "cargo:rustc-cfg=soc_clock_node_cpu_pll_div_in_is_configurable", @@ -6794,6 +8130,8 @@ impl Chip { "cargo:rustc-cfg=soc_has_clock_node_i2c_function_clock", "cargo:rustc-cfg=soc_clock_node_i2c_function_clock_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_spi_function_clock", + "cargo:rustc-cfg=soc_has_clock_node_i2s_mclk", + "cargo:rustc-cfg=soc_clock_node_i2s_mclk_is_configurable", "cargo:rustc-cfg=has_dram_region", "cargo:rustc-cfg=has_dram2_uninit_region", "cargo:rustc-cfg=has_irom_region", @@ -7074,6 +8412,7 @@ impl Chip { "soc_has_psram", "soc_has_ulp_riscv_core", "soc_has_wifi", + "soc_has_ipc", "soc_has_from_cpu_intr0", "soc_has_from_cpu_intr1", "soc_has_from_cpu_intr2", @@ -7100,7 +8439,6 @@ impl Chip { "camera_driver_supported", "rgb_display_driver_supported", "adc_driver_supported", - "temp_sensor_driver_supported", "ledc_driver_supported", "mcpwm_driver_supported", "pcnt_driver_supported", @@ -7119,6 +8457,7 @@ impl Chip { "dma_driver_supported", "interrupts_driver_supported", "mmu_driver_supported", + "flash_driver_supported", "psram_driver_supported", "rom_driver_supported", "soc_driver_supported", @@ -7135,6 +8474,7 @@ impl Chip { "i2s_i2s1", "adc_adc1", "adc_adc2", + "pcnt_PCNT", "timergroup_timg0", "timergroup_timg1", "gpio_version=\"2\"", @@ -7174,9 +8514,7 @@ impl Chip { "spi_master_has_dma_segmented_transfer", "i2s_version=\"2\"", "i2s_version_is_set", - "i2s_default_clock_source=\"2\"", - "i2s_default_clock_source_is_set", - "i2s_mclk_divider_bit_width=\"6\"", + "i2s_mclk_divider_bit_width=\"9\"", "i2s_mclk_divider_bit_width_is_set", "i2s_max_ws_width=\"128\"", "i2s_max_ws_width_is_set", @@ -7200,9 +8538,17 @@ impl Chip { "bt_controller=\"btdm\"", "wifi_mac_version=\"1\"", "wifi_csi_supported", + "wifi_has_ftm", "phy_combo_module", "phy_backed_up_digital_register_count=\"21\"", "phy_backed_up_digital_register_count_is_set", + "rgb_display_output_lines=\"16\"", + "adc_controller=\"rtc\"", + "adc_controller_is_set", + "adc_line_calibration", + "adc_curve_calibration", + "adc_basic_calibration", + "adc_calibration_v1_scheme_supported", "ledc_version=\"2\"", "ledc_channel_count=\"8\"", "soc_has_sdm_ch0", @@ -7215,6 +8561,7 @@ impl Chip { "soc_has_sdm_ch7", "timergroup_timg_has_timer1", "timergroup_rc_fast_calibration_is_set", + "timergroup_rc_slow_calibration_is_set", "aes_dma_mode_ecb", "aes_dma_mode_cbc", "aes_dma_mode_ofb", @@ -7227,6 +8574,13 @@ impl Chip { "rsa_version=\"2\"", "rsa_size_increment=\"32\"", "rsa_memory_size_bytes=\"512\"", + "sha_has_sha1", + "sha_has_sha224", + "sha_has_sha256", + "sha_has_sha384", + "sha_has_sha512", + "sha_has_sha512_224", + "sha_has_sha512_256", "sleep_light_sleep", "sleep_deep_sleep", "sleep_has_wakeup_source_ext0", @@ -7245,6 +8599,9 @@ impl Chip { "sleep_pin_wakeup_version=\"1\"", "sleep_pin_wakeup_version_is_set", "sleep_deep_sleep_needs_gpio_isolation", + "cpu_retention=\"rtc_cntl\"", + "supports_cpu_power_down", + "supports_tagmem_power_down", "assist_debug_has_region_monitor", "dma_mem2mem_requires_peripheral", "dma_ext_mem_configurable_block_size", @@ -7278,6 +8635,7 @@ impl Chip { "dma_max_priority_is_set", "interrupts_status_registers=\"4\"", "interrupt_controller=\"xtensa\"", + "context_switch_source=\"software0\"", "mmu_page_size=\"65536\"", "mmu_entry_num=\"384\"", "psram_octal_spi", @@ -7288,6 +8646,8 @@ impl Chip { "soc_multi_core_enabled", "soc_has_swd_watchdog", "soc_cpu_mcause_mask=\"0\"", + "soc_cpu_pmp_granularity=\"4\"", + "soc_cpu_pmp_granularity_is_set", "soc_has_clock_node_xtal_clk", "soc_clock_node_xtal_clk_is_configurable", "soc_has_clock_node_pll_clk", @@ -7316,6 +8676,9 @@ impl Chip { "soc_has_clock_node_xtal_div_clk", "soc_has_clock_node_rtc_slow_clk", "soc_clock_node_rtc_slow_clk_is_configurable", + "soc_has_clock_node_ble_lp_xtal_clk", + "soc_has_clock_node_ble_lp_clk", + "soc_clock_node_ble_lp_clk_is_configurable", "soc_has_clock_node_rtc_fast_clk", "soc_clock_node_rtc_fast_clk_is_configurable", "soc_has_clock_node_low_power_clk", @@ -7342,6 +8705,12 @@ impl Chip { "soc_clock_node_lcd_cam_cam_clock_is_configurable", "soc_has_clock_node_spi_function_clock", "soc_clock_node_spi_function_clock_is_configurable", + "soc_has_clock_node_i2s_tx_clk", + "soc_clock_node_i2s_tx_clk_is_configurable", + "soc_has_clock_node_i2s_rx_clk", + "soc_clock_node_i2s_rx_clk_is_configurable", + "soc_has_clock_node_i2s_mclk_out", + "soc_clock_node_i2s_mclk_out_is_configurable", "has_dram_region", "has_dram2_uninit_region", "has_irom_region", @@ -7416,6 +8785,7 @@ impl Chip { "cargo:rustc-cfg=soc_has_psram", "cargo:rustc-cfg=soc_has_ulp_riscv_core", "cargo:rustc-cfg=soc_has_wifi", + "cargo:rustc-cfg=soc_has_ipc", "cargo:rustc-cfg=soc_has_from_cpu_intr0", "cargo:rustc-cfg=soc_has_from_cpu_intr1", "cargo:rustc-cfg=soc_has_from_cpu_intr2", @@ -7442,7 +8812,6 @@ impl Chip { "cargo:rustc-cfg=camera_driver_supported", "cargo:rustc-cfg=rgb_display_driver_supported", "cargo:rustc-cfg=adc_driver_supported", - "cargo:rustc-cfg=temp_sensor_driver_supported", "cargo:rustc-cfg=ledc_driver_supported", "cargo:rustc-cfg=mcpwm_driver_supported", "cargo:rustc-cfg=pcnt_driver_supported", @@ -7461,6 +8830,7 @@ impl Chip { "cargo:rustc-cfg=dma_driver_supported", "cargo:rustc-cfg=interrupts_driver_supported", "cargo:rustc-cfg=mmu_driver_supported", + "cargo:rustc-cfg=flash_driver_supported", "cargo:rustc-cfg=psram_driver_supported", "cargo:rustc-cfg=rom_driver_supported", "cargo:rustc-cfg=soc_driver_supported", @@ -7477,6 +8847,7 @@ impl Chip { "cargo:rustc-cfg=i2s_i2s1", "cargo:rustc-cfg=adc_adc1", "cargo:rustc-cfg=adc_adc2", + "cargo:rustc-cfg=pcnt_PCNT", "cargo:rustc-cfg=timergroup_timg0", "cargo:rustc-cfg=timergroup_timg1", "cargo:rustc-cfg=gpio_version=\"2\"", @@ -7516,9 +8887,7 @@ impl Chip { "cargo:rustc-cfg=spi_master_has_dma_segmented_transfer", "cargo:rustc-cfg=i2s_version=\"2\"", "cargo:rustc-cfg=i2s_version_is_set", - "cargo:rustc-cfg=i2s_default_clock_source=\"2\"", - "cargo:rustc-cfg=i2s_default_clock_source_is_set", - "cargo:rustc-cfg=i2s_mclk_divider_bit_width=\"6\"", + "cargo:rustc-cfg=i2s_mclk_divider_bit_width=\"9\"", "cargo:rustc-cfg=i2s_mclk_divider_bit_width_is_set", "cargo:rustc-cfg=i2s_max_ws_width=\"128\"", "cargo:rustc-cfg=i2s_max_ws_width_is_set", @@ -7542,9 +8911,17 @@ impl Chip { "cargo:rustc-cfg=bt_controller=\"btdm\"", "cargo:rustc-cfg=wifi_mac_version=\"1\"", "cargo:rustc-cfg=wifi_csi_supported", + "cargo:rustc-cfg=wifi_has_ftm", "cargo:rustc-cfg=phy_combo_module", "cargo:rustc-cfg=phy_backed_up_digital_register_count=\"21\"", "cargo:rustc-cfg=phy_backed_up_digital_register_count_is_set", + "cargo:rustc-cfg=rgb_display_output_lines=\"16\"", + "cargo:rustc-cfg=adc_controller=\"rtc\"", + "cargo:rustc-cfg=adc_controller_is_set", + "cargo:rustc-cfg=adc_line_calibration", + "cargo:rustc-cfg=adc_curve_calibration", + "cargo:rustc-cfg=adc_basic_calibration", + "cargo:rustc-cfg=adc_calibration_v1_scheme_supported", "cargo:rustc-cfg=ledc_version=\"2\"", "cargo:rustc-cfg=ledc_channel_count=\"8\"", "cargo:rustc-cfg=soc_has_sdm_ch0", @@ -7557,6 +8934,7 @@ impl Chip { "cargo:rustc-cfg=soc_has_sdm_ch7", "cargo:rustc-cfg=timergroup_timg_has_timer1", "cargo:rustc-cfg=timergroup_rc_fast_calibration_is_set", + "cargo:rustc-cfg=timergroup_rc_slow_calibration_is_set", "cargo:rustc-cfg=aes_dma_mode_ecb", "cargo:rustc-cfg=aes_dma_mode_cbc", "cargo:rustc-cfg=aes_dma_mode_ofb", @@ -7569,6 +8947,13 @@ impl Chip { "cargo:rustc-cfg=rsa_version=\"2\"", "cargo:rustc-cfg=rsa_size_increment=\"32\"", "cargo:rustc-cfg=rsa_memory_size_bytes=\"512\"", + "cargo:rustc-cfg=sha_has_sha1", + "cargo:rustc-cfg=sha_has_sha224", + "cargo:rustc-cfg=sha_has_sha256", + "cargo:rustc-cfg=sha_has_sha384", + "cargo:rustc-cfg=sha_has_sha512", + "cargo:rustc-cfg=sha_has_sha512_224", + "cargo:rustc-cfg=sha_has_sha512_256", "cargo:rustc-cfg=sleep_light_sleep", "cargo:rustc-cfg=sleep_deep_sleep", "cargo:rustc-cfg=sleep_has_wakeup_source_ext0", @@ -7587,6 +8972,9 @@ impl Chip { "cargo:rustc-cfg=sleep_pin_wakeup_version=\"1\"", "cargo:rustc-cfg=sleep_pin_wakeup_version_is_set", "cargo:rustc-cfg=sleep_deep_sleep_needs_gpio_isolation", + "cargo:rustc-cfg=cpu_retention=\"rtc_cntl\"", + "cargo:rustc-cfg=supports_cpu_power_down", + "cargo:rustc-cfg=supports_tagmem_power_down", "cargo:rustc-cfg=assist_debug_has_region_monitor", "cargo:rustc-cfg=dma_mem2mem_requires_peripheral", "cargo:rustc-cfg=dma_ext_mem_configurable_block_size", @@ -7620,6 +9008,7 @@ impl Chip { "cargo:rustc-cfg=dma_max_priority_is_set", "cargo:rustc-cfg=interrupts_status_registers=\"4\"", "cargo:rustc-cfg=interrupt_controller=\"xtensa\"", + "cargo:rustc-cfg=context_switch_source=\"software0\"", "cargo:rustc-cfg=mmu_page_size=\"65536\"", "cargo:rustc-cfg=mmu_entry_num=\"384\"", "cargo:rustc-cfg=psram_octal_spi", @@ -7630,6 +9019,8 @@ impl Chip { "cargo:rustc-cfg=soc_multi_core_enabled", "cargo:rustc-cfg=soc_has_swd_watchdog", "cargo:rustc-cfg=soc_cpu_mcause_mask=\"0\"", + "cargo:rustc-cfg=soc_cpu_pmp_granularity=\"4\"", + "cargo:rustc-cfg=soc_cpu_pmp_granularity_is_set", "cargo:rustc-cfg=soc_has_clock_node_xtal_clk", "cargo:rustc-cfg=soc_clock_node_xtal_clk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_pll_clk", @@ -7658,6 +9049,9 @@ impl Chip { "cargo:rustc-cfg=soc_has_clock_node_xtal_div_clk", "cargo:rustc-cfg=soc_has_clock_node_rtc_slow_clk", "cargo:rustc-cfg=soc_clock_node_rtc_slow_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_ble_lp_xtal_clk", + "cargo:rustc-cfg=soc_has_clock_node_ble_lp_clk", + "cargo:rustc-cfg=soc_clock_node_ble_lp_clk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_rtc_fast_clk", "cargo:rustc-cfg=soc_clock_node_rtc_fast_clk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_low_power_clk", @@ -7684,6 +9078,12 @@ impl Chip { "cargo:rustc-cfg=soc_clock_node_lcd_cam_cam_clock_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_spi_function_clock", "cargo:rustc-cfg=soc_clock_node_spi_function_clock_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_i2s_tx_clk", + "cargo:rustc-cfg=soc_clock_node_i2s_tx_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_i2s_rx_clk", + "cargo:rustc-cfg=soc_clock_node_i2s_rx_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_i2s_mclk_out", + "cargo:rustc-cfg=soc_clock_node_i2s_mclk_out_is_configurable", "cargo:rustc-cfg=has_dram_region", "cargo:rustc-cfg=has_dram2_uninit_region", "cargo:rustc-cfg=has_irom_region", @@ -7912,8 +9312,13 @@ impl Chip { "soc_has_assist_debug", "soc_has_cache", "soc_has_clic", + "soc_has_clint", + "soc_has_clint_other_core", "soc_has_cnnt_sys", "soc_has_cnnt_io_mux", + "soc_has_eth", + "soc_has_emac_dma", + "soc_has_emac_mac", "soc_has_ecc", "soc_has_efuse", "soc_has_gpio", @@ -7925,9 +9330,13 @@ impl Chip { "soc_has_hp_sys_clkrst", "soc_has_i2c0", "soc_has_i2c1", + "soc_has_i2s0", + "soc_has_i2s1", + "soc_has_ieee802154", "soc_has_interrupt_core0", "soc_has_interrupt_core1", "soc_has_io_mux", + "soc_has_lcd_cam", "soc_has_iomux_mspi_pin", "soc_has_lp_aon_clk_rst", "soc_has_lp_apm", @@ -7942,6 +9351,8 @@ impl Chip { "soc_has_modem_lpcon", "soc_has_modem_syscon", "soc_has_pau", + "soc_has_pcnt", + "soc_has_pcnt1", "soc_has_pmu", "soc_has_rtc_timer", "soc_has_rng", @@ -7971,10 +9382,13 @@ impl Chip { "soc_has_usb_hs", "soc_has_adc1", "soc_has_adc2", + "soc_has_bt", "soc_has_flash", "soc_has_psram", "soc_has_gpio_dedicated", + "soc_has_wifi", "soc_has_cpu_ctrl", + "soc_has_ipc", "soc_has_from_cpu_intr0", "soc_has_from_cpu_intr1", "soc_has_from_cpu_intr2", @@ -7982,16 +9396,26 @@ impl Chip { "gpio_driver_supported", "dedicated_gpio_driver_supported", "io_mux_driver_supported", + "lp_io_driver_supported", "uart_driver_supported", "uhci_driver_supported", "i2c_master_driver_supported", "spi_master_driver_supported", "spi_slave_driver_supported", + "i2s_driver_supported", "rmt_driver_supported", "sdmmc_driver_supported", "usb_otg_hs_driver_supported", "usb_serial_jtag_driver_supported", + "bt_driver_supported", + "wifi_driver_supported", + "ieee802154_driver_supported", + "ethernet_driver_supported", + "phy_driver_supported", + "camera_driver_supported", + "rgb_display_driver_supported", "adc_driver_supported", + "pcnt_driver_supported", "lp_timer_driver_supported", "sdm_driver_supported", "systimer_driver_supported", @@ -8001,9 +9425,11 @@ impl Chip { "rng_driver_supported", "rsa_driver_supported", "sha_driver_supported", + "sleep_driver_supported", "dma_driver_supported", "interrupts_driver_supported", "mmu_driver_supported", + "flash_driver_supported", "psram_driver_supported", "rom_driver_supported", "soc_driver_supported", @@ -8017,8 +9443,12 @@ impl Chip { "spi_master_spi3", "spi_slave_spi2", "spi_slave_spi3", + "i2s_i2s0", + "i2s_i2s1", "adc_adc1", "adc_adc2", + "pcnt_PCNT", + "pcnt_PCNT1", "timergroup_timg0", "timergroup_timg1", "gpio_version=\"3\"", @@ -8027,11 +9457,14 @@ impl Chip { "gpio_constant_0_input=\"192\"", "gpio_constant_1_input=\"128\"", "gpio_func_in_sel_offset=\"0\"", + "gpio_need_soft_isolate_during_pd", "soc_has_xtal32k_pads", "gpio_has_bank_1", "gpio_input_signal_max=\"255\"", "gpio_output_signal_max=\"256\"", "dedicated_gpio_version=\"riscv_v2\"", + "lp_io_version=\"esp32s31\"", + "lp_io_has_gpio_matrix", "uart_ram_size=\"128\"", "uart_version=\"2\"", "uart_peripheral_controls_mem_clk", @@ -8056,6 +9489,18 @@ impl Chip { "spi_master_has_octal", "spi_master_has_app_interrupts", "spi_master_has_dma_segmented_transfer", + "i2s_version=\"3\"", + "i2s_version_is_set", + "i2s_mclk_divider_bit_width=\"8\"", + "i2s_mclk_divider_bit_width_is_set", + "i2s_max_ws_width=\"512\"", + "i2s_max_ws_width_is_set", + "i2s_clock_configured_by_hp_sys_clkrst", + "i2s_supports_pdm_rx_hp_filter", + "i2s_supports_pdm_tx", + "i2s_supports_pdm_rx", + "i2s_supports_pcm2pdm", + "i2s_supports_pdm2pcm", "rmt_ram_start=\"540366848\"", "rmt_channel_ram_size=\"48\"", "rmt_has_tx_immediate_stop", @@ -8070,6 +9515,17 @@ impl Chip { "sdmmc_has_iomux", "sdmmc_psram_dma", "usb_otg_hs_fifo_depth_words=\"896\"", + "bt_controller=\"btdm2\"", + "wifi_has_wifi6", + "wifi_mac_version=\"3\"", + "wifi_csi_supported", + "wifi_has_nan", + "wifi_has_ftm", + "ethernet_mii_via_gpio_matrix", + "ethernet_rx_checksum_offload", + "ethernet_dma_burst_len=\"16\"", + "ethernet_has_rgmii", + "rgb_display_output_lines=\"24\"", "soc_has_sdm_ch0", "soc_has_sdm_ch1", "soc_has_sdm_ch2", @@ -8078,9 +9534,12 @@ impl Chip { "soc_has_sdm_ch5", "soc_has_sdm_ch6", "soc_has_sdm_ch7", + "timergroup_timg_has_timer1", "timergroup_timg_has_divcnt_rst", + "timergroup_wdt_has_conf_update", "timergroup_rc_fast_calibration_divider", "timergroup_rc_fast_calibration_is_set", + "timergroup_rc_slow_calibration_is_set", "aes_dma_mode_ecb", "aes_dma_mode_cbc", "aes_dma_mode_ofb", @@ -8097,10 +9556,39 @@ impl Chip { "ecc_has_curve_p192", "ecc_has_curve_p256", "ecc_has_curve_p384", + "ecc_has_curve_sm2", "rng_apb_cycle_wait_num=\"16\"", + "rng_trng_supported", "rsa_version=\"3\"", "rsa_size_increment=\"32\"", "rsa_memory_size_bytes=\"512\"", + "sha_has_sha1", + "sha_has_sha224", + "sha_has_sha256", + "sha_has_sha384", + "sha_has_sha512", + "sha_has_sha512_224", + "sha_has_sha512_256", + "sha_has_sm3", + "sleep_light_sleep", + "sleep_deep_sleep", + "sleep_has_wakeup_source_lp_core", + "sleep_has_wakeup_source_gpio", + "sleep_has_wakeup_source_usb", + "sleep_has_wakeup_source_uart", + "sleep_has_wakeup_source_ext1", + "sleep_has_wakeup_source_timer", + "sleep_has_wakeup_source_wifi", + "sleep_has_wakeup_source_wifi_beacon", + "sleep_has_wakeup_source_bt", + "sleep_ext1_version=\"3\"", + "sleep_ext1_version_is_set", + "sleep_pin_wakeup_version=\"3\"", + "sleep_pin_wakeup_version_is_set", + "cpu_retention=\"software\"", + "cpu_retention_frame=\"s31\"", + "supports_cpu_power_down", + "supports_top_power_down", "dma_separate_in_out_interrupts", "dma_gdma_version=\"3\"", "dma_gdma_version_is_set", @@ -8115,17 +9603,22 @@ impl Chip { "dma_supports_mem2mem", "uhci_supports_dma", "uhci_dma_engine=\"AHB_GDMA\"", + "i2s_supports_dma", + "i2s_dma_engine=\"AHB_GDMA\"", "spi_master_supports_dma", "spi_master_dma_engine=\"AXI_GDMA\"", "spi_slave_supports_dma", "spi_slave_dma_engine=\"AXI_GDMA\"", "aes_supports_dma", "aes_dma_engine=\"AXI_GDMA\"", + "lcd_cam_supports_dma", + "lcd_cam_dma_engine=\"AXI_GDMA\"", "dma_can_access_psram", "dma_max_priority=\"15\"", "dma_max_priority_is_set", "interrupts_status_registers=\"6\"", "interrupt_controller=\"clic\"", + "context_switch_source=\"ipc\"", "mmu_page_size=\"65536\"", "mmu_entry_num=\"1024\"", "psram_octal_spi", @@ -8134,15 +9627,19 @@ impl Chip { "rom_has_crc_be", "rom_has_md5_bsd", "soc_cpu_has_branch_predictor", + "soc_cpu_has_zcmp_workaround", "soc_multi_core_enabled", "soc_cpu_csr_prv_mode=\"2064\"", "soc_cpu_csr_prv_mode_is_set", "soc_has_swd_watchdog", "soc_cpu_mcause_mask=\"63\"", + "soc_cpu_pmp_granularity=\"128\"", + "soc_cpu_pmp_granularity_is_set", "soc_has_clock_node_xtal_clk", "soc_has_clock_node_bbpll_clk", "soc_has_clock_node_cpll_clk", "soc_has_clock_node_mpll_clk", + "soc_clock_node_mpll_clk_is_configurable", "soc_has_clock_node_rc_fast_clk", "soc_has_clock_node_xtal32k_clk", "soc_has_clock_node_rc_slow_clk", @@ -8151,6 +9648,7 @@ impl Chip { "soc_has_clock_node_pll_f120m", "soc_has_clock_node_pll_f160m", "soc_has_clock_node_pll_f240m", + "soc_has_clock_node_bbpll_d3_clock", "soc_has_clock_node_pll_f25m", "soc_has_clock_node_pll_f50m", "soc_has_clock_node_xtal_d2_clk", @@ -8158,14 +9656,21 @@ impl Chip { "soc_clock_node_cpu_root_clk_is_configurable", "soc_has_clock_node_cpu_clk", "soc_clock_node_cpu_clk_is_configurable", - "soc_has_clock_node_ahb_clk", - "soc_clock_node_ahb_clk_is_configurable", + "soc_has_clock_node_mem_clk", + "soc_clock_node_mem_clk_is_configurable", + "soc_has_clock_node_sys_clk", + "soc_clock_node_sys_clk_is_configurable", "soc_has_clock_node_apb_clk", "soc_clock_node_apb_clk_is_configurable", "soc_has_clock_node_lp_fast_clk", "soc_clock_node_lp_fast_clk_is_configurable", "soc_has_clock_node_lp_slow_clk", "soc_clock_node_lp_slow_clk_is_configurable", + "soc_has_clock_node_ble_lp_xtal_clk", + "soc_has_clock_node_ble_lp_clk", + "soc_clock_node_ble_lp_clk_is_configurable", + "soc_has_clock_node_crypto_clk", + "soc_clock_node_crypto_clk_is_configurable", "soc_has_clock_node_iomux_function_clock", "soc_clock_node_iomux_function_clock_is_configurable", "soc_has_clock_node_timg_calibration_clock", @@ -8185,9 +9690,19 @@ impl Chip { "soc_clock_node_spi_function_clock_is_configurable", "soc_has_clock_node_i2c_function_clock", "soc_clock_node_i2c_function_clock_is_configurable", + "soc_has_clock_node_i2s_tx_clk", + "soc_clock_node_i2s_tx_clk_is_configurable", + "soc_has_clock_node_i2s_rx_clk", + "soc_clock_node_i2s_rx_clk_is_configurable", + "soc_has_clock_node_i2s_mclk_out", + "soc_clock_node_i2s_mclk_out_is_configurable", "soc_has_clock_node_rmt_sclk", "soc_clock_node_rmt_sclk_is_configurable", "soc_has_clock_node_sdm_function_clock", + "soc_has_clock_node_lcd_cam_lcd_clock", + "soc_clock_node_lcd_cam_lcd_clock_is_configurable", + "soc_has_clock_node_lcd_cam_cam_clock", + "soc_clock_node_lcd_cam_cam_clock_is_configurable", "has_dram_region", "has_dram2_uninit_region", "has_irom_region", @@ -8202,8 +9717,13 @@ impl Chip { "cargo:rustc-cfg=soc_has_assist_debug", "cargo:rustc-cfg=soc_has_cache", "cargo:rustc-cfg=soc_has_clic", + "cargo:rustc-cfg=soc_has_clint", + "cargo:rustc-cfg=soc_has_clint_other_core", "cargo:rustc-cfg=soc_has_cnnt_sys", "cargo:rustc-cfg=soc_has_cnnt_io_mux", + "cargo:rustc-cfg=soc_has_eth", + "cargo:rustc-cfg=soc_has_emac_dma", + "cargo:rustc-cfg=soc_has_emac_mac", "cargo:rustc-cfg=soc_has_ecc", "cargo:rustc-cfg=soc_has_efuse", "cargo:rustc-cfg=soc_has_gpio", @@ -8215,9 +9735,13 @@ impl Chip { "cargo:rustc-cfg=soc_has_hp_sys_clkrst", "cargo:rustc-cfg=soc_has_i2c0", "cargo:rustc-cfg=soc_has_i2c1", + "cargo:rustc-cfg=soc_has_i2s0", + "cargo:rustc-cfg=soc_has_i2s1", + "cargo:rustc-cfg=soc_has_ieee802154", "cargo:rustc-cfg=soc_has_interrupt_core0", "cargo:rustc-cfg=soc_has_interrupt_core1", "cargo:rustc-cfg=soc_has_io_mux", + "cargo:rustc-cfg=soc_has_lcd_cam", "cargo:rustc-cfg=soc_has_iomux_mspi_pin", "cargo:rustc-cfg=soc_has_lp_aon_clk_rst", "cargo:rustc-cfg=soc_has_lp_apm", @@ -8232,6 +9756,8 @@ impl Chip { "cargo:rustc-cfg=soc_has_modem_lpcon", "cargo:rustc-cfg=soc_has_modem_syscon", "cargo:rustc-cfg=soc_has_pau", + "cargo:rustc-cfg=soc_has_pcnt", + "cargo:rustc-cfg=soc_has_pcnt1", "cargo:rustc-cfg=soc_has_pmu", "cargo:rustc-cfg=soc_has_rtc_timer", "cargo:rustc-cfg=soc_has_rng", @@ -8261,10 +9787,13 @@ impl Chip { "cargo:rustc-cfg=soc_has_usb_hs", "cargo:rustc-cfg=soc_has_adc1", "cargo:rustc-cfg=soc_has_adc2", + "cargo:rustc-cfg=soc_has_bt", "cargo:rustc-cfg=soc_has_flash", "cargo:rustc-cfg=soc_has_psram", "cargo:rustc-cfg=soc_has_gpio_dedicated", + "cargo:rustc-cfg=soc_has_wifi", "cargo:rustc-cfg=soc_has_cpu_ctrl", + "cargo:rustc-cfg=soc_has_ipc", "cargo:rustc-cfg=soc_has_from_cpu_intr0", "cargo:rustc-cfg=soc_has_from_cpu_intr1", "cargo:rustc-cfg=soc_has_from_cpu_intr2", @@ -8272,16 +9801,26 @@ impl Chip { "cargo:rustc-cfg=gpio_driver_supported", "cargo:rustc-cfg=dedicated_gpio_driver_supported", "cargo:rustc-cfg=io_mux_driver_supported", + "cargo:rustc-cfg=lp_io_driver_supported", "cargo:rustc-cfg=uart_driver_supported", "cargo:rustc-cfg=uhci_driver_supported", "cargo:rustc-cfg=i2c_master_driver_supported", "cargo:rustc-cfg=spi_master_driver_supported", "cargo:rustc-cfg=spi_slave_driver_supported", + "cargo:rustc-cfg=i2s_driver_supported", "cargo:rustc-cfg=rmt_driver_supported", "cargo:rustc-cfg=sdmmc_driver_supported", "cargo:rustc-cfg=usb_otg_hs_driver_supported", "cargo:rustc-cfg=usb_serial_jtag_driver_supported", + "cargo:rustc-cfg=bt_driver_supported", + "cargo:rustc-cfg=wifi_driver_supported", + "cargo:rustc-cfg=ieee802154_driver_supported", + "cargo:rustc-cfg=ethernet_driver_supported", + "cargo:rustc-cfg=phy_driver_supported", + "cargo:rustc-cfg=camera_driver_supported", + "cargo:rustc-cfg=rgb_display_driver_supported", "cargo:rustc-cfg=adc_driver_supported", + "cargo:rustc-cfg=pcnt_driver_supported", "cargo:rustc-cfg=lp_timer_driver_supported", "cargo:rustc-cfg=sdm_driver_supported", "cargo:rustc-cfg=systimer_driver_supported", @@ -8291,9 +9830,11 @@ impl Chip { "cargo:rustc-cfg=rng_driver_supported", "cargo:rustc-cfg=rsa_driver_supported", "cargo:rustc-cfg=sha_driver_supported", + "cargo:rustc-cfg=sleep_driver_supported", "cargo:rustc-cfg=dma_driver_supported", "cargo:rustc-cfg=interrupts_driver_supported", "cargo:rustc-cfg=mmu_driver_supported", + "cargo:rustc-cfg=flash_driver_supported", "cargo:rustc-cfg=psram_driver_supported", "cargo:rustc-cfg=rom_driver_supported", "cargo:rustc-cfg=soc_driver_supported", @@ -8307,8 +9848,12 @@ impl Chip { "cargo:rustc-cfg=spi_master_spi3", "cargo:rustc-cfg=spi_slave_spi2", "cargo:rustc-cfg=spi_slave_spi3", + "cargo:rustc-cfg=i2s_i2s0", + "cargo:rustc-cfg=i2s_i2s1", "cargo:rustc-cfg=adc_adc1", "cargo:rustc-cfg=adc_adc2", + "cargo:rustc-cfg=pcnt_PCNT", + "cargo:rustc-cfg=pcnt_PCNT1", "cargo:rustc-cfg=timergroup_timg0", "cargo:rustc-cfg=timergroup_timg1", "cargo:rustc-cfg=gpio_version=\"3\"", @@ -8317,11 +9862,14 @@ impl Chip { "cargo:rustc-cfg=gpio_constant_0_input=\"192\"", "cargo:rustc-cfg=gpio_constant_1_input=\"128\"", "cargo:rustc-cfg=gpio_func_in_sel_offset=\"0\"", + "cargo:rustc-cfg=gpio_need_soft_isolate_during_pd", "cargo:rustc-cfg=soc_has_xtal32k_pads", "cargo:rustc-cfg=gpio_has_bank_1", "cargo:rustc-cfg=gpio_input_signal_max=\"255\"", "cargo:rustc-cfg=gpio_output_signal_max=\"256\"", "cargo:rustc-cfg=dedicated_gpio_version=\"riscv_v2\"", + "cargo:rustc-cfg=lp_io_version=\"esp32s31\"", + "cargo:rustc-cfg=lp_io_has_gpio_matrix", "cargo:rustc-cfg=uart_ram_size=\"128\"", "cargo:rustc-cfg=uart_version=\"2\"", "cargo:rustc-cfg=uart_peripheral_controls_mem_clk", @@ -8346,6 +9894,18 @@ impl Chip { "cargo:rustc-cfg=spi_master_has_octal", "cargo:rustc-cfg=spi_master_has_app_interrupts", "cargo:rustc-cfg=spi_master_has_dma_segmented_transfer", + "cargo:rustc-cfg=i2s_version=\"3\"", + "cargo:rustc-cfg=i2s_version_is_set", + "cargo:rustc-cfg=i2s_mclk_divider_bit_width=\"8\"", + "cargo:rustc-cfg=i2s_mclk_divider_bit_width_is_set", + "cargo:rustc-cfg=i2s_max_ws_width=\"512\"", + "cargo:rustc-cfg=i2s_max_ws_width_is_set", + "cargo:rustc-cfg=i2s_clock_configured_by_hp_sys_clkrst", + "cargo:rustc-cfg=i2s_supports_pdm_rx_hp_filter", + "cargo:rustc-cfg=i2s_supports_pdm_tx", + "cargo:rustc-cfg=i2s_supports_pdm_rx", + "cargo:rustc-cfg=i2s_supports_pcm2pdm", + "cargo:rustc-cfg=i2s_supports_pdm2pcm", "cargo:rustc-cfg=rmt_ram_start=\"540366848\"", "cargo:rustc-cfg=rmt_channel_ram_size=\"48\"", "cargo:rustc-cfg=rmt_has_tx_immediate_stop", @@ -8360,6 +9920,17 @@ impl Chip { "cargo:rustc-cfg=sdmmc_has_iomux", "cargo:rustc-cfg=sdmmc_psram_dma", "cargo:rustc-cfg=usb_otg_hs_fifo_depth_words=\"896\"", + "cargo:rustc-cfg=bt_controller=\"btdm2\"", + "cargo:rustc-cfg=wifi_has_wifi6", + "cargo:rustc-cfg=wifi_mac_version=\"3\"", + "cargo:rustc-cfg=wifi_csi_supported", + "cargo:rustc-cfg=wifi_has_nan", + "cargo:rustc-cfg=wifi_has_ftm", + "cargo:rustc-cfg=ethernet_mii_via_gpio_matrix", + "cargo:rustc-cfg=ethernet_rx_checksum_offload", + "cargo:rustc-cfg=ethernet_dma_burst_len=\"16\"", + "cargo:rustc-cfg=ethernet_has_rgmii", + "cargo:rustc-cfg=rgb_display_output_lines=\"24\"", "cargo:rustc-cfg=soc_has_sdm_ch0", "cargo:rustc-cfg=soc_has_sdm_ch1", "cargo:rustc-cfg=soc_has_sdm_ch2", @@ -8368,9 +9939,12 @@ impl Chip { "cargo:rustc-cfg=soc_has_sdm_ch5", "cargo:rustc-cfg=soc_has_sdm_ch6", "cargo:rustc-cfg=soc_has_sdm_ch7", + "cargo:rustc-cfg=timergroup_timg_has_timer1", "cargo:rustc-cfg=timergroup_timg_has_divcnt_rst", + "cargo:rustc-cfg=timergroup_wdt_has_conf_update", "cargo:rustc-cfg=timergroup_rc_fast_calibration_divider", "cargo:rustc-cfg=timergroup_rc_fast_calibration_is_set", + "cargo:rustc-cfg=timergroup_rc_slow_calibration_is_set", "cargo:rustc-cfg=aes_dma_mode_ecb", "cargo:rustc-cfg=aes_dma_mode_cbc", "cargo:rustc-cfg=aes_dma_mode_ofb", @@ -8387,10 +9961,39 @@ impl Chip { "cargo:rustc-cfg=ecc_has_curve_p192", "cargo:rustc-cfg=ecc_has_curve_p256", "cargo:rustc-cfg=ecc_has_curve_p384", + "cargo:rustc-cfg=ecc_has_curve_sm2", "cargo:rustc-cfg=rng_apb_cycle_wait_num=\"16\"", + "cargo:rustc-cfg=rng_trng_supported", "cargo:rustc-cfg=rsa_version=\"3\"", "cargo:rustc-cfg=rsa_size_increment=\"32\"", "cargo:rustc-cfg=rsa_memory_size_bytes=\"512\"", + "cargo:rustc-cfg=sha_has_sha1", + "cargo:rustc-cfg=sha_has_sha224", + "cargo:rustc-cfg=sha_has_sha256", + "cargo:rustc-cfg=sha_has_sha384", + "cargo:rustc-cfg=sha_has_sha512", + "cargo:rustc-cfg=sha_has_sha512_224", + "cargo:rustc-cfg=sha_has_sha512_256", + "cargo:rustc-cfg=sha_has_sm3", + "cargo:rustc-cfg=sleep_light_sleep", + "cargo:rustc-cfg=sleep_deep_sleep", + "cargo:rustc-cfg=sleep_has_wakeup_source_lp_core", + "cargo:rustc-cfg=sleep_has_wakeup_source_gpio", + "cargo:rustc-cfg=sleep_has_wakeup_source_usb", + "cargo:rustc-cfg=sleep_has_wakeup_source_uart", + "cargo:rustc-cfg=sleep_has_wakeup_source_ext1", + "cargo:rustc-cfg=sleep_has_wakeup_source_timer", + "cargo:rustc-cfg=sleep_has_wakeup_source_wifi", + "cargo:rustc-cfg=sleep_has_wakeup_source_wifi_beacon", + "cargo:rustc-cfg=sleep_has_wakeup_source_bt", + "cargo:rustc-cfg=sleep_ext1_version=\"3\"", + "cargo:rustc-cfg=sleep_ext1_version_is_set", + "cargo:rustc-cfg=sleep_pin_wakeup_version=\"3\"", + "cargo:rustc-cfg=sleep_pin_wakeup_version_is_set", + "cargo:rustc-cfg=cpu_retention=\"software\"", + "cargo:rustc-cfg=cpu_retention_frame=\"s31\"", + "cargo:rustc-cfg=supports_cpu_power_down", + "cargo:rustc-cfg=supports_top_power_down", "cargo:rustc-cfg=dma_separate_in_out_interrupts", "cargo:rustc-cfg=dma_gdma_version=\"3\"", "cargo:rustc-cfg=dma_gdma_version_is_set", @@ -8405,17 +10008,22 @@ impl Chip { "cargo:rustc-cfg=dma_supports_mem2mem", "cargo:rustc-cfg=uhci_supports_dma", "cargo:rustc-cfg=uhci_dma_engine=\"AHB_GDMA\"", + "cargo:rustc-cfg=i2s_supports_dma", + "cargo:rustc-cfg=i2s_dma_engine=\"AHB_GDMA\"", "cargo:rustc-cfg=spi_master_supports_dma", "cargo:rustc-cfg=spi_master_dma_engine=\"AXI_GDMA\"", "cargo:rustc-cfg=spi_slave_supports_dma", "cargo:rustc-cfg=spi_slave_dma_engine=\"AXI_GDMA\"", "cargo:rustc-cfg=aes_supports_dma", "cargo:rustc-cfg=aes_dma_engine=\"AXI_GDMA\"", + "cargo:rustc-cfg=lcd_cam_supports_dma", + "cargo:rustc-cfg=lcd_cam_dma_engine=\"AXI_GDMA\"", "cargo:rustc-cfg=dma_can_access_psram", "cargo:rustc-cfg=dma_max_priority=\"15\"", "cargo:rustc-cfg=dma_max_priority_is_set", "cargo:rustc-cfg=interrupts_status_registers=\"6\"", "cargo:rustc-cfg=interrupt_controller=\"clic\"", + "cargo:rustc-cfg=context_switch_source=\"ipc\"", "cargo:rustc-cfg=mmu_page_size=\"65536\"", "cargo:rustc-cfg=mmu_entry_num=\"1024\"", "cargo:rustc-cfg=psram_octal_spi", @@ -8424,15 +10032,19 @@ impl Chip { "cargo:rustc-cfg=rom_has_crc_be", "cargo:rustc-cfg=rom_has_md5_bsd", "cargo:rustc-cfg=soc_cpu_has_branch_predictor", + "cargo:rustc-cfg=soc_cpu_has_zcmp_workaround", "cargo:rustc-cfg=soc_multi_core_enabled", "cargo:rustc-cfg=soc_cpu_csr_prv_mode=\"2064\"", "cargo:rustc-cfg=soc_cpu_csr_prv_mode_is_set", "cargo:rustc-cfg=soc_has_swd_watchdog", "cargo:rustc-cfg=soc_cpu_mcause_mask=\"63\"", + "cargo:rustc-cfg=soc_cpu_pmp_granularity=\"128\"", + "cargo:rustc-cfg=soc_cpu_pmp_granularity_is_set", "cargo:rustc-cfg=soc_has_clock_node_xtal_clk", "cargo:rustc-cfg=soc_has_clock_node_bbpll_clk", "cargo:rustc-cfg=soc_has_clock_node_cpll_clk", "cargo:rustc-cfg=soc_has_clock_node_mpll_clk", + "cargo:rustc-cfg=soc_clock_node_mpll_clk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_rc_fast_clk", "cargo:rustc-cfg=soc_has_clock_node_xtal32k_clk", "cargo:rustc-cfg=soc_has_clock_node_rc_slow_clk", @@ -8441,6 +10053,7 @@ impl Chip { "cargo:rustc-cfg=soc_has_clock_node_pll_f120m", "cargo:rustc-cfg=soc_has_clock_node_pll_f160m", "cargo:rustc-cfg=soc_has_clock_node_pll_f240m", + "cargo:rustc-cfg=soc_has_clock_node_bbpll_d3_clock", "cargo:rustc-cfg=soc_has_clock_node_pll_f25m", "cargo:rustc-cfg=soc_has_clock_node_pll_f50m", "cargo:rustc-cfg=soc_has_clock_node_xtal_d2_clk", @@ -8448,14 +10061,21 @@ impl Chip { "cargo:rustc-cfg=soc_clock_node_cpu_root_clk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_cpu_clk", "cargo:rustc-cfg=soc_clock_node_cpu_clk_is_configurable", - "cargo:rustc-cfg=soc_has_clock_node_ahb_clk", - "cargo:rustc-cfg=soc_clock_node_ahb_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_mem_clk", + "cargo:rustc-cfg=soc_clock_node_mem_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_sys_clk", + "cargo:rustc-cfg=soc_clock_node_sys_clk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_apb_clk", "cargo:rustc-cfg=soc_clock_node_apb_clk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_lp_fast_clk", "cargo:rustc-cfg=soc_clock_node_lp_fast_clk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_lp_slow_clk", "cargo:rustc-cfg=soc_clock_node_lp_slow_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_ble_lp_xtal_clk", + "cargo:rustc-cfg=soc_has_clock_node_ble_lp_clk", + "cargo:rustc-cfg=soc_clock_node_ble_lp_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_crypto_clk", + "cargo:rustc-cfg=soc_clock_node_crypto_clk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_iomux_function_clock", "cargo:rustc-cfg=soc_clock_node_iomux_function_clock_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_timg_calibration_clock", @@ -8475,9 +10095,19 @@ impl Chip { "cargo:rustc-cfg=soc_clock_node_spi_function_clock_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_i2c_function_clock", "cargo:rustc-cfg=soc_clock_node_i2c_function_clock_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_i2s_tx_clk", + "cargo:rustc-cfg=soc_clock_node_i2s_tx_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_i2s_rx_clk", + "cargo:rustc-cfg=soc_clock_node_i2s_rx_clk_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_i2s_mclk_out", + "cargo:rustc-cfg=soc_clock_node_i2s_mclk_out_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_rmt_sclk", "cargo:rustc-cfg=soc_clock_node_rmt_sclk_is_configurable", "cargo:rustc-cfg=soc_has_clock_node_sdm_function_clock", + "cargo:rustc-cfg=soc_has_clock_node_lcd_cam_lcd_clock", + "cargo:rustc-cfg=soc_clock_node_lcd_cam_lcd_clock_is_configurable", + "cargo:rustc-cfg=soc_has_clock_node_lcd_cam_cam_clock", + "cargo:rustc-cfg=soc_clock_node_lcd_cam_cam_clock_is_configurable", "cargo:rustc-cfg=has_dram_region", "cargo:rustc-cfg=has_dram2_uninit_region", "cargo:rustc-cfg=has_irom_region", @@ -8488,13 +10118,13 @@ impl Chip { ( "dram", MemoryRegion { - address_range: 0x2F000000..0x2F07AFC0, + address_range: 0x2F000000..0x2F080000, }, ), ( "dram2_uninit", MemoryRegion { - address_range: 0x2F07AFC0..0x2F07CFB0, + address_range: 0x2F06CFB0..0x2F07CFB0, }, ), ( @@ -8828,6 +10458,7 @@ impl Chip { "soc_has_flash", "soc_has_psram", "soc_has_touch", + "soc_has_ipc", "soc_has_from_cpu_intr0", "soc_has_from_cpu_intr1", "soc_has_from_cpu_intr2", @@ -8850,7 +10481,6 @@ impl Chip { "rgb_display_driver_supported", "adc_driver_supported", "dac_driver_supported", - "temp_sensor_driver_supported", "touch_driver_supported", "ledc_driver_supported", "mcpwm_driver_supported", @@ -8866,6 +10496,7 @@ impl Chip { "dma_driver_supported", "interrupts_driver_supported", "mmu_driver_supported", + "flash_driver_supported", "psram_driver_supported", "rom_driver_supported", "soc_driver_supported", @@ -8884,6 +10515,7 @@ impl Chip { "adc_adc2", "dac_dac1", "dac_dac2", + "pcnt_PCNT", "timergroup_timg0", "timergroup_timg1", "gpio_remap_iomux_pin_registers", @@ -8893,7 +10525,6 @@ impl Chip { "i2c_master_i2c0_data_register_ahb_address_is_set", "spi_master_bit_order_is_bool", "i2s_version_is_set", - "i2s_default_clock_source_is_set", "i2s_mclk_divider_bit_width_is_set", "i2s_max_ws_width_is_set", "i2s_supports_pdm_tx", @@ -8903,7 +10534,10 @@ impl Chip { "rmt_has_per_channel_clock", "sdmmc_has_iomux", "wifi_csi_supported", + "wifi_has_nan", + "ethernet_rx_store_and_forward", "phy_combo_module", + "adc_line_calibration", "soc_has_sdm_ch0", "soc_has_sdm_ch1", "soc_has_sdm_ch2", @@ -8914,8 +10548,13 @@ impl Chip { "soc_has_sdm_ch7", "timergroup_timg_has_timer1", "timergroup_rc_fast_calibration_is_set", + "timergroup_rc_slow_calibration_is_set", "aes_endianness_configurable", "rng_trng_supported", + "sha_has_sha1", + "sha_has_sha256", + "sha_has_sha384", + "sha_has_sha512", "sleep_light_sleep", "sleep_deep_sleep", "sleep_has_wakeup_source_ext0", @@ -8942,6 +10581,7 @@ impl Chip { "rom_has_crc_be", "rom_has_md5_bsd", "soc_multi_core_enabled", + "soc_cpu_pmp_granularity_is_set", "soc_has_clock_node_xtal_clk", "soc_clock_node_xtal_clk_is_configurable", "soc_has_clock_node_pll_clk", @@ -8950,6 +10590,7 @@ impl Chip { "soc_clock_node_apll_clk_is_configurable", "soc_has_clock_node_rc_fast_clk", "soc_has_clock_node_pll_f160m_clk", + "soc_has_clock_node_pll_d2_clk", "soc_has_clock_node_cpu_pll_div_in", "soc_clock_node_cpu_pll_div_in_is_configurable", "soc_has_clock_node_cpu_pll_div", @@ -8980,6 +10621,9 @@ impl Chip { "soc_has_clock_node_xtal_div_clk", "soc_has_clock_node_rtc_slow_clk", "soc_clock_node_rtc_slow_clk_is_configurable", + "soc_has_clock_node_ble_lp_xtal_clk", + "soc_has_clock_node_ble_lp_clk", + "soc_clock_node_ble_lp_clk_is_configurable", "soc_has_clock_node_rtc_fast_clk", "soc_clock_node_rtc_fast_clk_is_configurable", "soc_has_clock_node_uart_mem_clk", @@ -8997,6 +10641,8 @@ impl Chip { "soc_has_clock_node_rmt_sclk", "soc_clock_node_rmt_sclk_is_configurable", "soc_has_clock_node_spi_function_clock", + "soc_has_clock_node_i2s_mclk", + "soc_clock_node_i2s_mclk_is_configurable", "has_dram_region", "has_dram2_uninit_region", "has_irom_region", @@ -9033,11 +10679,18 @@ impl Chip { "i2c_master_has_pd_en", "spi_master_has_app_interrupts", "spi_master_has_dma_segmented_transfer", + "wifi_has_ftm", + "adc_controller_is_set", + "adc_channel_count_is_set", + "adc_basic_calibration", + "adc_calibration_v1_scheme_supported", "timergroup_timg_has_divcnt_rst", + "timergroup_wdt_has_conf_update", "ecc_zero_extend_writes", "ecc_has_finite_field_division", "ecc_has_curve_p192", "ecc_has_curve_p256", + "sha_has_sha224", "assist_debug_has_sp_monitor", "dma_gdma_version_is_set", "soc_has_dma_ch0", @@ -9062,6 +10715,7 @@ impl Chip { "soc_clock_node_mspi_clk_is_configurable", "soc_has_clock_node_rc_fast_clk_div_n", "soc_clock_node_rc_fast_clk_div_n_is_configurable", + "soc_has_clock_node_ble_lp_rc_slow_clk", "soc_has_clock_node_low_power_clk", "soc_clock_node_low_power_clk_is_configurable", "soc_has_clock_node_timg_function_clock", @@ -9069,6 +10723,7 @@ impl Chip { "soc_has_clock_node_timg_wdt_clock", "soc_clock_node_timg_wdt_clock_is_configurable", "soc_clock_node_spi_function_clock_is_configurable", + "soc_has_clock_node_adc_function_clock", "esp32c3", "soc_has_ds", "soc_has_fe", @@ -9079,6 +10734,7 @@ impl Chip { "uhci_driver_supported", "i2c_slave_driver_supported", "usb_serial_jtag_driver_supported", + "temp_sensor_driver_supported", "hmac_driver_supported", "i2c_slave_i2c0", "rmt_has_tx_immediate_stop", @@ -9088,6 +10744,7 @@ impl Chip { "rmt_has_rx_wrap", "rmt_has_rx_demodulation", "phy_backed_up_digital_register_count_is_set", + "adc_curve_calibration", "aes_dma_mode_ecb", "aes_dma_mode_cbc", "aes_dma_mode_ofb", @@ -9095,6 +10752,7 @@ impl Chip { "aes_dma_mode_cfb8", "aes_dma_mode_cfb128", "aes_has_split_text_registers", + "supports_cpu_power_down", "assist_debug_has_region_monitor", "dma_mem2mem_requires_peripheral", "soc_has_dma_ch1", @@ -9104,8 +10762,17 @@ impl Chip { "soc_has_clock_node_cpu_pll_div_out", "soc_clock_node_cpu_pll_div_out_is_configurable", "soc_has_clock_node_pll_160m", + "soc_has_clock_node_tsens_sclk", + "soc_clock_node_tsens_sclk_is_configurable", + "soc_has_clock_node_i2s_tx_clk", + "soc_clock_node_i2s_tx_clk_is_configurable", + "soc_has_clock_node_i2s_rx_clk", + "soc_clock_node_i2s_rx_clk_is_configurable", + "soc_has_clock_node_i2s_mclk_out", + "soc_clock_node_i2s_mclk_out_is_configurable", "esp32c5", "soc_has_cache", + "soc_has_clic", "soc_has_clint", "soc_has_ecdsa", "soc_has_etm", @@ -9135,10 +10802,14 @@ impl Chip { "soc_has_pmu", "soc_has_pvt_monitor", "soc_has_tee", + "soc_has_twai1", "soc_has_lp_core", "lp_i2c_master_driver_supported", "parl_io_driver_supported", + "canfd_driver_supported", "ieee802154_driver_supported", + "canfd_twai0", + "canfd_twai1", "uart_peripheral_controls_mem_clk", "uhci_combined_uart_selector_field", "i2c_master_can_estimate_nack_reason", @@ -9147,8 +10818,14 @@ impl Chip { "spi_master_has_clk_pre_div", "spi_master_dma_can_access_flash", "i2s_clock_configured_by_pcr", + "parl_io_has_tx_cs", "rmt_has_tx_loop_auto_stop", + "wifi_has_wifi6", "wifi_has_5g", + "adc_channel_compensation", + "adc_pcr_clock", + "adc_pcr_sar_clk_div", + "adc_sar_power_override", "timergroup_rc_fast_calibration_divider", "ecc_separate_jacobian_point_memory", "ecc_has_memory_clock_gate", @@ -9159,6 +10836,7 @@ impl Chip { "rng_is_lp_sys", "sleep_has_wakeup_source_wifi_beacon", "sleep_has_wakeup_source_lp_core", + "supports_top_power_down", "dma_separate_in_out_interrupts", "parl_io_supports_dma", "dma_can_access_psram", @@ -9182,24 +10860,27 @@ impl Chip { "soc_clock_node_lp_fast_clk_is_configurable", "soc_has_clock_node_lp_slow_clk", "soc_clock_node_lp_slow_clk_is_configurable", + "soc_has_clock_node_crypto_pll_div", "soc_has_clock_node_iomux_function_clock", "soc_clock_node_iomux_function_clock_is_configurable", "soc_has_clock_node_parl_io_rx_clock", "soc_clock_node_parl_io_rx_clock_is_configurable", "soc_has_clock_node_parl_io_tx_clock", "soc_clock_node_parl_io_tx_clock_is_configurable", + "soc_has_clock_node_twai_function_clock", + "soc_clock_node_twai_function_clock_is_configurable", + "soc_clock_node_adc_function_clock_is_configurable", "esp32c6", "soc_has_atomic", "soc_has_lp_apm", "soc_has_lp_io", "soc_has_otp_debug", "soc_has_plic_mx", + "soc_has_plic_ux", "soc_has_trace0", - "soc_has_twai1", "lp_uart_driver_supported", "ulp_riscv_driver_supported", "etm_driver_supported", - "wifi_has_wifi6", "soc_has_clock_node_soc_root_clk", "soc_clock_node_soc_root_clk_is_configurable", "soc_has_clock_node_cpu_hs_div", @@ -9226,10 +10907,26 @@ impl Chip { "soc_has_clock_node_pll_f64m_clk", "soc_has_clock_node_pll_f48m_clk", "soc_has_clock_node_pll_lp_clk", + "esp32h4", + "soc_has_asrc", + "soc_has_bus_monitor", + "soc_has_clint_other_core", + "soc_has_cpu_apm", + "soc_has_interrupt_core1", + "soc_has_pvt", + "soc_has_touch_aon", + "soc_has_usb_fs", + "soc_has_usb_wrap", + "soc_has_zero_det", + "timergroup_rc_slow_calibration_multiplier", + "sleep_has_wakeup_source_usb", + "soc_has_dma_ch3", + "soc_has_dma_ch4", + "soc_cpu_has_zcmp_workaround", + "soc_has_clock_node_xtal_x2_clk", + "soc_has_clock_node_rc_slow_d4_clk", "esp32p4", "soc_has_hp_sys_clkrst", - "soc_has_interrupt_core1", - "soc_has_clic", "soc_has_iomux_mspi_pin", "soc_has_lp_aon_clkrst", "soc_has_lp_sys", @@ -9245,9 +10942,7 @@ impl Chip { "soc_has_mipi_dsi_host", "soc_has_mipi_dsi_bridge", "soc_has_lp_adc", - "soc_has_usb_fs", "soc_has_usb_hs", - "soc_has_usb_wrap", "usb_otg_driver_supported", "usb_otg_hs_driver_supported", "mipi_dsi_driver_supported", @@ -9261,8 +10956,10 @@ impl Chip { "sdmmc_has_gpio_matrix", "sdmmc_psram_dma", "ethernet_mii_via_gpio_matrix", + "ethernet_rx_checksum_offload", "aes_dma_mode_gcm", - "sleep_has_wakeup_source_usb", + "sha_has_sha512_224", + "sha_has_sha512_256", "soc_has_dma_axi_ch0", "soc_has_dma_axi_ch1", "soc_has_dma_axi_ch2", @@ -9280,6 +10977,7 @@ impl Chip { "soc_has_clock_node_mpll_clk", "soc_clock_node_mpll_clk_is_configurable", "soc_has_clock_node_rc32k_clk", + "soc_has_clock_node_spll_d3_clock", "soc_has_clock_node_pll_f25m", "soc_has_clock_node_pll_f50m", "soc_has_clock_node_cpu_root_clk", @@ -9315,8 +11013,7 @@ impl Chip { "soc_has_rtc_cntl", "soc_has_wcl", "camera_driver_supported", - "soc_has_dma_ch3", - "soc_has_dma_ch4", + "supports_tagmem_power_down", "rmt_supports_dma", "lcd_cam_supports_dma", "soc_has_clock_node_pll_d2", @@ -9333,16 +11030,24 @@ impl Chip { "soc_has_hp_mem_apm", "soc_has_hp_alive_sys", "soc_has_lp_aon_clk_rst", + "soc_has_pcnt1", + "pcnt_PCNT1", + "gpio_need_soft_isolate_during_pd", + "ethernet_has_rgmii", + "ecc_has_curve_sm2", + "sha_has_sm3", "soc_has_clock_node_bbpll_clk", + "soc_has_clock_node_bbpll_d3_clock", "gpio_version, values(\"1\",\"2\",\"3\")", "gpio_gpio_function, values(\"2\",\"1\")", "gpio_constant_0_input, values(\"48\",\"31\",\"96\",\"60\",\"62\",\"192\")", "gpio_constant_1_input, values(\"56\",\"30\",\"64\",\"63\",\"128\")", "gpio_func_in_sel_offset, values(\"0\",\"1\")", "gpio_input_signal_max, \ - values(\"206\",\"100\",\"116\",\"124\",\"249\",\"242\",\"255\")", + values(\"206\",\"100\",\"116\",\"124\",\"189\",\"249\",\"242\",\"255\")", "gpio_output_signal_max, values(\"256\",\"128\")", - "lp_io_version, values(\"esp32\",\"v3\",\"v4\",\"esp32h2\",\"esp32p4\",\"v2\")", + "lp_io_version, \ + values(\"esp32\",\"v3\",\"v4\",\"esp32h2\",\"esp32p4\",\"v2\",\"esp32s31\")", "uart_ram_size, values(\"128\")", "uart_version, values(\"1\",\"2\")", "i2c_master_version, values(\"1\",\"3\",\"4\",\"2\")", @@ -9353,15 +11058,16 @@ impl Chip { "spi_master_version, values(\"1\",\"3\",\"2\")", "spi_master_fifo_size, values(\"64\",\"72\")", "i2s_version, values(\"1\",\"2\",\"3\")", - "i2s_default_clock_source, values(\"2\",\"1\",\"3\")", - "i2s_mclk_divider_bit_width, values(\"6\",\"9\")", + "i2s_mclk_divider_bit_width, values(\"6\",\"9\",\"8\")", "i2s_max_ws_width, values(\"128\",\"512\")", "rmt_ram_start, \ values(\"1073047552\",\"1610703872\",\"1610638336\",\"1610642432\",\"1342842880\",\"\ 1061250048\",\"1610704896\",\"540366848\")", "rmt_channel_ram_size, values(\"64\",\"48\")", - "bt_controller, values(\"btdm\",\"npl\")", + "bt_controller, values(\"btdm\",\"npl\",\"btdm2\")", "wifi_mac_version, values(\"1\",\"3\",\"2\")", + "ethernet_dma_burst_len, values(\"32\",\"16\")", + "rgb_display_output_lines, values(\"24\",\"16\")", "ledc_version, values(\"1\",\"2\",\"3\")", "ledc_channel_count, values(\"8\",\"6\")", "rng_apb_cycle_wait_num, values(\"16\")", @@ -9373,24 +11079,31 @@ impl Chip { "spi_master_dma_engine, values(\"SPI_DMA\",\"AHB_GDMA\",\"AXI_GDMA\")", "spi_slave_dma_engine, values(\"SPI_DMA\",\"AHB_GDMA\",\"AXI_GDMA\")", "i2s_dma_engine, values(\"I2S_DMA\",\"AHB_GDMA\")", - "interrupts_status_registers, values(\"3\",\"2\",\"5\",\"4\",\"6\")", + "interrupts_status_registers, values(\"3\",\"2\",\"4\",\"5\",\"6\")", "interrupt_controller, values(\"xtensa\",\"riscv_basic\",\"clic\",\"plic\")", + "context_switch_source, values(\"ipc\",\"from_cpu\",\"clint\",\"software0\")", "mmu_page_size, values(\"65536\")", - "mmu_entry_num, values(\"256\",\"64\",\"128\",\"512\",\"384\",\"1024\")", + "mmu_entry_num, values(\"256\",\"64\",\"128\",\"512\",\"1024\",\"384\")", "psram_extmem_origin, \ values(\"1065353216\",\"1107296256\",\"1207959552\",\"1062207488\",\"1006632960\",\"\ 1342177280\")", "soc_cpu_mcause_mask, values(\"0\",\"31\",\"63\")", + "soc_cpu_pmp_granularity, values(\"4\",\"128\")", "dedicated_gpio_version, values(\"riscv_v1\",\"riscv_v2\",\"esp32s2\",\"esp32s3\")", + "adc_controller, values(\"digital\",\"rtc\")", + "adc_channel_count, values(\"5\",\"6\",\"7\",\"4\")", "dma_gdma_version, values(\"1\",\"2\",\"3\")", "sha_dma_engine, values(\"AHB_GDMA\",\"AXI_GDMA\",\"CRYPTO_DMA\")", "dma_max_priority, values(\"9\",\"5\",\"15\")", "phy_backed_up_digital_register_count, values(\"21\")", + "cpu_retention, values(\"rtc_cntl\",\"software\")", "aes_dma_engine, values(\"AHB_GDMA\",\"AXI_GDMA\",\"CRYPTO_DMA\")", "uhci_dma_engine, values(\"AHB_GDMA\")", "lp_i2c_master_version, values(\"lp_i2c\",\"rtc_i2c\")", "lp_i2c_master_fifo_size, values(\"16\")", "parl_io_version, values(\"2\",\"1\")", + "parl_io_max_data_width, values(\"8\",\"16\")", + "cpu_retention_frame, values(\"clic\",\"c6_h2\",\"p4\",\"s31\")", "parl_io_dma_engine, values(\"AHB_GDMA\")", "soc_cpu_csr_prv_mode, values(\"2064\",\"3088\")", "lp_uart_ram_size, values(\"32\")", @@ -9399,7 +11112,7 @@ impl Chip { "usb_otg_hs_fifo_depth_words, values(\"896\")", "mipi_dsi_dma_engine, values(\"VDMA\")", "rmt_dma_engine, values(\"AHB_GDMA\")", - "lcd_cam_dma_engine, values(\"AHB_GDMA\")", + "lcd_cam_dma_engine, values(\"AHB_GDMA\",\"AXI_GDMA\")", ] } } diff --git a/esp-metadata-generated/src/_generated_esp32.rs b/esp-metadata-generated/src/_generated_esp32.rs index 83388432b2e..974ca0442e2 100644 --- a/esp-metadata-generated/src/_generated_esp32.rs +++ b/esp-metadata-generated/src/_generated_esp32.rs @@ -88,6 +88,9 @@ macro_rules! property { ("gpio.func_in_sel_offset", str) => { stringify!(0) }; + ("gpio.need_soft_isolate_during_pd") => { + false + }; ("gpio.has_bank_1") => { true }; @@ -229,12 +232,6 @@ macro_rules! property { ("i2s.version", str) => { stringify!(1) }; - ("i2s.default_clock_source") => { - 2 - }; - ("i2s.default_clock_source", str) => { - stringify!(2) - }; ("i2s.mclk_divider_bit_width") => { 6 }; @@ -334,12 +331,66 @@ macro_rules! property { ("wifi.csi_supported") => { true }; + ("wifi.has_nan") => { + true + }; + ("wifi.has_ftm") => { + false + }; ("ethernet.mii_via_gpio_matrix") => { false }; + ("ethernet.rx_store_and_forward") => { + true + }; + ("ethernet.rx_checksum_offload") => { + false + }; + ("ethernet.tx_checksum_offload") => { + false + }; + ("ethernet.dma_burst_len") => { + 32 + }; + ("ethernet.dma_burst_len", str) => { + stringify!(32) + }; + ("ethernet.has_rgmii") => { + false + }; ("phy.combo_module") => { true }; + ("rgb_display.output_lines") => { + 24 + }; + ("rgb_display.output_lines", str) => { + stringify!(24) + }; + ("adc.line_calibration") => { + true + }; + ("adc.curve_calibration") => { + false + }; + ("adc.basic_calibration") => { + false + }; + ("adc.calibration_v1_scheme_supported") => { + false + }; + ("adc.channel_compensation") => { + false + }; + ("adc.pcr_clock") => { + false + }; + ("adc.pcr_sar_clk_div") => { + false + }; + ("adc.sar_power_override") => { + false + }; ("ledc.version") => { 1 }; @@ -364,6 +415,9 @@ macro_rules! property { ("timergroup.timg_has_divcnt_rst") => { false }; + ("timergroup.wdt_has_conf_update") => { + false + }; ("aes.has_split_text_registers") => { false }; @@ -481,6 +535,9 @@ macro_rules! property { ("soc.cpu_has_csr_pc") => { false }; + ("soc.cpu_has_zcmp_workaround") => { + false + }; ("soc.multi_core_enabled") => { true }; @@ -496,6 +553,12 @@ macro_rules! property { ("soc.cpu_mcause_mask", str) => { stringify!(0) }; + ("soc.cpu_pmp_granularity") => { + 4 + }; + ("soc.cpu_pmp_granularity", str) => { + stringify!(4) + }; ("clock_tree.cpu_pll_div_in") => { [crate ::soc::clocks::CpuPllDivInConfig::Pll, crate ::soc::clocks::CpuPllDivInConfig::Apll] @@ -537,18 +600,22 @@ macro_rules! property { crate ::soc::clocks::RefTickConfig::Fosc] }; ("clock_tree.rtc_slow_clk") => { - [crate ::soc::clocks::RtcSlowClkConfig::Xtal32k, crate + [#[cfg(use_xtal32k)] crate ::soc::clocks::RtcSlowClkConfig::Xtal32k, crate ::soc::clocks::RtcSlowClkConfig::RcSlow, crate ::soc::clocks::RtcSlowClkConfig::RcFast] }; + ("clock_tree.ble_lp_clk") => { + [crate ::soc::clocks::BleLpClkConfig::Xtal, crate + ::soc::clocks::BleLpClkConfig::RtcSlow] + }; ("clock_tree.rtc_fast_clk") => { [crate ::soc::clocks::RtcFastClkConfig::Xtal, crate ::soc::clocks::RtcFastClkConfig::Rc] }; ("clock_tree.timg_calibration_clock") => { [crate ::soc::clocks::TimgCalibrationClockConfig::RcSlowClk, crate - ::soc::clocks::TimgCalibrationClockConfig::RcFastDivClk, crate - ::soc::clocks::TimgCalibrationClockConfig::Xtal32kClk] + ::soc::clocks::TimgCalibrationClockConfig::RcFastDivClk, #[cfg(use_xtal32k)] + crate ::soc::clocks::TimgCalibrationClockConfig::Xtal32kClk] }; ("clock_tree.i2c.function_clock.sclk") => { [crate ::soc::clocks::I2cFunctionClockSclk::Apb] @@ -567,6 +634,19 @@ macro_rules! property { [crate ::soc::clocks::RmtSclkConfig::RefTick, crate ::soc::clocks::RmtSclkConfig::ApbClk] }; + ("clock_tree.i2s.mclk.sclk") => { + [crate ::soc::clocks::I2sMclkSclk::PllF160m, crate + ::soc::clocks::I2sMclkSclk::Apll] + }; + ("clock_tree.i2s.mclk.div_num") => { + (1, 255) + }; + ("clock_tree.i2s.mclk.div_a") => { + (1, 63) + }; + ("clock_tree.i2s.mclk.div_b") => { + (0, 63) + }; } /// Defines the `LpInputSignal` and `LpOutputSignal` enums. /// @@ -910,6 +990,12 @@ macro_rules! for_each_sw_interrupt { /// todo!() /// } /// +/// // PLL_D2_CLK +/// +/// fn enable_pll_d2_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// /// // CPU_PLL_DIV_IN /// /// fn enable_cpu_pll_div_in_impl(_clocks: &mut ClockTree, _en: bool) { @@ -1074,6 +1160,7 @@ macro_rules! for_each_sw_interrupt { /// /// // XTAL32K_CLK /// +/// #[cfg(use_xtal32k)] /// fn enable_xtal32k_clk_impl(_clocks: &mut ClockTree, _en: bool) { /// todo!() /// } @@ -1110,6 +1197,26 @@ macro_rules! for_each_sw_interrupt { /// todo!() /// } /// +/// // BLE_LP_XTAL_CLK +/// +/// fn enable_ble_lp_xtal_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// // BLE_LP_CLK +/// +/// fn enable_ble_lp_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_ble_lp_clk_impl( +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: BleLpClkConfig, +/// ) { +/// todo!() +/// } +/// /// // RTC_FAST_CLK /// /// fn enable_rtc_fast_clk_impl(_clocks: &mut ClockTree, _en: bool) { @@ -1167,6 +1274,22 @@ macro_rules! for_each_sw_interrupt { /// todo!() /// } /// } +/// impl I2sInstance { +/// // I2S_MCLK +/// +/// fn enable_mclk_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_mclk_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: I2sMclkConfig, +/// ) { +/// todo!() +/// } +/// } /// impl McpwmInstance { /// // MCPWM_FUNCTION_CLOCK /// @@ -1250,6 +1373,12 @@ macro_rules! define_clock_tree_types { } #[derive(Clone, Copy, PartialEq, Eq, Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum I2sInstance { + I2s0 = 0, + I2s1 = 1, + } + #[derive(Clone, Copy, PartialEq, Eq, Debug)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum McpwmInstance { Mcpwm0 = 0, Mcpwm1 = 1, @@ -1371,7 +1500,7 @@ macro_rules! define_clock_tree_types { pub const fn new(divisor: CpuPllDivDivisor) -> Self { Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -1406,7 +1535,7 @@ macro_rules! define_clock_tree_types { ); Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -1456,7 +1585,7 @@ macro_rules! define_clock_tree_types { ); Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -1482,7 +1611,7 @@ macro_rules! define_clock_tree_types { ); Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -1508,7 +1637,7 @@ macro_rules! define_clock_tree_types { ); Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -1534,7 +1663,7 @@ macro_rules! define_clock_tree_types { ); Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -1555,6 +1684,7 @@ macro_rules! define_clock_tree_types { #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum RtcSlowClkConfig { + #[cfg(use_xtal32k)] /// Selects `XTAL32K_CLK`. Xtal32k, /// Selects `RC_SLOW_CLK`. @@ -1562,6 +1692,15 @@ macro_rules! define_clock_tree_types { /// Selects `RC_FAST_DIV_CLK`. RcFast, } + /// The list of clock signals that the `BLE_LP_CLK` multiplexer can output. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum BleLpClkConfig { + /// Selects `BLE_LP_XTAL_CLK`. + Xtal, + /// Selects `RTC_SLOW_CLK`. + RtcSlow, + } /// The list of clock signals that the `RTC_FAST_CLK` multiplexer can output. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] @@ -1587,6 +1726,7 @@ macro_rules! define_clock_tree_types { RcSlowClk, /// Selects `RC_FAST_DIV_CLK`. RcFastDivClk, + #[cfg(use_xtal32k)] /// Selects `XTAL32K_CLK`. Xtal32kClk, } @@ -1610,10 +1750,76 @@ macro_rules! define_clock_tree_types { pub const fn new(sclk: I2cFunctionClockSclk) -> Self { Self { sclk } } - pub(crate) fn sclk(self) -> I2cFunctionClockSclk { + pub fn sclk(self) -> I2cFunctionClockSclk { self.sclk } } + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum I2sMclkSclk { + #[default] + /// Selects `PLL_F160M_CLK`. + PllF160m, + /// Selects `APLL_CLK`. + Apll, + } + /// Configures the `I2S0_MCLK` clock node. + /// + /// The output is calculated as `OUTPUT = (sclk * div_a) / (div_num * div_a + div_b)`. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub struct I2sMclkConfig { + sclk: I2sMclkSclk, + div_num: u32, + div_a: u32, + div_b: u32, + } + impl I2sMclkConfig { + /// Creates a new configuration for the MCLK clock node. + /// + /// ## Panics + /// + /// Panics if the div_num value is outside the + /// valid range (1 ..= 255). + /// + /// Panics if the div_a value is outside the + /// valid range (1 ..= 63). + /// + /// Panics if the div_b value is outside the + /// valid range (0 ..= 63). + pub const fn new(sclk: I2sMclkSclk, div_num: u32, div_a: u32, div_b: u32) -> Self { + ::core::assert!( + div_num >= 1 && div_num <= 255, + "`I2S0_MCLK` div_num must be between 1 and 255 (inclusive)." + ); + ::core::assert!( + div_a >= 1 && div_a <= 63, + "`I2S0_MCLK` div_a must be between 1 and 63 (inclusive)." + ); + ::core::assert!( + div_b <= 63, + "`I2S0_MCLK` div_b must be between 0 and 63 (inclusive)." + ); + Self { + sclk, + div_num, + div_a, + div_b, + } + } + pub fn sclk(self) -> I2sMclkSclk { + self.sclk + } + pub fn div_num(self) -> u32 { + self.div_num as u32 + } + pub fn div_a(self) -> u32 { + self.div_a as u32 + } + pub fn div_b(self) -> u32 { + self.div_b as u32 + } + } /// The list of clock signals that the `MCPWM0_FUNCTION_CLOCK` multiplexer can output. #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] @@ -1662,7 +1868,7 @@ macro_rules! define_clock_tree_types { pub const fn new(sclk: UartFunctionClockSclk) -> Self { Self { sclk } } - pub(crate) fn sclk(self) -> UartFunctionClockSclk { + pub fn sclk(self) -> UartFunctionClockSclk { self.sclk } } @@ -1701,10 +1907,10 @@ macro_rules! define_clock_tree_types { integral, } } - pub(crate) fn fractional(self) -> u32 { + pub fn fractional(self) -> u32 { self.fractional as u32 } - pub(crate) fn integral(self) -> u32 { + pub fn integral(self) -> u32 { self.integral as u32 } } @@ -1725,26 +1931,32 @@ macro_rules! define_clock_tree_types { ref_tick_pll: Option, cpu_clk: Option, rtc_slow_clk: Option, + ble_lp_clk: Option, rtc_fast_clk: Option, timg_calibration_clock: Option, i2c_function_clock: [Option; 2], + i2s_mclk: [Option; 2], rmt_sclk: [Option; 1], uart_function_clock: [Option; 3], uart_baud_rate_generator: [Option; 3], pll_clk_refcount: u32, + apll_clk_refcount: u32, rc_fast_clk_refcount: u32, pll_f160m_clk_refcount: u32, + pll_d2_clk_refcount: u32, apb_clk_refcount: u32, ref_tick_refcount: u32, + #[cfg(use_xtal32k)] xtal32k_clk_refcount: u32, rc_slow_clk_refcount: u32, rc_fast_div_clk_refcount: u32, - rtc_slow_clk_refcount: u32, + ble_lp_clk_refcount: u32, rtc_fast_clk_refcount: u32, uart_mem_clk_refcount: u32, timg_calibration_clock_refcount: u32, sdm_function_clock_refcount: [u32; 1], i2c_function_clock_refcount: [u32; 2], + i2s_mclk_refcount: [u32; 2], mcpwm_function_clock_refcount: [u32; 2], rmt_sclk_refcount: [u32; 1], spi_function_clock_refcount: [u32; 2], @@ -1817,6 +2029,10 @@ macro_rules! define_clock_tree_types { pub fn rtc_slow_clk(&self) -> Option { self.rtc_slow_clk } + /// Returns the current configuration of the BLE_LP_CLK clock tree node + pub fn ble_lp_clk(&self) -> Option { + self.ble_lp_clk + } /// Returns the current configuration of the RTC_FAST_CLK clock tree node pub fn rtc_fast_clk(&self) -> Option { self.rtc_fast_clk @@ -1833,6 +2049,14 @@ macro_rules! define_clock_tree_types { pub fn i2c1_function_clock(&self) -> Option { self.i2c_function_clock[I2cInstance::I2c1 as usize] } + /// Returns the current configuration of the I2S0_MCLK clock tree node + pub fn i2s0_mclk(&self) -> Option { + self.i2s_mclk[I2sInstance::I2s0 as usize] + } + /// Returns the current configuration of the I2S1_MCLK clock tree node + pub fn i2s1_mclk(&self) -> Option { + self.i2s_mclk[I2sInstance::I2s1 as usize] + } /// Returns the current configuration of the RMT_SCLK clock tree node pub fn rmt_sclk(&self) -> Option { self.rmt_sclk[RmtInstance::Rmt as usize] @@ -1879,26 +2103,32 @@ macro_rules! define_clock_tree_types { ref_tick_pll: None, cpu_clk: None, rtc_slow_clk: None, + ble_lp_clk: None, rtc_fast_clk: None, timg_calibration_clock: None, i2c_function_clock: [None; 2], + i2s_mclk: [None; 2], rmt_sclk: [None; 1], uart_function_clock: [None; 3], uart_baud_rate_generator: [None; 3], pll_clk_refcount: 0, + apll_clk_refcount: 0, rc_fast_clk_refcount: 0, pll_f160m_clk_refcount: 0, + pll_d2_clk_refcount: 0, apb_clk_refcount: 0, ref_tick_refcount: 0, + #[cfg(use_xtal32k)] xtal32k_clk_refcount: 0, rc_slow_clk_refcount: 0, rc_fast_div_clk_refcount: 0, - rtc_slow_clk_refcount: 0, + ble_lp_clk_refcount: 0, rtc_fast_clk_refcount: 0, uart_mem_clk_refcount: 0, timg_calibration_clock_refcount: 0, sdm_function_clock_refcount: [0; 1], i2c_function_clock_refcount: [0; 2], + i2s_mclk_refcount: [0; 2], mcpwm_function_clock_refcount: [0; 2], rmt_sclk_refcount: [0; 1], spi_function_clock_refcount: [0; 2], @@ -1924,10 +2154,14 @@ macro_rules! define_clock_tree_types { ::core::sync::atomic::AtomicU32::new(0); static RTC_SLOW_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); + static BLE_LP_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(0); static RTC_FAST_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); static TIMG_CALIBRATION_CLOCK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); + static I2S_MCLK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 2] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 2]; static APB_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); static REF_TICK_XTAL_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = @@ -1946,6 +2180,185 @@ macro_rules! define_clock_tree_types { [const { ::core::sync::atomic::AtomicU32::new(0) }; 3]; static UART_BAUD_RATE_GENERATOR_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 3] = [const { ::core::sync::atomic::AtomicU32::new(0) }; 3]; + /// The clock sources of the device. + /// + /// A clock source is a node of the clock tree that other nodes derive their output + /// from. Ask a node which source it runs on with its `..._root_source` function. + #[derive(Debug, enumset::EnumSetType)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum ClockSource { + /// `XTAL_CLK`. + XtalClk, + /// `RC_FAST_CLK`. + RcFastClk, + #[cfg(use_xtal32k)] + /// `XTAL32K_CLK`. + Xtal32kClk, + /// `RC_SLOW_CLK`. + RcSlowClk, + } + /// Returns the clock source that `XTAL_CLK` currently runs on. + pub fn xtal_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::XtalClk) + } + /// Returns the clock source that `PLL_CLK` currently runs on. + pub fn pll_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `APLL_CLK` currently runs on. + pub fn apll_clk_root_source(clocks: &mut ClockTree) -> Option { + pll_clk_root_source(clocks) + } + /// Returns the clock source that `RC_FAST_CLK` currently runs on. + pub fn rc_fast_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::RcFastClk) + } + /// Returns the clock source that `PLL_F160M_CLK` currently runs on. + pub fn pll_f160m_clk_root_source(clocks: &mut ClockTree) -> Option { + pll_clk_root_source(clocks) + } + /// Returns the clock source that `PLL_D2_CLK` currently runs on. + pub fn pll_d2_clk_root_source(clocks: &mut ClockTree) -> Option { + pll_clk_root_source(clocks) + } + /// Returns the clock source that `CPU_PLL_DIV_IN` currently runs on. + pub fn cpu_pll_div_in_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.cpu_pll_div_in?; + match config { + CpuPllDivInConfig::Pll => pll_clk_root_source(clocks), + CpuPllDivInConfig::Apll => apll_clk_root_source(clocks), + } + } + /// Returns the clock source that `CPU_PLL_DIV` currently runs on. + pub fn cpu_pll_div_root_source(clocks: &mut ClockTree) -> Option { + cpu_pll_div_in_root_source(clocks) + } + /// Returns the clock source that `SYSCON_PRE_DIV_IN` currently runs on. + pub fn syscon_pre_div_in_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.syscon_pre_div_in?; + match config { + SysconPreDivInConfig::Xtal => xtal_clk_root_source(clocks), + SysconPreDivInConfig::RcFast => rc_fast_clk_root_source(clocks), + } + } + /// Returns the clock source that `SYSCON_PRE_DIV` currently runs on. + pub fn syscon_pre_div_root_source(clocks: &mut ClockTree) -> Option { + syscon_pre_div_in_root_source(clocks) + } + /// Returns the clock source that `CPU_CLK` currently runs on. + pub fn cpu_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.cpu_clk?; + match config { + CpuClkConfig::Xtal => syscon_pre_div_root_source(clocks), + CpuClkConfig::RcFast => syscon_pre_div_root_source(clocks), + CpuClkConfig::Apll => cpu_pll_div_root_source(clocks), + CpuClkConfig::Pll => cpu_pll_div_root_source(clocks), + } + } + /// Returns the clock source that `APB_CLK_CPU_DIV2` currently runs on. + pub fn apb_clk_cpu_div2_root_source(clocks: &mut ClockTree) -> Option { + cpu_clk_root_source(clocks) + } + /// Returns the clock source that `APB_CLK_80M` currently runs on. + pub fn apb_clk_80m_root_source(clocks: &mut ClockTree) -> Option { + cpu_clk_root_source(clocks) + } + #[cfg(use_xtal32k)] + /// Returns the clock source that `XTAL32K_CLK` currently runs on. + pub fn xtal32k_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::Xtal32kClk) + } + /// Returns the clock source that `RC_SLOW_CLK` currently runs on. + pub fn rc_slow_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::RcSlowClk) + } + /// Returns the clock source that `RC_FAST_DIV_CLK` currently runs on. + pub fn rc_fast_div_clk_root_source(clocks: &mut ClockTree) -> Option { + rc_fast_clk_root_source(clocks) + } + /// Returns the clock source that `XTAL_DIV_CLK` currently runs on. + pub fn xtal_div_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `RTC_SLOW_CLK` currently runs on. + pub fn rtc_slow_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.rtc_slow_clk?; + match config { + #[cfg(use_xtal32k)] + RtcSlowClkConfig::Xtal32k => xtal32k_clk_root_source(clocks), + RtcSlowClkConfig::RcSlow => rc_slow_clk_root_source(clocks), + RtcSlowClkConfig::RcFast => rc_fast_div_clk_root_source(clocks), + } + } + /// Returns the clock source that `BLE_LP_XTAL_CLK` currently runs on. + pub fn ble_lp_xtal_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `BLE_LP_CLK` currently runs on. + pub fn ble_lp_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.ble_lp_clk?; + match config { + BleLpClkConfig::Xtal => ble_lp_xtal_clk_root_source(clocks), + BleLpClkConfig::RtcSlow => rtc_slow_clk_root_source(clocks), + } + } + /// Returns the clock source that `RTC_FAST_CLK` currently runs on. + pub fn rtc_fast_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.rtc_fast_clk?; + match config { + RtcFastClkConfig::Xtal => xtal_div_clk_root_source(clocks), + RtcFastClkConfig::Rc => rc_fast_clk_root_source(clocks), + } + } + /// Returns the clock source that `UART_MEM_CLK` currently runs on. + pub fn uart_mem_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `TIMG_CALIBRATION_CLOCK` currently runs on. + pub fn timg_calibration_clock_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.timg_calibration_clock?; + match config { + TimgCalibrationClockConfig::RcSlowClk => rc_slow_clk_root_source(clocks), + TimgCalibrationClockConfig::RcFastDivClk => rc_fast_div_clk_root_source(clocks), + #[cfg(use_xtal32k)] + TimgCalibrationClockConfig::Xtal32kClk => xtal32k_clk_root_source(clocks), + } + } + /// Returns the clock source that `APB_CLK` currently runs on. + pub fn apb_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.apb_clk?; + match config { + ApbClkConfig::Pll80m => apb_clk_80m_root_source(clocks), + ApbClkConfig::CpuDiv2 => apb_clk_cpu_div2_root_source(clocks), + ApbClkConfig::Cpu => cpu_clk_root_source(clocks), + } + } + /// Returns the clock source that `REF_TICK_XTAL` currently runs on. + pub fn ref_tick_xtal_root_source(clocks: &mut ClockTree) -> Option { + apb_clk_root_source(clocks) + } + /// Returns the clock source that `REF_TICK_FOSC` currently runs on. + pub fn ref_tick_fosc_root_source(clocks: &mut ClockTree) -> Option { + apb_clk_root_source(clocks) + } + /// Returns the clock source that `REF_TICK_APLL` currently runs on. + pub fn ref_tick_apll_root_source(clocks: &mut ClockTree) -> Option { + apb_clk_root_source(clocks) + } + /// Returns the clock source that `REF_TICK_PLL` currently runs on. + pub fn ref_tick_pll_root_source(clocks: &mut ClockTree) -> Option { + apb_clk_root_source(clocks) + } + /// Returns the clock source that `REF_TICK` currently runs on. + pub fn ref_tick_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.ref_tick?; + match config { + RefTickConfig::Pll => ref_tick_pll_root_source(clocks), + RefTickConfig::Apll => ref_tick_apll_root_source(clocks), + RefTickConfig::Xtal => ref_tick_xtal_root_source(clocks), + RefTickConfig::Fosc => ref_tick_fosc_root_source(clocks), + } + } pub fn configure_xtal_clk(clocks: &mut ClockTree, config: XtalClkConfig) { let old_config = clocks.xtal_clk.replace(config); refresh_xtal_clk_downstream(clocks); @@ -1956,8 +2369,7 @@ macro_rules! define_clock_tree_types { } fn request_xtal_clk(_clocks: &mut ClockTree) {} fn release_xtal_clk(_clocks: &mut ClockTree) {} - #[allow(unused_variables)] - pub fn xtal_clk_config_frequency(clocks: &mut ClockTree, config: XtalClkConfig) -> u32 { + pub fn xtal_clk_config_frequency(config: XtalClkConfig) -> u32 { config.value() } pub fn xtal_clk_frequency() -> u32 { @@ -1993,8 +2405,7 @@ macro_rules! define_clock_tree_types { release_xtal_clk(clocks); } } - #[allow(unused_variables)] - pub fn pll_clk_config_frequency(clocks: &mut ClockTree, config: PllClkConfig) -> u32 { + pub fn pll_clk_config_frequency(config: PllClkConfig) -> u32 { config.value() } pub fn pll_clk_frequency() -> u32 { @@ -2013,18 +2424,21 @@ macro_rules! define_clock_tree_types { } pub fn request_apll_clk(clocks: &mut ClockTree) { trace!("Requesting APLL_CLK"); - trace!("Enabling APLL_CLK"); - request_pll_clk(clocks); - enable_apll_clk_impl(clocks, true); + if increment_reference_count(&mut clocks.apll_clk_refcount) { + trace!("Enabling APLL_CLK"); + request_pll_clk(clocks); + enable_apll_clk_impl(clocks, true); + } } pub fn release_apll_clk(clocks: &mut ClockTree) { trace!("Releasing APLL_CLK"); - trace!("Disabling APLL_CLK"); - enable_apll_clk_impl(clocks, false); - release_pll_clk(clocks); + if decrement_reference_count(&mut clocks.apll_clk_refcount) { + trace!("Disabling APLL_CLK"); + enable_apll_clk_impl(clocks, false); + release_pll_clk(clocks); + } } - #[allow(unused_variables)] - pub fn apll_clk_config_frequency(clocks: &mut ClockTree, config: ApllClkConfig) -> u32 { + pub fn apll_clk_config_frequency(config: ApllClkConfig) -> u32 { config.value() } pub fn apll_clk_frequency() -> u32 { @@ -2047,9 +2461,30 @@ macro_rules! define_clock_tree_types { enable_rc_fast_clk_impl(clocks, false); } } - pub fn rc_fast_clk_frequency() -> u32 { + static RC_FAST_CLK_FREQUENCY: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(rc_fast_clk_nominal_frequency()); + pub const fn rc_fast_clk_nominal_frequency() -> u32 { 8000000 } + pub fn rc_fast_clk_frequency() -> u32 { + RC_FAST_CLK_FREQUENCY.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn set_rc_fast_clk_frequency(clocks: &mut ClockTree, frequency: u32) { + if !(4000000..=12000000).contains(&frequency) { + warn!( + "Ignoring out-of-range RC_FAST_CLK frequency: {} Hz", + frequency + ); + return; + } + debug!( + "Updating RC_FAST_CLK frequency to {} Hz (nominal {} Hz)", + frequency, + rc_fast_clk_nominal_frequency() + ); + RC_FAST_CLK_FREQUENCY.store(frequency, ::core::sync::atomic::Ordering::Release); + refresh_rc_fast_clk_downstream(clocks); + } pub fn request_pll_f160m_clk(clocks: &mut ClockTree) { trace!("Requesting PLL_F160M_CLK"); if increment_reference_count(&mut clocks.pll_f160m_clk_refcount) { @@ -2072,6 +2507,28 @@ macro_rules! define_clock_tree_types { pub fn pll_f160m_clk_source_frequency() -> u32 { pll_clk_frequency() } + pub fn request_pll_d2_clk(clocks: &mut ClockTree) { + trace!("Requesting PLL_D2_CLK"); + if increment_reference_count(&mut clocks.pll_d2_clk_refcount) { + trace!("Enabling PLL_D2_CLK"); + request_pll_clk(clocks); + enable_pll_d2_clk_impl(clocks, true); + } + } + pub fn release_pll_d2_clk(clocks: &mut ClockTree) { + trace!("Releasing PLL_D2_CLK"); + if decrement_reference_count(&mut clocks.pll_d2_clk_refcount) { + trace!("Disabling PLL_D2_CLK"); + enable_pll_d2_clk_impl(clocks, false); + release_pll_clk(clocks); + } + } + pub fn pll_d2_clk_frequency() -> u32 { + (pll_clk_frequency() / 2) + } + pub fn pll_d2_clk_source_frequency() -> u32 { + pll_clk_frequency() + } pub fn configure_cpu_pll_div_in(clocks: &mut ClockTree, new_selector: CpuPllDivInConfig) { let old_selector = clocks.cpu_pll_div_in.replace(new_selector); refresh_cpu_pll_div_in_downstream(clocks); @@ -2091,7 +2548,6 @@ macro_rules! define_clock_tree_types { clocks.cpu_pll_div_in } pub fn request_cpu_pll_div_in(clocks: &mut ClockTree) { - trace!("Requesting CPU_PLL_DIV_IN"); trace!("Enabling CPU_PLL_DIV_IN"); match unwrap!(clocks.cpu_pll_div_in) { CpuPllDivInConfig::Pll => request_pll_clk(clocks), @@ -2100,7 +2556,6 @@ macro_rules! define_clock_tree_types { enable_cpu_pll_div_in_impl(clocks, true); } pub fn release_cpu_pll_div_in(clocks: &mut ClockTree) { - trace!("Releasing CPU_PLL_DIV_IN"); trace!("Disabling CPU_PLL_DIV_IN"); enable_cpu_pll_div_in_impl(clocks, false); match unwrap!(clocks.cpu_pll_div_in) { @@ -2108,11 +2563,7 @@ macro_rules! define_clock_tree_types { CpuPllDivInConfig::Apll => release_apll_clk(clocks), } } - #[allow(unused_variables)] - pub fn cpu_pll_div_in_config_frequency( - clocks: &mut ClockTree, - config: CpuPllDivInConfig, - ) -> u32 { + pub fn cpu_pll_div_in_config_frequency(config: CpuPllDivInConfig) -> u32 { match config { CpuPllDivInConfig::Pll => pll_clk_frequency(), CpuPllDivInConfig::Apll => apll_clk_frequency(), @@ -2122,10 +2573,7 @@ macro_rules! define_clock_tree_types { CPU_PLL_DIV_IN_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn cpu_pll_div_in_source_frequency(source: CpuPllDivInConfig) -> u32 { - match source { - CpuPllDivInConfig::Pll => pll_clk_frequency(), - CpuPllDivInConfig::Apll => apll_clk_frequency(), - } + cpu_pll_div_in_config_frequency(source) } pub fn configure_cpu_pll_div(clocks: &mut ClockTree, config: CpuPllDivConfig) { if clocks.pll_clk.is_some() { @@ -2139,22 +2587,16 @@ macro_rules! define_clock_tree_types { clocks.cpu_pll_div } pub fn request_cpu_pll_div(clocks: &mut ClockTree) { - trace!("Requesting CPU_PLL_DIV"); trace!("Enabling CPU_PLL_DIV"); request_cpu_pll_div_in(clocks); enable_cpu_pll_div_impl(clocks, true); } pub fn release_cpu_pll_div(clocks: &mut ClockTree) { - trace!("Releasing CPU_PLL_DIV"); trace!("Disabling CPU_PLL_DIV"); enable_cpu_pll_div_impl(clocks, false); release_cpu_pll_div_in(clocks); } - #[allow(unused_variables)] - pub fn cpu_pll_div_config_frequency( - clocks: &mut ClockTree, - config: CpuPllDivConfig, - ) -> u32 { + pub fn cpu_pll_div_config_frequency(config: CpuPllDivConfig) -> u32 { (cpu_pll_div_in_frequency() / config.divisor()) } pub fn cpu_pll_div_frequency() -> u32 { @@ -2185,7 +2627,6 @@ macro_rules! define_clock_tree_types { clocks.syscon_pre_div_in } pub fn request_syscon_pre_div_in(clocks: &mut ClockTree) { - trace!("Requesting SYSCON_PRE_DIV_IN"); trace!("Enabling SYSCON_PRE_DIV_IN"); match unwrap!(clocks.syscon_pre_div_in) { SysconPreDivInConfig::Xtal => request_xtal_clk(clocks), @@ -2194,7 +2635,6 @@ macro_rules! define_clock_tree_types { enable_syscon_pre_div_in_impl(clocks, true); } pub fn release_syscon_pre_div_in(clocks: &mut ClockTree) { - trace!("Releasing SYSCON_PRE_DIV_IN"); trace!("Disabling SYSCON_PRE_DIV_IN"); enable_syscon_pre_div_in_impl(clocks, false); match unwrap!(clocks.syscon_pre_div_in) { @@ -2202,11 +2642,7 @@ macro_rules! define_clock_tree_types { SysconPreDivInConfig::RcFast => release_rc_fast_clk(clocks), } } - #[allow(unused_variables)] - pub fn syscon_pre_div_in_config_frequency( - clocks: &mut ClockTree, - config: SysconPreDivInConfig, - ) -> u32 { + pub fn syscon_pre_div_in_config_frequency(config: SysconPreDivInConfig) -> u32 { match config { SysconPreDivInConfig::Xtal => xtal_clk_frequency(), SysconPreDivInConfig::RcFast => rc_fast_clk_frequency(), @@ -2216,10 +2652,7 @@ macro_rules! define_clock_tree_types { SYSCON_PRE_DIV_IN_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn syscon_pre_div_in_source_frequency(source: SysconPreDivInConfig) -> u32 { - match source { - SysconPreDivInConfig::Xtal => xtal_clk_frequency(), - SysconPreDivInConfig::RcFast => rc_fast_clk_frequency(), - } + syscon_pre_div_in_config_frequency(source) } pub fn configure_syscon_pre_div(clocks: &mut ClockTree, config: SysconPreDivConfig) { let old_config = clocks.syscon_pre_div.replace(config); @@ -2230,22 +2663,16 @@ macro_rules! define_clock_tree_types { clocks.syscon_pre_div } pub fn request_syscon_pre_div(clocks: &mut ClockTree) { - trace!("Requesting SYSCON_PRE_DIV"); trace!("Enabling SYSCON_PRE_DIV"); request_syscon_pre_div_in(clocks); enable_syscon_pre_div_impl(clocks, true); } pub fn release_syscon_pre_div(clocks: &mut ClockTree) { - trace!("Releasing SYSCON_PRE_DIV"); trace!("Disabling SYSCON_PRE_DIV"); enable_syscon_pre_div_impl(clocks, false); release_syscon_pre_div_in(clocks); } - #[allow(unused_variables)] - pub fn syscon_pre_div_config_frequency( - clocks: &mut ClockTree, - config: SysconPreDivConfig, - ) -> u32 { + pub fn syscon_pre_div_config_frequency(config: SysconPreDivConfig) -> u32 { (syscon_pre_div_in_frequency() / (config.divisor() + 1)) } pub fn syscon_pre_div_frequency() -> u32 { @@ -2257,22 +2684,21 @@ macro_rules! define_clock_tree_types { pub fn configure_apb_clk(clocks: &mut ClockTree, new_selector: ApbClkConfig) { let old_selector = clocks.apb_clk.replace(new_selector); refresh_apb_clk_downstream(clocks); - if clocks.apb_clk_refcount > 0 { + let active = clocks.apb_clk_refcount > 0; + if active { match new_selector { ApbClkConfig::Pll80m => request_apb_clk_80m(clocks), ApbClkConfig::CpuDiv2 => request_apb_clk_cpu_div2(clocks), ApbClkConfig::Cpu => request_cpu_clk(clocks), } - configure_apb_clk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - ApbClkConfig::Pll80m => release_apb_clk_80m(clocks), - ApbClkConfig::CpuDiv2 => release_apb_clk_cpu_div2(clocks), - ApbClkConfig::Cpu => release_cpu_clk(clocks), - } + } + configure_apb_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + ApbClkConfig::Pll80m => release_apb_clk_80m(clocks), + ApbClkConfig::CpuDiv2 => release_apb_clk_cpu_div2(clocks), + ApbClkConfig::Cpu => release_cpu_clk(clocks), } - } else { - configure_apb_clk_impl(clocks, old_selector, new_selector); } } pub fn apb_clk_config(clocks: &mut ClockTree) -> Option { @@ -2302,8 +2728,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn apb_clk_config_frequency(clocks: &mut ClockTree, config: ApbClkConfig) -> u32 { + pub fn apb_clk_config_frequency(config: ApbClkConfig) -> u32 { match config { ApbClkConfig::Pll80m => apb_clk_80m_frequency(), ApbClkConfig::CpuDiv2 => apb_clk_cpu_div2_frequency(), @@ -2314,33 +2739,28 @@ macro_rules! define_clock_tree_types { APB_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn apb_clk_source_frequency(source: ApbClkConfig) -> u32 { - match source { - ApbClkConfig::Pll80m => apb_clk_80m_frequency(), - ApbClkConfig::CpuDiv2 => apb_clk_cpu_div2_frequency(), - ApbClkConfig::Cpu => cpu_clk_frequency(), - } + apb_clk_config_frequency(source) } pub fn configure_ref_tick(clocks: &mut ClockTree, new_selector: RefTickConfig) { let old_selector = clocks.ref_tick.replace(new_selector); refresh_ref_tick_downstream(clocks); - if clocks.ref_tick_refcount > 0 { + let active = clocks.ref_tick_refcount > 0; + if active { match new_selector { RefTickConfig::Pll => request_ref_tick_pll(clocks), RefTickConfig::Apll => request_ref_tick_apll(clocks), RefTickConfig::Xtal => request_ref_tick_xtal(clocks), RefTickConfig::Fosc => request_ref_tick_fosc(clocks), } - configure_ref_tick_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - RefTickConfig::Pll => release_ref_tick_pll(clocks), - RefTickConfig::Apll => release_ref_tick_apll(clocks), - RefTickConfig::Xtal => release_ref_tick_xtal(clocks), - RefTickConfig::Fosc => release_ref_tick_fosc(clocks), - } + } + configure_ref_tick_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + RefTickConfig::Pll => release_ref_tick_pll(clocks), + RefTickConfig::Apll => release_ref_tick_apll(clocks), + RefTickConfig::Xtal => release_ref_tick_xtal(clocks), + RefTickConfig::Fosc => release_ref_tick_fosc(clocks), } - } else { - configure_ref_tick_impl(clocks, old_selector, new_selector); } } pub fn ref_tick_config(clocks: &mut ClockTree) -> Option { @@ -2372,8 +2792,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn ref_tick_config_frequency(clocks: &mut ClockTree, config: RefTickConfig) -> u32 { + pub fn ref_tick_config_frequency(config: RefTickConfig) -> u32 { match config { RefTickConfig::Pll => ref_tick_pll_frequency(), RefTickConfig::Apll => ref_tick_apll_frequency(), @@ -2385,12 +2804,7 @@ macro_rules! define_clock_tree_types { REF_TICK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn ref_tick_source_frequency(source: RefTickConfig) -> u32 { - match source { - RefTickConfig::Pll => ref_tick_pll_frequency(), - RefTickConfig::Apll => ref_tick_apll_frequency(), - RefTickConfig::Xtal => ref_tick_xtal_frequency(), - RefTickConfig::Fosc => ref_tick_fosc_frequency(), - } + ref_tick_config_frequency(source) } pub fn configure_ref_tick_xtal(clocks: &mut ClockTree, config: RefTickXtalConfig) { let old_config = clocks.ref_tick_xtal.replace(config); @@ -2401,22 +2815,16 @@ macro_rules! define_clock_tree_types { clocks.ref_tick_xtal } pub fn request_ref_tick_xtal(clocks: &mut ClockTree) { - trace!("Requesting REF_TICK_XTAL"); trace!("Enabling REF_TICK_XTAL"); request_apb_clk(clocks); enable_ref_tick_xtal_impl(clocks, true); } pub fn release_ref_tick_xtal(clocks: &mut ClockTree) { - trace!("Releasing REF_TICK_XTAL"); trace!("Disabling REF_TICK_XTAL"); enable_ref_tick_xtal_impl(clocks, false); release_apb_clk(clocks); } - #[allow(unused_variables)] - pub fn ref_tick_xtal_config_frequency( - clocks: &mut ClockTree, - config: RefTickXtalConfig, - ) -> u32 { + pub fn ref_tick_xtal_config_frequency(config: RefTickXtalConfig) -> u32 { (apb_clk_frequency() / (config.divisor() + 1)) } pub fn ref_tick_xtal_frequency() -> u32 { @@ -2434,22 +2842,16 @@ macro_rules! define_clock_tree_types { clocks.ref_tick_fosc } pub fn request_ref_tick_fosc(clocks: &mut ClockTree) { - trace!("Requesting REF_TICK_FOSC"); trace!("Enabling REF_TICK_FOSC"); request_apb_clk(clocks); enable_ref_tick_fosc_impl(clocks, true); } pub fn release_ref_tick_fosc(clocks: &mut ClockTree) { - trace!("Releasing REF_TICK_FOSC"); trace!("Disabling REF_TICK_FOSC"); enable_ref_tick_fosc_impl(clocks, false); release_apb_clk(clocks); } - #[allow(unused_variables)] - pub fn ref_tick_fosc_config_frequency( - clocks: &mut ClockTree, - config: RefTickFoscConfig, - ) -> u32 { + pub fn ref_tick_fosc_config_frequency(config: RefTickFoscConfig) -> u32 { (apb_clk_frequency() / (config.divisor() + 1)) } pub fn ref_tick_fosc_frequency() -> u32 { @@ -2467,22 +2869,16 @@ macro_rules! define_clock_tree_types { clocks.ref_tick_apll } pub fn request_ref_tick_apll(clocks: &mut ClockTree) { - trace!("Requesting REF_TICK_APLL"); trace!("Enabling REF_TICK_APLL"); request_apb_clk(clocks); enable_ref_tick_apll_impl(clocks, true); } pub fn release_ref_tick_apll(clocks: &mut ClockTree) { - trace!("Releasing REF_TICK_APLL"); trace!("Disabling REF_TICK_APLL"); enable_ref_tick_apll_impl(clocks, false); release_apb_clk(clocks); } - #[allow(unused_variables)] - pub fn ref_tick_apll_config_frequency( - clocks: &mut ClockTree, - config: RefTickApllConfig, - ) -> u32 { + pub fn ref_tick_apll_config_frequency(config: RefTickApllConfig) -> u32 { (apb_clk_frequency() / (config.divisor() + 1)) } pub fn ref_tick_apll_frequency() -> u32 { @@ -2500,22 +2896,16 @@ macro_rules! define_clock_tree_types { clocks.ref_tick_pll } pub fn request_ref_tick_pll(clocks: &mut ClockTree) { - trace!("Requesting REF_TICK_PLL"); trace!("Enabling REF_TICK_PLL"); request_apb_clk(clocks); enable_ref_tick_pll_impl(clocks, true); } pub fn release_ref_tick_pll(clocks: &mut ClockTree) { - trace!("Releasing REF_TICK_PLL"); trace!("Disabling REF_TICK_PLL"); enable_ref_tick_pll_impl(clocks, false); release_apb_clk(clocks); } - #[allow(unused_variables)] - pub fn ref_tick_pll_config_frequency( - clocks: &mut ClockTree, - config: RefTickPllConfig, - ) -> u32 { + pub fn ref_tick_pll_config_frequency(config: RefTickPllConfig) -> u32 { (apb_clk_frequency() / (config.divisor() + 1)) } pub fn ref_tick_pll_frequency() -> u32 { @@ -2581,8 +2971,7 @@ macro_rules! define_clock_tree_types { } fn request_cpu_clk(_clocks: &mut ClockTree) {} fn release_cpu_clk(_clocks: &mut ClockTree) {} - #[allow(unused_variables)] - pub fn cpu_clk_config_frequency(clocks: &mut ClockTree, config: CpuClkConfig) -> u32 { + pub fn cpu_clk_config_frequency(config: CpuClkConfig) -> u32 { match config { CpuClkConfig::Xtal => syscon_pre_div_frequency(), CpuClkConfig::RcFast => syscon_pre_div_frequency(), @@ -2594,13 +2983,11 @@ macro_rules! define_clock_tree_types { CPU_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn request_apb_clk_cpu_div2(clocks: &mut ClockTree) { - trace!("Requesting APB_CLK_CPU_DIV2"); trace!("Enabling APB_CLK_CPU_DIV2"); request_cpu_clk(clocks); enable_apb_clk_cpu_div2_impl(clocks, true); } pub fn release_apb_clk_cpu_div2(clocks: &mut ClockTree) { - trace!("Releasing APB_CLK_CPU_DIV2"); trace!("Disabling APB_CLK_CPU_DIV2"); enable_apb_clk_cpu_div2_impl(clocks, false); release_cpu_clk(clocks); @@ -2612,13 +2999,11 @@ macro_rules! define_clock_tree_types { cpu_clk_frequency() } pub fn request_apb_clk_80m(clocks: &mut ClockTree) { - trace!("Requesting APB_CLK_80M"); trace!("Enabling APB_CLK_80M"); request_cpu_clk(clocks); enable_apb_clk_80m_impl(clocks, true); } pub fn release_apb_clk_80m(clocks: &mut ClockTree) { - trace!("Releasing APB_CLK_80M"); trace!("Disabling APB_CLK_80M"); enable_apb_clk_80m_impl(clocks, false); release_cpu_clk(clocks); @@ -2629,6 +3014,7 @@ macro_rules! define_clock_tree_types { pub fn apb_clk_80m_source_frequency() -> u32 { cpu_clk_frequency() } + #[cfg(use_xtal32k)] pub fn request_xtal32k_clk(clocks: &mut ClockTree) { trace!("Requesting XTAL32K_CLK"); if increment_reference_count(&mut clocks.xtal32k_clk_refcount) { @@ -2636,6 +3022,7 @@ macro_rules! define_clock_tree_types { enable_xtal32k_clk_impl(clocks, true); } } + #[cfg(use_xtal32k)] pub fn release_xtal32k_clk(clocks: &mut ClockTree) { trace!("Releasing XTAL32K_CLK"); if decrement_reference_count(&mut clocks.xtal32k_clk_refcount) { @@ -2643,6 +3030,7 @@ macro_rules! define_clock_tree_types { enable_xtal32k_clk_impl(clocks, false); } } + #[cfg(use_xtal32k)] pub fn xtal32k_clk_frequency() -> u32 { 32768 } @@ -2660,9 +3048,30 @@ macro_rules! define_clock_tree_types { enable_rc_slow_clk_impl(clocks, false); } } - pub fn rc_slow_clk_frequency() -> u32 { + static RC_SLOW_CLK_FREQUENCY: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(rc_slow_clk_nominal_frequency()); + pub const fn rc_slow_clk_nominal_frequency() -> u32 { 150000 } + pub fn rc_slow_clk_frequency() -> u32 { + RC_SLOW_CLK_FREQUENCY.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn set_rc_slow_clk_frequency(clocks: &mut ClockTree, frequency: u32) { + if !(75000..=225000).contains(&frequency) { + warn!( + "Ignoring out-of-range RC_SLOW_CLK frequency: {} Hz", + frequency + ); + return; + } + debug!( + "Updating RC_SLOW_CLK frequency to {} Hz (nominal {} Hz)", + frequency, + rc_slow_clk_nominal_frequency() + ); + RC_SLOW_CLK_FREQUENCY.store(frequency, ::core::sync::atomic::Ordering::Release); + refresh_rc_slow_clk_downstream(clocks); + } pub fn request_rc_fast_div_clk(clocks: &mut ClockTree) { trace!("Requesting RC_FAST_DIV_CLK"); if increment_reference_count(&mut clocks.rc_fast_div_clk_refcount) { @@ -2686,13 +3095,11 @@ macro_rules! define_clock_tree_types { rc_fast_clk_frequency() } pub fn request_xtal_div_clk(clocks: &mut ClockTree) { - trace!("Requesting XTAL_DIV_CLK"); trace!("Enabling XTAL_DIV_CLK"); request_xtal_clk(clocks); enable_xtal_div_clk_impl(clocks, true); } pub fn release_xtal_div_clk(clocks: &mut ClockTree) { - trace!("Releasing XTAL_DIV_CLK"); trace!("Disabling XTAL_DIV_CLK"); enable_xtal_div_clk_impl(clocks, false); release_xtal_clk(clocks); @@ -2706,57 +3113,48 @@ macro_rules! define_clock_tree_types { pub fn configure_rtc_slow_clk(clocks: &mut ClockTree, new_selector: RtcSlowClkConfig) { let old_selector = clocks.rtc_slow_clk.replace(new_selector); refresh_rtc_slow_clk_downstream(clocks); - if clocks.rtc_slow_clk_refcount > 0 { - match new_selector { - RtcSlowClkConfig::Xtal32k => request_xtal32k_clk(clocks), - RtcSlowClkConfig::RcSlow => request_rc_slow_clk(clocks), - RtcSlowClkConfig::RcFast => request_rc_fast_div_clk(clocks), - } - configure_rtc_slow_clk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - RtcSlowClkConfig::Xtal32k => release_xtal32k_clk(clocks), - RtcSlowClkConfig::RcSlow => release_rc_slow_clk(clocks), - RtcSlowClkConfig::RcFast => release_rc_fast_div_clk(clocks), - } + match new_selector { + #[cfg(use_xtal32k)] + RtcSlowClkConfig::Xtal32k => request_xtal32k_clk(clocks), + RtcSlowClkConfig::RcSlow => request_rc_slow_clk(clocks), + RtcSlowClkConfig::RcFast => request_rc_fast_div_clk(clocks), + } + configure_rtc_slow_clk_impl(clocks, old_selector, new_selector); + if let Some(old_selector) = old_selector { + match old_selector { + #[cfg(use_xtal32k)] + RtcSlowClkConfig::Xtal32k => release_xtal32k_clk(clocks), + RtcSlowClkConfig::RcSlow => release_rc_slow_clk(clocks), + RtcSlowClkConfig::RcFast => release_rc_fast_div_clk(clocks), } - } else { - configure_rtc_slow_clk_impl(clocks, old_selector, new_selector); } } pub fn rtc_slow_clk_config(clocks: &mut ClockTree) -> Option { clocks.rtc_slow_clk } pub fn request_rtc_slow_clk(clocks: &mut ClockTree) { - trace!("Requesting RTC_SLOW_CLK"); - if increment_reference_count(&mut clocks.rtc_slow_clk_refcount) { - trace!("Enabling RTC_SLOW_CLK"); - match unwrap!(clocks.rtc_slow_clk) { - RtcSlowClkConfig::Xtal32k => request_xtal32k_clk(clocks), - RtcSlowClkConfig::RcSlow => request_rc_slow_clk(clocks), - RtcSlowClkConfig::RcFast => request_rc_fast_div_clk(clocks), - } - enable_rtc_slow_clk_impl(clocks, true); + trace!("Enabling RTC_SLOW_CLK"); + match unwrap!(clocks.rtc_slow_clk) { + #[cfg(use_xtal32k)] + RtcSlowClkConfig::Xtal32k => request_xtal32k_clk(clocks), + RtcSlowClkConfig::RcSlow => request_rc_slow_clk(clocks), + RtcSlowClkConfig::RcFast => request_rc_fast_div_clk(clocks), } + enable_rtc_slow_clk_impl(clocks, true); } pub fn release_rtc_slow_clk(clocks: &mut ClockTree) { - trace!("Releasing RTC_SLOW_CLK"); - if decrement_reference_count(&mut clocks.rtc_slow_clk_refcount) { - trace!("Disabling RTC_SLOW_CLK"); - enable_rtc_slow_clk_impl(clocks, false); - match unwrap!(clocks.rtc_slow_clk) { - RtcSlowClkConfig::Xtal32k => release_xtal32k_clk(clocks), - RtcSlowClkConfig::RcSlow => release_rc_slow_clk(clocks), - RtcSlowClkConfig::RcFast => release_rc_fast_div_clk(clocks), - } + trace!("Disabling RTC_SLOW_CLK"); + enable_rtc_slow_clk_impl(clocks, false); + match unwrap!(clocks.rtc_slow_clk) { + #[cfg(use_xtal32k)] + RtcSlowClkConfig::Xtal32k => release_xtal32k_clk(clocks), + RtcSlowClkConfig::RcSlow => release_rc_slow_clk(clocks), + RtcSlowClkConfig::RcFast => release_rc_fast_div_clk(clocks), } } - #[allow(unused_variables)] - pub fn rtc_slow_clk_config_frequency( - clocks: &mut ClockTree, - config: RtcSlowClkConfig, - ) -> u32 { + pub fn rtc_slow_clk_config_frequency(config: RtcSlowClkConfig) -> u32 { match config { + #[cfg(use_xtal32k)] RtcSlowClkConfig::Xtal32k => xtal32k_clk_frequency(), RtcSlowClkConfig::RcSlow => rc_slow_clk_frequency(), RtcSlowClkConfig::RcFast => rc_fast_div_clk_frequency(), @@ -2766,29 +3164,95 @@ macro_rules! define_clock_tree_types { RTC_SLOW_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn rtc_slow_clk_source_frequency(source: RtcSlowClkConfig) -> u32 { - match source { - RtcSlowClkConfig::Xtal32k => xtal32k_clk_frequency(), - RtcSlowClkConfig::RcSlow => rc_slow_clk_frequency(), - RtcSlowClkConfig::RcFast => rc_fast_div_clk_frequency(), + rtc_slow_clk_config_frequency(source) + } + pub fn request_ble_lp_xtal_clk(clocks: &mut ClockTree) { + trace!("Enabling BLE_LP_XTAL_CLK"); + request_xtal_clk(clocks); + enable_ble_lp_xtal_clk_impl(clocks, true); + } + pub fn release_ble_lp_xtal_clk(clocks: &mut ClockTree) { + trace!("Disabling BLE_LP_XTAL_CLK"); + enable_ble_lp_xtal_clk_impl(clocks, false); + release_xtal_clk(clocks); + } + pub fn ble_lp_xtal_clk_frequency() -> u32 { + 500000 + } + pub fn ble_lp_xtal_clk_source_frequency() -> u32 { + xtal_clk_frequency() + } + pub fn configure_ble_lp_clk(clocks: &mut ClockTree, new_selector: BleLpClkConfig) { + let old_selector = clocks.ble_lp_clk.replace(new_selector); + refresh_ble_lp_clk_downstream(clocks); + let active = clocks.ble_lp_clk_refcount > 0; + if active { + match new_selector { + BleLpClkConfig::Xtal => request_ble_lp_xtal_clk(clocks), + BleLpClkConfig::RtcSlow => request_rtc_slow_clk(clocks), + } + } + configure_ble_lp_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + BleLpClkConfig::Xtal => release_ble_lp_xtal_clk(clocks), + BleLpClkConfig::RtcSlow => release_rtc_slow_clk(clocks), + } + } + } + pub fn ble_lp_clk_config(clocks: &mut ClockTree) -> Option { + clocks.ble_lp_clk + } + pub fn request_ble_lp_clk(clocks: &mut ClockTree) { + trace!("Requesting BLE_LP_CLK"); + if increment_reference_count(&mut clocks.ble_lp_clk_refcount) { + trace!("Enabling BLE_LP_CLK"); + match unwrap!(clocks.ble_lp_clk) { + BleLpClkConfig::Xtal => request_ble_lp_xtal_clk(clocks), + BleLpClkConfig::RtcSlow => request_rtc_slow_clk(clocks), + } + enable_ble_lp_clk_impl(clocks, true); } } + pub fn release_ble_lp_clk(clocks: &mut ClockTree) { + trace!("Releasing BLE_LP_CLK"); + if decrement_reference_count(&mut clocks.ble_lp_clk_refcount) { + trace!("Disabling BLE_LP_CLK"); + enable_ble_lp_clk_impl(clocks, false); + match unwrap!(clocks.ble_lp_clk) { + BleLpClkConfig::Xtal => release_ble_lp_xtal_clk(clocks), + BleLpClkConfig::RtcSlow => release_rtc_slow_clk(clocks), + } + } + } + pub fn ble_lp_clk_config_frequency(config: BleLpClkConfig) -> u32 { + match config { + BleLpClkConfig::Xtal => ble_lp_xtal_clk_frequency(), + BleLpClkConfig::RtcSlow => rtc_slow_clk_frequency(), + } + } + pub fn ble_lp_clk_frequency() -> u32 { + BLE_LP_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn ble_lp_clk_source_frequency(source: BleLpClkConfig) -> u32 { + ble_lp_clk_config_frequency(source) + } pub fn configure_rtc_fast_clk(clocks: &mut ClockTree, new_selector: RtcFastClkConfig) { let old_selector = clocks.rtc_fast_clk.replace(new_selector); refresh_rtc_fast_clk_downstream(clocks); - if clocks.rtc_fast_clk_refcount > 0 { + let active = clocks.rtc_fast_clk_refcount > 0; + if active { match new_selector { RtcFastClkConfig::Xtal => request_xtal_div_clk(clocks), RtcFastClkConfig::Rc => request_rc_fast_clk(clocks), } - configure_rtc_fast_clk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - RtcFastClkConfig::Xtal => release_xtal_div_clk(clocks), - RtcFastClkConfig::Rc => release_rc_fast_clk(clocks), - } + } + configure_rtc_fast_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + RtcFastClkConfig::Xtal => release_xtal_div_clk(clocks), + RtcFastClkConfig::Rc => release_rc_fast_clk(clocks), } - } else { - configure_rtc_fast_clk_impl(clocks, old_selector, new_selector); } } pub fn rtc_fast_clk_config(clocks: &mut ClockTree) -> Option { @@ -2816,11 +3280,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn rtc_fast_clk_config_frequency( - clocks: &mut ClockTree, - config: RtcFastClkConfig, - ) -> u32 { + pub fn rtc_fast_clk_config_frequency(config: RtcFastClkConfig) -> u32 { match config { RtcFastClkConfig::Xtal => xtal_div_clk_frequency(), RtcFastClkConfig::Rc => rc_fast_clk_frequency(), @@ -2830,10 +3290,7 @@ macro_rules! define_clock_tree_types { RTC_FAST_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn rtc_fast_clk_source_frequency(source: RtcFastClkConfig) -> u32 { - match source { - RtcFastClkConfig::Xtal => xtal_div_clk_frequency(), - RtcFastClkConfig::Rc => rc_fast_clk_frequency(), - } + rtc_fast_clk_config_frequency(source) } pub fn request_uart_mem_clk(clocks: &mut ClockTree) { trace!("Requesting UART_MEM_CLK"); @@ -2865,22 +3322,23 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.timg_calibration_clock.replace(new_selector); refresh_timg_calibration_clock_downstream(clocks); - if clocks.timg_calibration_clock_refcount > 0 { + let active = clocks.timg_calibration_clock_refcount > 0; + if active { match new_selector { TimgCalibrationClockConfig::RcSlowClk => request_rc_slow_clk(clocks), TimgCalibrationClockConfig::RcFastDivClk => request_rc_fast_div_clk(clocks), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => request_xtal32k_clk(clocks), } - configure_timg_calibration_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - TimgCalibrationClockConfig::RcSlowClk => release_rc_slow_clk(clocks), - TimgCalibrationClockConfig::RcFastDivClk => release_rc_fast_div_clk(clocks), - TimgCalibrationClockConfig::Xtal32kClk => release_xtal32k_clk(clocks), - } + } + configure_timg_calibration_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + TimgCalibrationClockConfig::RcSlowClk => release_rc_slow_clk(clocks), + TimgCalibrationClockConfig::RcFastDivClk => release_rc_fast_div_clk(clocks), + #[cfg(use_xtal32k)] + TimgCalibrationClockConfig::Xtal32kClk => release_xtal32k_clk(clocks), } - } else { - configure_timg_calibration_clock_impl(clocks, old_selector, new_selector); } } pub fn timg_calibration_clock_config( @@ -2896,6 +3354,7 @@ macro_rules! define_clock_tree_types { match unwrap!(clocks.timg_calibration_clock) { TimgCalibrationClockConfig::RcSlowClk => request_rc_slow_clk(clocks), TimgCalibrationClockConfig::RcFastDivClk => request_rc_fast_div_clk(clocks), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => request_xtal32k_clk(clocks), } enable_timg_calibration_clock_impl(clocks, true); @@ -2910,18 +3369,16 @@ macro_rules! define_clock_tree_types { match unwrap!(clocks.timg_calibration_clock) { TimgCalibrationClockConfig::RcSlowClk => release_rc_slow_clk(clocks), TimgCalibrationClockConfig::RcFastDivClk => release_rc_fast_div_clk(clocks), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => release_xtal32k_clk(clocks), } } } - #[allow(unused_variables)] - pub fn timg_calibration_clock_config_frequency( - clocks: &mut ClockTree, - config: TimgCalibrationClockConfig, - ) -> u32 { + pub fn timg_calibration_clock_config_frequency(config: TimgCalibrationClockConfig) -> u32 { match config { TimgCalibrationClockConfig::RcSlowClk => rc_slow_clk_frequency(), TimgCalibrationClockConfig::RcFastDivClk => rc_fast_div_clk_frequency(), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => xtal32k_clk_frequency(), } } @@ -2929,11 +3386,7 @@ macro_rules! define_clock_tree_types { TIMG_CALIBRATION_CLOCK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn timg_calibration_clock_source_frequency(source: TimgCalibrationClockConfig) -> u32 { - match source { - TimgCalibrationClockConfig::RcSlowClk => rc_slow_clk_frequency(), - TimgCalibrationClockConfig::RcFastDivClk => rc_fast_div_clk_frequency(), - TimgCalibrationClockConfig::Xtal32kClk => xtal32k_clk_frequency(), - } + timg_calibration_clock_config_frequency(source) } impl SdmInstance { pub fn request_function_clock(self, clocks: &mut ClockTree) { @@ -3002,10 +3455,7 @@ macro_rules! define_clock_tree_types { } } #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: I2cFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: I2cFunctionClockConfig) -> u32 { apb_clk_frequency() } pub fn function_clock_frequency(self) -> u32 { @@ -3017,6 +3467,71 @@ macro_rules! define_clock_tree_types { } } } + impl I2sInstance { + pub fn configure_mclk(self, clocks: &mut ClockTree, config: I2sMclkConfig) { + let old_config = clocks.i2s_mclk[self as usize].replace(config); + refresh_i2s_mclk_downstream(clocks, self); + let active = clocks.i2s_mclk_refcount[self as usize] > 0; + if active { + match config.sclk { + I2sMclkSclk::PllF160m => request_pll_f160m_clk(clocks), + I2sMclkSclk::Apll => request_apll_clk(clocks), + } + } + self.configure_mclk_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + I2sMclkSclk::PllF160m => release_pll_f160m_clk(clocks), + I2sMclkSclk::Apll => release_apll_clk(clocks), + } + } + } + pub fn mclk_config(self, clocks: &mut ClockTree) -> Option { + clocks.i2s_mclk[self as usize] + } + pub fn request_mclk(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::MCLK", self); + if increment_reference_count(&mut clocks.i2s_mclk_refcount[self as usize]) { + trace!("Enabling {:?}::MCLK", self); + crate::rtc_cntl::WakeLock::acquire(); + match unwrap!(clocks.i2s_mclk[self as usize]).sclk { + I2sMclkSclk::PllF160m => request_pll_f160m_clk(clocks), + I2sMclkSclk::Apll => request_apll_clk(clocks), + } + self.enable_mclk_impl(clocks, true); + } + } + pub fn release_mclk(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::MCLK", self); + if decrement_reference_count(&mut clocks.i2s_mclk_refcount[self as usize]) { + trace!("Disabling {:?}::MCLK", self); + crate::rtc_cntl::WakeLock::release(); + self.enable_mclk_impl(clocks, false); + match unwrap!(clocks.i2s_mclk[self as usize]).sclk { + I2sMclkSclk::PllF160m => release_pll_f160m_clk(clocks), + I2sMclkSclk::Apll => release_apll_clk(clocks), + } + } + } + pub fn mclk_config_frequency(config: I2sMclkConfig) -> u32 { + (((match config.sclk { + I2sMclkSclk::PllF160m => pll_f160m_clk_frequency(), + I2sMclkSclk::Apll => apll_clk_frequency(), + } as u64) + * (config.div_a() as u64)) + / (((config.div_num() * config.div_a()) + config.div_b()) as u64)) + as u32 + } + pub fn mclk_frequency(self) -> u32 { + I2S_MCLK_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) + } + pub fn mclk_source_frequency(sclk: I2sMclkSclk) -> u32 { + match sclk { + I2sMclkSclk::PllF160m => pll_f160m_clk_frequency(), + I2sMclkSclk::Apll => apll_clk_frequency(), + } + } + } impl McpwmInstance { pub fn request_function_clock(self, clocks: &mut ClockTree) { trace!("Requesting {:?}::FUNCTION_CLOCK", self); @@ -3053,20 +3568,19 @@ macro_rules! define_clock_tree_types { pub fn configure_sclk(self, clocks: &mut ClockTree, new_selector: RmtSclkConfig) { let old_selector = clocks.rmt_sclk[self as usize].replace(new_selector); refresh_rmt_sclk_downstream(clocks, self); - if clocks.rmt_sclk_refcount[self as usize] > 0 { + let active = clocks.rmt_sclk_refcount[self as usize] > 0; + if active { match new_selector { RmtSclkConfig::RefTick => request_ref_tick(clocks), RmtSclkConfig::ApbClk => request_apb_clk(clocks), } - self.configure_sclk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - RmtSclkConfig::RefTick => release_ref_tick(clocks), - RmtSclkConfig::ApbClk => release_apb_clk(clocks), - } + } + self.configure_sclk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + RmtSclkConfig::RefTick => release_ref_tick(clocks), + RmtSclkConfig::ApbClk => release_apb_clk(clocks), } - } else { - self.configure_sclk_impl(clocks, old_selector, new_selector); } } pub fn sclk_config(self, clocks: &mut ClockTree) -> Option { @@ -3096,8 +3610,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn sclk_config_frequency(clocks: &mut ClockTree, config: RmtSclkConfig) -> u32 { + pub fn sclk_config_frequency(config: RmtSclkConfig) -> u32 { match config { RmtSclkConfig::RefTick => ref_tick_frequency(), RmtSclkConfig::ApbClk => apb_clk_frequency(), @@ -3107,10 +3620,7 @@ macro_rules! define_clock_tree_types { RMT_SCLK_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) } pub fn sclk_source_frequency(source: RmtSclkConfig) -> u32 { - match source { - RmtSclkConfig::RefTick => ref_tick_frequency(), - RmtSclkConfig::ApbClk => apb_clk_frequency(), - } + Self::sclk_config_frequency(source) } } impl SpiInstance { @@ -3151,20 +3661,19 @@ macro_rules! define_clock_tree_types { ) { let old_config = clocks.uart_function_clock[self as usize].replace(config); refresh_uart_function_clock_downstream(clocks, self); - if clocks.uart_function_clock_refcount[self as usize] > 0 { + let active = clocks.uart_function_clock_refcount[self as usize] > 0; + if active { match config.sclk { UartFunctionClockSclk::Apb => request_apb_clk(clocks), UartFunctionClockSclk::RefTick => request_ref_tick(clocks), } - self.configure_function_clock_impl(clocks, old_config, config); - if let Some(old_config) = old_config { - match old_config.sclk { - UartFunctionClockSclk::Apb => release_apb_clk(clocks), - UartFunctionClockSclk::RefTick => release_ref_tick(clocks), - } + } + self.configure_function_clock_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + UartFunctionClockSclk::Apb => release_apb_clk(clocks), + UartFunctionClockSclk::RefTick => release_ref_tick(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_config, config); } } pub fn function_clock_config( @@ -3199,11 +3708,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: UartFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: UartFunctionClockConfig) -> u32 { match config.sclk { UartFunctionClockSclk::Apb => apb_clk_frequency(), UartFunctionClockSclk::RefTick => ref_tick_frequency(), @@ -3276,10 +3781,8 @@ macro_rules! define_clock_tree_types { self.release_function_clock(clocks); } } - #[allow(unused_variables)] pub fn baud_rate_generator_config_frequency( self, - clocks: &mut ClockTree, config: UartBaudRateGeneratorConfig, ) -> u32 { ((self.function_clock_frequency() * 16) @@ -3315,6 +3818,8 @@ macro_rules! define_clock_tree_types { pub cpu_clk: Option, /// `RTC_SLOW_CLK` configuration. pub rtc_slow_clk: Option, + /// `BLE_LP_CLK` configuration. + pub ble_lp_clk: Option, /// `RTC_FAST_CLK` configuration. pub rtc_fast_clk: Option, /// `TIMG_CALIBRATION_CLOCK` configuration. @@ -3343,6 +3848,9 @@ macro_rules! define_clock_tree_types { if let Some(config) = self.rtc_slow_clk { configure_rtc_slow_clk(clocks, config); } + if let Some(config) = self.ble_lp_clk { + configure_ble_lp_clk(clocks, config); + } if let Some(config) = self.rtc_fast_clk { configure_rtc_fast_clk(clocks, config); } @@ -3364,37 +3872,50 @@ macro_rules! define_clock_tree_types { fn refresh_xtal_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.xtal_clk { XTAL_CLK_FREQ_CACHE.store( - xtal_clk_config_frequency(clocks, config), + xtal_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } refresh_pll_clk_downstream(clocks); refresh_syscon_pre_div_in_downstream(clocks); + refresh_ble_lp_clk_downstream(clocks); refresh_rtc_fast_clk_downstream(clocks); } fn refresh_pll_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.pll_clk { PLL_CLK_FREQ_CACHE.store( - pll_clk_config_frequency(clocks, config), + pll_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } refresh_apll_clk_downstream(clocks); refresh_cpu_pll_div_in_downstream(clocks); + for child_instance in [I2sInstance::I2s0, I2sInstance::I2s1] { + refresh_i2s_mclk_downstream(clocks, child_instance); + } } fn refresh_apll_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.apll_clk { APLL_CLK_FREQ_CACHE.store( - apll_clk_config_frequency(clocks, config), + apll_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } refresh_cpu_pll_div_in_downstream(clocks); + for child_instance in [I2sInstance::I2s0, I2sInstance::I2s1] { + refresh_i2s_mclk_downstream(clocks, child_instance); + } + } + fn refresh_rc_fast_clk_downstream(clocks: &mut ClockTree) { + refresh_syscon_pre_div_in_downstream(clocks); + refresh_rtc_slow_clk_downstream(clocks); + refresh_rtc_fast_clk_downstream(clocks); + refresh_timg_calibration_clock_downstream(clocks); } fn refresh_cpu_pll_div_in_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.cpu_pll_div_in { CPU_PLL_DIV_IN_FREQ_CACHE.store( - cpu_pll_div_in_config_frequency(clocks, config), + cpu_pll_div_in_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3403,7 +3924,7 @@ macro_rules! define_clock_tree_types { fn refresh_cpu_pll_div_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.cpu_pll_div { CPU_PLL_DIV_FREQ_CACHE.store( - cpu_pll_div_config_frequency(clocks, config), + cpu_pll_div_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3412,7 +3933,7 @@ macro_rules! define_clock_tree_types { fn refresh_syscon_pre_div_in_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.syscon_pre_div_in { SYSCON_PRE_DIV_IN_FREQ_CACHE.store( - syscon_pre_div_in_config_frequency(clocks, config), + syscon_pre_div_in_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3421,7 +3942,7 @@ macro_rules! define_clock_tree_types { fn refresh_syscon_pre_div_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.syscon_pre_div { SYSCON_PRE_DIV_FREQ_CACHE.store( - syscon_pre_div_config_frequency(clocks, config), + syscon_pre_div_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3430,16 +3951,29 @@ macro_rules! define_clock_tree_types { fn refresh_cpu_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.cpu_clk { CPU_CLK_FREQ_CACHE.store( - cpu_clk_config_frequency(clocks, config), + cpu_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } refresh_apb_clk_downstream(clocks); } + fn refresh_rc_slow_clk_downstream(clocks: &mut ClockTree) { + refresh_rtc_slow_clk_downstream(clocks); + refresh_timg_calibration_clock_downstream(clocks); + } fn refresh_rtc_slow_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.rtc_slow_clk { RTC_SLOW_CLK_FREQ_CACHE.store( - rtc_slow_clk_config_frequency(clocks, config), + rtc_slow_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + refresh_ble_lp_clk_downstream(clocks); + } + fn refresh_ble_lp_clk_downstream(clocks: &mut ClockTree) { + if let Some(config) = clocks.ble_lp_clk { + BLE_LP_CLK_FREQ_CACHE.store( + ble_lp_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3447,7 +3981,7 @@ macro_rules! define_clock_tree_types { fn refresh_rtc_fast_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.rtc_fast_clk { RTC_FAST_CLK_FREQ_CACHE.store( - rtc_fast_clk_config_frequency(clocks, config), + rtc_fast_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3455,7 +3989,15 @@ macro_rules! define_clock_tree_types { fn refresh_timg_calibration_clock_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.timg_calibration_clock { TIMG_CALIBRATION_CLOCK_FREQ_CACHE.store( - timg_calibration_clock_config_frequency(clocks, config), + timg_calibration_clock_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + fn refresh_i2s_mclk_downstream(clocks: &mut ClockTree, instance: I2sInstance) { + if let Some(config) = clocks.i2s_mclk[instance as usize] { + I2S_MCLK_FREQ_CACHE[instance as usize].store( + I2sInstance::mclk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3463,7 +4005,7 @@ macro_rules! define_clock_tree_types { fn refresh_apb_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.apb_clk { APB_CLK_FREQ_CACHE.store( - apb_clk_config_frequency(clocks, config), + apb_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3488,7 +4030,7 @@ macro_rules! define_clock_tree_types { fn refresh_ref_tick_xtal_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.ref_tick_xtal { REF_TICK_XTAL_FREQ_CACHE.store( - ref_tick_xtal_config_frequency(clocks, config), + ref_tick_xtal_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3497,7 +4039,7 @@ macro_rules! define_clock_tree_types { fn refresh_ref_tick_fosc_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.ref_tick_fosc { REF_TICK_FOSC_FREQ_CACHE.store( - ref_tick_fosc_config_frequency(clocks, config), + ref_tick_fosc_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3506,7 +4048,7 @@ macro_rules! define_clock_tree_types { fn refresh_ref_tick_apll_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.ref_tick_apll { REF_TICK_APLL_FREQ_CACHE.store( - ref_tick_apll_config_frequency(clocks, config), + ref_tick_apll_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3515,7 +4057,7 @@ macro_rules! define_clock_tree_types { fn refresh_ref_tick_pll_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.ref_tick_pll { REF_TICK_PLL_FREQ_CACHE.store( - ref_tick_pll_config_frequency(clocks, config), + ref_tick_pll_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3525,7 +4067,7 @@ macro_rules! define_clock_tree_types { fn refresh_ref_tick_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.ref_tick { REF_TICK_FREQ_CACHE.store( - ref_tick_config_frequency(clocks, config), + ref_tick_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3543,7 +4085,7 @@ macro_rules! define_clock_tree_types { fn refresh_rmt_sclk_downstream(clocks: &mut ClockTree, instance: RmtInstance) { if let Some(config) = clocks.rmt_sclk[instance as usize] { RMT_SCLK_FREQ_CACHE[instance as usize].store( - RmtInstance::sclk_config_frequency(clocks, config), + RmtInstance::sclk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3551,7 +4093,7 @@ macro_rules! define_clock_tree_types { fn refresh_uart_function_clock_downstream(clocks: &mut ClockTree, instance: UartInstance) { if let Some(config) = clocks.uart_function_clock[instance as usize] { UART_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - UartInstance::function_clock_config_frequency(clocks, config), + UartInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3563,7 +4105,7 @@ macro_rules! define_clock_tree_types { ) { if let Some(config) = clocks.uart_baud_rate_generator[instance as usize] { UART_BAUD_RATE_GENERATOR_FREQ_CACHE[instance as usize].store( - instance.baud_rate_generator_config_frequency(clocks, config), + instance.baud_rate_generator_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4149,6 +4691,76 @@ macro_rules! for_each_spi_slave { (SPI3, Spi3, VSPICLK, VSPID, VSPIQ, VSPICS0))); }; } +/// This macro can be used to generate code for each PCNT unit. +/// +/// For an explanation on the general syntax, as well as usage of individual/repeated +/// matchers, refer to [the crate-level documentation][crate#for_each-macros]. +/// +/// This macro has four options for its "Individual matcher" case: +/// +/// - `names`: `($instance:ident)` +/// - `all`: `($peri:ident, $variant:ident, $sys:ident, $regs:ident, $unit:literal, +/// $interrupt:ident, $sig_ch0:ident, $sig_ch1:ident, $ctrl_ch0:ident, $ctrl_ch1:ident)` +/// - `interrupt`: `($interrupt:ident)` (repeated: one ident per unique IRQ) +/// - `regs`: `($regs:ident)` (repeated: one ident per register block) +/// +/// Macro fragments: +/// +/// - `$peri`: unit singleton name (`PCNT0_UNIT0`, `PCNT1_UNIT0`, …) +/// - `$variant`: `AnyPcntUnit` enum variant (`Pcnt0Unit0`, `Pcnt1Unit0`, …) +/// - `$sys`: `esp_hal::system::Peripheral` variant for clocks +/// - `$regs`: register-block singleton (`PCNT`, `PCNT1`) +/// - `$unit`: hardware unit index within that register block +/// - `$interrupt`: shared peripheral interrupt +/// - `$sig_ch0`, `$sig_ch1`, `$ctrl_ch0`, `$ctrl_ch1`: GPIO matrix input signals +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! for_each_pcnt_unit { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _for_each_inner_pcnt_unit { $(($pattern) => $code;)* ($other : tt) + => {} } _for_each_inner_pcnt_unit!((PCNT0_UNIT0)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT2)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT3)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT4)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT5)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT6)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT7)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT0, Pcnt0Unit0, Pcnt, PCNT, 0, PCNT, + PCNT0_SIG_CH0, PCNT0_SIG_CH1, PCNT0_CTRL_CH0, PCNT0_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT1, Pcnt0Unit1, Pcnt, PCNT, 1, PCNT, + PCNT1_SIG_CH0, PCNT1_SIG_CH1, PCNT1_CTRL_CH0, PCNT1_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT2, Pcnt0Unit2, Pcnt, PCNT, 2, PCNT, + PCNT2_SIG_CH0, PCNT2_SIG_CH1, PCNT2_CTRL_CH0, PCNT2_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT3, Pcnt0Unit3, Pcnt, PCNT, 3, PCNT, + PCNT3_SIG_CH0, PCNT3_SIG_CH1, PCNT3_CTRL_CH0, PCNT3_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT4, Pcnt0Unit4, Pcnt, PCNT, 4, PCNT, + PCNT4_SIG_CH0, PCNT4_SIG_CH1, PCNT4_CTRL_CH0, PCNT4_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT5, Pcnt0Unit5, Pcnt, PCNT, 5, PCNT, + PCNT5_SIG_CH0, PCNT5_SIG_CH1, PCNT5_CTRL_CH0, PCNT5_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT6, Pcnt0Unit6, Pcnt, PCNT, 6, PCNT, + PCNT6_SIG_CH0, PCNT6_SIG_CH1, PCNT6_CTRL_CH0, PCNT6_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT7, Pcnt0Unit7, Pcnt, PCNT, 7, PCNT, + PCNT7_SIG_CH0, PCNT7_SIG_CH1, PCNT7_CTRL_CH0, PCNT7_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT)); _for_each_inner_pcnt_unit!((PCNT)); + _for_each_inner_pcnt_unit!((names(PCNT0_UNIT0), (PCNT0_UNIT1), (PCNT0_UNIT2), + (PCNT0_UNIT3), (PCNT0_UNIT4), (PCNT0_UNIT5), (PCNT0_UNIT6), (PCNT0_UNIT7))); + _for_each_inner_pcnt_unit!((all(PCNT0_UNIT0, Pcnt0Unit0, Pcnt, PCNT, 0, PCNT, + PCNT0_SIG_CH0, PCNT0_SIG_CH1, PCNT0_CTRL_CH0, PCNT0_CTRL_CH1), (PCNT0_UNIT1, + Pcnt0Unit1, Pcnt, PCNT, 1, PCNT, PCNT1_SIG_CH0, PCNT1_SIG_CH1, PCNT1_CTRL_CH0, + PCNT1_CTRL_CH1), (PCNT0_UNIT2, Pcnt0Unit2, Pcnt, PCNT, 2, PCNT, PCNT2_SIG_CH0, + PCNT2_SIG_CH1, PCNT2_CTRL_CH0, PCNT2_CTRL_CH1), (PCNT0_UNIT3, Pcnt0Unit3, Pcnt, + PCNT, 3, PCNT, PCNT3_SIG_CH0, PCNT3_SIG_CH1, PCNT3_CTRL_CH0, PCNT3_CTRL_CH1), + (PCNT0_UNIT4, Pcnt0Unit4, Pcnt, PCNT, 4, PCNT, PCNT4_SIG_CH0, PCNT4_SIG_CH1, + PCNT4_CTRL_CH0, PCNT4_CTRL_CH1), (PCNT0_UNIT5, Pcnt0Unit5, Pcnt, PCNT, 5, PCNT, + PCNT5_SIG_CH0, PCNT5_SIG_CH1, PCNT5_CTRL_CH0, PCNT5_CTRL_CH1), (PCNT0_UNIT6, + Pcnt0Unit6, Pcnt, PCNT, 6, PCNT, PCNT6_SIG_CH0, PCNT6_SIG_CH1, PCNT6_CTRL_CH0, + PCNT6_CTRL_CH1), (PCNT0_UNIT7, Pcnt0Unit7, Pcnt, PCNT, 7, PCNT, PCNT7_SIG_CH0, + PCNT7_SIG_CH1, PCNT7_CTRL_CH0, PCNT7_CTRL_CH1))); + _for_each_inner_pcnt_unit!((interrupt(PCNT))); + _for_each_inner_pcnt_unit!((regs(PCNT))); + }; +} #[macro_export] #[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] macro_rules! for_each_peripheral { @@ -4352,6 +4964,22 @@ macro_rules! for_each_peripheral { disable_dma_interrupt }) (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "DMA_I2S1 peripheral singleton"] DMA_I2S1 <= I2S1(I2S1 : { bind_dma_interrupt, enable_dma_interrupt, disable_dma_interrupt }) (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT0_UNIT0 peripheral singleton"] PCNT0_UNIT0 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT0_UNIT1 peripheral singleton"] PCNT0_UNIT1 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT0_UNIT2 peripheral singleton"] PCNT0_UNIT2 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT0_UNIT3 peripheral singleton"] PCNT0_UNIT3 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT0_UNIT4 peripheral singleton"] PCNT0_UNIT4 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT0_UNIT5 peripheral singleton"] PCNT0_UNIT5 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT0_UNIT6 peripheral singleton"] PCNT0_UNIT6 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT0_UNIT7 peripheral singleton"] PCNT0_UNIT7 <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "SDM_CH0 peripheral singleton"] SDM_CH0 <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "SDM_CH1 peripheral singleton"] SDM_CH1 <= virtual() (unstable))); @@ -4374,11 +5002,12 @@ macro_rules! for_each_peripheral { SYSTEM <= DPORT() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "EFUSE peripheral singleton"] EFUSE <= EFUSE() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "ETH peripheral singleton"] ETH - <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "EMAC_DMA peripheral singleton"] EMAC_DMA <= EMAC_DMA() (unstable))); + <= virtual(ETH_MAC : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt }) (unstable))); _for_each_inner_peripheral!((@ peri_type + #[doc = "EMAC_DMA peripheral singleton"] EMAC_DMA <= GMAC_DMA() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "EMAC_EXT peripheral singleton"] EMAC_EXT <= EMAC_EXT() (unstable))); _for_each_inner_peripheral!((@ peri_type - #[doc = "EMAC_MAC peripheral singleton"] EMAC_MAC <= EMAC_MAC() (unstable))); + #[doc = "EMAC_MAC peripheral singleton"] EMAC_MAC <= GMAC() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "FLASH_ENCRYPTION peripheral singleton"] FLASH_ENCRYPTION <= FLASH_ENCRYPTION() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = @@ -4408,8 +5037,9 @@ macro_rules! for_each_peripheral { MCPWM1 <= MCPWM1() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "NRX peripheral singleton"] NRX <= NRX() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "PCNT peripheral singleton"] - PCNT <= PCNT() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "RMT peripheral singleton"] RMT <= RMT() (unstable))); + PCNT <= PCNT(PCNT : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt }) (unstable))); _for_each_inner_peripheral!((@ peri_type + #[doc = "RMT peripheral singleton"] RMT <= RMT() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "RNG peripheral singleton"] RNG <= RNG() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "RSA peripheral singleton"] RSA <= RSA(RSA : { bind_peri_interrupt, @@ -4471,7 +5101,8 @@ macro_rules! for_each_peripheral { _for_each_inner_peripheral!((@ peri_type #[doc = "PSRAM peripheral singleton"] PSRAM <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "TOUCH peripheral singleton"] TOUCH <= virtual() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = + _for_each_inner_peripheral!((@ peri_type #[doc = "IPC peripheral singleton"] IPC + <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "FROM_CPU_INTR0 peripheral singleton"] FROM_CPU_INTR0 <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "FROM_CPU_INTR1 peripheral singleton"] FROM_CPU_INTR1 <= virtual() (unstable))); @@ -4502,6 +5133,14 @@ macro_rules! for_each_peripheral { _for_each_inner_peripheral!((DMA_SPI3(unstable))); _for_each_inner_peripheral!((DMA_I2S0(unstable))); _for_each_inner_peripheral!((DMA_I2S1(unstable))); + _for_each_inner_peripheral!((PCNT0_UNIT0(unstable))); + _for_each_inner_peripheral!((PCNT0_UNIT1(unstable))); + _for_each_inner_peripheral!((PCNT0_UNIT2(unstable))); + _for_each_inner_peripheral!((PCNT0_UNIT3(unstable))); + _for_each_inner_peripheral!((PCNT0_UNIT4(unstable))); + _for_each_inner_peripheral!((PCNT0_UNIT5(unstable))); + _for_each_inner_peripheral!((PCNT0_UNIT6(unstable))); + _for_each_inner_peripheral!((PCNT0_UNIT7(unstable))); _for_each_inner_peripheral!((SDM_CH0(unstable))); _for_each_inner_peripheral!((SDM_CH1(unstable))); _for_each_inner_peripheral!((SDM_CH2(unstable))); @@ -4562,8 +5201,7 @@ macro_rules! for_each_peripheral { _for_each_inner_peripheral!((FLASH(unstable))); _for_each_inner_peripheral!((PSRAM(unstable))); _for_each_inner_peripheral!((TOUCH(unstable))); - _for_each_inner_peripheral!((FROM_CPU_INTR0(unstable))); - _for_each_inner_peripheral!((FROM_CPU_INTR1(unstable))); + _for_each_inner_peripheral!((IPC(unstable))); _for_each_inner_peripheral!((FROM_CPU_INTR2(unstable))); _for_each_inner_peripheral!((FROM_CPU_INTR3(unstable))); _for_each_inner_peripheral!((SPI2, Spi2, 0, SpiDmaChannel)); @@ -4738,26 +5376,38 @@ macro_rules! for_each_peripheral { bind_dma_interrupt, enable_dma_interrupt, disable_dma_interrupt }) (unstable)), (@ peri_type #[doc = "DMA_I2S1 peripheral singleton"] DMA_I2S1 <= I2S1(I2S1 : { bind_dma_interrupt, enable_dma_interrupt, disable_dma_interrupt }) (unstable)), - (@ peri_type #[doc = "SDM_CH0 peripheral singleton"] SDM_CH0 <= virtual() - (unstable)), (@ peri_type #[doc = "SDM_CH1 peripheral singleton"] SDM_CH1 <= - virtual() (unstable)), (@ peri_type #[doc = "SDM_CH2 peripheral singleton"] - SDM_CH2 <= virtual() (unstable)), (@ peri_type #[doc = - "SDM_CH3 peripheral singleton"] SDM_CH3 <= virtual() (unstable)), (@ peri_type - #[doc = "SDM_CH4 peripheral singleton"] SDM_CH4 <= virtual() (unstable)), (@ - peri_type #[doc = "SDM_CH5 peripheral singleton"] SDM_CH5 <= virtual() - (unstable)), (@ peri_type #[doc = "SDM_CH6 peripheral singleton"] SDM_CH6 <= - virtual() (unstable)), (@ peri_type #[doc = "SDM_CH7 peripheral singleton"] - SDM_CH7 <= virtual() (unstable)), (@ peri_type #[doc = - "AES peripheral singleton"] AES <= AES() (unstable)), (@ peri_type #[doc = - "APB_CTRL peripheral singleton"] APB_CTRL <= APB_CTRL() (unstable)), (@ peri_type - #[doc = "BB peripheral singleton"] BB <= BB() (unstable)), (@ peri_type #[doc = - "DPORT peripheral singleton"] DPORT <= DPORT() (unstable)), (@ peri_type #[doc = - "SYSTEM peripheral singleton"] SYSTEM <= DPORT() (unstable)), (@ peri_type #[doc - = "EFUSE peripheral singleton"] EFUSE <= EFUSE() (unstable)), (@ peri_type #[doc - = "ETH peripheral singleton"] ETH <= virtual() (unstable)), (@ peri_type #[doc = - "EMAC_DMA peripheral singleton"] EMAC_DMA <= EMAC_DMA() (unstable)), (@ peri_type + (@ peri_type #[doc = "PCNT0_UNIT0 peripheral singleton"] PCNT0_UNIT0 <= virtual() + (unstable)), (@ peri_type #[doc = "PCNT0_UNIT1 peripheral singleton"] PCNT0_UNIT1 + <= virtual() (unstable)), (@ peri_type #[doc = + "PCNT0_UNIT2 peripheral singleton"] PCNT0_UNIT2 <= virtual() (unstable)), (@ + peri_type #[doc = "PCNT0_UNIT3 peripheral singleton"] PCNT0_UNIT3 <= virtual() + (unstable)), (@ peri_type #[doc = "PCNT0_UNIT4 peripheral singleton"] PCNT0_UNIT4 + <= virtual() (unstable)), (@ peri_type #[doc = + "PCNT0_UNIT5 peripheral singleton"] PCNT0_UNIT5 <= virtual() (unstable)), (@ + peri_type #[doc = "PCNT0_UNIT6 peripheral singleton"] PCNT0_UNIT6 <= virtual() + (unstable)), (@ peri_type #[doc = "PCNT0_UNIT7 peripheral singleton"] PCNT0_UNIT7 + <= virtual() (unstable)), (@ peri_type #[doc = "SDM_CH0 peripheral singleton"] + SDM_CH0 <= virtual() (unstable)), (@ peri_type #[doc = + "SDM_CH1 peripheral singleton"] SDM_CH1 <= virtual() (unstable)), (@ peri_type + #[doc = "SDM_CH2 peripheral singleton"] SDM_CH2 <= virtual() (unstable)), (@ + peri_type #[doc = "SDM_CH3 peripheral singleton"] SDM_CH3 <= virtual() + (unstable)), (@ peri_type #[doc = "SDM_CH4 peripheral singleton"] SDM_CH4 <= + virtual() (unstable)), (@ peri_type #[doc = "SDM_CH5 peripheral singleton"] + SDM_CH5 <= virtual() (unstable)), (@ peri_type #[doc = + "SDM_CH6 peripheral singleton"] SDM_CH6 <= virtual() (unstable)), (@ peri_type + #[doc = "SDM_CH7 peripheral singleton"] SDM_CH7 <= virtual() (unstable)), (@ + peri_type #[doc = "AES peripheral singleton"] AES <= AES() (unstable)), (@ + peri_type #[doc = "APB_CTRL peripheral singleton"] APB_CTRL <= APB_CTRL() + (unstable)), (@ peri_type #[doc = "BB peripheral singleton"] BB <= BB() + (unstable)), (@ peri_type #[doc = "DPORT peripheral singleton"] DPORT <= DPORT() + (unstable)), (@ peri_type #[doc = "SYSTEM peripheral singleton"] SYSTEM <= + DPORT() (unstable)), (@ peri_type #[doc = "EFUSE peripheral singleton"] EFUSE <= + EFUSE() (unstable)), (@ peri_type #[doc = "ETH peripheral singleton"] ETH <= + virtual(ETH_MAC : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt }) (unstable)), (@ peri_type #[doc = + "EMAC_DMA peripheral singleton"] EMAC_DMA <= GMAC_DMA() (unstable)), (@ peri_type #[doc = "EMAC_EXT peripheral singleton"] EMAC_EXT <= EMAC_EXT() (unstable)), (@ - peri_type #[doc = "EMAC_MAC peripheral singleton"] EMAC_MAC <= EMAC_MAC() + peri_type #[doc = "EMAC_MAC peripheral singleton"] EMAC_MAC <= GMAC() (unstable)), (@ peri_type #[doc = "FLASH_ENCRYPTION peripheral singleton"] FLASH_ENCRYPTION <= FLASH_ENCRYPTION() (unstable)), (@ peri_type #[doc = "FRC_TIMER peripheral singleton"] FRC_TIMER <= FRC_TIMER() (unstable)), (@ @@ -4780,7 +5430,8 @@ macro_rules! for_each_peripheral { (unstable)), (@ peri_type #[doc = "MCPWM1 peripheral singleton"] MCPWM1 <= MCPWM1() (unstable)), (@ peri_type #[doc = "NRX peripheral singleton"] NRX <= NRX() (unstable)), (@ peri_type #[doc = "PCNT peripheral singleton"] PCNT <= - PCNT() (unstable)), (@ peri_type #[doc = "RMT peripheral singleton"] RMT <= RMT() + PCNT(PCNT : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt + }) (unstable)), (@ peri_type #[doc = "RMT peripheral singleton"] RMT <= RMT() (unstable)), (@ peri_type #[doc = "RNG peripheral singleton"] RNG <= RNG() (unstable)), (@ peri_type #[doc = "RSA peripheral singleton"] RSA <= RSA(RSA : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) @@ -4827,6 +5478,7 @@ macro_rules! for_each_peripheral { peri_type #[doc = "FLASH peripheral singleton"] FLASH <= virtual() (unstable)), (@ peri_type #[doc = "PSRAM peripheral singleton"] PSRAM <= virtual() (unstable)), (@ peri_type #[doc = "TOUCH peripheral singleton"] TOUCH <= + virtual() (unstable)), (@ peri_type #[doc = "IPC peripheral singleton"] IPC <= virtual() (unstable)), (@ peri_type #[doc = "FROM_CPU_INTR0 peripheral singleton"] FROM_CPU_INTR0 <= virtual() (unstable)), (@ peri_type #[doc = "FROM_CPU_INTR1 peripheral singleton"] FROM_CPU_INTR1 <= @@ -4840,10 +5492,13 @@ macro_rules! for_each_peripheral { (#[cfg(not(use_xtal32k))] GPIO32), (#[cfg(not(use_xtal32k))] GPIO33), (GPIO34), (GPIO35), (GPIO36), (GPIO37), (GPIO38), (GPIO39), (DMA_SPI2(unstable)), (DMA_SPI3(unstable)), (DMA_I2S0(unstable)), (DMA_I2S1(unstable)), - (SDM_CH0(unstable)), (SDM_CH1(unstable)), (SDM_CH2(unstable)), - (SDM_CH3(unstable)), (SDM_CH4(unstable)), (SDM_CH5(unstable)), - (SDM_CH6(unstable)), (SDM_CH7(unstable)), (AES(unstable)), (APB_CTRL(unstable)), - (BB(unstable)), (DPORT(unstable)), (SYSTEM(unstable)), (ETH(unstable)), + (PCNT0_UNIT0(unstable)), (PCNT0_UNIT1(unstable)), (PCNT0_UNIT2(unstable)), + (PCNT0_UNIT3(unstable)), (PCNT0_UNIT4(unstable)), (PCNT0_UNIT5(unstable)), + (PCNT0_UNIT6(unstable)), (PCNT0_UNIT7(unstable)), (SDM_CH0(unstable)), + (SDM_CH1(unstable)), (SDM_CH2(unstable)), (SDM_CH3(unstable)), + (SDM_CH4(unstable)), (SDM_CH5(unstable)), (SDM_CH6(unstable)), + (SDM_CH7(unstable)), (AES(unstable)), (APB_CTRL(unstable)), (BB(unstable)), + (DPORT(unstable)), (SYSTEM(unstable)), (ETH(unstable)), (FLASH_ENCRYPTION(unstable)), (FRC_TIMER(unstable)), (GPIO(unstable)), (GPIO_SD(unstable)), (HINF(unstable)), (I2C0), (I2C1), (I2S0(unstable)), (I2S1(unstable)), (IO_MUX(unstable)), (LEDC(unstable)), (MCPWM0(unstable)), @@ -4855,11 +5510,11 @@ macro_rules! for_each_peripheral { (TWAI0(unstable)), (UART0), (UART1), (UART2), (UHCI0(unstable)), (UHCI1(unstable)), (WIFI), (ADC1(unstable)), (ADC2(unstable)), (BT(unstable)), (CPU_CTRL(unstable)), (DAC1(unstable)), (DAC2(unstable)), (FLASH(unstable)), - (PSRAM(unstable)), (TOUCH(unstable)), (FROM_CPU_INTR0(unstable)), - (FROM_CPU_INTR1(unstable)), (FROM_CPU_INTR2(unstable)), - (FROM_CPU_INTR3(unstable)))); _for_each_inner_peripheral!((dma_eligible(SPI2, - Spi2, 0, SpiDmaChannel), (I2S0, I2s0, 0, I2sDmaChannel), (SPI3, Spi3, 1, - SpiDmaChannel), (I2S1, I2s1, 1, I2sDmaChannel))); + (PSRAM(unstable)), (TOUCH(unstable)), (IPC(unstable)), + (FROM_CPU_INTR2(unstable)), (FROM_CPU_INTR3(unstable)))); + _for_each_inner_peripheral!((dma_eligible(SPI2, Spi2, 0, SpiDmaChannel), (I2S0, + I2s0, 0, I2sDmaChannel), (SPI3, Spi3, 1, SpiDmaChannel), (I2S1, I2s1, 1, + I2sDmaChannel))); }; } /// This macro can be used to generate code for each `GPIOn` instance. diff --git a/esp-metadata-generated/src/_generated_esp32c2.rs b/esp-metadata-generated/src/_generated_esp32c2.rs index cbef53dce7e..412e7e45077 100644 --- a/esp-metadata-generated/src/_generated_esp32c2.rs +++ b/esp-metadata-generated/src/_generated_esp32c2.rs @@ -88,6 +88,9 @@ macro_rules! property { ("gpio.func_in_sel_offset", str) => { stringify!(0) }; + ("gpio.need_soft_isolate_during_pd") => { + false + }; ("gpio.has_bank_1") => { false }; @@ -247,9 +250,48 @@ macro_rules! property { ("wifi.csi_supported") => { false }; + ("wifi.has_nan") => { + false + }; + ("wifi.has_ftm") => { + true + }; ("phy.combo_module") => { true }; + ("adc.controller") => { + "digital" + }; + ("adc.channel_count") => { + 5 + }; + ("adc.channel_count", str) => { + stringify!(5) + }; + ("adc.line_calibration") => { + true + }; + ("adc.curve_calibration") => { + false + }; + ("adc.basic_calibration") => { + true + }; + ("adc.calibration_v1_scheme_supported") => { + true + }; + ("adc.channel_compensation") => { + false + }; + ("adc.pcr_clock") => { + false + }; + ("adc.pcr_sar_clk_div") => { + false + }; + ("adc.sar_power_override") => { + false + }; ("ledc.version") => { 2 }; @@ -268,6 +310,9 @@ macro_rules! property { ("timergroup.timg_has_divcnt_rst") => { true }; + ("timergroup.wdt_has_conf_update") => { + true + }; ("ecc.zero_extend_writes") => { true }; @@ -373,6 +418,9 @@ macro_rules! property { ("soc.cpu_has_csr_pc") => { true }; + ("soc.cpu_has_zcmp_workaround") => { + false + }; ("soc.multi_core_enabled") => { false }; @@ -388,6 +436,12 @@ macro_rules! property { ("soc.cpu_mcause_mask", str) => { stringify!(31) }; + ("soc.cpu_pmp_granularity") => { + 4 + }; + ("soc.cpu_pmp_granularity", str) => { + stringify!(4) + }; ("clock_tree.system_pre_div_in") => { [crate ::soc::clocks::SystemPreDivInConfig::Xtal, crate ::soc::clocks::SystemPreDivInConfig::RcFast] @@ -422,6 +476,13 @@ macro_rules! property { ::soc::clocks::RtcSlowClkConfig::RcSlow, crate ::soc::clocks::RtcSlowClkConfig::RcFast] }; + ("clock_tree.ble_lp_clk.sclk") => { + [crate ::soc::clocks::BleLpClkSclk::Xtal, crate + ::soc::clocks::BleLpClkSclk::RcSlow] + }; + ("clock_tree.ble_lp_clk.divisor") => { + (0, 255) + }; ("clock_tree.rtc_fast_clk") => { [crate ::soc::clocks::RtcFastClkConfig::Xtal, crate ::soc::clocks::RtcFastClkConfig::Rc] @@ -647,21 +708,21 @@ macro_rules! for_each_interrupt { macro_rules! _for_each_inner_interrupt { $(($pattern) => $code;)* ($other : tt) => {} } _for_each_inner_interrupt!(([disabled 0] 0)); _for_each_inner_interrupt!(([reserved 0] 1)); - _for_each_inner_interrupt!(([direct_bindable 0] 2)); - _for_each_inner_interrupt!(([direct_bindable 1] 3)); - _for_each_inner_interrupt!(([direct_bindable 2] 4)); - _for_each_inner_interrupt!(([direct_bindable 3] 5)); - _for_each_inner_interrupt!(([direct_bindable 4] 6)); - _for_each_inner_interrupt!(([direct_bindable 5] 7)); - _for_each_inner_interrupt!(([direct_bindable 6] 8)); - _for_each_inner_interrupt!(([direct_bindable 7] 9)); - _for_each_inner_interrupt!(([direct_bindable 8] 10)); - _for_each_inner_interrupt!(([direct_bindable 9] 11)); - _for_each_inner_interrupt!(([direct_bindable 10] 12)); - _for_each_inner_interrupt!(([direct_bindable 11] 13)); - _for_each_inner_interrupt!(([direct_bindable 12] 14)); - _for_each_inner_interrupt!(([direct_bindable 13] 15)); - _for_each_inner_interrupt!(([direct_bindable 14] 16)); + _for_each_inner_interrupt!(([context_switch 0] 2)); + _for_each_inner_interrupt!(([direct_bindable 0] 3)); + _for_each_inner_interrupt!(([direct_bindable 1] 4)); + _for_each_inner_interrupt!(([direct_bindable 2] 5)); + _for_each_inner_interrupt!(([direct_bindable 3] 6)); + _for_each_inner_interrupt!(([direct_bindable 4] 7)); + _for_each_inner_interrupt!(([direct_bindable 5] 8)); + _for_each_inner_interrupt!(([direct_bindable 6] 9)); + _for_each_inner_interrupt!(([direct_bindable 7] 10)); + _for_each_inner_interrupt!(([direct_bindable 8] 11)); + _for_each_inner_interrupt!(([direct_bindable 9] 12)); + _for_each_inner_interrupt!(([direct_bindable 10] 13)); + _for_each_inner_interrupt!(([direct_bindable 11] 14)); + _for_each_inner_interrupt!(([direct_bindable 12] 15)); + _for_each_inner_interrupt!(([direct_bindable 13] 16)); _for_each_inner_interrupt!(([vector 0] 17)); _for_each_inner_interrupt!(([vector 1] 18)); _for_each_inner_interrupt!(([vector 2] 19)); _for_each_inner_interrupt!(([vector 3] 20)); _for_each_inner_interrupt!(([vector @@ -673,11 +734,11 @@ macro_rules! for_each_interrupt { _for_each_inner_interrupt!(([vector 12] 29)); _for_each_inner_interrupt!(([vector 13] 30)); _for_each_inner_interrupt!(([vector 14] 31)); _for_each_inner_interrupt!((all([disabled 0] 0), ([reserved 0] 1), - ([direct_bindable 0] 2), ([direct_bindable 1] 3), ([direct_bindable 2] 4), - ([direct_bindable 3] 5), ([direct_bindable 4] 6), ([direct_bindable 5] 7), - ([direct_bindable 6] 8), ([direct_bindable 7] 9), ([direct_bindable 8] 10), - ([direct_bindable 9] 11), ([direct_bindable 10] 12), ([direct_bindable 11] 13), - ([direct_bindable 12] 14), ([direct_bindable 13] 15), ([direct_bindable 14] 16), + ([context_switch 0] 2), ([direct_bindable 0] 3), ([direct_bindable 1] 4), + ([direct_bindable 2] 5), ([direct_bindable 3] 6), ([direct_bindable 4] 7), + ([direct_bindable 5] 8), ([direct_bindable 6] 9), ([direct_bindable 7] 10), + ([direct_bindable 8] 11), ([direct_bindable 9] 12), ([direct_bindable 10] 13), + ([direct_bindable 11] 14), ([direct_bindable 12] 15), ([direct_bindable 13] 16), ([vector 0] 17), ([vector 1] 18), ([vector 2] 19), ([vector 3] 20), ([vector 4] 21), ([vector 5] 22), ([vector 6] 23), ([vector 7] 24), ([vector 8] 25), ([vector 9] 26), ([vector 10] 27), ([vector 11] 28), ([vector 12] 29), ([vector 13] 30), @@ -690,20 +751,19 @@ macro_rules! for_each_classified_interrupt { ($($pattern:tt => $code:tt;)*) => { macro_rules! _for_each_inner_classified_interrupt { $(($pattern) => $code;)* ($other : tt) => {} } _for_each_inner_classified_interrupt!(([direct_bindable 0] - 2)); _for_each_inner_classified_interrupt!(([direct_bindable 1] 3)); - _for_each_inner_classified_interrupt!(([direct_bindable 2] 4)); - _for_each_inner_classified_interrupt!(([direct_bindable 3] 5)); - _for_each_inner_classified_interrupt!(([direct_bindable 4] 6)); - _for_each_inner_classified_interrupt!(([direct_bindable 5] 7)); - _for_each_inner_classified_interrupt!(([direct_bindable 6] 8)); - _for_each_inner_classified_interrupt!(([direct_bindable 7] 9)); - _for_each_inner_classified_interrupt!(([direct_bindable 8] 10)); - _for_each_inner_classified_interrupt!(([direct_bindable 9] 11)); - _for_each_inner_classified_interrupt!(([direct_bindable 10] 12)); - _for_each_inner_classified_interrupt!(([direct_bindable 11] 13)); - _for_each_inner_classified_interrupt!(([direct_bindable 12] 14)); - _for_each_inner_classified_interrupt!(([direct_bindable 13] 15)); - _for_each_inner_classified_interrupt!(([direct_bindable 14] 16)); + 3)); _for_each_inner_classified_interrupt!(([direct_bindable 1] 4)); + _for_each_inner_classified_interrupt!(([direct_bindable 2] 5)); + _for_each_inner_classified_interrupt!(([direct_bindable 3] 6)); + _for_each_inner_classified_interrupt!(([direct_bindable 4] 7)); + _for_each_inner_classified_interrupt!(([direct_bindable 5] 8)); + _for_each_inner_classified_interrupt!(([direct_bindable 6] 9)); + _for_each_inner_classified_interrupt!(([direct_bindable 7] 10)); + _for_each_inner_classified_interrupt!(([direct_bindable 8] 11)); + _for_each_inner_classified_interrupt!(([direct_bindable 9] 12)); + _for_each_inner_classified_interrupt!(([direct_bindable 10] 13)); + _for_each_inner_classified_interrupt!(([direct_bindable 11] 14)); + _for_each_inner_classified_interrupt!(([direct_bindable 12] 15)); + _for_each_inner_classified_interrupt!(([direct_bindable 13] 16)); _for_each_inner_classified_interrupt!(([vector 0] 17)); _for_each_inner_classified_interrupt!(([vector 1] 18)); _for_each_inner_classified_interrupt!(([vector 2] 19)); @@ -720,17 +780,19 @@ macro_rules! for_each_classified_interrupt { _for_each_inner_classified_interrupt!(([vector 13] 30)); _for_each_inner_classified_interrupt!(([vector 14] 31)); _for_each_inner_classified_interrupt!(([reserved 0] 1)); - _for_each_inner_classified_interrupt!((direct_bindable([direct_bindable 0] 2), - ([direct_bindable 1] 3), ([direct_bindable 2] 4), ([direct_bindable 3] 5), - ([direct_bindable 4] 6), ([direct_bindable 5] 7), ([direct_bindable 6] 8), - ([direct_bindable 7] 9), ([direct_bindable 8] 10), ([direct_bindable 9] 11), - ([direct_bindable 10] 12), ([direct_bindable 11] 13), ([direct_bindable 12] 14), - ([direct_bindable 13] 15), ([direct_bindable 14] 16))); + _for_each_inner_classified_interrupt!(([context_switch 0] 2)); + _for_each_inner_classified_interrupt!((direct_bindable([direct_bindable 0] 3), + ([direct_bindable 1] 4), ([direct_bindable 2] 5), ([direct_bindable 3] 6), + ([direct_bindable 4] 7), ([direct_bindable 5] 8), ([direct_bindable 6] 9), + ([direct_bindable 7] 10), ([direct_bindable 8] 11), ([direct_bindable 9] 12), + ([direct_bindable 10] 13), ([direct_bindable 11] 14), ([direct_bindable 12] 15), + ([direct_bindable 13] 16))); _for_each_inner_classified_interrupt!((vector([vector 0] 17), ([vector 1] 18), ([vector 2] 19), ([vector 3] 20), ([vector 4] 21), ([vector 5] 22), ([vector 6] 23), ([vector 7] 24), ([vector 8] 25), ([vector 9] 26), ([vector 10] 27), ([vector 11] 28), ([vector 12] 29), ([vector 13] 30), ([vector 14] 31))); _for_each_inner_classified_interrupt!((reserved([reserved 0] 1))); + _for_each_inner_classified_interrupt!((context_switch([context_switch 0] 2))); }; } #[macro_export] @@ -970,6 +1032,32 @@ macro_rules! for_each_sw_interrupt { /// todo!() /// } /// +/// // BLE_LP_XTAL_CLK +/// +/// fn enable_ble_lp_xtal_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// // BLE_LP_RC_SLOW_CLK +/// +/// fn enable_ble_lp_rc_slow_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// // BLE_LP_CLK +/// +/// fn enable_ble_lp_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_ble_lp_clk_impl( +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: BleLpClkConfig, +/// ) { +/// todo!() +/// } +/// /// // RTC_FAST_CLK /// /// fn enable_rtc_fast_clk_impl(_clocks: &mut ClockTree, _en: bool) { @@ -1018,6 +1106,13 @@ macro_rules! for_each_sw_interrupt { /// todo!() /// } /// +/// impl AdcInstance { +/// // ADC_FUNCTION_CLOCK +/// +/// fn enable_function_clock_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// } /// impl I2cInstance { /// // I2C_FUNCTION_CLOCK /// @@ -1121,6 +1216,11 @@ macro_rules! for_each_sw_interrupt { /// ``` macro_rules! define_clock_tree_types { () => { + #[derive(Clone, Copy, PartialEq, Eq, Debug)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum AdcInstance { + ApbSaradc = 0, + } #[derive(Clone, Copy, PartialEq, Eq, Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum I2cInstance { @@ -1190,7 +1290,7 @@ macro_rules! define_clock_tree_types { ); Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -1225,7 +1325,7 @@ macro_rules! define_clock_tree_types { pub const fn new(divisor: CpuPllDivDivisor) -> Self { Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -1289,7 +1389,7 @@ macro_rules! define_clock_tree_types { ); Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -1304,6 +1404,45 @@ macro_rules! define_clock_tree_types { /// Selects `RC_FAST_DIV_CLK`. RcFast, } + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum BleLpClkSclk { + #[default] + /// Selects `BLE_LP_XTAL_CLK`. + Xtal, + /// Selects `BLE_LP_RC_SLOW_CLK`. + RcSlow, + } + /// Configures the `BLE_LP_CLK` clock node. + /// + /// The output is calculated as `OUTPUT = sclk / (divisor + 1)`. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub struct BleLpClkConfig { + sclk: BleLpClkSclk, + divisor: u32, + } + impl BleLpClkConfig { + /// Creates a new configuration for the BLE_LP_CLK clock node. + /// + /// ## Panics + /// + /// Panics if the divisor value is outside the + /// valid range (0 ..= 255). + pub const fn new(sclk: BleLpClkSclk, divisor: u32) -> Self { + ::core::assert!( + divisor <= 255, + "`BLE_LP_CLK` divisor must be between 0 and 255 (inclusive)." + ); + Self { sclk, divisor } + } + pub fn sclk(self) -> BleLpClkSclk { + self.sclk + } + pub fn divisor(self) -> u32 { + self.divisor as u32 + } + } /// The list of clock signals that the `RTC_FAST_CLK` multiplexer can output. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] @@ -1377,10 +1516,10 @@ macro_rules! define_clock_tree_types { ); Self { sclk, div_num } } - pub(crate) fn sclk(self) -> I2cFunctionClockSclk { + pub fn sclk(self) -> I2cFunctionClockSclk { self.sclk } - pub(crate) fn div_num(self) -> u32 { + pub fn div_num(self) -> u32 { self.div_num as u32 } } @@ -1388,9 +1527,9 @@ macro_rules! define_clock_tree_types { #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum SpiFunctionClockConfig { - #[default] /// Selects `XTAL_CLK`. Xtal, + #[default] /// Selects `PLL_40M`. Pll40m, } @@ -1448,10 +1587,10 @@ macro_rules! define_clock_tree_types { ); Self { sclk, div_num } } - pub(crate) fn sclk(self) -> UartFunctionClockSclk { + pub fn sclk(self) -> UartFunctionClockSclk { self.sclk } - pub(crate) fn div_num(self) -> u32 { + pub fn div_num(self) -> u32 { self.div_num as u32 } } @@ -1489,10 +1628,10 @@ macro_rules! define_clock_tree_types { integral, } } - pub(crate) fn fractional(self) -> u32 { + pub fn fractional(self) -> u32 { self.fractional as u32 } - pub(crate) fn integral(self) -> u32 { + pub fn integral(self) -> u32 { self.integral as u32 } } @@ -1508,6 +1647,7 @@ macro_rules! define_clock_tree_types { cpu_clk: Option, rc_fast_clk_div_n: Option, rtc_slow_clk: Option, + ble_lp_clk: Option, rtc_fast_clk: Option, low_power_clk: Option, timg_calibration_clock: Option, @@ -1521,15 +1661,16 @@ macro_rules! define_clock_tree_types { osc_slow_clk_refcount: u32, rc_slow_clk_refcount: u32, rc_fast_div_clk_refcount: u32, - apb_clk_refcount: u32, crypto_clk_refcount: u32, mspi_clk_refcount: u32, pll_40m_refcount: u32, pll_60m_refcount: u32, + ble_lp_clk_refcount: u32, rtc_fast_clk_refcount: u32, low_power_clk_refcount: u32, uart_mem_clk_refcount: u32, timg_calibration_clock_refcount: u32, + adc_function_clock_refcount: [u32; 1], i2c_function_clock_refcount: [u32; 1], spi_function_clock_refcount: [u32; 1], timg_function_clock_refcount: [u32; 1], @@ -1583,6 +1724,10 @@ macro_rules! define_clock_tree_types { pub fn rtc_slow_clk(&self) -> Option { self.rtc_slow_clk } + /// Returns the current configuration of the BLE_LP_CLK clock tree node + pub fn ble_lp_clk(&self) -> Option { + self.ble_lp_clk + } /// Returns the current configuration of the RTC_FAST_CLK clock tree node pub fn rtc_fast_clk(&self) -> Option { self.rtc_fast_clk @@ -1640,6 +1785,7 @@ macro_rules! define_clock_tree_types { cpu_clk: None, rc_fast_clk_div_n: None, rtc_slow_clk: None, + ble_lp_clk: None, rtc_fast_clk: None, low_power_clk: None, timg_calibration_clock: None, @@ -1653,15 +1799,16 @@ macro_rules! define_clock_tree_types { osc_slow_clk_refcount: 0, rc_slow_clk_refcount: 0, rc_fast_div_clk_refcount: 0, - apb_clk_refcount: 0, crypto_clk_refcount: 0, mspi_clk_refcount: 0, pll_40m_refcount: 0, pll_60m_refcount: 0, + ble_lp_clk_refcount: 0, rtc_fast_clk_refcount: 0, low_power_clk_refcount: 0, uart_mem_clk_refcount: 0, timg_calibration_clock_refcount: 0, + adc_function_clock_refcount: [0; 1], i2c_function_clock_refcount: [0; 1], spi_function_clock_refcount: [0; 1], timg_function_clock_refcount: [0; 1], @@ -1684,6 +1831,8 @@ macro_rules! define_clock_tree_types { ::core::sync::atomic::AtomicU32::new(0); static RTC_SLOW_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); + static BLE_LP_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(0); static RTC_FAST_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); static LOW_POWER_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = @@ -1708,6 +1857,175 @@ macro_rules! define_clock_tree_types { ::core::sync::atomic::AtomicU32::new(0); static MSPI_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); + /// The clock sources of the device. + /// + /// A clock source is a node of the clock tree that other nodes derive their output + /// from. Ask a node which source it runs on with its `..._root_source` function. + #[derive(Debug, enumset::EnumSetType)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum ClockSource { + /// `XTAL_CLK`. + XtalClk, + /// `RC_FAST_CLK`. + RcFastClk, + /// `OSC_SLOW_CLK`. + OscSlowClk, + /// `RC_SLOW_CLK`. + RcSlowClk, + } + /// Returns the clock source that `XTAL_CLK` currently runs on. + pub fn xtal_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::XtalClk) + } + /// Returns the clock source that `PLL_CLK` currently runs on. + pub fn pll_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `RC_FAST_CLK` currently runs on. + pub fn rc_fast_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::RcFastClk) + } + /// Returns the clock source that `OSC_SLOW_CLK` currently runs on. + pub fn osc_slow_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::OscSlowClk) + } + /// Returns the clock source that `RC_SLOW_CLK` currently runs on. + pub fn rc_slow_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::RcSlowClk) + } + /// Returns the clock source that `RC_FAST_DIV_CLK` currently runs on. + pub fn rc_fast_div_clk_root_source(clocks: &mut ClockTree) -> Option { + rc_fast_clk_root_source(clocks) + } + /// Returns the clock source that `SYSTEM_PRE_DIV_IN` currently runs on. + pub fn system_pre_div_in_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.system_pre_div_in?; + match config { + SystemPreDivInConfig::Xtal => xtal_clk_root_source(clocks), + SystemPreDivInConfig::RcFast => rc_fast_clk_root_source(clocks), + } + } + /// Returns the clock source that `SYSTEM_PRE_DIV` currently runs on. + pub fn system_pre_div_root_source(clocks: &mut ClockTree) -> Option { + system_pre_div_in_root_source(clocks) + } + /// Returns the clock source that `CPU_PLL_DIV` currently runs on. + pub fn cpu_pll_div_root_source(clocks: &mut ClockTree) -> Option { + pll_clk_root_source(clocks) + } + /// Returns the clock source that `CPU_CLK` currently runs on. + pub fn cpu_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.cpu_clk?; + match config { + CpuClkConfig::Xtal => system_pre_div_root_source(clocks), + CpuClkConfig::RcFast => system_pre_div_root_source(clocks), + CpuClkConfig::Pll => cpu_pll_div_root_source(clocks), + } + } + /// Returns the clock source that `PLL_40M` currently runs on. + pub fn pll_40m_root_source(clocks: &mut ClockTree) -> Option { + cpu_clk_root_source(clocks) + } + /// Returns the clock source that `PLL_60M` currently runs on. + pub fn pll_60m_root_source(clocks: &mut ClockTree) -> Option { + cpu_clk_root_source(clocks) + } + /// Returns the clock source that `PLL_80M` currently runs on. + pub fn pll_80m_root_source(clocks: &mut ClockTree) -> Option { + cpu_clk_root_source(clocks) + } + /// Returns the clock source that `CPU_DIV2` currently runs on. + pub fn cpu_div2_root_source(clocks: &mut ClockTree) -> Option { + cpu_clk_root_source(clocks) + } + /// Returns the clock source that `RC_FAST_CLK_DIV_N` currently runs on. + pub fn rc_fast_clk_div_n_root_source(clocks: &mut ClockTree) -> Option { + rc_fast_clk_root_source(clocks) + } + /// Returns the clock source that `XTAL_DIV_CLK` currently runs on. + pub fn xtal_div_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `RTC_SLOW_CLK` currently runs on. + pub fn rtc_slow_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.rtc_slow_clk?; + match config { + RtcSlowClkConfig::OscSlow => osc_slow_clk_root_source(clocks), + RtcSlowClkConfig::RcSlow => rc_slow_clk_root_source(clocks), + RtcSlowClkConfig::RcFast => rc_fast_div_clk_root_source(clocks), + } + } + /// Returns the clock source that `BLE_LP_XTAL_CLK` currently runs on. + pub fn ble_lp_xtal_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `BLE_LP_RC_SLOW_CLK` currently runs on. + pub fn ble_lp_rc_slow_clk_root_source(clocks: &mut ClockTree) -> Option { + rc_slow_clk_root_source(clocks) + } + /// Returns the clock source that `BLE_LP_CLK` currently runs on. + pub fn ble_lp_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.ble_lp_clk?; + match config.sclk() { + BleLpClkSclk::Xtal => ble_lp_xtal_clk_root_source(clocks), + BleLpClkSclk::RcSlow => ble_lp_rc_slow_clk_root_source(clocks), + } + } + /// Returns the clock source that `RTC_FAST_CLK` currently runs on. + pub fn rtc_fast_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.rtc_fast_clk?; + match config { + RtcFastClkConfig::Xtal => xtal_div_clk_root_source(clocks), + RtcFastClkConfig::Rc => rc_fast_clk_div_n_root_source(clocks), + } + } + /// Returns the clock source that `LOW_POWER_CLK` currently runs on. + pub fn low_power_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.low_power_clk?; + match config { + LowPowerClkConfig::Xtal => xtal_clk_root_source(clocks), + LowPowerClkConfig::RcFast => rc_fast_clk_root_source(clocks), + LowPowerClkConfig::OscSlow => osc_slow_clk_root_source(clocks), + LowPowerClkConfig::RtcSlow => rtc_slow_clk_root_source(clocks), + } + } + /// Returns the clock source that `UART_MEM_CLK` currently runs on. + pub fn uart_mem_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `TIMG_CALIBRATION_CLOCK` currently runs on. + pub fn timg_calibration_clock_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.timg_calibration_clock?; + match config { + TimgCalibrationClockConfig::RcSlowClk => rc_slow_clk_root_source(clocks), + TimgCalibrationClockConfig::RcFastDivClk => rc_fast_div_clk_root_source(clocks), + TimgCalibrationClockConfig::Osc32kClk => osc_slow_clk_root_source(clocks), + } + } + /// Returns the clock source that `APB_CLK` currently runs on. + pub fn apb_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.apb_clk?; + match config { + ApbClkConfig::Pll40m => pll_40m_root_source(clocks), + ApbClkConfig::Cpu => cpu_clk_root_source(clocks), + } + } + /// Returns the clock source that `CRYPTO_CLK` currently runs on. + pub fn crypto_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.crypto_clk?; + match config { + CryptoClkConfig::Pll80m => pll_80m_root_source(clocks), + CryptoClkConfig::Cpu => cpu_clk_root_source(clocks), + } + } + /// Returns the clock source that `MSPI_CLK` currently runs on. + pub fn mspi_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.mspi_clk?; + match config { + MspiClkConfig::CpuDiv2 => cpu_div2_root_source(clocks), + MspiClkConfig::Cpu => cpu_clk_root_source(clocks), + } + } pub fn configure_xtal_clk(clocks: &mut ClockTree, config: XtalClkConfig) { let old_config = clocks.xtal_clk.replace(config); refresh_xtal_clk_downstream(clocks); @@ -1718,21 +2036,18 @@ macro_rules! define_clock_tree_types { } fn request_xtal_clk(_clocks: &mut ClockTree) {} fn release_xtal_clk(_clocks: &mut ClockTree) {} - #[allow(unused_variables)] - pub fn xtal_clk_config_frequency(clocks: &mut ClockTree, config: XtalClkConfig) -> u32 { + pub fn xtal_clk_config_frequency(config: XtalClkConfig) -> u32 { config.value() } pub fn xtal_clk_frequency() -> u32 { XTAL_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn request_pll_clk(clocks: &mut ClockTree) { - trace!("Requesting PLL_CLK"); trace!("Enabling PLL_CLK"); request_xtal_clk(clocks); enable_pll_clk_impl(clocks, true); } pub fn release_pll_clk(clocks: &mut ClockTree) { - trace!("Releasing PLL_CLK"); trace!("Disabling PLL_CLK"); enable_pll_clk_impl(clocks, false); release_xtal_clk(clocks); @@ -1757,9 +2072,30 @@ macro_rules! define_clock_tree_types { enable_rc_fast_clk_impl(clocks, false); } } - pub fn rc_fast_clk_frequency() -> u32 { + static RC_FAST_CLK_FREQUENCY: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(rc_fast_clk_nominal_frequency()); + pub const fn rc_fast_clk_nominal_frequency() -> u32 { 17500000 } + pub fn rc_fast_clk_frequency() -> u32 { + RC_FAST_CLK_FREQUENCY.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn set_rc_fast_clk_frequency(clocks: &mut ClockTree, frequency: u32) { + if !(8750000..=26250000).contains(&frequency) { + warn!( + "Ignoring out-of-range RC_FAST_CLK frequency: {} Hz", + frequency + ); + return; + } + debug!( + "Updating RC_FAST_CLK frequency to {} Hz (nominal {} Hz)", + frequency, + rc_fast_clk_nominal_frequency() + ); + RC_FAST_CLK_FREQUENCY.store(frequency, ::core::sync::atomic::Ordering::Release); + refresh_rc_fast_clk_downstream(clocks); + } pub fn request_osc_slow_clk(clocks: &mut ClockTree) { trace!("Requesting OSC_SLOW_CLK"); if increment_reference_count(&mut clocks.osc_slow_clk_refcount) { @@ -1791,9 +2127,30 @@ macro_rules! define_clock_tree_types { enable_rc_slow_clk_impl(clocks, false); } } - pub fn rc_slow_clk_frequency() -> u32 { + static RC_SLOW_CLK_FREQUENCY: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(rc_slow_clk_nominal_frequency()); + pub const fn rc_slow_clk_nominal_frequency() -> u32 { 136000 } + pub fn rc_slow_clk_frequency() -> u32 { + RC_SLOW_CLK_FREQUENCY.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn set_rc_slow_clk_frequency(clocks: &mut ClockTree, frequency: u32) { + if !(68000..=204000).contains(&frequency) { + warn!( + "Ignoring out-of-range RC_SLOW_CLK frequency: {} Hz", + frequency + ); + return; + } + debug!( + "Updating RC_SLOW_CLK frequency to {} Hz (nominal {} Hz)", + frequency, + rc_slow_clk_nominal_frequency() + ); + RC_SLOW_CLK_FREQUENCY.store(frequency, ::core::sync::atomic::Ordering::Release); + refresh_rc_slow_clk_downstream(clocks); + } pub fn request_rc_fast_div_clk(clocks: &mut ClockTree) { trace!("Requesting RC_FAST_DIV_CLK"); if increment_reference_count(&mut clocks.rc_fast_div_clk_refcount) { @@ -1838,7 +2195,6 @@ macro_rules! define_clock_tree_types { clocks.system_pre_div_in } pub fn request_system_pre_div_in(clocks: &mut ClockTree) { - trace!("Requesting SYSTEM_PRE_DIV_IN"); trace!("Enabling SYSTEM_PRE_DIV_IN"); match unwrap!(clocks.system_pre_div_in) { SystemPreDivInConfig::Xtal => request_xtal_clk(clocks), @@ -1847,7 +2203,6 @@ macro_rules! define_clock_tree_types { enable_system_pre_div_in_impl(clocks, true); } pub fn release_system_pre_div_in(clocks: &mut ClockTree) { - trace!("Releasing SYSTEM_PRE_DIV_IN"); trace!("Disabling SYSTEM_PRE_DIV_IN"); enable_system_pre_div_in_impl(clocks, false); match unwrap!(clocks.system_pre_div_in) { @@ -1855,11 +2210,7 @@ macro_rules! define_clock_tree_types { SystemPreDivInConfig::RcFast => release_rc_fast_clk(clocks), } } - #[allow(unused_variables)] - pub fn system_pre_div_in_config_frequency( - clocks: &mut ClockTree, - config: SystemPreDivInConfig, - ) -> u32 { + pub fn system_pre_div_in_config_frequency(config: SystemPreDivInConfig) -> u32 { match config { SystemPreDivInConfig::Xtal => xtal_clk_frequency(), SystemPreDivInConfig::RcFast => rc_fast_clk_frequency(), @@ -1869,10 +2220,7 @@ macro_rules! define_clock_tree_types { SYSTEM_PRE_DIV_IN_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn system_pre_div_in_source_frequency(source: SystemPreDivInConfig) -> u32 { - match source { - SystemPreDivInConfig::Xtal => xtal_clk_frequency(), - SystemPreDivInConfig::RcFast => rc_fast_clk_frequency(), - } + system_pre_div_in_config_frequency(source) } pub fn configure_system_pre_div(clocks: &mut ClockTree, config: SystemPreDivConfig) { let old_config = clocks.system_pre_div.replace(config); @@ -1883,22 +2231,16 @@ macro_rules! define_clock_tree_types { clocks.system_pre_div } pub fn request_system_pre_div(clocks: &mut ClockTree) { - trace!("Requesting SYSTEM_PRE_DIV"); trace!("Enabling SYSTEM_PRE_DIV"); request_system_pre_div_in(clocks); enable_system_pre_div_impl(clocks, true); } pub fn release_system_pre_div(clocks: &mut ClockTree) { - trace!("Releasing SYSTEM_PRE_DIV"); trace!("Disabling SYSTEM_PRE_DIV"); enable_system_pre_div_impl(clocks, false); release_system_pre_div_in(clocks); } - #[allow(unused_variables)] - pub fn system_pre_div_config_frequency( - clocks: &mut ClockTree, - config: SystemPreDivConfig, - ) -> u32 { + pub fn system_pre_div_config_frequency(config: SystemPreDivConfig) -> u32 { (system_pre_div_in_frequency() / (config.divisor() + 1)) } pub fn system_pre_div_frequency() -> u32 { @@ -1916,22 +2258,16 @@ macro_rules! define_clock_tree_types { clocks.cpu_pll_div } pub fn request_cpu_pll_div(clocks: &mut ClockTree) { - trace!("Requesting CPU_PLL_DIV"); trace!("Enabling CPU_PLL_DIV"); request_pll_clk(clocks); enable_cpu_pll_div_impl(clocks, true); } pub fn release_cpu_pll_div(clocks: &mut ClockTree) { - trace!("Releasing CPU_PLL_DIV"); trace!("Disabling CPU_PLL_DIV"); enable_cpu_pll_div_impl(clocks, false); release_pll_clk(clocks); } - #[allow(unused_variables)] - pub fn cpu_pll_div_config_frequency( - clocks: &mut ClockTree, - config: CpuPllDivConfig, - ) -> u32 { + pub fn cpu_pll_div_config_frequency(config: CpuPllDivConfig) -> u32 { (pll_clk_frequency() / config.divisor()) } pub fn cpu_pll_div_frequency() -> u32 { @@ -1943,49 +2279,38 @@ macro_rules! define_clock_tree_types { pub fn configure_apb_clk(clocks: &mut ClockTree, new_selector: ApbClkConfig) { let old_selector = clocks.apb_clk.replace(new_selector); refresh_apb_clk_downstream(clocks); - if clocks.apb_clk_refcount > 0 { - match new_selector { - ApbClkConfig::Pll40m => request_pll_40m(clocks), - ApbClkConfig::Cpu => request_cpu_clk(clocks), - } - configure_apb_clk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - ApbClkConfig::Pll40m => release_pll_40m(clocks), - ApbClkConfig::Cpu => release_cpu_clk(clocks), - } + match new_selector { + ApbClkConfig::Pll40m => request_pll_40m(clocks), + ApbClkConfig::Cpu => request_cpu_clk(clocks), + } + configure_apb_clk_impl(clocks, old_selector, new_selector); + if let Some(old_selector) = old_selector { + match old_selector { + ApbClkConfig::Pll40m => release_pll_40m(clocks), + ApbClkConfig::Cpu => release_cpu_clk(clocks), } - } else { - configure_apb_clk_impl(clocks, old_selector, new_selector); } } pub fn apb_clk_config(clocks: &mut ClockTree) -> Option { clocks.apb_clk } pub fn request_apb_clk(clocks: &mut ClockTree) { - trace!("Requesting APB_CLK"); - if increment_reference_count(&mut clocks.apb_clk_refcount) { - trace!("Enabling APB_CLK"); - match unwrap!(clocks.apb_clk) { - ApbClkConfig::Pll40m => request_pll_40m(clocks), - ApbClkConfig::Cpu => request_cpu_clk(clocks), - } - enable_apb_clk_impl(clocks, true); + trace!("Enabling APB_CLK"); + match unwrap!(clocks.apb_clk) { + ApbClkConfig::Pll40m => request_pll_40m(clocks), + ApbClkConfig::Cpu => request_cpu_clk(clocks), } + enable_apb_clk_impl(clocks, true); } pub fn release_apb_clk(clocks: &mut ClockTree) { - trace!("Releasing APB_CLK"); - if decrement_reference_count(&mut clocks.apb_clk_refcount) { - trace!("Disabling APB_CLK"); - enable_apb_clk_impl(clocks, false); - match unwrap!(clocks.apb_clk) { - ApbClkConfig::Pll40m => release_pll_40m(clocks), - ApbClkConfig::Cpu => release_cpu_clk(clocks), - } + trace!("Disabling APB_CLK"); + enable_apb_clk_impl(clocks, false); + match unwrap!(clocks.apb_clk) { + ApbClkConfig::Pll40m => release_pll_40m(clocks), + ApbClkConfig::Cpu => release_cpu_clk(clocks), } } - #[allow(unused_variables)] - pub fn apb_clk_config_frequency(clocks: &mut ClockTree, config: ApbClkConfig) -> u32 { + pub fn apb_clk_config_frequency(config: ApbClkConfig) -> u32 { match config { ApbClkConfig::Pll40m => pll_40m_frequency(), ApbClkConfig::Cpu => cpu_clk_frequency(), @@ -1995,28 +2320,24 @@ macro_rules! define_clock_tree_types { APB_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn apb_clk_source_frequency(source: ApbClkConfig) -> u32 { - match source { - ApbClkConfig::Pll40m => pll_40m_frequency(), - ApbClkConfig::Cpu => cpu_clk_frequency(), - } + apb_clk_config_frequency(source) } pub fn configure_crypto_clk(clocks: &mut ClockTree, new_selector: CryptoClkConfig) { let old_selector = clocks.crypto_clk.replace(new_selector); refresh_crypto_clk_downstream(clocks); - if clocks.crypto_clk_refcount > 0 { + let active = clocks.crypto_clk_refcount > 0; + if active { match new_selector { CryptoClkConfig::Pll80m => request_pll_80m(clocks), CryptoClkConfig::Cpu => request_cpu_clk(clocks), } - configure_crypto_clk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - CryptoClkConfig::Pll80m => release_pll_80m(clocks), - CryptoClkConfig::Cpu => release_cpu_clk(clocks), - } + } + configure_crypto_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + CryptoClkConfig::Pll80m => release_pll_80m(clocks), + CryptoClkConfig::Cpu => release_cpu_clk(clocks), } - } else { - configure_crypto_clk_impl(clocks, old_selector, new_selector); } } pub fn crypto_clk_config(clocks: &mut ClockTree) -> Option { @@ -2044,8 +2365,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn crypto_clk_config_frequency(clocks: &mut ClockTree, config: CryptoClkConfig) -> u32 { + pub fn crypto_clk_config_frequency(config: CryptoClkConfig) -> u32 { match config { CryptoClkConfig::Pll80m => pll_80m_frequency(), CryptoClkConfig::Cpu => cpu_clk_frequency(), @@ -2055,28 +2375,24 @@ macro_rules! define_clock_tree_types { CRYPTO_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn crypto_clk_source_frequency(source: CryptoClkConfig) -> u32 { - match source { - CryptoClkConfig::Pll80m => pll_80m_frequency(), - CryptoClkConfig::Cpu => cpu_clk_frequency(), - } + crypto_clk_config_frequency(source) } pub fn configure_mspi_clk(clocks: &mut ClockTree, new_selector: MspiClkConfig) { let old_selector = clocks.mspi_clk.replace(new_selector); refresh_mspi_clk_downstream(clocks); - if clocks.mspi_clk_refcount > 0 { + let active = clocks.mspi_clk_refcount > 0; + if active { match new_selector { MspiClkConfig::CpuDiv2 => request_cpu_div2(clocks), MspiClkConfig::Cpu => request_cpu_clk(clocks), } - configure_mspi_clk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - MspiClkConfig::CpuDiv2 => release_cpu_div2(clocks), - MspiClkConfig::Cpu => release_cpu_clk(clocks), - } + } + configure_mspi_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + MspiClkConfig::CpuDiv2 => release_cpu_div2(clocks), + MspiClkConfig::Cpu => release_cpu_clk(clocks), } - } else { - configure_mspi_clk_impl(clocks, old_selector, new_selector); } } pub fn mspi_clk_config(clocks: &mut ClockTree) -> Option { @@ -2104,8 +2420,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn mspi_clk_config_frequency(clocks: &mut ClockTree, config: MspiClkConfig) -> u32 { + pub fn mspi_clk_config_frequency(config: MspiClkConfig) -> u32 { match config { MspiClkConfig::CpuDiv2 => cpu_div2_frequency(), MspiClkConfig::Cpu => cpu_clk_frequency(), @@ -2115,10 +2430,7 @@ macro_rules! define_clock_tree_types { MSPI_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn mspi_clk_source_frequency(source: MspiClkConfig) -> u32 { - match source { - MspiClkConfig::CpuDiv2 => cpu_div2_frequency(), - MspiClkConfig::Cpu => cpu_clk_frequency(), - } + mspi_clk_config_frequency(source) } pub fn configure_cpu_clk(clocks: &mut ClockTree, new_selector: CpuClkConfig) { let old_selector = clocks.cpu_clk.replace(new_selector); @@ -2161,8 +2473,7 @@ macro_rules! define_clock_tree_types { } fn request_cpu_clk(_clocks: &mut ClockTree) {} fn release_cpu_clk(_clocks: &mut ClockTree) {} - #[allow(unused_variables)] - pub fn cpu_clk_config_frequency(clocks: &mut ClockTree, config: CpuClkConfig) -> u32 { + pub fn cpu_clk_config_frequency(config: CpuClkConfig) -> u32 { match config { CpuClkConfig::Xtal => system_pre_div_frequency(), CpuClkConfig::RcFast => system_pre_div_frequency(), @@ -2217,13 +2528,11 @@ macro_rules! define_clock_tree_types { cpu_clk_frequency() } pub fn request_pll_80m(clocks: &mut ClockTree) { - trace!("Requesting PLL_80M"); trace!("Enabling PLL_80M"); request_cpu_clk(clocks); enable_pll_80m_impl(clocks, true); } pub fn release_pll_80m(clocks: &mut ClockTree) { - trace!("Releasing PLL_80M"); trace!("Disabling PLL_80M"); enable_pll_80m_impl(clocks, false); release_cpu_clk(clocks); @@ -2235,13 +2544,11 @@ macro_rules! define_clock_tree_types { cpu_clk_frequency() } pub fn request_cpu_div2(clocks: &mut ClockTree) { - trace!("Requesting CPU_DIV2"); trace!("Enabling CPU_DIV2"); request_cpu_clk(clocks); enable_cpu_div2_impl(clocks, true); } pub fn release_cpu_div2(clocks: &mut ClockTree) { - trace!("Releasing CPU_DIV2"); trace!("Disabling CPU_DIV2"); enable_cpu_div2_impl(clocks, false); release_cpu_clk(clocks); @@ -2261,22 +2568,16 @@ macro_rules! define_clock_tree_types { clocks.rc_fast_clk_div_n } pub fn request_rc_fast_clk_div_n(clocks: &mut ClockTree) { - trace!("Requesting RC_FAST_CLK_DIV_N"); trace!("Enabling RC_FAST_CLK_DIV_N"); request_rc_fast_clk(clocks); enable_rc_fast_clk_div_n_impl(clocks, true); } pub fn release_rc_fast_clk_div_n(clocks: &mut ClockTree) { - trace!("Releasing RC_FAST_CLK_DIV_N"); trace!("Disabling RC_FAST_CLK_DIV_N"); enable_rc_fast_clk_div_n_impl(clocks, false); release_rc_fast_clk(clocks); } - #[allow(unused_variables)] - pub fn rc_fast_clk_div_n_config_frequency( - clocks: &mut ClockTree, - config: RcFastClkDivNConfig, - ) -> u32 { + pub fn rc_fast_clk_div_n_config_frequency(config: RcFastClkDivNConfig) -> u32 { (rc_fast_clk_frequency() / (config.divisor() + 1)) } pub fn rc_fast_clk_div_n_frequency() -> u32 { @@ -2286,13 +2587,11 @@ macro_rules! define_clock_tree_types { rc_fast_clk_frequency() } pub fn request_xtal_div_clk(clocks: &mut ClockTree) { - trace!("Requesting XTAL_DIV_CLK"); trace!("Enabling XTAL_DIV_CLK"); request_xtal_clk(clocks); enable_xtal_div_clk_impl(clocks, true); } pub fn release_xtal_div_clk(clocks: &mut ClockTree) { - trace!("Releasing XTAL_DIV_CLK"); trace!("Disabling XTAL_DIV_CLK"); enable_xtal_div_clk_impl(clocks, false); release_xtal_clk(clocks); @@ -2324,7 +2623,6 @@ macro_rules! define_clock_tree_types { clocks.rtc_slow_clk } pub fn request_rtc_slow_clk(clocks: &mut ClockTree) { - trace!("Requesting RTC_SLOW_CLK"); trace!("Enabling RTC_SLOW_CLK"); match unwrap!(clocks.rtc_slow_clk) { RtcSlowClkConfig::OscSlow => request_osc_slow_clk(clocks), @@ -2334,7 +2632,6 @@ macro_rules! define_clock_tree_types { enable_rtc_slow_clk_impl(clocks, true); } pub fn release_rtc_slow_clk(clocks: &mut ClockTree) { - trace!("Releasing RTC_SLOW_CLK"); trace!("Disabling RTC_SLOW_CLK"); enable_rtc_slow_clk_impl(clocks, false); match unwrap!(clocks.rtc_slow_clk) { @@ -2343,11 +2640,7 @@ macro_rules! define_clock_tree_types { RtcSlowClkConfig::RcFast => release_rc_fast_div_clk(clocks), } } - #[allow(unused_variables)] - pub fn rtc_slow_clk_config_frequency( - clocks: &mut ClockTree, - config: RtcSlowClkConfig, - ) -> u32 { + pub fn rtc_slow_clk_config_frequency(config: RtcSlowClkConfig) -> u32 { match config { RtcSlowClkConfig::OscSlow => osc_slow_clk_frequency(), RtcSlowClkConfig::RcSlow => rc_slow_clk_frequency(), @@ -2358,29 +2651,114 @@ macro_rules! define_clock_tree_types { RTC_SLOW_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn rtc_slow_clk_source_frequency(source: RtcSlowClkConfig) -> u32 { - match source { - RtcSlowClkConfig::OscSlow => osc_slow_clk_frequency(), - RtcSlowClkConfig::RcSlow => rc_slow_clk_frequency(), - RtcSlowClkConfig::RcFast => rc_fast_div_clk_frequency(), + rtc_slow_clk_config_frequency(source) + } + pub fn request_ble_lp_xtal_clk(clocks: &mut ClockTree) { + trace!("Enabling BLE_LP_XTAL_CLK"); + request_xtal_clk(clocks); + enable_ble_lp_xtal_clk_impl(clocks, true); + } + pub fn release_ble_lp_xtal_clk(clocks: &mut ClockTree) { + trace!("Disabling BLE_LP_XTAL_CLK"); + enable_ble_lp_xtal_clk_impl(clocks, false); + release_xtal_clk(clocks); + } + pub fn ble_lp_xtal_clk_frequency() -> u32 { + (xtal_clk_frequency() / 5) + } + pub fn ble_lp_xtal_clk_source_frequency() -> u32 { + xtal_clk_frequency() + } + pub fn request_ble_lp_rc_slow_clk(clocks: &mut ClockTree) { + trace!("Enabling BLE_LP_RC_SLOW_CLK"); + request_rc_slow_clk(clocks); + enable_ble_lp_rc_slow_clk_impl(clocks, true); + } + pub fn release_ble_lp_rc_slow_clk(clocks: &mut ClockTree) { + trace!("Disabling BLE_LP_RC_SLOW_CLK"); + enable_ble_lp_rc_slow_clk_impl(clocks, false); + release_rc_slow_clk(clocks); + } + pub fn ble_lp_rc_slow_clk_frequency() -> u32 { + (rc_slow_clk_frequency() / 5) + } + pub fn ble_lp_rc_slow_clk_source_frequency() -> u32 { + rc_slow_clk_frequency() + } + pub fn configure_ble_lp_clk(clocks: &mut ClockTree, config: BleLpClkConfig) { + let old_config = clocks.ble_lp_clk.replace(config); + refresh_ble_lp_clk_downstream(clocks); + let active = clocks.ble_lp_clk_refcount > 0; + if active { + match config.sclk { + BleLpClkSclk::Xtal => request_ble_lp_xtal_clk(clocks), + BleLpClkSclk::RcSlow => request_ble_lp_rc_slow_clk(clocks), + } + } + configure_ble_lp_clk_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + BleLpClkSclk::Xtal => release_ble_lp_xtal_clk(clocks), + BleLpClkSclk::RcSlow => release_ble_lp_rc_slow_clk(clocks), + } + } + } + pub fn ble_lp_clk_config(clocks: &mut ClockTree) -> Option { + clocks.ble_lp_clk + } + pub fn request_ble_lp_clk(clocks: &mut ClockTree) { + trace!("Requesting BLE_LP_CLK"); + if increment_reference_count(&mut clocks.ble_lp_clk_refcount) { + trace!("Enabling BLE_LP_CLK"); + match unwrap!(clocks.ble_lp_clk).sclk { + BleLpClkSclk::Xtal => request_ble_lp_xtal_clk(clocks), + BleLpClkSclk::RcSlow => request_ble_lp_rc_slow_clk(clocks), + } + enable_ble_lp_clk_impl(clocks, true); + } + } + pub fn release_ble_lp_clk(clocks: &mut ClockTree) { + trace!("Releasing BLE_LP_CLK"); + if decrement_reference_count(&mut clocks.ble_lp_clk_refcount) { + trace!("Disabling BLE_LP_CLK"); + enable_ble_lp_clk_impl(clocks, false); + match unwrap!(clocks.ble_lp_clk).sclk { + BleLpClkSclk::Xtal => release_ble_lp_xtal_clk(clocks), + BleLpClkSclk::RcSlow => release_ble_lp_rc_slow_clk(clocks), + } + } + } + pub fn ble_lp_clk_config_frequency(config: BleLpClkConfig) -> u32 { + (match config.sclk { + BleLpClkSclk::Xtal => ble_lp_xtal_clk_frequency(), + BleLpClkSclk::RcSlow => ble_lp_rc_slow_clk_frequency(), + } / (config.divisor() + 1)) + } + pub fn ble_lp_clk_frequency() -> u32 { + BLE_LP_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn ble_lp_clk_source_frequency(sclk: BleLpClkSclk) -> u32 { + match sclk { + BleLpClkSclk::Xtal => ble_lp_xtal_clk_frequency(), + BleLpClkSclk::RcSlow => ble_lp_rc_slow_clk_frequency(), } } pub fn configure_rtc_fast_clk(clocks: &mut ClockTree, new_selector: RtcFastClkConfig) { let old_selector = clocks.rtc_fast_clk.replace(new_selector); refresh_rtc_fast_clk_downstream(clocks); - if clocks.rtc_fast_clk_refcount > 0 { + let active = clocks.rtc_fast_clk_refcount > 0; + if active { match new_selector { RtcFastClkConfig::Xtal => request_xtal_div_clk(clocks), RtcFastClkConfig::Rc => request_rc_fast_clk_div_n(clocks), } - configure_rtc_fast_clk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - RtcFastClkConfig::Xtal => release_xtal_div_clk(clocks), - RtcFastClkConfig::Rc => release_rc_fast_clk_div_n(clocks), - } + } + configure_rtc_fast_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + RtcFastClkConfig::Xtal => release_xtal_div_clk(clocks), + RtcFastClkConfig::Rc => release_rc_fast_clk_div_n(clocks), } - } else { - configure_rtc_fast_clk_impl(clocks, old_selector, new_selector); } } pub fn rtc_fast_clk_config(clocks: &mut ClockTree) -> Option { @@ -2408,11 +2786,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn rtc_fast_clk_config_frequency( - clocks: &mut ClockTree, - config: RtcFastClkConfig, - ) -> u32 { + pub fn rtc_fast_clk_config_frequency(config: RtcFastClkConfig) -> u32 { match config { RtcFastClkConfig::Xtal => xtal_div_clk_frequency(), RtcFastClkConfig::Rc => rc_fast_clk_div_n_frequency(), @@ -2422,32 +2796,28 @@ macro_rules! define_clock_tree_types { RTC_FAST_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn rtc_fast_clk_source_frequency(source: RtcFastClkConfig) -> u32 { - match source { - RtcFastClkConfig::Xtal => xtal_div_clk_frequency(), - RtcFastClkConfig::Rc => rc_fast_clk_div_n_frequency(), - } + rtc_fast_clk_config_frequency(source) } pub fn configure_low_power_clk(clocks: &mut ClockTree, new_selector: LowPowerClkConfig) { let old_selector = clocks.low_power_clk.replace(new_selector); refresh_low_power_clk_downstream(clocks); - if clocks.low_power_clk_refcount > 0 { + let active = clocks.low_power_clk_refcount > 0; + if active { match new_selector { LowPowerClkConfig::Xtal => request_xtal_clk(clocks), LowPowerClkConfig::RcFast => request_rc_fast_clk(clocks), LowPowerClkConfig::OscSlow => request_osc_slow_clk(clocks), LowPowerClkConfig::RtcSlow => request_rtc_slow_clk(clocks), } - configure_low_power_clk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - LowPowerClkConfig::Xtal => release_xtal_clk(clocks), - LowPowerClkConfig::RcFast => release_rc_fast_clk(clocks), - LowPowerClkConfig::OscSlow => release_osc_slow_clk(clocks), - LowPowerClkConfig::RtcSlow => release_rtc_slow_clk(clocks), - } + } + configure_low_power_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + LowPowerClkConfig::Xtal => release_xtal_clk(clocks), + LowPowerClkConfig::RcFast => release_rc_fast_clk(clocks), + LowPowerClkConfig::OscSlow => release_osc_slow_clk(clocks), + LowPowerClkConfig::RtcSlow => release_rtc_slow_clk(clocks), } - } else { - configure_low_power_clk_impl(clocks, old_selector, new_selector); } } pub fn low_power_clk_config(clocks: &mut ClockTree) -> Option { @@ -2479,11 +2849,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn low_power_clk_config_frequency( - clocks: &mut ClockTree, - config: LowPowerClkConfig, - ) -> u32 { + pub fn low_power_clk_config_frequency(config: LowPowerClkConfig) -> u32 { match config { LowPowerClkConfig::Xtal => xtal_clk_frequency(), LowPowerClkConfig::RcFast => rc_fast_clk_frequency(), @@ -2495,12 +2861,7 @@ macro_rules! define_clock_tree_types { LOW_POWER_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn low_power_clk_source_frequency(source: LowPowerClkConfig) -> u32 { - match source { - LowPowerClkConfig::Xtal => xtal_clk_frequency(), - LowPowerClkConfig::RcFast => rc_fast_clk_frequency(), - LowPowerClkConfig::OscSlow => osc_slow_clk_frequency(), - LowPowerClkConfig::RtcSlow => rtc_slow_clk_frequency(), - } + low_power_clk_config_frequency(source) } pub fn request_uart_mem_clk(clocks: &mut ClockTree) { trace!("Requesting UART_MEM_CLK"); @@ -2532,22 +2893,21 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.timg_calibration_clock.replace(new_selector); refresh_timg_calibration_clock_downstream(clocks); - if clocks.timg_calibration_clock_refcount > 0 { + let active = clocks.timg_calibration_clock_refcount > 0; + if active { match new_selector { TimgCalibrationClockConfig::RcSlowClk => request_rc_slow_clk(clocks), TimgCalibrationClockConfig::RcFastDivClk => request_rc_fast_div_clk(clocks), TimgCalibrationClockConfig::Osc32kClk => request_osc_slow_clk(clocks), } - configure_timg_calibration_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - TimgCalibrationClockConfig::RcSlowClk => release_rc_slow_clk(clocks), - TimgCalibrationClockConfig::RcFastDivClk => release_rc_fast_div_clk(clocks), - TimgCalibrationClockConfig::Osc32kClk => release_osc_slow_clk(clocks), - } + } + configure_timg_calibration_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + TimgCalibrationClockConfig::RcSlowClk => release_rc_slow_clk(clocks), + TimgCalibrationClockConfig::RcFastDivClk => release_rc_fast_div_clk(clocks), + TimgCalibrationClockConfig::Osc32kClk => release_osc_slow_clk(clocks), } - } else { - configure_timg_calibration_clock_impl(clocks, old_selector, new_selector); } } pub fn timg_calibration_clock_config( @@ -2581,11 +2941,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn timg_calibration_clock_config_frequency( - clocks: &mut ClockTree, - config: TimgCalibrationClockConfig, - ) -> u32 { + pub fn timg_calibration_clock_config_frequency(config: TimgCalibrationClockConfig) -> u32 { match config { TimgCalibrationClockConfig::RcSlowClk => rc_slow_clk_frequency(), TimgCalibrationClockConfig::RcFastDivClk => rc_fast_div_clk_frequency(), @@ -2596,10 +2952,32 @@ macro_rules! define_clock_tree_types { TIMG_CALIBRATION_CLOCK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn timg_calibration_clock_source_frequency(source: TimgCalibrationClockConfig) -> u32 { - match source { - TimgCalibrationClockConfig::RcSlowClk => rc_slow_clk_frequency(), - TimgCalibrationClockConfig::RcFastDivClk => rc_fast_div_clk_frequency(), - TimgCalibrationClockConfig::Osc32kClk => osc_slow_clk_frequency(), + timg_calibration_clock_config_frequency(source) + } + impl AdcInstance { + pub fn request_function_clock(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::FUNCTION_CLOCK", self); + if increment_reference_count(&mut clocks.adc_function_clock_refcount[self as usize]) + { + trace!("Enabling {:?}::FUNCTION_CLOCK", self); + request_apb_clk(clocks); + self.enable_function_clock_impl(clocks, true); + } + } + pub fn release_function_clock(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::FUNCTION_CLOCK", self); + if decrement_reference_count(&mut clocks.adc_function_clock_refcount[self as usize]) + { + trace!("Disabling {:?}::FUNCTION_CLOCK", self); + self.enable_function_clock_impl(clocks, false); + release_apb_clk(clocks); + } + } + pub fn function_clock_frequency(self) -> u32 { + apb_clk_frequency() + } + pub fn function_clock_source_frequency() -> u32 { + apb_clk_frequency() } } impl I2cInstance { @@ -2610,20 +2988,19 @@ macro_rules! define_clock_tree_types { ) { let old_config = clocks.i2c_function_clock[self as usize].replace(config); refresh_i2c_function_clock_downstream(clocks, self); - if clocks.i2c_function_clock_refcount[self as usize] > 0 { + let active = clocks.i2c_function_clock_refcount[self as usize] > 0; + if active { match config.sclk { I2cFunctionClockSclk::Xtal => request_xtal_clk(clocks), I2cFunctionClockSclk::RcFast => request_rc_fast_clk(clocks), } - self.configure_function_clock_impl(clocks, old_config, config); - if let Some(old_config) = old_config { - match old_config.sclk { - I2cFunctionClockSclk::Xtal => release_xtal_clk(clocks), - I2cFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), - } + } + self.configure_function_clock_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + I2cFunctionClockSclk::Xtal => release_xtal_clk(clocks), + I2cFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_config, config); } } pub fn function_clock_config( @@ -2658,11 +3035,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: I2cFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: I2cFunctionClockConfig) -> u32 { (match config.sclk { I2cFunctionClockSclk::Xtal => xtal_clk_frequency(), I2cFunctionClockSclk::RcFast => rc_fast_clk_frequency(), @@ -2687,20 +3060,19 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.spi_function_clock[self as usize].replace(new_selector); refresh_spi_function_clock_downstream(clocks, self); - if clocks.spi_function_clock_refcount[self as usize] > 0 { + let active = clocks.spi_function_clock_refcount[self as usize] > 0; + if active { match new_selector { SpiFunctionClockConfig::Xtal => request_xtal_clk(clocks), SpiFunctionClockConfig::Pll40m => request_pll_40m(clocks), } - self.configure_function_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - SpiFunctionClockConfig::Xtal => release_xtal_clk(clocks), - SpiFunctionClockConfig::Pll40m => release_pll_40m(clocks), - } + } + self.configure_function_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + SpiFunctionClockConfig::Xtal => release_xtal_clk(clocks), + SpiFunctionClockConfig::Pll40m => release_pll_40m(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_selector, new_selector); } } pub fn function_clock_config( @@ -2735,11 +3107,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: SpiFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: SpiFunctionClockConfig) -> u32 { match config { SpiFunctionClockConfig::Xtal => xtal_clk_frequency(), SpiFunctionClockConfig::Pll40m => pll_40m_frequency(), @@ -2750,10 +3118,7 @@ macro_rules! define_clock_tree_types { .load(::core::sync::atomic::Ordering::Acquire) } pub fn function_clock_source_frequency(source: SpiFunctionClockConfig) -> u32 { - match source { - SpiFunctionClockConfig::Xtal => xtal_clk_frequency(), - SpiFunctionClockConfig::Pll40m => pll_40m_frequency(), - } + Self::function_clock_config_frequency(source) } } impl TimgInstance { @@ -2764,20 +3129,19 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.timg_function_clock[self as usize].replace(new_selector); refresh_timg_function_clock_downstream(clocks, self); - if clocks.timg_function_clock_refcount[self as usize] > 0 { + let active = clocks.timg_function_clock_refcount[self as usize] > 0; + if active { match new_selector { TimgFunctionClockConfig::XtalClk => request_xtal_clk(clocks), TimgFunctionClockConfig::Pll40m => request_pll_40m(clocks), } - self.configure_function_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - TimgFunctionClockConfig::XtalClk => release_xtal_clk(clocks), - TimgFunctionClockConfig::Pll40m => release_pll_40m(clocks), - } + } + self.configure_function_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + TimgFunctionClockConfig::XtalClk => release_xtal_clk(clocks), + TimgFunctionClockConfig::Pll40m => release_pll_40m(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_selector, new_selector); } } pub fn function_clock_config( @@ -2812,11 +3176,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: TimgFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: TimgFunctionClockConfig) -> u32 { match config { TimgFunctionClockConfig::XtalClk => xtal_clk_frequency(), TimgFunctionClockConfig::Pll40m => pll_40m_frequency(), @@ -2827,10 +3187,7 @@ macro_rules! define_clock_tree_types { .load(::core::sync::atomic::Ordering::Acquire) } pub fn function_clock_source_frequency(source: TimgFunctionClockConfig) -> u32 { - match source { - TimgFunctionClockConfig::XtalClk => xtal_clk_frequency(), - TimgFunctionClockConfig::Pll40m => pll_40m_frequency(), - } + Self::function_clock_config_frequency(source) } pub fn configure_wdt_clock( self, @@ -2839,20 +3196,19 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.timg_wdt_clock[self as usize].replace(new_selector); refresh_timg_wdt_clock_downstream(clocks, self); - if clocks.timg_wdt_clock_refcount[self as usize] > 0 { + let active = clocks.timg_wdt_clock_refcount[self as usize] > 0; + if active { match new_selector { TimgWdtClockConfig::Pll40m => request_pll_40m(clocks), TimgWdtClockConfig::XtalClk => request_xtal_clk(clocks), } - self.configure_wdt_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - TimgWdtClockConfig::Pll40m => release_pll_40m(clocks), - TimgWdtClockConfig::XtalClk => release_xtal_clk(clocks), - } + } + self.configure_wdt_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + TimgWdtClockConfig::Pll40m => release_pll_40m(clocks), + TimgWdtClockConfig::XtalClk => release_xtal_clk(clocks), } - } else { - self.configure_wdt_clock_impl(clocks, old_selector, new_selector); } } pub fn wdt_clock_config(self, clocks: &mut ClockTree) -> Option { @@ -2880,11 +3236,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn wdt_clock_config_frequency( - clocks: &mut ClockTree, - config: TimgWdtClockConfig, - ) -> u32 { + pub fn wdt_clock_config_frequency(config: TimgWdtClockConfig) -> u32 { match config { TimgWdtClockConfig::Pll40m => pll_40m_frequency(), TimgWdtClockConfig::XtalClk => xtal_clk_frequency(), @@ -2895,10 +3247,7 @@ macro_rules! define_clock_tree_types { .load(::core::sync::atomic::Ordering::Acquire) } pub fn wdt_clock_source_frequency(source: TimgWdtClockConfig) -> u32 { - match source { - TimgWdtClockConfig::Pll40m => pll_40m_frequency(), - TimgWdtClockConfig::XtalClk => xtal_clk_frequency(), - } + Self::wdt_clock_config_frequency(source) } } impl UartInstance { @@ -2909,22 +3258,21 @@ macro_rules! define_clock_tree_types { ) { let old_config = clocks.uart_function_clock[self as usize].replace(config); refresh_uart_function_clock_downstream(clocks, self); - if clocks.uart_function_clock_refcount[self as usize] > 0 { + let active = clocks.uart_function_clock_refcount[self as usize] > 0; + if active { match config.sclk { UartFunctionClockSclk::PllF40m => request_pll_40m(clocks), UartFunctionClockSclk::RcFast => request_rc_fast_clk(clocks), UartFunctionClockSclk::Xtal => request_xtal_clk(clocks), } - self.configure_function_clock_impl(clocks, old_config, config); - if let Some(old_config) = old_config { - match old_config.sclk { - UartFunctionClockSclk::PllF40m => release_pll_40m(clocks), - UartFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), - UartFunctionClockSclk::Xtal => release_xtal_clk(clocks), - } + } + self.configure_function_clock_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + UartFunctionClockSclk::PllF40m => release_pll_40m(clocks), + UartFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), + UartFunctionClockSclk::Xtal => release_xtal_clk(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_config, config); } } pub fn function_clock_config( @@ -2961,11 +3309,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: UartFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: UartFunctionClockConfig) -> u32 { (match config.sclk { UartFunctionClockSclk::PllF40m => pll_40m_frequency(), UartFunctionClockSclk::RcFast => rc_fast_clk_frequency(), @@ -3040,10 +3384,8 @@ macro_rules! define_clock_tree_types { self.release_function_clock(clocks); } } - #[allow(unused_variables)] pub fn baud_rate_generator_config_frequency( self, - clocks: &mut ClockTree, config: UartBaudRateGeneratorConfig, ) -> u32 { ((self.function_clock_frequency() * 16) @@ -3077,6 +3419,8 @@ macro_rules! define_clock_tree_types { pub rc_fast_clk_div_n: Option, /// `RTC_SLOW_CLK` configuration. pub rtc_slow_clk: Option, + /// `BLE_LP_CLK` configuration. + pub ble_lp_clk: Option, /// `RTC_FAST_CLK` configuration. pub rtc_fast_clk: Option, /// `LOW_POWER_CLK` configuration. @@ -3104,6 +3448,9 @@ macro_rules! define_clock_tree_types { if let Some(config) = self.rtc_slow_clk { configure_rtc_slow_clk(clocks, config); } + if let Some(config) = self.ble_lp_clk { + configure_ble_lp_clk(clocks, config); + } if let Some(config) = self.rtc_fast_clk { configure_rtc_fast_clk(clocks, config); } @@ -3128,12 +3475,13 @@ macro_rules! define_clock_tree_types { fn refresh_xtal_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.xtal_clk { XTAL_CLK_FREQ_CACHE.store( - xtal_clk_config_frequency(clocks, config), + xtal_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } refresh_system_pre_div_in_downstream(clocks); refresh_cpu_pll_div_downstream(clocks); + refresh_ble_lp_clk_downstream(clocks); refresh_rtc_fast_clk_downstream(clocks); refresh_low_power_clk_downstream(clocks); for child_instance in [I2cInstance::I2c0] { @@ -3150,10 +3498,28 @@ macro_rules! define_clock_tree_types { refresh_uart_function_clock_downstream(clocks, child_instance); } } + fn refresh_rc_fast_clk_downstream(clocks: &mut ClockTree) { + refresh_system_pre_div_in_downstream(clocks); + refresh_rc_fast_clk_div_n_downstream(clocks); + refresh_rtc_slow_clk_downstream(clocks); + refresh_low_power_clk_downstream(clocks); + refresh_timg_calibration_clock_downstream(clocks); + for child_instance in [I2cInstance::I2c0] { + refresh_i2c_function_clock_downstream(clocks, child_instance); + } + for child_instance in [UartInstance::Uart0, UartInstance::Uart1] { + refresh_uart_function_clock_downstream(clocks, child_instance); + } + } + fn refresh_rc_slow_clk_downstream(clocks: &mut ClockTree) { + refresh_rtc_slow_clk_downstream(clocks); + refresh_ble_lp_clk_downstream(clocks); + refresh_timg_calibration_clock_downstream(clocks); + } fn refresh_system_pre_div_in_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.system_pre_div_in { SYSTEM_PRE_DIV_IN_FREQ_CACHE.store( - system_pre_div_in_config_frequency(clocks, config), + system_pre_div_in_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3162,7 +3528,7 @@ macro_rules! define_clock_tree_types { fn refresh_system_pre_div_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.system_pre_div { SYSTEM_PRE_DIV_FREQ_CACHE.store( - system_pre_div_config_frequency(clocks, config), + system_pre_div_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3171,7 +3537,7 @@ macro_rules! define_clock_tree_types { fn refresh_cpu_pll_div_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.cpu_pll_div { CPU_PLL_DIV_FREQ_CACHE.store( - cpu_pll_div_config_frequency(clocks, config), + cpu_pll_div_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3180,7 +3546,7 @@ macro_rules! define_clock_tree_types { fn refresh_cpu_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.cpu_clk { CPU_CLK_FREQ_CACHE.store( - cpu_clk_config_frequency(clocks, config), + cpu_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3201,7 +3567,7 @@ macro_rules! define_clock_tree_types { fn refresh_rc_fast_clk_div_n_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.rc_fast_clk_div_n { RC_FAST_CLK_DIV_N_FREQ_CACHE.store( - rc_fast_clk_div_n_config_frequency(clocks, config), + rc_fast_clk_div_n_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3210,16 +3576,24 @@ macro_rules! define_clock_tree_types { fn refresh_rtc_slow_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.rtc_slow_clk { RTC_SLOW_CLK_FREQ_CACHE.store( - rtc_slow_clk_config_frequency(clocks, config), + rtc_slow_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } refresh_low_power_clk_downstream(clocks); } + fn refresh_ble_lp_clk_downstream(clocks: &mut ClockTree) { + if let Some(config) = clocks.ble_lp_clk { + BLE_LP_CLK_FREQ_CACHE.store( + ble_lp_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } fn refresh_rtc_fast_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.rtc_fast_clk { RTC_FAST_CLK_FREQ_CACHE.store( - rtc_fast_clk_config_frequency(clocks, config), + rtc_fast_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3227,7 +3601,7 @@ macro_rules! define_clock_tree_types { fn refresh_low_power_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.low_power_clk { LOW_POWER_CLK_FREQ_CACHE.store( - low_power_clk_config_frequency(clocks, config), + low_power_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3235,7 +3609,7 @@ macro_rules! define_clock_tree_types { fn refresh_timg_calibration_clock_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.timg_calibration_clock { TIMG_CALIBRATION_CLOCK_FREQ_CACHE.store( - timg_calibration_clock_config_frequency(clocks, config), + timg_calibration_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3243,7 +3617,7 @@ macro_rules! define_clock_tree_types { fn refresh_i2c_function_clock_downstream(clocks: &mut ClockTree, instance: I2cInstance) { if let Some(config) = clocks.i2c_function_clock[instance as usize] { I2C_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - I2cInstance::function_clock_config_frequency(clocks, config), + I2cInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3251,7 +3625,7 @@ macro_rules! define_clock_tree_types { fn refresh_spi_function_clock_downstream(clocks: &mut ClockTree, instance: SpiInstance) { if let Some(config) = clocks.spi_function_clock[instance as usize] { SPI_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - SpiInstance::function_clock_config_frequency(clocks, config), + SpiInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3259,7 +3633,7 @@ macro_rules! define_clock_tree_types { fn refresh_timg_function_clock_downstream(clocks: &mut ClockTree, instance: TimgInstance) { if let Some(config) = clocks.timg_function_clock[instance as usize] { TIMG_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - TimgInstance::function_clock_config_frequency(clocks, config), + TimgInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3267,7 +3641,7 @@ macro_rules! define_clock_tree_types { fn refresh_timg_wdt_clock_downstream(clocks: &mut ClockTree, instance: TimgInstance) { if let Some(config) = clocks.timg_wdt_clock[instance as usize] { TIMG_WDT_CLOCK_FREQ_CACHE[instance as usize].store( - TimgInstance::wdt_clock_config_frequency(clocks, config), + TimgInstance::wdt_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3275,7 +3649,7 @@ macro_rules! define_clock_tree_types { fn refresh_uart_function_clock_downstream(clocks: &mut ClockTree, instance: UartInstance) { if let Some(config) = clocks.uart_function_clock[instance as usize] { UART_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - UartInstance::function_clock_config_frequency(clocks, config), + UartInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3287,7 +3661,7 @@ macro_rules! define_clock_tree_types { ) { if let Some(config) = clocks.uart_baud_rate_generator[instance as usize] { UART_BAUD_RATE_GENERATOR_FREQ_CACHE[instance as usize].store( - instance.baud_rate_generator_config_frequency(clocks, config), + instance.baud_rate_generator_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3295,7 +3669,7 @@ macro_rules! define_clock_tree_types { fn refresh_apb_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.apb_clk { APB_CLK_FREQ_CACHE.store( - apb_clk_config_frequency(clocks, config), + apb_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3303,7 +3677,7 @@ macro_rules! define_clock_tree_types { fn refresh_crypto_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.crypto_clk { CRYPTO_CLK_FREQ_CACHE.store( - crypto_clk_config_frequency(clocks, config), + crypto_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3311,7 +3685,7 @@ macro_rules! define_clock_tree_types { fn refresh_mspi_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.mspi_clk { MSPI_CLK_FREQ_CACHE.store( - mspi_clk_config_frequency(clocks, config), + mspi_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3904,7 +4278,6 @@ macro_rules! for_each_peripheral { _for_each_inner_peripheral!((FLASH(unstable))); _for_each_inner_peripheral!((GPIO_DEDICATED(unstable))); _for_each_inner_peripheral!((WIFI)); - _for_each_inner_peripheral!((FROM_CPU_INTR0(unstable))); _for_each_inner_peripheral!((FROM_CPU_INTR1(unstable))); _for_each_inner_peripheral!((FROM_CPU_INTR2(unstable))); _for_each_inner_peripheral!((FROM_CPU_INTR3(unstable))); @@ -4075,10 +4448,9 @@ macro_rules! for_each_peripheral { (SPI0(unstable)), (SPI1(unstable)), (SPI2), (SYSTEM(unstable)), (SYSTIMER(unstable)), (TIMG0(unstable)), (UART0), (UART1), (XTS_AES(unstable)), (ADC1(unstable)), (BT(unstable)), (FLASH(unstable)), (GPIO_DEDICATED(unstable)), - (WIFI), (FROM_CPU_INTR0(unstable)), (FROM_CPU_INTR1(unstable)), - (FROM_CPU_INTR2(unstable)), (FROM_CPU_INTR3(unstable)))); - _for_each_inner_peripheral!((dma_eligible(SPI2, Spi2, 0, AhbGdmaChannel), (SHA, - Sha, 7, AhbGdmaChannel))); + (WIFI), (FROM_CPU_INTR1(unstable)), (FROM_CPU_INTR2(unstable)), + (FROM_CPU_INTR3(unstable)))); _for_each_inner_peripheral!((dma_eligible(SPI2, + Spi2, 0, AhbGdmaChannel), (SHA, Sha, 7, AhbGdmaChannel))); }; } /// This macro can be used to generate code for each `GPIOn` instance. diff --git a/esp-metadata-generated/src/_generated_esp32c3.rs b/esp-metadata-generated/src/_generated_esp32c3.rs index d610e3ffd63..5b83b292bc3 100644 --- a/esp-metadata-generated/src/_generated_esp32c3.rs +++ b/esp-metadata-generated/src/_generated_esp32c3.rs @@ -88,6 +88,9 @@ macro_rules! property { ("gpio.func_in_sel_offset", str) => { stringify!(0) }; + ("gpio.need_soft_isolate_during_pd") => { + false + }; ("gpio.has_bank_1") => { false }; @@ -238,12 +241,6 @@ macro_rules! property { ("i2s.version", str) => { stringify!(2) }; - ("i2s.default_clock_source") => { - 2 - }; - ("i2s.default_clock_source", str) => { - stringify!(2) - }; ("i2s.mclk_divider_bit_width") => { 9 }; @@ -331,6 +328,12 @@ macro_rules! property { ("wifi.csi_supported") => { true }; + ("wifi.has_nan") => { + false + }; + ("wifi.has_ftm") => { + true + }; ("phy.combo_module") => { true }; @@ -340,6 +343,39 @@ macro_rules! property { ("phy.backed_up_digital_register_count", str) => { stringify!(21) }; + ("adc.controller") => { + "digital" + }; + ("adc.channel_count") => { + 5 + }; + ("adc.channel_count", str) => { + stringify!(5) + }; + ("adc.line_calibration") => { + true + }; + ("adc.curve_calibration") => { + true + }; + ("adc.basic_calibration") => { + true + }; + ("adc.calibration_v1_scheme_supported") => { + true + }; + ("adc.channel_compensation") => { + false + }; + ("adc.pcr_clock") => { + false + }; + ("adc.pcr_sar_clk_div") => { + false + }; + ("adc.sar_power_override") => { + false + }; ("ledc.version") => { 2 }; @@ -364,6 +400,9 @@ macro_rules! property { ("timergroup.timg_has_divcnt_rst") => { true }; + ("timergroup.wdt_has_conf_update") => { + true + }; ("aes.has_split_text_registers") => { true }; @@ -418,6 +457,18 @@ macro_rules! property { ("sleep.deep_sleep_needs_gpio_isolation") => { true }; + ("sleep.cpu_retention_mem_size") => { + 1744 + }; + ("sleep.cpu_retention_mem_align") => { + 16 + }; + ("sleep.cpu_retention_mem_start") => { + 1070333952 + }; + ("sleep.cpu_retention_mem_end") => { + 1070465024 + }; ("assist_debug.has_sp_monitor") => { true }; @@ -478,6 +529,9 @@ macro_rules! property { ("soc.cpu_has_csr_pc") => { true }; + ("soc.cpu_has_zcmp_workaround") => { + false + }; ("soc.multi_core_enabled") => { false }; @@ -493,6 +547,12 @@ macro_rules! property { ("soc.cpu_mcause_mask", str) => { stringify!(31) }; + ("soc.cpu_pmp_granularity") => { + 4 + }; + ("soc.cpu_pmp_granularity", str) => { + stringify!(4) + }; ("clock_tree.system_pre_div_in") => { [crate ::soc::clocks::SystemPreDivInConfig::Xtal, crate ::soc::clocks::SystemPreDivInConfig::RcFast] @@ -516,24 +576,28 @@ macro_rules! property { (0, 3) }; ("clock_tree.rtc_slow_clk") => { - [crate ::soc::clocks::RtcSlowClkConfig::Xtal32k, crate + [#[cfg(use_xtal32k)] crate ::soc::clocks::RtcSlowClkConfig::Xtal32k, crate ::soc::clocks::RtcSlowClkConfig::RcSlow, crate ::soc::clocks::RtcSlowClkConfig::RcFast] }; + ("clock_tree.ble_lp_clk") => { + [crate ::soc::clocks::BleLpClkConfig::Xtal, crate + ::soc::clocks::BleLpClkConfig::RtcSlow] + }; ("clock_tree.rtc_fast_clk") => { [crate ::soc::clocks::RtcFastClkConfig::Xtal, crate ::soc::clocks::RtcFastClkConfig::Rc] }; ("clock_tree.low_power_clk") => { [crate ::soc::clocks::LowPowerClkConfig::Xtal, crate - ::soc::clocks::LowPowerClkConfig::RcFast, crate + ::soc::clocks::LowPowerClkConfig::RcFast, #[cfg(use_xtal32k)] crate ::soc::clocks::LowPowerClkConfig::Xtal32k, crate ::soc::clocks::LowPowerClkConfig::RtcSlow] }; ("clock_tree.timg_calibration_clock") => { [crate ::soc::clocks::TimgCalibrationClockConfig::RcSlowClk, crate - ::soc::clocks::TimgCalibrationClockConfig::RcFastDivClk, crate - ::soc::clocks::TimgCalibrationClockConfig::Xtal32kClk] + ::soc::clocks::TimgCalibrationClockConfig::RcFastDivClk, #[cfg(use_xtal32k)] + crate ::soc::clocks::TimgCalibrationClockConfig::Xtal32kClk] }; ("clock_tree.timg.function_clock") => { [crate ::soc::clocks::TimgFunctionClockConfig::XtalClk, crate @@ -569,10 +633,42 @@ macro_rules! property { ("clock_tree.i2c.function_clock.div_num") => { (0, 255) }; + ("clock_tree.tsens.sclk") => { + [crate ::soc::clocks::TsensSclkConfig::RcFast, crate + ::soc::clocks::TsensSclkConfig::Xtal] + }; ("clock_tree.spi.function_clock") => { [crate ::soc::clocks::SpiFunctionClockConfig::Xtal, crate ::soc::clocks::SpiFunctionClockConfig::Pll80m] }; + ("clock_tree.i2s.tx_clk.sclk") => { + [crate ::soc::clocks::I2sClkSclk::Xtal, crate ::soc::clocks::I2sClkSclk::Pll160m] + }; + ("clock_tree.i2s.tx_clk.div_num") => { + (1, 255) + }; + ("clock_tree.i2s.tx_clk.div_a") => { + (1, 511) + }; + ("clock_tree.i2s.tx_clk.div_b") => { + (0, 511) + }; + ("clock_tree.i2s.rx_clk.sclk") => { + [crate ::soc::clocks::I2sClkSclk::Xtal, crate ::soc::clocks::I2sClkSclk::Pll160m] + }; + ("clock_tree.i2s.rx_clk.div_num") => { + (1, 255) + }; + ("clock_tree.i2s.rx_clk.div_a") => { + (1, 511) + }; + ("clock_tree.i2s.rx_clk.div_b") => { + (0, 511) + }; + ("clock_tree.i2s.mclk_out") => { + [crate ::soc::clocks::I2sMclkOutConfig::Tx, crate + ::soc::clocks::I2sMclkOutConfig::Rx] + }; } #[macro_export] #[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] @@ -1029,21 +1125,21 @@ macro_rules! for_each_interrupt { macro_rules! _for_each_inner_interrupt { $(($pattern) => $code;)* ($other : tt) => {} } _for_each_inner_interrupt!(([disabled 0] 0)); _for_each_inner_interrupt!(([reserved 0] 1)); - _for_each_inner_interrupt!(([direct_bindable 0] 2)); - _for_each_inner_interrupt!(([direct_bindable 1] 3)); - _for_each_inner_interrupt!(([direct_bindable 2] 4)); - _for_each_inner_interrupt!(([direct_bindable 3] 5)); - _for_each_inner_interrupt!(([direct_bindable 4] 6)); - _for_each_inner_interrupt!(([direct_bindable 5] 7)); - _for_each_inner_interrupt!(([direct_bindable 6] 8)); - _for_each_inner_interrupt!(([direct_bindable 7] 9)); - _for_each_inner_interrupt!(([direct_bindable 8] 10)); - _for_each_inner_interrupt!(([direct_bindable 9] 11)); - _for_each_inner_interrupt!(([direct_bindable 10] 12)); - _for_each_inner_interrupt!(([direct_bindable 11] 13)); - _for_each_inner_interrupt!(([direct_bindable 12] 14)); - _for_each_inner_interrupt!(([direct_bindable 13] 15)); - _for_each_inner_interrupt!(([direct_bindable 14] 16)); + _for_each_inner_interrupt!(([context_switch 0] 2)); + _for_each_inner_interrupt!(([direct_bindable 0] 3)); + _for_each_inner_interrupt!(([direct_bindable 1] 4)); + _for_each_inner_interrupt!(([direct_bindable 2] 5)); + _for_each_inner_interrupt!(([direct_bindable 3] 6)); + _for_each_inner_interrupt!(([direct_bindable 4] 7)); + _for_each_inner_interrupt!(([direct_bindable 5] 8)); + _for_each_inner_interrupt!(([direct_bindable 6] 9)); + _for_each_inner_interrupt!(([direct_bindable 7] 10)); + _for_each_inner_interrupt!(([direct_bindable 8] 11)); + _for_each_inner_interrupt!(([direct_bindable 9] 12)); + _for_each_inner_interrupt!(([direct_bindable 10] 13)); + _for_each_inner_interrupt!(([direct_bindable 11] 14)); + _for_each_inner_interrupt!(([direct_bindable 12] 15)); + _for_each_inner_interrupt!(([direct_bindable 13] 16)); _for_each_inner_interrupt!(([vector 0] 17)); _for_each_inner_interrupt!(([vector 1] 18)); _for_each_inner_interrupt!(([vector 2] 19)); _for_each_inner_interrupt!(([vector 3] 20)); _for_each_inner_interrupt!(([vector @@ -1055,11 +1151,11 @@ macro_rules! for_each_interrupt { _for_each_inner_interrupt!(([vector 12] 29)); _for_each_inner_interrupt!(([vector 13] 30)); _for_each_inner_interrupt!(([vector 14] 31)); _for_each_inner_interrupt!((all([disabled 0] 0), ([reserved 0] 1), - ([direct_bindable 0] 2), ([direct_bindable 1] 3), ([direct_bindable 2] 4), - ([direct_bindable 3] 5), ([direct_bindable 4] 6), ([direct_bindable 5] 7), - ([direct_bindable 6] 8), ([direct_bindable 7] 9), ([direct_bindable 8] 10), - ([direct_bindable 9] 11), ([direct_bindable 10] 12), ([direct_bindable 11] 13), - ([direct_bindable 12] 14), ([direct_bindable 13] 15), ([direct_bindable 14] 16), + ([context_switch 0] 2), ([direct_bindable 0] 3), ([direct_bindable 1] 4), + ([direct_bindable 2] 5), ([direct_bindable 3] 6), ([direct_bindable 4] 7), + ([direct_bindable 5] 8), ([direct_bindable 6] 9), ([direct_bindable 7] 10), + ([direct_bindable 8] 11), ([direct_bindable 9] 12), ([direct_bindable 10] 13), + ([direct_bindable 11] 14), ([direct_bindable 12] 15), ([direct_bindable 13] 16), ([vector 0] 17), ([vector 1] 18), ([vector 2] 19), ([vector 3] 20), ([vector 4] 21), ([vector 5] 22), ([vector 6] 23), ([vector 7] 24), ([vector 8] 25), ([vector 9] 26), ([vector 10] 27), ([vector 11] 28), ([vector 12] 29), ([vector 13] 30), @@ -1072,20 +1168,19 @@ macro_rules! for_each_classified_interrupt { ($($pattern:tt => $code:tt;)*) => { macro_rules! _for_each_inner_classified_interrupt { $(($pattern) => $code;)* ($other : tt) => {} } _for_each_inner_classified_interrupt!(([direct_bindable 0] - 2)); _for_each_inner_classified_interrupt!(([direct_bindable 1] 3)); - _for_each_inner_classified_interrupt!(([direct_bindable 2] 4)); - _for_each_inner_classified_interrupt!(([direct_bindable 3] 5)); - _for_each_inner_classified_interrupt!(([direct_bindable 4] 6)); - _for_each_inner_classified_interrupt!(([direct_bindable 5] 7)); - _for_each_inner_classified_interrupt!(([direct_bindable 6] 8)); - _for_each_inner_classified_interrupt!(([direct_bindable 7] 9)); - _for_each_inner_classified_interrupt!(([direct_bindable 8] 10)); - _for_each_inner_classified_interrupt!(([direct_bindable 9] 11)); - _for_each_inner_classified_interrupt!(([direct_bindable 10] 12)); - _for_each_inner_classified_interrupt!(([direct_bindable 11] 13)); - _for_each_inner_classified_interrupt!(([direct_bindable 12] 14)); - _for_each_inner_classified_interrupt!(([direct_bindable 13] 15)); - _for_each_inner_classified_interrupt!(([direct_bindable 14] 16)); + 3)); _for_each_inner_classified_interrupt!(([direct_bindable 1] 4)); + _for_each_inner_classified_interrupt!(([direct_bindable 2] 5)); + _for_each_inner_classified_interrupt!(([direct_bindable 3] 6)); + _for_each_inner_classified_interrupt!(([direct_bindable 4] 7)); + _for_each_inner_classified_interrupt!(([direct_bindable 5] 8)); + _for_each_inner_classified_interrupt!(([direct_bindable 6] 9)); + _for_each_inner_classified_interrupt!(([direct_bindable 7] 10)); + _for_each_inner_classified_interrupt!(([direct_bindable 8] 11)); + _for_each_inner_classified_interrupt!(([direct_bindable 9] 12)); + _for_each_inner_classified_interrupt!(([direct_bindable 10] 13)); + _for_each_inner_classified_interrupt!(([direct_bindable 11] 14)); + _for_each_inner_classified_interrupt!(([direct_bindable 12] 15)); + _for_each_inner_classified_interrupt!(([direct_bindable 13] 16)); _for_each_inner_classified_interrupt!(([vector 0] 17)); _for_each_inner_classified_interrupt!(([vector 1] 18)); _for_each_inner_classified_interrupt!(([vector 2] 19)); @@ -1102,17 +1197,19 @@ macro_rules! for_each_classified_interrupt { _for_each_inner_classified_interrupt!(([vector 13] 30)); _for_each_inner_classified_interrupt!(([vector 14] 31)); _for_each_inner_classified_interrupt!(([reserved 0] 1)); - _for_each_inner_classified_interrupt!((direct_bindable([direct_bindable 0] 2), - ([direct_bindable 1] 3), ([direct_bindable 2] 4), ([direct_bindable 3] 5), - ([direct_bindable 4] 6), ([direct_bindable 5] 7), ([direct_bindable 6] 8), - ([direct_bindable 7] 9), ([direct_bindable 8] 10), ([direct_bindable 9] 11), - ([direct_bindable 10] 12), ([direct_bindable 11] 13), ([direct_bindable 12] 14), - ([direct_bindable 13] 15), ([direct_bindable 14] 16))); + _for_each_inner_classified_interrupt!(([context_switch 0] 2)); + _for_each_inner_classified_interrupt!((direct_bindable([direct_bindable 0] 3), + ([direct_bindable 1] 4), ([direct_bindable 2] 5), ([direct_bindable 3] 6), + ([direct_bindable 4] 7), ([direct_bindable 5] 8), ([direct_bindable 6] 9), + ([direct_bindable 7] 10), ([direct_bindable 8] 11), ([direct_bindable 9] 12), + ([direct_bindable 10] 13), ([direct_bindable 11] 14), ([direct_bindable 12] 15), + ([direct_bindable 13] 16))); _for_each_inner_classified_interrupt!((vector([vector 0] 17), ([vector 1] 18), ([vector 2] 19), ([vector 3] 20), ([vector 4] 21), ([vector 5] 22), ([vector 6] 23), ([vector 7] 24), ([vector 8] 25), ([vector 9] 26), ([vector 10] 27), ([vector 11] 28), ([vector 12] 29), ([vector 13] 30), ([vector 14] 31))); _for_each_inner_classified_interrupt!((reserved([reserved 0] 1))); + _for_each_inner_classified_interrupt!((context_switch([context_switch 0] 2))); }; } #[macro_export] @@ -1192,6 +1289,7 @@ macro_rules! for_each_sw_interrupt { /// /// // XTAL32K_CLK /// +/// #[cfg(use_xtal32k)] /// fn enable_xtal32k_clk_impl(_clocks: &mut ClockTree, _en: bool) { /// todo!() /// } @@ -1334,6 +1432,26 @@ macro_rules! for_each_sw_interrupt { /// todo!() /// } /// +/// // BLE_LP_XTAL_CLK +/// +/// fn enable_ble_lp_xtal_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// // BLE_LP_CLK +/// +/// fn enable_ble_lp_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_ble_lp_clk_impl( +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: BleLpClkConfig, +/// ) { +/// todo!() +/// } +/// /// // RTC_FAST_CLK /// /// fn enable_rtc_fast_clk_impl(_clocks: &mut ClockTree, _en: bool) { @@ -1382,6 +1500,13 @@ macro_rules! for_each_sw_interrupt { /// todo!() /// } /// +/// impl AdcInstance { +/// // ADC_FUNCTION_CLOCK +/// +/// fn enable_function_clock_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// } /// impl SdmInstance { /// // SDM_FUNCTION_CLOCK /// @@ -1405,6 +1530,52 @@ macro_rules! for_each_sw_interrupt { /// todo!() /// } /// } +/// impl I2sInstance { +/// // I2S_TX_CLK +/// +/// fn enable_tx_clk_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_tx_clk_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: I2sClkConfig, +/// ) { +/// todo!() +/// } +/// +/// // I2S_RX_CLK +/// +/// fn enable_rx_clk_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_rx_clk_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: I2sClkConfig, +/// ) { +/// todo!() +/// } +/// +/// // I2S_MCLK_OUT +/// +/// fn enable_mclk_out_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_mclk_out_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: I2sMclkOutConfig, +/// ) { +/// todo!() +/// } +/// } /// impl RmtInstance { /// // RMT_SCLK /// @@ -1505,9 +1676,30 @@ macro_rules! for_each_sw_interrupt { /// todo!() /// } /// } +/// impl TsensInstance { +/// // TSENS_SCLK +/// +/// fn enable_sclk_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_sclk_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: TsensSclkConfig, +/// ) { +/// todo!() +/// } +/// } /// ``` macro_rules! define_clock_tree_types { () => { + #[derive(Clone, Copy, PartialEq, Eq, Debug)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum AdcInstance { + ApbSaradc = 0, + } #[derive(Clone, Copy, PartialEq, Eq, Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum SdmInstance { @@ -1520,6 +1712,11 @@ macro_rules! define_clock_tree_types { } #[derive(Clone, Copy, PartialEq, Eq, Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum I2sInstance { + I2s0 = 0, + } + #[derive(Clone, Copy, PartialEq, Eq, Debug)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum RmtInstance { Rmt = 0, } @@ -1540,6 +1737,11 @@ macro_rules! define_clock_tree_types { Uart0 = 0, Uart1 = 1, } + #[derive(Clone, Copy, PartialEq, Eq, Debug)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum TsensInstance { + Tsens = 0, + } /// Selects the output frequency of `XTAL_CLK`. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] @@ -1602,7 +1804,7 @@ macro_rules! define_clock_tree_types { ); Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -1674,7 +1876,7 @@ macro_rules! define_clock_tree_types { ); Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -1682,6 +1884,7 @@ macro_rules! define_clock_tree_types { #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum RtcSlowClkConfig { + #[cfg(use_xtal32k)] /// Selects `XTAL32K_CLK`. Xtal32k, /// Selects `RC_SLOW_CLK`. @@ -1689,6 +1892,15 @@ macro_rules! define_clock_tree_types { /// Selects `RC_FAST_DIV_CLK`. RcFast, } + /// The list of clock signals that the `BLE_LP_CLK` multiplexer can output. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum BleLpClkConfig { + /// Selects `BLE_LP_XTAL_CLK`. + Xtal, + /// Selects `RTC_SLOW_CLK`. + RtcSlow, + } /// The list of clock signals that the `RTC_FAST_CLK` multiplexer can output. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] @@ -1706,6 +1918,7 @@ macro_rules! define_clock_tree_types { Xtal, /// Selects `RC_FAST_CLK`. RcFast, + #[cfg(use_xtal32k)] /// Selects `XTAL32K_CLK`. Xtal32k, /// Selects `RTC_SLOW_CLK`. @@ -1727,6 +1940,7 @@ macro_rules! define_clock_tree_types { RcSlowClk, /// Selects `RC_FAST_DIV_CLK`. RcFastDivClk, + #[cfg(use_xtal32k)] /// Selects `XTAL32K_CLK`. Xtal32kClk, } @@ -1762,13 +1976,89 @@ macro_rules! define_clock_tree_types { ); Self { sclk, div_num } } - pub(crate) fn sclk(self) -> I2cFunctionClockSclk { + pub fn sclk(self) -> I2cFunctionClockSclk { self.sclk } - pub(crate) fn div_num(self) -> u32 { + pub fn div_num(self) -> u32 { self.div_num as u32 } } + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum I2sClkSclk { + /// Selects `XTAL_CLK`. + Xtal, + #[default] + /// Selects `PLL_160M`. + Pll160m, + } + /// Configures the `I2S0_TX_CLK` clock node. + /// + /// The output is calculated as `OUTPUT = (sclk * div_a) / (div_num * div_a + div_b)`. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub struct I2sClkConfig { + sclk: I2sClkSclk, + div_num: u32, + div_a: u32, + div_b: u32, + } + impl I2sClkConfig { + /// Creates a new configuration for the TX_CLK clock node. + /// + /// ## Panics + /// + /// Panics if the div_num value is outside the + /// valid range (1 ..= 255). + /// + /// Panics if the div_a value is outside the + /// valid range (1 ..= 511). + /// + /// Panics if the div_b value is outside the + /// valid range (0 ..= 511). + pub const fn new(sclk: I2sClkSclk, div_num: u32, div_a: u32, div_b: u32) -> Self { + ::core::assert!( + div_num >= 1 && div_num <= 255, + "`I2S0_TX_CLK` div_num must be between 1 and 255 (inclusive)." + ); + ::core::assert!( + div_a >= 1 && div_a <= 511, + "`I2S0_TX_CLK` div_a must be between 1 and 511 (inclusive)." + ); + ::core::assert!( + div_b <= 511, + "`I2S0_TX_CLK` div_b must be between 0 and 511 (inclusive)." + ); + Self { + sclk, + div_num, + div_a, + div_b, + } + } + pub fn sclk(self) -> I2sClkSclk { + self.sclk + } + pub fn div_num(self) -> u32 { + self.div_num as u32 + } + pub fn div_a(self) -> u32 { + self.div_a as u32 + } + pub fn div_b(self) -> u32 { + self.div_b as u32 + } + } + /// The list of clock signals that the `I2S0_MCLK_OUT` multiplexer can output. + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum I2sMclkOutConfig { + /// Selects `TX_CLK`. + Tx, + #[default] + /// Selects `RX_CLK`. + Rx, + } /// The list of clock signals that the `RMT_SCLK` multiplexer can output. #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] @@ -1785,9 +2075,9 @@ macro_rules! define_clock_tree_types { #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum SpiFunctionClockConfig { - #[default] /// Selects `XTAL_CLK`. Xtal, + #[default] /// Selects `PLL_80M`. Pll80m, } @@ -1845,10 +2135,10 @@ macro_rules! define_clock_tree_types { ); Self { sclk, div_num } } - pub(crate) fn sclk(self) -> UartFunctionClockSclk { + pub fn sclk(self) -> UartFunctionClockSclk { self.sclk } - pub(crate) fn div_num(self) -> u32 { + pub fn div_num(self) -> u32 { self.div_num as u32 } } @@ -1886,13 +2176,23 @@ macro_rules! define_clock_tree_types { integral, } } - pub(crate) fn fractional(self) -> u32 { + pub fn fractional(self) -> u32 { self.fractional as u32 } - pub(crate) fn integral(self) -> u32 { + pub fn integral(self) -> u32 { self.integral as u32 } } + /// The list of clock signals that the `TSENS_SCLK` multiplexer can output. + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum TsensSclkConfig { + /// Selects `RC_FAST_CLK`. + RcFast, + #[default] + /// Selects `XTAL_CLK`. + Xtal, + } /// Represents the device's clock tree. pub struct ClockTree { xtal_clk: Option, @@ -1905,29 +2205,42 @@ macro_rules! define_clock_tree_types { cpu_clk: Option, rc_fast_clk_div_n: Option, rtc_slow_clk: Option, + ble_lp_clk: Option, rtc_fast_clk: Option, low_power_clk: Option, timg_calibration_clock: Option, i2c_function_clock: [Option; 1], + i2s_tx_clk: [Option; 1], + i2s_rx_clk: [Option; 1], + i2s_mclk_out: [Option; 1], rmt_sclk: [Option; 1], spi_function_clock: [Option; 1], timg_function_clock: [Option; 2], timg_wdt_clock: [Option; 2], uart_function_clock: [Option; 2], uart_baud_rate_generator: [Option; 2], + tsens_sclk: [Option; 1], rc_fast_clk_refcount: u32, + #[cfg(use_xtal32k)] xtal32k_clk_refcount: u32, rc_slow_clk_refcount: u32, rc_fast_div_clk_refcount: u32, apb_clk_refcount: u32, crypto_clk_refcount: u32, pll_80m_refcount: u32, + pll_160m_refcount: u32, + rtc_slow_clk_refcount: u32, + ble_lp_clk_refcount: u32, rtc_fast_clk_refcount: u32, low_power_clk_refcount: u32, uart_mem_clk_refcount: u32, timg_calibration_clock_refcount: u32, + adc_function_clock_refcount: [u32; 1], sdm_function_clock_refcount: [u32; 1], i2c_function_clock_refcount: [u32; 1], + i2s_tx_clk_refcount: [u32; 1], + i2s_rx_clk_refcount: [u32; 1], + i2s_mclk_out_refcount: [u32; 1], rmt_sclk_refcount: [u32; 1], spi_function_clock_refcount: [u32; 1], timg_function_clock_refcount: [u32; 2], @@ -1935,6 +2248,7 @@ macro_rules! define_clock_tree_types { uart_function_clock_refcount: [u32; 2], uart_mem_clock_refcount: [u32; 2], uart_baud_rate_generator_refcount: [u32; 2], + tsens_sclk_refcount: [u32; 1], } impl ClockTree { /// Locks the clock tree for exclusive access. @@ -1981,6 +2295,10 @@ macro_rules! define_clock_tree_types { pub fn rtc_slow_clk(&self) -> Option { self.rtc_slow_clk } + /// Returns the current configuration of the BLE_LP_CLK clock tree node + pub fn ble_lp_clk(&self) -> Option { + self.ble_lp_clk + } /// Returns the current configuration of the RTC_FAST_CLK clock tree node pub fn rtc_fast_clk(&self) -> Option { self.rtc_fast_clk @@ -1997,6 +2315,18 @@ macro_rules! define_clock_tree_types { pub fn i2c0_function_clock(&self) -> Option { self.i2c_function_clock[I2cInstance::I2c0 as usize] } + /// Returns the current configuration of the I2S0_TX_CLK clock tree node + pub fn i2s0_tx_clk(&self) -> Option { + self.i2s_tx_clk[I2sInstance::I2s0 as usize] + } + /// Returns the current configuration of the I2S0_RX_CLK clock tree node + pub fn i2s0_rx_clk(&self) -> Option { + self.i2s_rx_clk[I2sInstance::I2s0 as usize] + } + /// Returns the current configuration of the I2S0_MCLK_OUT clock tree node + pub fn i2s0_mclk_out(&self) -> Option { + self.i2s_mclk_out[I2sInstance::I2s0 as usize] + } /// Returns the current configuration of the RMT_SCLK clock tree node pub fn rmt_sclk(&self) -> Option { self.rmt_sclk[RmtInstance::Rmt as usize] @@ -2037,6 +2367,10 @@ macro_rules! define_clock_tree_types { pub fn uart1_baud_rate_generator(&self) -> Option { self.uart_baud_rate_generator[UartInstance::Uart1 as usize] } + /// Returns the current configuration of the TSENS_SCLK clock tree node + pub fn tsens_sclk(&self) -> Option { + self.tsens_sclk[TsensInstance::Tsens as usize] + } } static CLOCK_TREE: ::esp_sync::NonReentrantMutex = ::esp_sync::NonReentrantMutex::new(ClockTree { @@ -2050,29 +2384,42 @@ macro_rules! define_clock_tree_types { cpu_clk: None, rc_fast_clk_div_n: None, rtc_slow_clk: None, + ble_lp_clk: None, rtc_fast_clk: None, low_power_clk: None, timg_calibration_clock: None, i2c_function_clock: [None; 1], + i2s_tx_clk: [None; 1], + i2s_rx_clk: [None; 1], + i2s_mclk_out: [None; 1], rmt_sclk: [None; 1], spi_function_clock: [None; 1], timg_function_clock: [None; 2], timg_wdt_clock: [None; 2], uart_function_clock: [None; 2], uart_baud_rate_generator: [None; 2], + tsens_sclk: [None; 1], rc_fast_clk_refcount: 0, + #[cfg(use_xtal32k)] xtal32k_clk_refcount: 0, rc_slow_clk_refcount: 0, rc_fast_div_clk_refcount: 0, apb_clk_refcount: 0, crypto_clk_refcount: 0, pll_80m_refcount: 0, + pll_160m_refcount: 0, + rtc_slow_clk_refcount: 0, + ble_lp_clk_refcount: 0, rtc_fast_clk_refcount: 0, low_power_clk_refcount: 0, uart_mem_clk_refcount: 0, timg_calibration_clock_refcount: 0, + adc_function_clock_refcount: [0; 1], sdm_function_clock_refcount: [0; 1], i2c_function_clock_refcount: [0; 1], + i2s_tx_clk_refcount: [0; 1], + i2s_rx_clk_refcount: [0; 1], + i2s_mclk_out_refcount: [0; 1], rmt_sclk_refcount: [0; 1], spi_function_clock_refcount: [0; 1], timg_function_clock_refcount: [0; 2], @@ -2080,6 +2427,7 @@ macro_rules! define_clock_tree_types { uart_function_clock_refcount: [0; 2], uart_mem_clock_refcount: [0; 2], uart_baud_rate_generator_refcount: [0; 2], + tsens_sclk_refcount: [0; 1], }); static XTAL_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); @@ -2097,6 +2445,8 @@ macro_rules! define_clock_tree_types { ::core::sync::atomic::AtomicU32::new(0); static RTC_SLOW_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); + static BLE_LP_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(0); static RTC_FAST_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); static LOW_POWER_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = @@ -2105,8 +2455,16 @@ macro_rules! define_clock_tree_types { ::core::sync::atomic::AtomicU32::new(0); static I2C_FUNCTION_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; + static I2S_TX_CLK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; + static I2S_RX_CLK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; + static I2S_MCLK_OUT_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; static SPI_FUNCTION_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; + static TSENS_SCLK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; static APB_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); static CRYPTO_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = @@ -2121,6 +2479,160 @@ macro_rules! define_clock_tree_types { [const { ::core::sync::atomic::AtomicU32::new(0) }; 2]; static UART_BAUD_RATE_GENERATOR_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 2] = [const { ::core::sync::atomic::AtomicU32::new(0) }; 2]; + /// The clock sources of the device. + /// + /// A clock source is a node of the clock tree that other nodes derive their output + /// from. Ask a node which source it runs on with its `..._root_source` function. + #[derive(Debug, enumset::EnumSetType)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum ClockSource { + /// `XTAL_CLK`. + XtalClk, + /// `RC_FAST_CLK`. + RcFastClk, + #[cfg(use_xtal32k)] + /// `XTAL32K_CLK`. + Xtal32kClk, + /// `RC_SLOW_CLK`. + RcSlowClk, + } + /// Returns the clock source that `XTAL_CLK` currently runs on. + pub fn xtal_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::XtalClk) + } + /// Returns the clock source that `PLL_CLK` currently runs on. + pub fn pll_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `RC_FAST_CLK` currently runs on. + pub fn rc_fast_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::RcFastClk) + } + #[cfg(use_xtal32k)] + /// Returns the clock source that `XTAL32K_CLK` currently runs on. + pub fn xtal32k_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::Xtal32kClk) + } + /// Returns the clock source that `RC_SLOW_CLK` currently runs on. + pub fn rc_slow_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::RcSlowClk) + } + /// Returns the clock source that `RC_FAST_DIV_CLK` currently runs on. + pub fn rc_fast_div_clk_root_source(clocks: &mut ClockTree) -> Option { + rc_fast_clk_root_source(clocks) + } + /// Returns the clock source that `SYSTEM_PRE_DIV_IN` currently runs on. + pub fn system_pre_div_in_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.system_pre_div_in?; + match config { + SystemPreDivInConfig::Xtal => xtal_clk_root_source(clocks), + SystemPreDivInConfig::RcFast => rc_fast_clk_root_source(clocks), + } + } + /// Returns the clock source that `SYSTEM_PRE_DIV` currently runs on. + pub fn system_pre_div_root_source(clocks: &mut ClockTree) -> Option { + system_pre_div_in_root_source(clocks) + } + /// Returns the clock source that `CPU_PLL_DIV_OUT` currently runs on. + pub fn cpu_pll_div_out_root_source(clocks: &mut ClockTree) -> Option { + pll_clk_root_source(clocks) + } + /// Returns the clock source that `CPU_CLK` currently runs on. + pub fn cpu_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.cpu_clk?; + match config { + CpuClkConfig::Xtal => system_pre_div_root_source(clocks), + CpuClkConfig::RcFast => system_pre_div_root_source(clocks), + CpuClkConfig::Pll => cpu_pll_div_out_root_source(clocks), + } + } + /// Returns the clock source that `PLL_80M` currently runs on. + pub fn pll_80m_root_source(clocks: &mut ClockTree) -> Option { + cpu_clk_root_source(clocks) + } + /// Returns the clock source that `PLL_160M` currently runs on. + pub fn pll_160m_root_source(clocks: &mut ClockTree) -> Option { + cpu_clk_root_source(clocks) + } + /// Returns the clock source that `RC_FAST_CLK_DIV_N` currently runs on. + pub fn rc_fast_clk_div_n_root_source(clocks: &mut ClockTree) -> Option { + rc_fast_clk_root_source(clocks) + } + /// Returns the clock source that `XTAL_DIV_CLK` currently runs on. + pub fn xtal_div_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `RTC_SLOW_CLK` currently runs on. + pub fn rtc_slow_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.rtc_slow_clk?; + match config { + #[cfg(use_xtal32k)] + RtcSlowClkConfig::Xtal32k => xtal32k_clk_root_source(clocks), + RtcSlowClkConfig::RcSlow => rc_slow_clk_root_source(clocks), + RtcSlowClkConfig::RcFast => rc_fast_div_clk_root_source(clocks), + } + } + /// Returns the clock source that `BLE_LP_XTAL_CLK` currently runs on. + pub fn ble_lp_xtal_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `BLE_LP_CLK` currently runs on. + pub fn ble_lp_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.ble_lp_clk?; + match config { + BleLpClkConfig::Xtal => ble_lp_xtal_clk_root_source(clocks), + BleLpClkConfig::RtcSlow => rtc_slow_clk_root_source(clocks), + } + } + /// Returns the clock source that `RTC_FAST_CLK` currently runs on. + pub fn rtc_fast_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.rtc_fast_clk?; + match config { + RtcFastClkConfig::Xtal => xtal_div_clk_root_source(clocks), + RtcFastClkConfig::Rc => rc_fast_clk_div_n_root_source(clocks), + } + } + /// Returns the clock source that `LOW_POWER_CLK` currently runs on. + pub fn low_power_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.low_power_clk?; + match config { + LowPowerClkConfig::Xtal => xtal_clk_root_source(clocks), + LowPowerClkConfig::RcFast => rc_fast_clk_root_source(clocks), + #[cfg(use_xtal32k)] + LowPowerClkConfig::Xtal32k => xtal32k_clk_root_source(clocks), + LowPowerClkConfig::RtcSlow => rtc_slow_clk_root_source(clocks), + } + } + /// Returns the clock source that `UART_MEM_CLK` currently runs on. + pub fn uart_mem_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `TIMG_CALIBRATION_CLOCK` currently runs on. + pub fn timg_calibration_clock_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.timg_calibration_clock?; + match config { + TimgCalibrationClockConfig::RcSlowClk => rc_slow_clk_root_source(clocks), + TimgCalibrationClockConfig::RcFastDivClk => rc_fast_div_clk_root_source(clocks), + #[cfg(use_xtal32k)] + TimgCalibrationClockConfig::Xtal32kClk => xtal32k_clk_root_source(clocks), + } + } + /// Returns the clock source that `APB_CLK` currently runs on. + pub fn apb_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.apb_clk?; + match config { + ApbClkConfig::Pll80m => pll_80m_root_source(clocks), + ApbClkConfig::Cpu => cpu_clk_root_source(clocks), + } + } + /// Returns the clock source that `CRYPTO_CLK` currently runs on. + pub fn crypto_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.crypto_clk?; + match config { + CryptoClkConfig::Pll160m => pll_160m_root_source(clocks), + CryptoClkConfig::Cpu => cpu_clk_root_source(clocks), + } + } pub fn configure_xtal_clk(clocks: &mut ClockTree, config: XtalClkConfig) { let old_config = clocks.xtal_clk.replace(config); refresh_xtal_clk_downstream(clocks); @@ -2131,8 +2643,7 @@ macro_rules! define_clock_tree_types { } fn request_xtal_clk(_clocks: &mut ClockTree) {} fn release_xtal_clk(_clocks: &mut ClockTree) {} - #[allow(unused_variables)] - pub fn xtal_clk_config_frequency(clocks: &mut ClockTree, config: XtalClkConfig) -> u32 { + pub fn xtal_clk_config_frequency(config: XtalClkConfig) -> u32 { config.value() } pub fn xtal_clk_frequency() -> u32 { @@ -2147,19 +2658,16 @@ macro_rules! define_clock_tree_types { clocks.pll_clk } pub fn request_pll_clk(clocks: &mut ClockTree) { - trace!("Requesting PLL_CLK"); trace!("Enabling PLL_CLK"); request_xtal_clk(clocks); enable_pll_clk_impl(clocks, true); } pub fn release_pll_clk(clocks: &mut ClockTree) { - trace!("Releasing PLL_CLK"); trace!("Disabling PLL_CLK"); enable_pll_clk_impl(clocks, false); release_xtal_clk(clocks); } - #[allow(unused_variables)] - pub fn pll_clk_config_frequency(clocks: &mut ClockTree, config: PllClkConfig) -> u32 { + pub fn pll_clk_config_frequency(config: PllClkConfig) -> u32 { config.value() } pub fn pll_clk_frequency() -> u32 { @@ -2182,9 +2690,31 @@ macro_rules! define_clock_tree_types { enable_rc_fast_clk_impl(clocks, false); } } - pub fn rc_fast_clk_frequency() -> u32 { + static RC_FAST_CLK_FREQUENCY: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(rc_fast_clk_nominal_frequency()); + pub const fn rc_fast_clk_nominal_frequency() -> u32 { 17500000 } + pub fn rc_fast_clk_frequency() -> u32 { + RC_FAST_CLK_FREQUENCY.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn set_rc_fast_clk_frequency(clocks: &mut ClockTree, frequency: u32) { + if !(8750000..=26250000).contains(&frequency) { + warn!( + "Ignoring out-of-range RC_FAST_CLK frequency: {} Hz", + frequency + ); + return; + } + debug!( + "Updating RC_FAST_CLK frequency to {} Hz (nominal {} Hz)", + frequency, + rc_fast_clk_nominal_frequency() + ); + RC_FAST_CLK_FREQUENCY.store(frequency, ::core::sync::atomic::Ordering::Release); + refresh_rc_fast_clk_downstream(clocks); + } + #[cfg(use_xtal32k)] pub fn request_xtal32k_clk(clocks: &mut ClockTree) { trace!("Requesting XTAL32K_CLK"); if increment_reference_count(&mut clocks.xtal32k_clk_refcount) { @@ -2192,6 +2722,7 @@ macro_rules! define_clock_tree_types { enable_xtal32k_clk_impl(clocks, true); } } + #[cfg(use_xtal32k)] pub fn release_xtal32k_clk(clocks: &mut ClockTree) { trace!("Releasing XTAL32K_CLK"); if decrement_reference_count(&mut clocks.xtal32k_clk_refcount) { @@ -2199,6 +2730,7 @@ macro_rules! define_clock_tree_types { enable_xtal32k_clk_impl(clocks, false); } } + #[cfg(use_xtal32k)] pub fn xtal32k_clk_frequency() -> u32 { 32768 } @@ -2216,9 +2748,30 @@ macro_rules! define_clock_tree_types { enable_rc_slow_clk_impl(clocks, false); } } - pub fn rc_slow_clk_frequency() -> u32 { + static RC_SLOW_CLK_FREQUENCY: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(rc_slow_clk_nominal_frequency()); + pub const fn rc_slow_clk_nominal_frequency() -> u32 { 136000 } + pub fn rc_slow_clk_frequency() -> u32 { + RC_SLOW_CLK_FREQUENCY.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn set_rc_slow_clk_frequency(clocks: &mut ClockTree, frequency: u32) { + if !(68000..=204000).contains(&frequency) { + warn!( + "Ignoring out-of-range RC_SLOW_CLK frequency: {} Hz", + frequency + ); + return; + } + debug!( + "Updating RC_SLOW_CLK frequency to {} Hz (nominal {} Hz)", + frequency, + rc_slow_clk_nominal_frequency() + ); + RC_SLOW_CLK_FREQUENCY.store(frequency, ::core::sync::atomic::Ordering::Release); + refresh_rc_slow_clk_downstream(clocks); + } pub fn request_rc_fast_div_clk(clocks: &mut ClockTree) { trace!("Requesting RC_FAST_DIV_CLK"); if increment_reference_count(&mut clocks.rc_fast_div_clk_refcount) { @@ -2263,7 +2816,6 @@ macro_rules! define_clock_tree_types { clocks.system_pre_div_in } pub fn request_system_pre_div_in(clocks: &mut ClockTree) { - trace!("Requesting SYSTEM_PRE_DIV_IN"); trace!("Enabling SYSTEM_PRE_DIV_IN"); match unwrap!(clocks.system_pre_div_in) { SystemPreDivInConfig::Xtal => request_xtal_clk(clocks), @@ -2272,7 +2824,6 @@ macro_rules! define_clock_tree_types { enable_system_pre_div_in_impl(clocks, true); } pub fn release_system_pre_div_in(clocks: &mut ClockTree) { - trace!("Releasing SYSTEM_PRE_DIV_IN"); trace!("Disabling SYSTEM_PRE_DIV_IN"); enable_system_pre_div_in_impl(clocks, false); match unwrap!(clocks.system_pre_div_in) { @@ -2280,11 +2831,7 @@ macro_rules! define_clock_tree_types { SystemPreDivInConfig::RcFast => release_rc_fast_clk(clocks), } } - #[allow(unused_variables)] - pub fn system_pre_div_in_config_frequency( - clocks: &mut ClockTree, - config: SystemPreDivInConfig, - ) -> u32 { + pub fn system_pre_div_in_config_frequency(config: SystemPreDivInConfig) -> u32 { match config { SystemPreDivInConfig::Xtal => xtal_clk_frequency(), SystemPreDivInConfig::RcFast => rc_fast_clk_frequency(), @@ -2294,10 +2841,7 @@ macro_rules! define_clock_tree_types { SYSTEM_PRE_DIV_IN_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn system_pre_div_in_source_frequency(source: SystemPreDivInConfig) -> u32 { - match source { - SystemPreDivInConfig::Xtal => xtal_clk_frequency(), - SystemPreDivInConfig::RcFast => rc_fast_clk_frequency(), - } + system_pre_div_in_config_frequency(source) } pub fn configure_system_pre_div(clocks: &mut ClockTree, config: SystemPreDivConfig) { let old_config = clocks.system_pre_div.replace(config); @@ -2308,22 +2852,16 @@ macro_rules! define_clock_tree_types { clocks.system_pre_div } pub fn request_system_pre_div(clocks: &mut ClockTree) { - trace!("Requesting SYSTEM_PRE_DIV"); trace!("Enabling SYSTEM_PRE_DIV"); request_system_pre_div_in(clocks); enable_system_pre_div_impl(clocks, true); } pub fn release_system_pre_div(clocks: &mut ClockTree) { - trace!("Releasing SYSTEM_PRE_DIV"); trace!("Disabling SYSTEM_PRE_DIV"); enable_system_pre_div_impl(clocks, false); release_system_pre_div_in(clocks); } - #[allow(unused_variables)] - pub fn system_pre_div_config_frequency( - clocks: &mut ClockTree, - config: SystemPreDivConfig, - ) -> u32 { + pub fn system_pre_div_config_frequency(config: SystemPreDivConfig) -> u32 { (system_pre_div_in_frequency() / (config.divisor() + 1)) } pub fn system_pre_div_frequency() -> u32 { @@ -2341,22 +2879,16 @@ macro_rules! define_clock_tree_types { clocks.cpu_pll_div_out } pub fn request_cpu_pll_div_out(clocks: &mut ClockTree) { - trace!("Requesting CPU_PLL_DIV_OUT"); trace!("Enabling CPU_PLL_DIV_OUT"); request_pll_clk(clocks); enable_cpu_pll_div_out_impl(clocks, true); } pub fn release_cpu_pll_div_out(clocks: &mut ClockTree) { - trace!("Releasing CPU_PLL_DIV_OUT"); trace!("Disabling CPU_PLL_DIV_OUT"); enable_cpu_pll_div_out_impl(clocks, false); release_pll_clk(clocks); } - #[allow(unused_variables)] - pub fn cpu_pll_div_out_config_frequency( - clocks: &mut ClockTree, - config: CpuPllDivOutConfig, - ) -> u32 { + pub fn cpu_pll_div_out_config_frequency(config: CpuPllDivOutConfig) -> u32 { config.value() } pub fn cpu_pll_div_out_frequency() -> u32 { @@ -2368,20 +2900,19 @@ macro_rules! define_clock_tree_types { pub fn configure_apb_clk(clocks: &mut ClockTree, new_selector: ApbClkConfig) { let old_selector = clocks.apb_clk.replace(new_selector); refresh_apb_clk_downstream(clocks); - if clocks.apb_clk_refcount > 0 { + let active = clocks.apb_clk_refcount > 0; + if active { match new_selector { ApbClkConfig::Pll80m => request_pll_80m(clocks), ApbClkConfig::Cpu => request_cpu_clk(clocks), } - configure_apb_clk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - ApbClkConfig::Pll80m => release_pll_80m(clocks), - ApbClkConfig::Cpu => release_cpu_clk(clocks), - } + } + configure_apb_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + ApbClkConfig::Pll80m => release_pll_80m(clocks), + ApbClkConfig::Cpu => release_cpu_clk(clocks), } - } else { - configure_apb_clk_impl(clocks, old_selector, new_selector); } } pub fn apb_clk_config(clocks: &mut ClockTree) -> Option { @@ -2409,8 +2940,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn apb_clk_config_frequency(clocks: &mut ClockTree, config: ApbClkConfig) -> u32 { + pub fn apb_clk_config_frequency(config: ApbClkConfig) -> u32 { match config { ApbClkConfig::Pll80m => pll_80m_frequency(), ApbClkConfig::Cpu => cpu_clk_frequency(), @@ -2420,28 +2950,24 @@ macro_rules! define_clock_tree_types { APB_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn apb_clk_source_frequency(source: ApbClkConfig) -> u32 { - match source { - ApbClkConfig::Pll80m => pll_80m_frequency(), - ApbClkConfig::Cpu => cpu_clk_frequency(), - } + apb_clk_config_frequency(source) } pub fn configure_crypto_clk(clocks: &mut ClockTree, new_selector: CryptoClkConfig) { let old_selector = clocks.crypto_clk.replace(new_selector); refresh_crypto_clk_downstream(clocks); - if clocks.crypto_clk_refcount > 0 { + let active = clocks.crypto_clk_refcount > 0; + if active { match new_selector { CryptoClkConfig::Pll160m => request_pll_160m(clocks), CryptoClkConfig::Cpu => request_cpu_clk(clocks), } - configure_crypto_clk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - CryptoClkConfig::Pll160m => release_pll_160m(clocks), - CryptoClkConfig::Cpu => release_cpu_clk(clocks), - } + } + configure_crypto_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + CryptoClkConfig::Pll160m => release_pll_160m(clocks), + CryptoClkConfig::Cpu => release_cpu_clk(clocks), } - } else { - configure_crypto_clk_impl(clocks, old_selector, new_selector); } } pub fn crypto_clk_config(clocks: &mut ClockTree) -> Option { @@ -2469,8 +2995,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn crypto_clk_config_frequency(clocks: &mut ClockTree, config: CryptoClkConfig) -> u32 { + pub fn crypto_clk_config_frequency(config: CryptoClkConfig) -> u32 { match config { CryptoClkConfig::Pll160m => pll_160m_frequency(), CryptoClkConfig::Cpu => cpu_clk_frequency(), @@ -2480,10 +3005,7 @@ macro_rules! define_clock_tree_types { CRYPTO_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn crypto_clk_source_frequency(source: CryptoClkConfig) -> u32 { - match source { - CryptoClkConfig::Pll160m => pll_160m_frequency(), - CryptoClkConfig::Cpu => cpu_clk_frequency(), - } + crypto_clk_config_frequency(source) } pub fn configure_cpu_clk(clocks: &mut ClockTree, new_selector: CpuClkConfig) { let old_selector = clocks.cpu_clk.replace(new_selector); @@ -2523,8 +3045,7 @@ macro_rules! define_clock_tree_types { } fn request_cpu_clk(_clocks: &mut ClockTree) {} fn release_cpu_clk(_clocks: &mut ClockTree) {} - #[allow(unused_variables)] - pub fn cpu_clk_config_frequency(clocks: &mut ClockTree, config: CpuClkConfig) -> u32 { + pub fn cpu_clk_config_frequency(config: CpuClkConfig) -> u32 { match config { CpuClkConfig::Xtal => system_pre_div_frequency(), CpuClkConfig::RcFast => system_pre_div_frequency(), @@ -2558,15 +3079,19 @@ macro_rules! define_clock_tree_types { } pub fn request_pll_160m(clocks: &mut ClockTree) { trace!("Requesting PLL_160M"); - trace!("Enabling PLL_160M"); - request_cpu_clk(clocks); - enable_pll_160m_impl(clocks, true); + if increment_reference_count(&mut clocks.pll_160m_refcount) { + trace!("Enabling PLL_160M"); + request_cpu_clk(clocks); + enable_pll_160m_impl(clocks, true); + } } pub fn release_pll_160m(clocks: &mut ClockTree) { trace!("Releasing PLL_160M"); - trace!("Disabling PLL_160M"); - enable_pll_160m_impl(clocks, false); - release_cpu_clk(clocks); + if decrement_reference_count(&mut clocks.pll_160m_refcount) { + trace!("Disabling PLL_160M"); + enable_pll_160m_impl(clocks, false); + release_cpu_clk(clocks); + } } pub fn pll_160m_frequency() -> u32 { 160000000 @@ -2583,22 +3108,16 @@ macro_rules! define_clock_tree_types { clocks.rc_fast_clk_div_n } pub fn request_rc_fast_clk_div_n(clocks: &mut ClockTree) { - trace!("Requesting RC_FAST_CLK_DIV_N"); trace!("Enabling RC_FAST_CLK_DIV_N"); request_rc_fast_clk(clocks); enable_rc_fast_clk_div_n_impl(clocks, true); } pub fn release_rc_fast_clk_div_n(clocks: &mut ClockTree) { - trace!("Releasing RC_FAST_CLK_DIV_N"); trace!("Disabling RC_FAST_CLK_DIV_N"); enable_rc_fast_clk_div_n_impl(clocks, false); release_rc_fast_clk(clocks); } - #[allow(unused_variables)] - pub fn rc_fast_clk_div_n_config_frequency( - clocks: &mut ClockTree, - config: RcFastClkDivNConfig, - ) -> u32 { + pub fn rc_fast_clk_div_n_config_frequency(config: RcFastClkDivNConfig) -> u32 { (rc_fast_clk_frequency() / (config.divisor() + 1)) } pub fn rc_fast_clk_div_n_frequency() -> u32 { @@ -2608,13 +3127,11 @@ macro_rules! define_clock_tree_types { rc_fast_clk_frequency() } pub fn request_xtal_div_clk(clocks: &mut ClockTree) { - trace!("Requesting XTAL_DIV_CLK"); trace!("Enabling XTAL_DIV_CLK"); request_xtal_clk(clocks); enable_xtal_div_clk_impl(clocks, true); } pub fn release_xtal_div_clk(clocks: &mut ClockTree) { - trace!("Releasing XTAL_DIV_CLK"); trace!("Disabling XTAL_DIV_CLK"); enable_xtal_div_clk_impl(clocks, false); release_xtal_clk(clocks); @@ -2628,14 +3145,19 @@ macro_rules! define_clock_tree_types { pub fn configure_rtc_slow_clk(clocks: &mut ClockTree, new_selector: RtcSlowClkConfig) { let old_selector = clocks.rtc_slow_clk.replace(new_selector); refresh_rtc_slow_clk_downstream(clocks); - match new_selector { - RtcSlowClkConfig::Xtal32k => request_xtal32k_clk(clocks), - RtcSlowClkConfig::RcSlow => request_rc_slow_clk(clocks), - RtcSlowClkConfig::RcFast => request_rc_fast_div_clk(clocks), + let active = clocks.rtc_slow_clk_refcount > 0; + if active { + match new_selector { + #[cfg(use_xtal32k)] + RtcSlowClkConfig::Xtal32k => request_xtal32k_clk(clocks), + RtcSlowClkConfig::RcSlow => request_rc_slow_clk(clocks), + RtcSlowClkConfig::RcFast => request_rc_fast_div_clk(clocks), + } } configure_rtc_slow_clk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { + if active && let Some(old_selector) = old_selector { match old_selector { + #[cfg(use_xtal32k)] RtcSlowClkConfig::Xtal32k => release_xtal32k_clk(clocks), RtcSlowClkConfig::RcSlow => release_rc_slow_clk(clocks), RtcSlowClkConfig::RcFast => release_rc_fast_div_clk(clocks), @@ -2647,30 +3169,33 @@ macro_rules! define_clock_tree_types { } pub fn request_rtc_slow_clk(clocks: &mut ClockTree) { trace!("Requesting RTC_SLOW_CLK"); - trace!("Enabling RTC_SLOW_CLK"); - match unwrap!(clocks.rtc_slow_clk) { - RtcSlowClkConfig::Xtal32k => request_xtal32k_clk(clocks), - RtcSlowClkConfig::RcSlow => request_rc_slow_clk(clocks), - RtcSlowClkConfig::RcFast => request_rc_fast_div_clk(clocks), + if increment_reference_count(&mut clocks.rtc_slow_clk_refcount) { + trace!("Enabling RTC_SLOW_CLK"); + match unwrap!(clocks.rtc_slow_clk) { + #[cfg(use_xtal32k)] + RtcSlowClkConfig::Xtal32k => request_xtal32k_clk(clocks), + RtcSlowClkConfig::RcSlow => request_rc_slow_clk(clocks), + RtcSlowClkConfig::RcFast => request_rc_fast_div_clk(clocks), + } + enable_rtc_slow_clk_impl(clocks, true); } - enable_rtc_slow_clk_impl(clocks, true); } pub fn release_rtc_slow_clk(clocks: &mut ClockTree) { trace!("Releasing RTC_SLOW_CLK"); - trace!("Disabling RTC_SLOW_CLK"); - enable_rtc_slow_clk_impl(clocks, false); - match unwrap!(clocks.rtc_slow_clk) { - RtcSlowClkConfig::Xtal32k => release_xtal32k_clk(clocks), - RtcSlowClkConfig::RcSlow => release_rc_slow_clk(clocks), - RtcSlowClkConfig::RcFast => release_rc_fast_div_clk(clocks), + if decrement_reference_count(&mut clocks.rtc_slow_clk_refcount) { + trace!("Disabling RTC_SLOW_CLK"); + enable_rtc_slow_clk_impl(clocks, false); + match unwrap!(clocks.rtc_slow_clk) { + #[cfg(use_xtal32k)] + RtcSlowClkConfig::Xtal32k => release_xtal32k_clk(clocks), + RtcSlowClkConfig::RcSlow => release_rc_slow_clk(clocks), + RtcSlowClkConfig::RcFast => release_rc_fast_div_clk(clocks), + } } } - #[allow(unused_variables)] - pub fn rtc_slow_clk_config_frequency( - clocks: &mut ClockTree, - config: RtcSlowClkConfig, - ) -> u32 { + pub fn rtc_slow_clk_config_frequency(config: RtcSlowClkConfig) -> u32 { match config { + #[cfg(use_xtal32k)] RtcSlowClkConfig::Xtal32k => xtal32k_clk_frequency(), RtcSlowClkConfig::RcSlow => rc_slow_clk_frequency(), RtcSlowClkConfig::RcFast => rc_fast_div_clk_frequency(), @@ -2680,29 +3205,95 @@ macro_rules! define_clock_tree_types { RTC_SLOW_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn rtc_slow_clk_source_frequency(source: RtcSlowClkConfig) -> u32 { - match source { - RtcSlowClkConfig::Xtal32k => xtal32k_clk_frequency(), - RtcSlowClkConfig::RcSlow => rc_slow_clk_frequency(), - RtcSlowClkConfig::RcFast => rc_fast_div_clk_frequency(), + rtc_slow_clk_config_frequency(source) + } + pub fn request_ble_lp_xtal_clk(clocks: &mut ClockTree) { + trace!("Enabling BLE_LP_XTAL_CLK"); + request_xtal_clk(clocks); + enable_ble_lp_xtal_clk_impl(clocks, true); + } + pub fn release_ble_lp_xtal_clk(clocks: &mut ClockTree) { + trace!("Disabling BLE_LP_XTAL_CLK"); + enable_ble_lp_xtal_clk_impl(clocks, false); + release_xtal_clk(clocks); + } + pub fn ble_lp_xtal_clk_frequency() -> u32 { + 1000000 + } + pub fn ble_lp_xtal_clk_source_frequency() -> u32 { + xtal_clk_frequency() + } + pub fn configure_ble_lp_clk(clocks: &mut ClockTree, new_selector: BleLpClkConfig) { + let old_selector = clocks.ble_lp_clk.replace(new_selector); + refresh_ble_lp_clk_downstream(clocks); + let active = clocks.ble_lp_clk_refcount > 0; + if active { + match new_selector { + BleLpClkConfig::Xtal => request_ble_lp_xtal_clk(clocks), + BleLpClkConfig::RtcSlow => request_rtc_slow_clk(clocks), + } + } + configure_ble_lp_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + BleLpClkConfig::Xtal => release_ble_lp_xtal_clk(clocks), + BleLpClkConfig::RtcSlow => release_rtc_slow_clk(clocks), + } + } + } + pub fn ble_lp_clk_config(clocks: &mut ClockTree) -> Option { + clocks.ble_lp_clk + } + pub fn request_ble_lp_clk(clocks: &mut ClockTree) { + trace!("Requesting BLE_LP_CLK"); + if increment_reference_count(&mut clocks.ble_lp_clk_refcount) { + trace!("Enabling BLE_LP_CLK"); + match unwrap!(clocks.ble_lp_clk) { + BleLpClkConfig::Xtal => request_ble_lp_xtal_clk(clocks), + BleLpClkConfig::RtcSlow => request_rtc_slow_clk(clocks), + } + enable_ble_lp_clk_impl(clocks, true); + } + } + pub fn release_ble_lp_clk(clocks: &mut ClockTree) { + trace!("Releasing BLE_LP_CLK"); + if decrement_reference_count(&mut clocks.ble_lp_clk_refcount) { + trace!("Disabling BLE_LP_CLK"); + enable_ble_lp_clk_impl(clocks, false); + match unwrap!(clocks.ble_lp_clk) { + BleLpClkConfig::Xtal => release_ble_lp_xtal_clk(clocks), + BleLpClkConfig::RtcSlow => release_rtc_slow_clk(clocks), + } } } + pub fn ble_lp_clk_config_frequency(config: BleLpClkConfig) -> u32 { + match config { + BleLpClkConfig::Xtal => ble_lp_xtal_clk_frequency(), + BleLpClkConfig::RtcSlow => rtc_slow_clk_frequency(), + } + } + pub fn ble_lp_clk_frequency() -> u32 { + BLE_LP_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn ble_lp_clk_source_frequency(source: BleLpClkConfig) -> u32 { + ble_lp_clk_config_frequency(source) + } pub fn configure_rtc_fast_clk(clocks: &mut ClockTree, new_selector: RtcFastClkConfig) { let old_selector = clocks.rtc_fast_clk.replace(new_selector); refresh_rtc_fast_clk_downstream(clocks); - if clocks.rtc_fast_clk_refcount > 0 { + let active = clocks.rtc_fast_clk_refcount > 0; + if active { match new_selector { RtcFastClkConfig::Xtal => request_xtal_div_clk(clocks), RtcFastClkConfig::Rc => request_rc_fast_clk_div_n(clocks), } - configure_rtc_fast_clk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - RtcFastClkConfig::Xtal => release_xtal_div_clk(clocks), - RtcFastClkConfig::Rc => release_rc_fast_clk_div_n(clocks), - } + } + configure_rtc_fast_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + RtcFastClkConfig::Xtal => release_xtal_div_clk(clocks), + RtcFastClkConfig::Rc => release_rc_fast_clk_div_n(clocks), } - } else { - configure_rtc_fast_clk_impl(clocks, old_selector, new_selector); } } pub fn rtc_fast_clk_config(clocks: &mut ClockTree) -> Option { @@ -2730,11 +3321,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn rtc_fast_clk_config_frequency( - clocks: &mut ClockTree, - config: RtcFastClkConfig, - ) -> u32 { + pub fn rtc_fast_clk_config_frequency(config: RtcFastClkConfig) -> u32 { match config { RtcFastClkConfig::Xtal => xtal_div_clk_frequency(), RtcFastClkConfig::Rc => rc_fast_clk_div_n_frequency(), @@ -2744,32 +3331,30 @@ macro_rules! define_clock_tree_types { RTC_FAST_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn rtc_fast_clk_source_frequency(source: RtcFastClkConfig) -> u32 { - match source { - RtcFastClkConfig::Xtal => xtal_div_clk_frequency(), - RtcFastClkConfig::Rc => rc_fast_clk_div_n_frequency(), - } + rtc_fast_clk_config_frequency(source) } pub fn configure_low_power_clk(clocks: &mut ClockTree, new_selector: LowPowerClkConfig) { let old_selector = clocks.low_power_clk.replace(new_selector); refresh_low_power_clk_downstream(clocks); - if clocks.low_power_clk_refcount > 0 { + let active = clocks.low_power_clk_refcount > 0; + if active { match new_selector { LowPowerClkConfig::Xtal => request_xtal_clk(clocks), LowPowerClkConfig::RcFast => request_rc_fast_clk(clocks), + #[cfg(use_xtal32k)] LowPowerClkConfig::Xtal32k => request_xtal32k_clk(clocks), LowPowerClkConfig::RtcSlow => request_rtc_slow_clk(clocks), } - configure_low_power_clk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - LowPowerClkConfig::Xtal => release_xtal_clk(clocks), - LowPowerClkConfig::RcFast => release_rc_fast_clk(clocks), - LowPowerClkConfig::Xtal32k => release_xtal32k_clk(clocks), - LowPowerClkConfig::RtcSlow => release_rtc_slow_clk(clocks), - } + } + configure_low_power_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + LowPowerClkConfig::Xtal => release_xtal_clk(clocks), + LowPowerClkConfig::RcFast => release_rc_fast_clk(clocks), + #[cfg(use_xtal32k)] + LowPowerClkConfig::Xtal32k => release_xtal32k_clk(clocks), + LowPowerClkConfig::RtcSlow => release_rtc_slow_clk(clocks), } - } else { - configure_low_power_clk_impl(clocks, old_selector, new_selector); } } pub fn low_power_clk_config(clocks: &mut ClockTree) -> Option { @@ -2782,6 +3367,7 @@ macro_rules! define_clock_tree_types { match unwrap!(clocks.low_power_clk) { LowPowerClkConfig::Xtal => request_xtal_clk(clocks), LowPowerClkConfig::RcFast => request_rc_fast_clk(clocks), + #[cfg(use_xtal32k)] LowPowerClkConfig::Xtal32k => request_xtal32k_clk(clocks), LowPowerClkConfig::RtcSlow => request_rtc_slow_clk(clocks), } @@ -2796,19 +3382,17 @@ macro_rules! define_clock_tree_types { match unwrap!(clocks.low_power_clk) { LowPowerClkConfig::Xtal => release_xtal_clk(clocks), LowPowerClkConfig::RcFast => release_rc_fast_clk(clocks), + #[cfg(use_xtal32k)] LowPowerClkConfig::Xtal32k => release_xtal32k_clk(clocks), LowPowerClkConfig::RtcSlow => release_rtc_slow_clk(clocks), } } } - #[allow(unused_variables)] - pub fn low_power_clk_config_frequency( - clocks: &mut ClockTree, - config: LowPowerClkConfig, - ) -> u32 { + pub fn low_power_clk_config_frequency(config: LowPowerClkConfig) -> u32 { match config { LowPowerClkConfig::Xtal => xtal_clk_frequency(), LowPowerClkConfig::RcFast => rc_fast_clk_frequency(), + #[cfg(use_xtal32k)] LowPowerClkConfig::Xtal32k => xtal32k_clk_frequency(), LowPowerClkConfig::RtcSlow => rtc_slow_clk_frequency(), } @@ -2817,12 +3401,7 @@ macro_rules! define_clock_tree_types { LOW_POWER_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn low_power_clk_source_frequency(source: LowPowerClkConfig) -> u32 { - match source { - LowPowerClkConfig::Xtal => xtal_clk_frequency(), - LowPowerClkConfig::RcFast => rc_fast_clk_frequency(), - LowPowerClkConfig::Xtal32k => xtal32k_clk_frequency(), - LowPowerClkConfig::RtcSlow => rtc_slow_clk_frequency(), - } + low_power_clk_config_frequency(source) } pub fn request_uart_mem_clk(clocks: &mut ClockTree) { trace!("Requesting UART_MEM_CLK"); @@ -2854,22 +3433,23 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.timg_calibration_clock.replace(new_selector); refresh_timg_calibration_clock_downstream(clocks); - if clocks.timg_calibration_clock_refcount > 0 { + let active = clocks.timg_calibration_clock_refcount > 0; + if active { match new_selector { TimgCalibrationClockConfig::RcSlowClk => request_rc_slow_clk(clocks), TimgCalibrationClockConfig::RcFastDivClk => request_rc_fast_div_clk(clocks), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => request_xtal32k_clk(clocks), } - configure_timg_calibration_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - TimgCalibrationClockConfig::RcSlowClk => release_rc_slow_clk(clocks), - TimgCalibrationClockConfig::RcFastDivClk => release_rc_fast_div_clk(clocks), - TimgCalibrationClockConfig::Xtal32kClk => release_xtal32k_clk(clocks), - } + } + configure_timg_calibration_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + TimgCalibrationClockConfig::RcSlowClk => release_rc_slow_clk(clocks), + TimgCalibrationClockConfig::RcFastDivClk => release_rc_fast_div_clk(clocks), + #[cfg(use_xtal32k)] + TimgCalibrationClockConfig::Xtal32kClk => release_xtal32k_clk(clocks), } - } else { - configure_timg_calibration_clock_impl(clocks, old_selector, new_selector); } } pub fn timg_calibration_clock_config( @@ -2885,6 +3465,7 @@ macro_rules! define_clock_tree_types { match unwrap!(clocks.timg_calibration_clock) { TimgCalibrationClockConfig::RcSlowClk => request_rc_slow_clk(clocks), TimgCalibrationClockConfig::RcFastDivClk => request_rc_fast_div_clk(clocks), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => request_xtal32k_clk(clocks), } enable_timg_calibration_clock_impl(clocks, true); @@ -2899,18 +3480,16 @@ macro_rules! define_clock_tree_types { match unwrap!(clocks.timg_calibration_clock) { TimgCalibrationClockConfig::RcSlowClk => release_rc_slow_clk(clocks), TimgCalibrationClockConfig::RcFastDivClk => release_rc_fast_div_clk(clocks), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => release_xtal32k_clk(clocks), } } } - #[allow(unused_variables)] - pub fn timg_calibration_clock_config_frequency( - clocks: &mut ClockTree, - config: TimgCalibrationClockConfig, - ) -> u32 { + pub fn timg_calibration_clock_config_frequency(config: TimgCalibrationClockConfig) -> u32 { match config { TimgCalibrationClockConfig::RcSlowClk => rc_slow_clk_frequency(), TimgCalibrationClockConfig::RcFastDivClk => rc_fast_div_clk_frequency(), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => xtal32k_clk_frequency(), } } @@ -2918,10 +3497,32 @@ macro_rules! define_clock_tree_types { TIMG_CALIBRATION_CLOCK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn timg_calibration_clock_source_frequency(source: TimgCalibrationClockConfig) -> u32 { - match source { - TimgCalibrationClockConfig::RcSlowClk => rc_slow_clk_frequency(), - TimgCalibrationClockConfig::RcFastDivClk => rc_fast_div_clk_frequency(), - TimgCalibrationClockConfig::Xtal32kClk => xtal32k_clk_frequency(), + timg_calibration_clock_config_frequency(source) + } + impl AdcInstance { + pub fn request_function_clock(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::FUNCTION_CLOCK", self); + if increment_reference_count(&mut clocks.adc_function_clock_refcount[self as usize]) + { + trace!("Enabling {:?}::FUNCTION_CLOCK", self); + request_apb_clk(clocks); + self.enable_function_clock_impl(clocks, true); + } + } + pub fn release_function_clock(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::FUNCTION_CLOCK", self); + if decrement_reference_count(&mut clocks.adc_function_clock_refcount[self as usize]) + { + trace!("Disabling {:?}::FUNCTION_CLOCK", self); + self.enable_function_clock_impl(clocks, false); + release_apb_clk(clocks); + } + } + pub fn function_clock_frequency(self) -> u32 { + apb_clk_frequency() + } + pub fn function_clock_source_frequency() -> u32 { + apb_clk_frequency() } } impl SdmInstance { @@ -2958,20 +3559,19 @@ macro_rules! define_clock_tree_types { ) { let old_config = clocks.i2c_function_clock[self as usize].replace(config); refresh_i2c_function_clock_downstream(clocks, self); - if clocks.i2c_function_clock_refcount[self as usize] > 0 { + let active = clocks.i2c_function_clock_refcount[self as usize] > 0; + if active { match config.sclk { I2cFunctionClockSclk::Xtal => request_xtal_clk(clocks), I2cFunctionClockSclk::RcFast => request_rc_fast_clk(clocks), } - self.configure_function_clock_impl(clocks, old_config, config); - if let Some(old_config) = old_config { - match old_config.sclk { - I2cFunctionClockSclk::Xtal => release_xtal_clk(clocks), - I2cFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), - } + } + self.configure_function_clock_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + I2cFunctionClockSclk::Xtal => release_xtal_clk(clocks), + I2cFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_config, config); } } pub fn function_clock_config( @@ -3006,11 +3606,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: I2cFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: I2cFunctionClockConfig) -> u32 { (match config.sclk { I2cFunctionClockSclk::Xtal => xtal_clk_frequency(), I2cFunctionClockSclk::RcFast => rc_fast_clk_frequency(), @@ -3027,26 +3623,209 @@ macro_rules! define_clock_tree_types { } } } + impl I2sInstance { + pub fn configure_tx_clk(self, clocks: &mut ClockTree, config: I2sClkConfig) { + let old_config = clocks.i2s_tx_clk[self as usize].replace(config); + refresh_i2s_tx_clk_downstream(clocks, self); + let active = clocks.i2s_tx_clk_refcount[self as usize] > 0; + if active { + match config.sclk { + I2sClkSclk::Xtal => request_xtal_clk(clocks), + I2sClkSclk::Pll160m => request_pll_160m(clocks), + } + } + self.configure_tx_clk_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + I2sClkSclk::Xtal => release_xtal_clk(clocks), + I2sClkSclk::Pll160m => release_pll_160m(clocks), + } + } + } + pub fn tx_clk_config(self, clocks: &mut ClockTree) -> Option { + clocks.i2s_tx_clk[self as usize] + } + pub fn request_tx_clk(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::TX_CLK", self); + if increment_reference_count(&mut clocks.i2s_tx_clk_refcount[self as usize]) { + trace!("Enabling {:?}::TX_CLK", self); + crate::rtc_cntl::WakeLock::acquire(); + match unwrap!(clocks.i2s_tx_clk[self as usize]).sclk { + I2sClkSclk::Xtal => request_xtal_clk(clocks), + I2sClkSclk::Pll160m => request_pll_160m(clocks), + } + self.enable_tx_clk_impl(clocks, true); + } + } + pub fn release_tx_clk(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::TX_CLK", self); + if decrement_reference_count(&mut clocks.i2s_tx_clk_refcount[self as usize]) { + trace!("Disabling {:?}::TX_CLK", self); + crate::rtc_cntl::WakeLock::release(); + self.enable_tx_clk_impl(clocks, false); + match unwrap!(clocks.i2s_tx_clk[self as usize]).sclk { + I2sClkSclk::Xtal => release_xtal_clk(clocks), + I2sClkSclk::Pll160m => release_pll_160m(clocks), + } + } + } + pub fn tx_clk_config_frequency(config: I2sClkConfig) -> u32 { + (((match config.sclk { + I2sClkSclk::Xtal => xtal_clk_frequency(), + I2sClkSclk::Pll160m => pll_160m_frequency(), + } as u64) + * (config.div_a() as u64)) + / (((config.div_num() * config.div_a()) + config.div_b()) as u64)) + as u32 + } + pub fn tx_clk_frequency(self) -> u32 { + I2S_TX_CLK_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) + } + pub fn tx_clk_source_frequency(sclk: I2sClkSclk) -> u32 { + match sclk { + I2sClkSclk::Xtal => xtal_clk_frequency(), + I2sClkSclk::Pll160m => pll_160m_frequency(), + } + } + pub fn configure_rx_clk(self, clocks: &mut ClockTree, config: I2sClkConfig) { + let old_config = clocks.i2s_rx_clk[self as usize].replace(config); + refresh_i2s_rx_clk_downstream(clocks, self); + let active = clocks.i2s_rx_clk_refcount[self as usize] > 0; + if active { + match config.sclk { + I2sClkSclk::Xtal => request_xtal_clk(clocks), + I2sClkSclk::Pll160m => request_pll_160m(clocks), + } + } + self.configure_rx_clk_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + I2sClkSclk::Xtal => release_xtal_clk(clocks), + I2sClkSclk::Pll160m => release_pll_160m(clocks), + } + } + } + pub fn rx_clk_config(self, clocks: &mut ClockTree) -> Option { + clocks.i2s_rx_clk[self as usize] + } + pub fn request_rx_clk(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::RX_CLK", self); + if increment_reference_count(&mut clocks.i2s_rx_clk_refcount[self as usize]) { + trace!("Enabling {:?}::RX_CLK", self); + crate::rtc_cntl::WakeLock::acquire(); + match unwrap!(clocks.i2s_rx_clk[self as usize]).sclk { + I2sClkSclk::Xtal => request_xtal_clk(clocks), + I2sClkSclk::Pll160m => request_pll_160m(clocks), + } + self.enable_rx_clk_impl(clocks, true); + } + } + pub fn release_rx_clk(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::RX_CLK", self); + if decrement_reference_count(&mut clocks.i2s_rx_clk_refcount[self as usize]) { + trace!("Disabling {:?}::RX_CLK", self); + crate::rtc_cntl::WakeLock::release(); + self.enable_rx_clk_impl(clocks, false); + match unwrap!(clocks.i2s_rx_clk[self as usize]).sclk { + I2sClkSclk::Xtal => release_xtal_clk(clocks), + I2sClkSclk::Pll160m => release_pll_160m(clocks), + } + } + } + pub fn rx_clk_config_frequency(config: I2sClkConfig) -> u32 { + (((match config.sclk { + I2sClkSclk::Xtal => xtal_clk_frequency(), + I2sClkSclk::Pll160m => pll_160m_frequency(), + } as u64) + * (config.div_a() as u64)) + / (((config.div_num() * config.div_a()) + config.div_b()) as u64)) + as u32 + } + pub fn rx_clk_frequency(self) -> u32 { + I2S_RX_CLK_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) + } + pub fn rx_clk_source_frequency(sclk: I2sClkSclk) -> u32 { + match sclk { + I2sClkSclk::Xtal => xtal_clk_frequency(), + I2sClkSclk::Pll160m => pll_160m_frequency(), + } + } + pub fn configure_mclk_out( + self, + clocks: &mut ClockTree, + new_selector: I2sMclkOutConfig, + ) { + let old_selector = clocks.i2s_mclk_out[self as usize].replace(new_selector); + refresh_i2s_mclk_out_downstream(clocks, self); + let active = clocks.i2s_mclk_out_refcount[self as usize] > 0; + if active { + match new_selector { + I2sMclkOutConfig::Tx => self.request_tx_clk(clocks), + I2sMclkOutConfig::Rx => self.request_rx_clk(clocks), + } + } + self.configure_mclk_out_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + I2sMclkOutConfig::Tx => self.release_tx_clk(clocks), + I2sMclkOutConfig::Rx => self.release_rx_clk(clocks), + } + } + } + pub fn mclk_out_config(self, clocks: &mut ClockTree) -> Option { + clocks.i2s_mclk_out[self as usize] + } + pub fn request_mclk_out(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::MCLK_OUT", self); + if increment_reference_count(&mut clocks.i2s_mclk_out_refcount[self as usize]) { + trace!("Enabling {:?}::MCLK_OUT", self); + match unwrap!(clocks.i2s_mclk_out[self as usize]) { + I2sMclkOutConfig::Tx => self.request_tx_clk(clocks), + I2sMclkOutConfig::Rx => self.request_rx_clk(clocks), + } + self.enable_mclk_out_impl(clocks, true); + } + } + pub fn release_mclk_out(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::MCLK_OUT", self); + if decrement_reference_count(&mut clocks.i2s_mclk_out_refcount[self as usize]) { + trace!("Disabling {:?}::MCLK_OUT", self); + self.enable_mclk_out_impl(clocks, false); + match unwrap!(clocks.i2s_mclk_out[self as usize]) { + I2sMclkOutConfig::Tx => self.release_tx_clk(clocks), + I2sMclkOutConfig::Rx => self.release_rx_clk(clocks), + } + } + } + pub fn mclk_out_config_frequency(self, config: I2sMclkOutConfig) -> u32 { + match config { + I2sMclkOutConfig::Tx => self.tx_clk_frequency(), + I2sMclkOutConfig::Rx => self.rx_clk_frequency(), + } + } + pub fn mclk_out_frequency(self) -> u32 { + I2S_MCLK_OUT_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) + } + } impl RmtInstance { pub fn configure_sclk(self, clocks: &mut ClockTree, new_selector: RmtSclkConfig) { let old_selector = clocks.rmt_sclk[self as usize].replace(new_selector); refresh_rmt_sclk_downstream(clocks, self); - if clocks.rmt_sclk_refcount[self as usize] > 0 { + let active = clocks.rmt_sclk_refcount[self as usize] > 0; + if active { match new_selector { RmtSclkConfig::ApbClk => request_apb_clk(clocks), RmtSclkConfig::RcFastClk => request_rc_fast_clk(clocks), RmtSclkConfig::XtalClk => request_xtal_clk(clocks), } - self.configure_sclk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - RmtSclkConfig::ApbClk => release_apb_clk(clocks), - RmtSclkConfig::RcFastClk => release_rc_fast_clk(clocks), - RmtSclkConfig::XtalClk => release_xtal_clk(clocks), - } + } + self.configure_sclk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + RmtSclkConfig::ApbClk => release_apb_clk(clocks), + RmtSclkConfig::RcFastClk => release_rc_fast_clk(clocks), + RmtSclkConfig::XtalClk => release_xtal_clk(clocks), } - } else { - self.configure_sclk_impl(clocks, old_selector, new_selector); } } pub fn sclk_config(self, clocks: &mut ClockTree) -> Option { @@ -3078,8 +3857,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn sclk_config_frequency(clocks: &mut ClockTree, config: RmtSclkConfig) -> u32 { + pub fn sclk_config_frequency(config: RmtSclkConfig) -> u32 { match config { RmtSclkConfig::ApbClk => apb_clk_frequency(), RmtSclkConfig::RcFastClk => rc_fast_clk_frequency(), @@ -3090,11 +3868,7 @@ macro_rules! define_clock_tree_types { RMT_SCLK_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) } pub fn sclk_source_frequency(source: RmtSclkConfig) -> u32 { - match source { - RmtSclkConfig::ApbClk => apb_clk_frequency(), - RmtSclkConfig::RcFastClk => rc_fast_clk_frequency(), - RmtSclkConfig::XtalClk => xtal_clk_frequency(), - } + Self::sclk_config_frequency(source) } } impl SpiInstance { @@ -3105,20 +3879,19 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.spi_function_clock[self as usize].replace(new_selector); refresh_spi_function_clock_downstream(clocks, self); - if clocks.spi_function_clock_refcount[self as usize] > 0 { + let active = clocks.spi_function_clock_refcount[self as usize] > 0; + if active { match new_selector { SpiFunctionClockConfig::Xtal => request_xtal_clk(clocks), SpiFunctionClockConfig::Pll80m => request_pll_80m(clocks), } - self.configure_function_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - SpiFunctionClockConfig::Xtal => release_xtal_clk(clocks), - SpiFunctionClockConfig::Pll80m => release_pll_80m(clocks), - } + } + self.configure_function_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + SpiFunctionClockConfig::Xtal => release_xtal_clk(clocks), + SpiFunctionClockConfig::Pll80m => release_pll_80m(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_selector, new_selector); } } pub fn function_clock_config( @@ -3153,11 +3926,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: SpiFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: SpiFunctionClockConfig) -> u32 { match config { SpiFunctionClockConfig::Xtal => xtal_clk_frequency(), SpiFunctionClockConfig::Pll80m => pll_80m_frequency(), @@ -3168,10 +3937,7 @@ macro_rules! define_clock_tree_types { .load(::core::sync::atomic::Ordering::Acquire) } pub fn function_clock_source_frequency(source: SpiFunctionClockConfig) -> u32 { - match source { - SpiFunctionClockConfig::Xtal => xtal_clk_frequency(), - SpiFunctionClockConfig::Pll80m => pll_80m_frequency(), - } + Self::function_clock_config_frequency(source) } } impl TimgInstance { @@ -3182,20 +3948,19 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.timg_function_clock[self as usize].replace(new_selector); refresh_timg_function_clock_downstream(clocks, self); - if clocks.timg_function_clock_refcount[self as usize] > 0 { + let active = clocks.timg_function_clock_refcount[self as usize] > 0; + if active { match new_selector { TimgFunctionClockConfig::XtalClk => request_xtal_clk(clocks), TimgFunctionClockConfig::ApbClk => request_apb_clk(clocks), } - self.configure_function_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - TimgFunctionClockConfig::XtalClk => release_xtal_clk(clocks), - TimgFunctionClockConfig::ApbClk => release_apb_clk(clocks), - } + } + self.configure_function_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + TimgFunctionClockConfig::XtalClk => release_xtal_clk(clocks), + TimgFunctionClockConfig::ApbClk => release_apb_clk(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_selector, new_selector); } } pub fn function_clock_config( @@ -3230,11 +3995,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: TimgFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: TimgFunctionClockConfig) -> u32 { match config { TimgFunctionClockConfig::XtalClk => xtal_clk_frequency(), TimgFunctionClockConfig::ApbClk => apb_clk_frequency(), @@ -3245,10 +4006,7 @@ macro_rules! define_clock_tree_types { .load(::core::sync::atomic::Ordering::Acquire) } pub fn function_clock_source_frequency(source: TimgFunctionClockConfig) -> u32 { - match source { - TimgFunctionClockConfig::XtalClk => xtal_clk_frequency(), - TimgFunctionClockConfig::ApbClk => apb_clk_frequency(), - } + Self::function_clock_config_frequency(source) } pub fn configure_wdt_clock( self, @@ -3257,20 +4015,19 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.timg_wdt_clock[self as usize].replace(new_selector); refresh_timg_wdt_clock_downstream(clocks, self); - if clocks.timg_wdt_clock_refcount[self as usize] > 0 { + let active = clocks.timg_wdt_clock_refcount[self as usize] > 0; + if active { match new_selector { TimgWdtClockConfig::ApbClk => request_apb_clk(clocks), TimgWdtClockConfig::XtalClk => request_xtal_clk(clocks), } - self.configure_wdt_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - TimgWdtClockConfig::ApbClk => release_apb_clk(clocks), - TimgWdtClockConfig::XtalClk => release_xtal_clk(clocks), - } + } + self.configure_wdt_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + TimgWdtClockConfig::ApbClk => release_apb_clk(clocks), + TimgWdtClockConfig::XtalClk => release_xtal_clk(clocks), } - } else { - self.configure_wdt_clock_impl(clocks, old_selector, new_selector); } } pub fn wdt_clock_config(self, clocks: &mut ClockTree) -> Option { @@ -3298,11 +4055,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn wdt_clock_config_frequency( - clocks: &mut ClockTree, - config: TimgWdtClockConfig, - ) -> u32 { + pub fn wdt_clock_config_frequency(config: TimgWdtClockConfig) -> u32 { match config { TimgWdtClockConfig::ApbClk => apb_clk_frequency(), TimgWdtClockConfig::XtalClk => xtal_clk_frequency(), @@ -3313,10 +4066,7 @@ macro_rules! define_clock_tree_types { .load(::core::sync::atomic::Ordering::Acquire) } pub fn wdt_clock_source_frequency(source: TimgWdtClockConfig) -> u32 { - match source { - TimgWdtClockConfig::ApbClk => apb_clk_frequency(), - TimgWdtClockConfig::XtalClk => xtal_clk_frequency(), - } + Self::wdt_clock_config_frequency(source) } } impl UartInstance { @@ -3327,22 +4077,21 @@ macro_rules! define_clock_tree_types { ) { let old_config = clocks.uart_function_clock[self as usize].replace(config); refresh_uart_function_clock_downstream(clocks, self); - if clocks.uart_function_clock_refcount[self as usize] > 0 { + let active = clocks.uart_function_clock_refcount[self as usize] > 0; + if active { match config.sclk { UartFunctionClockSclk::Apb => request_apb_clk(clocks), UartFunctionClockSclk::RcFast => request_rc_fast_clk(clocks), UartFunctionClockSclk::Xtal => request_xtal_clk(clocks), } - self.configure_function_clock_impl(clocks, old_config, config); - if let Some(old_config) = old_config { - match old_config.sclk { - UartFunctionClockSclk::Apb => release_apb_clk(clocks), - UartFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), - UartFunctionClockSclk::Xtal => release_xtal_clk(clocks), - } + } + self.configure_function_clock_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + UartFunctionClockSclk::Apb => release_apb_clk(clocks), + UartFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), + UartFunctionClockSclk::Xtal => release_xtal_clk(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_config, config); } } pub fn function_clock_config( @@ -3379,11 +4128,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: UartFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: UartFunctionClockConfig) -> u32 { (match config.sclk { UartFunctionClockSclk::Apb => apb_clk_frequency(), UartFunctionClockSclk::RcFast => rc_fast_clk_frequency(), @@ -3458,10 +4203,8 @@ macro_rules! define_clock_tree_types { self.release_function_clock(clocks); } } - #[allow(unused_variables)] pub fn baud_rate_generator_config_frequency( self, - clocks: &mut ClockTree, config: UartBaudRateGeneratorConfig, ) -> u32 { ((self.function_clock_frequency() * 16) @@ -3472,6 +4215,63 @@ macro_rules! define_clock_tree_types { .load(::core::sync::atomic::Ordering::Acquire) } } + impl TsensInstance { + pub fn configure_sclk(self, clocks: &mut ClockTree, new_selector: TsensSclkConfig) { + let old_selector = clocks.tsens_sclk[self as usize].replace(new_selector); + refresh_tsens_sclk_downstream(clocks, self); + let active = clocks.tsens_sclk_refcount[self as usize] > 0; + if active { + match new_selector { + TsensSclkConfig::RcFast => request_rc_fast_clk(clocks), + TsensSclkConfig::Xtal => request_xtal_clk(clocks), + } + } + self.configure_sclk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + TsensSclkConfig::RcFast => release_rc_fast_clk(clocks), + TsensSclkConfig::Xtal => release_xtal_clk(clocks), + } + } + } + pub fn sclk_config(self, clocks: &mut ClockTree) -> Option { + clocks.tsens_sclk[self as usize] + } + pub fn request_sclk(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::SCLK", self); + if increment_reference_count(&mut clocks.tsens_sclk_refcount[self as usize]) { + trace!("Enabling {:?}::SCLK", self); + match unwrap!(clocks.tsens_sclk[self as usize]) { + TsensSclkConfig::RcFast => request_rc_fast_clk(clocks), + TsensSclkConfig::Xtal => request_xtal_clk(clocks), + } + self.enable_sclk_impl(clocks, true); + } + } + pub fn release_sclk(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::SCLK", self); + if decrement_reference_count(&mut clocks.tsens_sclk_refcount[self as usize]) { + trace!("Disabling {:?}::SCLK", self); + self.enable_sclk_impl(clocks, false); + match unwrap!(clocks.tsens_sclk[self as usize]) { + TsensSclkConfig::RcFast => release_rc_fast_clk(clocks), + TsensSclkConfig::Xtal => release_xtal_clk(clocks), + } + } + } + pub fn sclk_config_frequency(config: TsensSclkConfig) -> u32 { + match config { + TsensSclkConfig::RcFast => rc_fast_clk_frequency(), + TsensSclkConfig::Xtal => xtal_clk_frequency(), + } + } + pub fn sclk_frequency(self) -> u32 { + TSENS_SCLK_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) + } + pub fn sclk_source_frequency(source: TsensSclkConfig) -> u32 { + Self::sclk_config_frequency(source) + } + } /// Clock tree configuration. /// /// The fields of this struct are optional, with the following caveats: @@ -3497,6 +4297,8 @@ macro_rules! define_clock_tree_types { pub rc_fast_clk_div_n: Option, /// `RTC_SLOW_CLK` configuration. pub rtc_slow_clk: Option, + /// `BLE_LP_CLK` configuration. + pub ble_lp_clk: Option, /// `RTC_FAST_CLK` configuration. pub rtc_fast_clk: Option, /// `LOW_POWER_CLK` configuration. @@ -3527,6 +4329,9 @@ macro_rules! define_clock_tree_types { if let Some(config) = self.rtc_slow_clk { configure_rtc_slow_clk(clocks, config); } + if let Some(config) = self.ble_lp_clk { + configure_ble_lp_clk(clocks, config); + } if let Some(config) = self.rtc_fast_clk { configure_rtc_fast_clk(clocks, config); } @@ -3551,20 +4356,28 @@ macro_rules! define_clock_tree_types { fn refresh_xtal_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.xtal_clk { XTAL_CLK_FREQ_CACHE.store( - xtal_clk_config_frequency(clocks, config), + xtal_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } refresh_pll_clk_downstream(clocks); refresh_system_pre_div_in_downstream(clocks); + refresh_ble_lp_clk_downstream(clocks); refresh_rtc_fast_clk_downstream(clocks); refresh_low_power_clk_downstream(clocks); for child_instance in [I2cInstance::I2c0] { refresh_i2c_function_clock_downstream(clocks, child_instance); } + for child_instance in [I2sInstance::I2s0] { + refresh_i2s_tx_clk_downstream(clocks, child_instance); + refresh_i2s_rx_clk_downstream(clocks, child_instance); + } for child_instance in [SpiInstance::Spi2] { refresh_spi_function_clock_downstream(clocks, child_instance); } + for child_instance in [TsensInstance::Tsens] { + refresh_tsens_sclk_downstream(clocks, child_instance); + } for child_instance in [RmtInstance::Rmt] { refresh_rmt_sclk_downstream(clocks, child_instance); } @@ -3579,16 +4392,39 @@ macro_rules! define_clock_tree_types { fn refresh_pll_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.pll_clk { PLL_CLK_FREQ_CACHE.store( - pll_clk_config_frequency(clocks, config), + pll_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } refresh_cpu_pll_div_out_downstream(clocks); } + fn refresh_rc_fast_clk_downstream(clocks: &mut ClockTree) { + refresh_system_pre_div_in_downstream(clocks); + refresh_rc_fast_clk_div_n_downstream(clocks); + refresh_rtc_slow_clk_downstream(clocks); + refresh_low_power_clk_downstream(clocks); + refresh_timg_calibration_clock_downstream(clocks); + for child_instance in [I2cInstance::I2c0] { + refresh_i2c_function_clock_downstream(clocks, child_instance); + } + for child_instance in [TsensInstance::Tsens] { + refresh_tsens_sclk_downstream(clocks, child_instance); + } + for child_instance in [RmtInstance::Rmt] { + refresh_rmt_sclk_downstream(clocks, child_instance); + } + for child_instance in [UartInstance::Uart0, UartInstance::Uart1] { + refresh_uart_function_clock_downstream(clocks, child_instance); + } + } + fn refresh_rc_slow_clk_downstream(clocks: &mut ClockTree) { + refresh_rtc_slow_clk_downstream(clocks); + refresh_timg_calibration_clock_downstream(clocks); + } fn refresh_system_pre_div_in_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.system_pre_div_in { SYSTEM_PRE_DIV_IN_FREQ_CACHE.store( - system_pre_div_in_config_frequency(clocks, config), + system_pre_div_in_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3597,7 +4433,7 @@ macro_rules! define_clock_tree_types { fn refresh_system_pre_div_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.system_pre_div { SYSTEM_PRE_DIV_FREQ_CACHE.store( - system_pre_div_config_frequency(clocks, config), + system_pre_div_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3606,7 +4442,7 @@ macro_rules! define_clock_tree_types { fn refresh_cpu_pll_div_out_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.cpu_pll_div_out { CPU_PLL_DIV_OUT_FREQ_CACHE.store( - cpu_pll_div_out_config_frequency(clocks, config), + cpu_pll_div_out_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3615,12 +4451,16 @@ macro_rules! define_clock_tree_types { fn refresh_cpu_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.cpu_clk { CPU_CLK_FREQ_CACHE.store( - cpu_clk_config_frequency(clocks, config), + cpu_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } refresh_apb_clk_downstream(clocks); refresh_crypto_clk_downstream(clocks); + for child_instance in [I2sInstance::I2s0] { + refresh_i2s_tx_clk_downstream(clocks, child_instance); + refresh_i2s_rx_clk_downstream(clocks, child_instance); + } for child_instance in [SpiInstance::Spi2] { refresh_spi_function_clock_downstream(clocks, child_instance); } @@ -3628,7 +4468,7 @@ macro_rules! define_clock_tree_types { fn refresh_rc_fast_clk_div_n_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.rc_fast_clk_div_n { RC_FAST_CLK_DIV_N_FREQ_CACHE.store( - rc_fast_clk_div_n_config_frequency(clocks, config), + rc_fast_clk_div_n_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3637,16 +4477,25 @@ macro_rules! define_clock_tree_types { fn refresh_rtc_slow_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.rtc_slow_clk { RTC_SLOW_CLK_FREQ_CACHE.store( - rtc_slow_clk_config_frequency(clocks, config), + rtc_slow_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } + refresh_ble_lp_clk_downstream(clocks); refresh_low_power_clk_downstream(clocks); } + fn refresh_ble_lp_clk_downstream(clocks: &mut ClockTree) { + if let Some(config) = clocks.ble_lp_clk { + BLE_LP_CLK_FREQ_CACHE.store( + ble_lp_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } fn refresh_rtc_fast_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.rtc_fast_clk { RTC_FAST_CLK_FREQ_CACHE.store( - rtc_fast_clk_config_frequency(clocks, config), + rtc_fast_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3654,7 +4503,7 @@ macro_rules! define_clock_tree_types { fn refresh_low_power_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.low_power_clk { LOW_POWER_CLK_FREQ_CACHE.store( - low_power_clk_config_frequency(clocks, config), + low_power_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3662,7 +4511,7 @@ macro_rules! define_clock_tree_types { fn refresh_timg_calibration_clock_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.timg_calibration_clock { TIMG_CALIBRATION_CLOCK_FREQ_CACHE.store( - timg_calibration_clock_config_frequency(clocks, config), + timg_calibration_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3670,7 +4519,33 @@ macro_rules! define_clock_tree_types { fn refresh_i2c_function_clock_downstream(clocks: &mut ClockTree, instance: I2cInstance) { if let Some(config) = clocks.i2c_function_clock[instance as usize] { I2C_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - I2cInstance::function_clock_config_frequency(clocks, config), + I2cInstance::function_clock_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + fn refresh_i2s_tx_clk_downstream(clocks: &mut ClockTree, instance: I2sInstance) { + if let Some(config) = clocks.i2s_tx_clk[instance as usize] { + I2S_TX_CLK_FREQ_CACHE[instance as usize].store( + I2sInstance::tx_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + refresh_i2s_mclk_out_downstream(clocks, instance); + } + fn refresh_i2s_rx_clk_downstream(clocks: &mut ClockTree, instance: I2sInstance) { + if let Some(config) = clocks.i2s_rx_clk[instance as usize] { + I2S_RX_CLK_FREQ_CACHE[instance as usize].store( + I2sInstance::rx_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + refresh_i2s_mclk_out_downstream(clocks, instance); + } + fn refresh_i2s_mclk_out_downstream(clocks: &mut ClockTree, instance: I2sInstance) { + if let Some(config) = clocks.i2s_mclk_out[instance as usize] { + I2S_MCLK_OUT_FREQ_CACHE[instance as usize].store( + instance.mclk_out_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3678,7 +4553,15 @@ macro_rules! define_clock_tree_types { fn refresh_spi_function_clock_downstream(clocks: &mut ClockTree, instance: SpiInstance) { if let Some(config) = clocks.spi_function_clock[instance as usize] { SPI_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - SpiInstance::function_clock_config_frequency(clocks, config), + SpiInstance::function_clock_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + fn refresh_tsens_sclk_downstream(clocks: &mut ClockTree, instance: TsensInstance) { + if let Some(config) = clocks.tsens_sclk[instance as usize] { + TSENS_SCLK_FREQ_CACHE[instance as usize].store( + TsensInstance::sclk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3686,7 +4569,7 @@ macro_rules! define_clock_tree_types { fn refresh_apb_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.apb_clk { APB_CLK_FREQ_CACHE.store( - apb_clk_config_frequency(clocks, config), + apb_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3704,7 +4587,7 @@ macro_rules! define_clock_tree_types { fn refresh_crypto_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.crypto_clk { CRYPTO_CLK_FREQ_CACHE.store( - crypto_clk_config_frequency(clocks, config), + crypto_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3712,7 +4595,7 @@ macro_rules! define_clock_tree_types { fn refresh_rmt_sclk_downstream(clocks: &mut ClockTree, instance: RmtInstance) { if let Some(config) = clocks.rmt_sclk[instance as usize] { RMT_SCLK_FREQ_CACHE[instance as usize].store( - RmtInstance::sclk_config_frequency(clocks, config), + RmtInstance::sclk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3720,7 +4603,7 @@ macro_rules! define_clock_tree_types { fn refresh_timg_function_clock_downstream(clocks: &mut ClockTree, instance: TimgInstance) { if let Some(config) = clocks.timg_function_clock[instance as usize] { TIMG_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - TimgInstance::function_clock_config_frequency(clocks, config), + TimgInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3728,7 +4611,7 @@ macro_rules! define_clock_tree_types { fn refresh_timg_wdt_clock_downstream(clocks: &mut ClockTree, instance: TimgInstance) { if let Some(config) = clocks.timg_wdt_clock[instance as usize] { TIMG_WDT_CLOCK_FREQ_CACHE[instance as usize].store( - TimgInstance::wdt_clock_config_frequency(clocks, config), + TimgInstance::wdt_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3736,7 +4619,7 @@ macro_rules! define_clock_tree_types { fn refresh_uart_function_clock_downstream(clocks: &mut ClockTree, instance: UartInstance) { if let Some(config) = clocks.uart_function_clock[instance as usize] { UART_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - UartInstance::function_clock_config_frequency(clocks, config), + UartInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3748,7 +4631,7 @@ macro_rules! define_clock_tree_types { ) { if let Some(config) = clocks.uart_baud_rate_generator[instance as usize] { UART_BAUD_RATE_GENERATOR_FREQ_CACHE[instance as usize].store( - instance.baud_rate_generator_config_frequency(clocks, config), + instance.baud_rate_generator_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4501,14 +5384,12 @@ macro_rules! for_each_peripheral { "XTS_AES peripheral singleton"] XTS_AES <= XTS_AES() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "ADC1 peripheral singleton"] ADC1 <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "ADC2 peripheral singleton"] ADC2 <= virtual() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "BT peripheral singleton"] BT <= - virtual(BT_BB : { bind_bb_interrupt, enable_bb_interrupt, disable_bb_interrupt }, - RWBLE : { bind_rwble_interrupt, enable_rwble_interrupt, disable_rwble_interrupt - }, RWBT : { bind_rwbt_interrupt, enable_rwbt_interrupt, disable_rwbt_interrupt }) - (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "FLASH peripheral singleton"] FLASH <= virtual() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = + "BT peripheral singleton"] BT <= virtual(BT_BB : { bind_bb_interrupt, + enable_bb_interrupt, disable_bb_interrupt }, RWBLE : { bind_rwble_interrupt, + enable_rwble_interrupt, disable_rwble_interrupt }, RWBT : { bind_rwbt_interrupt, + enable_rwbt_interrupt, disable_rwbt_interrupt }) (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "FLASH peripheral singleton"] + FLASH <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "GPIO_DEDICATED peripheral singleton"] GPIO_DEDICATED <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "TSENS peripheral singleton"] TSENS <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = @@ -4580,13 +5461,11 @@ macro_rules! for_each_peripheral { _for_each_inner_peripheral!((USB_DEVICE(unstable))); _for_each_inner_peripheral!((XTS_AES(unstable))); _for_each_inner_peripheral!((ADC1(unstable))); - _for_each_inner_peripheral!((ADC2(unstable))); _for_each_inner_peripheral!((BT(unstable))); _for_each_inner_peripheral!((FLASH(unstable))); _for_each_inner_peripheral!((GPIO_DEDICATED(unstable))); _for_each_inner_peripheral!((TSENS(unstable))); _for_each_inner_peripheral!((WIFI)); - _for_each_inner_peripheral!((FROM_CPU_INTR0(unstable))); _for_each_inner_peripheral!((FROM_CPU_INTR1(unstable))); _for_each_inner_peripheral!((FROM_CPU_INTR2(unstable))); _for_each_inner_peripheral!((FROM_CPU_INTR3(unstable))); @@ -4776,7 +5655,6 @@ macro_rules! for_each_peripheral { disable_peri_interrupt }) (unstable)), (@ peri_type #[doc = "XTS_AES peripheral singleton"] XTS_AES <= XTS_AES() (unstable)), (@ peri_type #[doc = "ADC1 peripheral singleton"] ADC1 <= virtual() (unstable)), (@ peri_type - #[doc = "ADC2 peripheral singleton"] ADC2 <= virtual() (unstable)), (@ peri_type #[doc = "BT peripheral singleton"] BT <= virtual(BT_BB : { bind_bb_interrupt, enable_bb_interrupt, disable_bb_interrupt }, RWBLE : { bind_rwble_interrupt, enable_rwble_interrupt, disable_rwble_interrupt }, RWBT : { bind_rwbt_interrupt, @@ -4808,14 +5686,13 @@ macro_rules! for_each_peripheral { (SENSITIVE(unstable)), (SHA(unstable)), (SPI0(unstable)), (SPI1(unstable)), (SPI2), (SYSTEM(unstable)), (SYSTIMER(unstable)), (TIMG0(unstable)), (TIMG1(unstable)), (TWAI0(unstable)), (UART0), (UART1), (UHCI0(unstable)), - (USB_DEVICE(unstable)), (XTS_AES(unstable)), (ADC1(unstable)), (ADC2(unstable)), - (BT(unstable)), (FLASH(unstable)), (GPIO_DEDICATED(unstable)), (TSENS(unstable)), - (WIFI), (FROM_CPU_INTR0(unstable)), (FROM_CPU_INTR1(unstable)), - (FROM_CPU_INTR2(unstable)), (FROM_CPU_INTR3(unstable)))); - _for_each_inner_peripheral!((dma_eligible(SPI2, Spi2, 0, AhbGdmaChannel), (UHCI0, - Uhci0, 2, AhbGdmaChannel), (I2S0, I2s0, 3, AhbGdmaChannel), (AES, Aes, 6, - AhbGdmaChannel), (SHA, Sha, 7, AhbGdmaChannel), (APB_SARADC, ApbSaradc, 8, - AhbGdmaChannel))); + (USB_DEVICE(unstable)), (XTS_AES(unstable)), (ADC1(unstable)), (BT(unstable)), + (FLASH(unstable)), (GPIO_DEDICATED(unstable)), (TSENS(unstable)), (WIFI), + (FROM_CPU_INTR1(unstable)), (FROM_CPU_INTR2(unstable)), + (FROM_CPU_INTR3(unstable)))); _for_each_inner_peripheral!((dma_eligible(SPI2, + Spi2, 0, AhbGdmaChannel), (UHCI0, Uhci0, 2, AhbGdmaChannel), (I2S0, I2s0, 3, + AhbGdmaChannel), (AES, Aes, 6, AhbGdmaChannel), (SHA, Sha, 7, AhbGdmaChannel), + (APB_SARADC, ApbSaradc, 8, AhbGdmaChannel))); }; } /// This macro can be used to generate code for each `GPIOn` instance. @@ -4925,7 +5802,6 @@ macro_rules! for_each_analog_function { _for_each_inner_analog_function!((ADC1_CH2, GPIO2)); _for_each_inner_analog_function!((ADC1_CH3, GPIO3)); _for_each_inner_analog_function!((ADC1_CH4, GPIO4)); - _for_each_inner_analog_function!((ADC2_CH0, GPIO5)); _for_each_inner_analog_function!((USJ_DM, GPIO18)); _for_each_inner_analog_function!((USJ_DP, GPIO19)); _for_each_inner_analog_function!(((ADC1_CH0, ADCn_CHm, 1, 0), GPIO0)); @@ -4933,14 +5809,12 @@ macro_rules! for_each_analog_function { _for_each_inner_analog_function!(((ADC1_CH2, ADCn_CHm, 1, 2), GPIO2)); _for_each_inner_analog_function!(((ADC1_CH3, ADCn_CHm, 1, 3), GPIO3)); _for_each_inner_analog_function!(((ADC1_CH4, ADCn_CHm, 1, 4), GPIO4)); - _for_each_inner_analog_function!(((ADC2_CH0, ADCn_CHm, 2, 0), GPIO5)); _for_each_inner_analog_function!((all(ADC1_CH0, GPIO0), (ADC1_CH1, GPIO1), - (ADC1_CH2, GPIO2), (ADC1_CH3, GPIO3), (ADC1_CH4, GPIO4), (ADC2_CH0, GPIO5), - (USJ_DM, GPIO18), (USJ_DP, GPIO19))); - _for_each_inner_analog_function!((ADCn_CHm((ADC1_CH0, ADCn_CHm, 1, 0), GPIO0), - ((ADC1_CH1, ADCn_CHm, 1, 1), GPIO1), ((ADC1_CH2, ADCn_CHm, 1, 2), GPIO2), - ((ADC1_CH3, ADCn_CHm, 1, 3), GPIO3), ((ADC1_CH4, ADCn_CHm, 1, 4), GPIO4), - ((ADC2_CH0, ADCn_CHm, 2, 0), GPIO5))); + (ADC1_CH2, GPIO2), (ADC1_CH3, GPIO3), (ADC1_CH4, GPIO4), (USJ_DM, GPIO18), + (USJ_DP, GPIO19))); _for_each_inner_analog_function!((ADCn_CHm((ADC1_CH0, + ADCn_CHm, 1, 0), GPIO0), ((ADC1_CH1, ADCn_CHm, 1, 1), GPIO1), ((ADC1_CH2, + ADCn_CHm, 1, 2), GPIO2), ((ADC1_CH3, ADCn_CHm, 1, 3), GPIO3), ((ADC1_CH4, + ADCn_CHm, 1, 4), GPIO4))); }; } /// This macro can be used to generate code for each LP function of each GPIO. @@ -5135,9 +6009,6 @@ macro_rules! gpio_for_signal { (FSPIWP $(, $_fallback:literal)?) => { "GPIO5" }; - (ADC2_CH0 $(, $_fallback:literal)?) => { - "GPIO5" - }; (LP_GPIO5 $(, $_fallback:literal)?) => { "GPIO5" }; diff --git a/esp-metadata-generated/src/_generated_esp32c5.rs b/esp-metadata-generated/src/_generated_esp32c5.rs index b5e51e003e3..fc6dc18702b 100644 --- a/esp-metadata-generated/src/_generated_esp32c5.rs +++ b/esp-metadata-generated/src/_generated_esp32c5.rs @@ -88,6 +88,9 @@ macro_rules! property { ("gpio.func_in_sel_offset", str) => { stringify!(0) }; + ("gpio.need_soft_isolate_during_pd") => { + false + }; ("gpio.has_bank_1") => { false }; @@ -247,12 +250,6 @@ macro_rules! property { ("i2s.version", str) => { stringify!(3) }; - ("i2s.default_clock_source") => { - 2 - }; - ("i2s.default_clock_source", str) => { - stringify!(2) - }; ("i2s.mclk_divider_bit_width") => { 9 }; @@ -292,6 +289,15 @@ macro_rules! property { ("parl_io.version", str) => { stringify!(2) }; + ("parl_io.max_data_width") => { + 8 + }; + ("parl_io.max_data_width", str) => { + stringify!(8) + }; + ("parl_io.has_tx_cs") => { + true + }; ("rmt.ram_start") => { 1610638336 }; @@ -332,7 +338,7 @@ macro_rules! property { "npl" }; ("wifi.has_wifi6") => { - false + true }; ("wifi.mac_version") => { 3 @@ -346,7 +352,46 @@ macro_rules! property { ("wifi.csi_supported") => { true }; + ("wifi.has_nan") => { + true + }; + ("wifi.has_ftm") => { + true + }; ("phy.combo_module") => { + false + }; + ("adc.controller") => { + "digital" + }; + ("adc.channel_count") => { + 6 + }; + ("adc.channel_count", str) => { + stringify!(6) + }; + ("adc.line_calibration") => { + true + }; + ("adc.curve_calibration") => { + true + }; + ("adc.basic_calibration") => { + true + }; + ("adc.calibration_v1_scheme_supported") => { + true + }; + ("adc.channel_compensation") => { + true + }; + ("adc.pcr_clock") => { + true + }; + ("adc.pcr_sar_clk_div") => { + true + }; + ("adc.sar_power_override") => { true }; ("sdm.channel_count") => { @@ -361,6 +406,9 @@ macro_rules! property { ("timergroup.timg_has_divcnt_rst") => { true }; + ("timergroup.wdt_has_conf_update") => { + true + }; ("timergroup.rc_fast_calibration_divider_min_rev") => { 0 }; @@ -398,7 +446,7 @@ macro_rules! property { stringify!(16) }; ("rng.trng_supported") => { - false + true }; ("rng.is_lp_sys") => { true @@ -517,6 +565,9 @@ macro_rules! property { ("soc.cpu_has_csr_pc") => { false }; + ("soc.cpu_has_zcmp_workaround") => { + false + }; ("soc.multi_core_enabled") => { false }; @@ -538,6 +589,12 @@ macro_rules! property { ("soc.cpu_mcause_mask", str) => { stringify!(31) }; + ("soc.cpu_pmp_granularity") => { + 128 + }; + ("soc.cpu_pmp_granularity", str) => { + stringify!(128) + }; ("clock_tree.hp_root_clk") => { [crate ::soc::clocks::HpRootClkConfig::Xtal, crate ::soc::clocks::HpRootClkConfig::RcFast, crate @@ -559,10 +616,15 @@ macro_rules! property { ::soc::clocks::LpFastClkConfig::Xtal] }; ("clock_tree.lp_slow_clk") => { - [crate ::soc::clocks::LpSlowClkConfig::RcSlow, crate + [crate ::soc::clocks::LpSlowClkConfig::RcSlow, #[cfg(use_xtal32k)] crate ::soc::clocks::LpSlowClkConfig::Xtal32k, crate ::soc::clocks::LpSlowClkConfig::OscSlow] }; + ("clock_tree.ble_lp_clk") => { + [crate ::soc::clocks::BleLpClkConfig::Xtal, crate + ::soc::clocks::BleLpClkConfig::RcSlow, #[cfg(use_xtal32k)] crate + ::soc::clocks::BleLpClkConfig::Xtal32k] + }; ("clock_tree.crypto_clk") => { [crate ::soc::clocks::CryptoClkConfig::Xtal, crate ::soc::clocks::CryptoClkConfig::Fosc, crate @@ -576,8 +638,8 @@ macro_rules! property { ("clock_tree.timg_calibration_clock") => { [crate ::soc::clocks::TimgCalibrationClockConfig::OscSlowClk, crate ::soc::clocks::TimgCalibrationClockConfig::RcSlowClk, crate - ::soc::clocks::TimgCalibrationClockConfig::RcFastDivClk, crate - ::soc::clocks::TimgCalibrationClockConfig::Xtal32kClk] + ::soc::clocks::TimgCalibrationClockConfig::RcFastDivClk, #[cfg(use_xtal32k)] + crate ::soc::clocks::TimgCalibrationClockConfig::Xtal32kClk] }; ("clock_tree.uart.function_clock.sclk") => { [crate ::soc::clocks::UartFunctionClockSclk::Xtal, crate @@ -609,14 +671,44 @@ macro_rules! property { ::soc::clocks::RmtSclkConfig::PllF80m] }; ("clock_tree.parl_io.rx_clock") => { - [crate ::soc::clocks::ParlIoRxClockConfig::XtalClk, crate - ::soc::clocks::ParlIoRxClockConfig::RcFastClk, crate - ::soc::clocks::ParlIoRxClockConfig::PllF240m] + [crate ::soc::clocks::ParlIoClkConfig::XtalClk, crate + ::soc::clocks::ParlIoClkConfig::RcFastClk, crate + ::soc::clocks::ParlIoClkConfig::PllF240m] }; ("clock_tree.parl_io.tx_clock") => { - [crate ::soc::clocks::ParlIoTxClockConfig::XtalClk, crate - ::soc::clocks::ParlIoTxClockConfig::RcFastClk, crate - ::soc::clocks::ParlIoTxClockConfig::PllF240m] + [crate ::soc::clocks::ParlIoClkConfig::XtalClk, crate + ::soc::clocks::ParlIoClkConfig::RcFastClk, crate + ::soc::clocks::ParlIoClkConfig::PllF240m] + }; + ("clock_tree.i2s.tx_clk.sclk") => { + [crate ::soc::clocks::I2sClkSclk::Xtal, crate + ::soc::clocks::I2sClkSclk::PllF240m, crate ::soc::clocks::I2sClkSclk::PllF160m] + }; + ("clock_tree.i2s.tx_clk.div_num") => { + (1, 255) + }; + ("clock_tree.i2s.tx_clk.div_a") => { + (1, 511) + }; + ("clock_tree.i2s.tx_clk.div_b") => { + (0, 511) + }; + ("clock_tree.i2s.rx_clk.sclk") => { + [crate ::soc::clocks::I2sClkSclk::Xtal, crate + ::soc::clocks::I2sClkSclk::PllF240m, crate ::soc::clocks::I2sClkSclk::PllF160m] + }; + ("clock_tree.i2s.rx_clk.div_num") => { + (1, 255) + }; + ("clock_tree.i2s.rx_clk.div_a") => { + (1, 511) + }; + ("clock_tree.i2s.rx_clk.div_b") => { + (0, 511) + }; + ("clock_tree.i2s.mclk_out") => { + [crate ::soc::clocks::I2sMclkOutConfig::Tx, crate + ::soc::clocks::I2sMclkOutConfig::Rx] }; ("clock_tree.i2c.function_clock.sclk") => { [crate ::soc::clocks::I2cFunctionClockSclk::Xtal, crate @@ -631,6 +723,15 @@ macro_rules! property { ::soc::clocks::SpiFunctionClockConfig::PllF120m, crate ::soc::clocks::SpiFunctionClockConfig::RcFast] }; + ("clock_tree.twai.function_clock") => { + [crate ::soc::clocks::TwaiFunctionClockConfig::Xtal, crate + ::soc::clocks::TwaiFunctionClockConfig::PllF80m] + }; + ("clock_tree.adc.function_clock") => { + [crate ::soc::clocks::AdcFunctionClockConfig::Xtal, crate + ::soc::clocks::AdcFunctionClockConfig::RcFast, crate + ::soc::clocks::AdcFunctionClockConfig::PllF80m] + }; } #[macro_export] #[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] @@ -1268,6 +1369,7 @@ macro_rules! for_each_classified_interrupt { ([reserved 5] 6), ([reserved 6] 7), ([reserved 7] 8), ([reserved 8] 9), ([reserved 9] 10), ([reserved 10] 11), ([reserved 11] 12), ([reserved 12] 13), ([reserved 13] 14), ([reserved 14] 15))); + _for_each_inner_classified_interrupt!((context_switch)); }; } #[macro_export] @@ -1330,6 +1432,7 @@ macro_rules! for_each_sw_interrupt { /// /// // XTAL32K_CLK /// +/// #[cfg(use_xtal32k)] /// fn enable_xtal32k_clk_impl(_clocks: &mut ClockTree, _en: bool) { /// todo!() /// } @@ -1490,6 +1593,38 @@ macro_rules! for_each_sw_interrupt { /// todo!() /// } /// +/// // BLE_LP_XTAL_CLK +/// +/// fn enable_ble_lp_xtal_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// // BLE_LP_RC_SLOW_CLK +/// +/// fn enable_ble_lp_rc_slow_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// // BLE_LP_CLK +/// +/// fn enable_ble_lp_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_ble_lp_clk_impl( +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: BleLpClkConfig, +/// ) { +/// todo!() +/// } +/// +/// // CRYPTO_PLL_DIV +/// +/// fn enable_crypto_pll_div_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// /// // CRYPTO_CLK /// /// fn enable_crypto_clk_impl(_clocks: &mut ClockTree, _en: bool) { @@ -1528,6 +1663,22 @@ macro_rules! for_each_sw_interrupt { /// todo!() /// } /// +/// impl AdcInstance { +/// // ADC_FUNCTION_CLOCK +/// +/// fn enable_function_clock_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_function_clock_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: AdcFunctionClockConfig, +/// ) { +/// todo!() +/// } +/// } /// impl SdmInstance { /// // SDM_FUNCTION_CLOCK /// @@ -1551,6 +1702,52 @@ macro_rules! for_each_sw_interrupt { /// todo!() /// } /// } +/// impl I2sInstance { +/// // I2S_TX_CLK +/// +/// fn enable_tx_clk_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_tx_clk_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: I2sClkConfig, +/// ) { +/// todo!() +/// } +/// +/// // I2S_RX_CLK +/// +/// fn enable_rx_clk_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_rx_clk_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: I2sClkConfig, +/// ) { +/// todo!() +/// } +/// +/// // I2S_MCLK_OUT +/// +/// fn enable_mclk_out_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_mclk_out_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: I2sMclkOutConfig, +/// ) { +/// todo!() +/// } +/// } /// impl ParlIoInstance { /// // PARL_IO_RX_CLOCK /// @@ -1561,8 +1758,8 @@ macro_rules! for_each_sw_interrupt { /// fn configure_rx_clock_impl( /// self, /// _clocks: &mut ClockTree, -/// _old_config: Option, -/// _new_config: ParlIoRxClockConfig, +/// _old_config: Option, +/// _new_config: ParlIoClkConfig, /// ) { /// todo!() /// } @@ -1576,8 +1773,8 @@ macro_rules! for_each_sw_interrupt { /// fn configure_tx_clock_impl( /// self, /// _clocks: &mut ClockTree, -/// _old_config: Option, -/// _new_config: ParlIoTxClockConfig, +/// _old_config: Option, +/// _new_config: ParlIoClkConfig, /// ) { /// todo!() /// } @@ -1645,6 +1842,22 @@ macro_rules! for_each_sw_interrupt { /// todo!() /// } /// } +/// impl TwaiInstance { +/// // TWAI_FUNCTION_CLOCK +/// +/// fn enable_function_clock_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_function_clock_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: TwaiFunctionClockConfig, +/// ) { +/// todo!() +/// } +/// } /// impl UartInstance { /// // UART_FUNCTION_CLOCK /// @@ -1679,6 +1892,11 @@ macro_rules! for_each_sw_interrupt { /// ``` macro_rules! define_clock_tree_types { () => { + #[derive(Clone, Copy, PartialEq, Eq, Debug)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum AdcInstance { + ApbSaradc = 0, + } #[derive(Clone, Copy, PartialEq, Eq, Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum SdmInstance { @@ -1691,6 +1909,11 @@ macro_rules! define_clock_tree_types { } #[derive(Clone, Copy, PartialEq, Eq, Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum I2sInstance { + I2s0 = 0, + } + #[derive(Clone, Copy, PartialEq, Eq, Debug)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum ParlIoInstance { ParlIo = 0, } @@ -1712,6 +1935,12 @@ macro_rules! define_clock_tree_types { } #[derive(Clone, Copy, PartialEq, Eq, Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum TwaiInstance { + Twai0 = 0, + Twai1 = 1, + } + #[derive(Clone, Copy, PartialEq, Eq, Debug)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum UartInstance { Uart0 = 0, Uart1 = 1, @@ -1768,7 +1997,7 @@ macro_rules! define_clock_tree_types { ); Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -1794,7 +2023,7 @@ macro_rules! define_clock_tree_types { ); Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -1820,7 +2049,7 @@ macro_rules! define_clock_tree_types { ); Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -1841,11 +2070,24 @@ macro_rules! define_clock_tree_types { pub enum LpSlowClkConfig { /// Selects `RC_SLOW_CLK`. RcSlow, + #[cfg(use_xtal32k)] /// Selects `XTAL32K_CLK`. Xtal32k, /// Selects `OSC_SLOW_CLK`. OscSlow, } + /// The list of clock signals that the `BLE_LP_CLK` multiplexer can output. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum BleLpClkConfig { + /// Selects `BLE_LP_XTAL_CLK`. + Xtal, + /// Selects `BLE_LP_RC_SLOW_CLK`. + RcSlow, + #[cfg(use_xtal32k)] + /// Selects `XTAL32K_CLK`. + Xtal32k, + } /// The list of clock signals that the `CRYPTO_CLK` multiplexer can output. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] @@ -1854,7 +2096,7 @@ macro_rules! define_clock_tree_types { Xtal, /// Selects `RC_FAST_CLK`. Fosc, - /// Selects `PLL_CLK`. + /// Selects `CRYPTO_PLL_DIV`. PllF480m, } /// The list of clock signals that the `IOMUX_FUNCTION_CLOCK` multiplexer can output. @@ -1879,9 +2121,22 @@ macro_rules! define_clock_tree_types { RcSlowClk, /// Selects `RC_FAST_CLK`. RcFastDivClk, + #[cfg(use_xtal32k)] /// Selects `XTAL32K_CLK`. Xtal32kClk, } + /// The list of clock signals that the `APB_SARADC_FUNCTION_CLOCK` multiplexer can output. + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum AdcFunctionClockConfig { + /// Selects `XTAL_CLK`. + Xtal, + /// Selects `RC_FAST_CLK`. + RcFast, + #[default] + /// Selects `PLL_F80M`. + PllF80m, + } #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum I2cFunctionClockSclk { @@ -1914,29 +2169,95 @@ macro_rules! define_clock_tree_types { ); Self { sclk, div_num } } - pub(crate) fn sclk(self) -> I2cFunctionClockSclk { + pub fn sclk(self) -> I2cFunctionClockSclk { self.sclk } - pub(crate) fn div_num(self) -> u32 { + pub fn div_num(self) -> u32 { self.div_num as u32 } } - /// The list of clock signals that the `PARL_IO_RX_CLOCK` multiplexer can output. #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] - pub enum ParlIoRxClockConfig { + pub enum I2sClkSclk { /// Selects `XTAL_CLK`. - XtalClk, - /// Selects `RC_FAST_CLK`. - RcFastClk, - #[default] + Xtal, /// Selects `PLL_F240M`. PllF240m, + #[default] + /// Selects `PLL_F160M`. + PllF160m, + } + /// Configures the `I2S0_TX_CLK` clock node. + /// + /// The output is calculated as `OUTPUT = (sclk * div_a) / (div_num * div_a + div_b)`. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub struct I2sClkConfig { + sclk: I2sClkSclk, + div_num: u32, + div_a: u32, + div_b: u32, + } + impl I2sClkConfig { + /// Creates a new configuration for the TX_CLK clock node. + /// + /// ## Panics + /// + /// Panics if the div_num value is outside the + /// valid range (1 ..= 255). + /// + /// Panics if the div_a value is outside the + /// valid range (1 ..= 511). + /// + /// Panics if the div_b value is outside the + /// valid range (0 ..= 511). + pub const fn new(sclk: I2sClkSclk, div_num: u32, div_a: u32, div_b: u32) -> Self { + ::core::assert!( + div_num >= 1 && div_num <= 255, + "`I2S0_TX_CLK` div_num must be between 1 and 255 (inclusive)." + ); + ::core::assert!( + div_a >= 1 && div_a <= 511, + "`I2S0_TX_CLK` div_a must be between 1 and 511 (inclusive)." + ); + ::core::assert!( + div_b <= 511, + "`I2S0_TX_CLK` div_b must be between 0 and 511 (inclusive)." + ); + Self { + sclk, + div_num, + div_a, + div_b, + } + } + pub fn sclk(self) -> I2sClkSclk { + self.sclk + } + pub fn div_num(self) -> u32 { + self.div_num as u32 + } + pub fn div_a(self) -> u32 { + self.div_a as u32 + } + pub fn div_b(self) -> u32 { + self.div_b as u32 + } + } + /// The list of clock signals that the `I2S0_MCLK_OUT` multiplexer can output. + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum I2sMclkOutConfig { + /// Selects `TX_CLK`. + Tx, + #[default] + /// Selects `RX_CLK`. + Rx, } - /// The list of clock signals that the `PARL_IO_TX_CLOCK` multiplexer can output. + /// The list of clock signals that the `PARL_IO_RX_CLOCK` multiplexer can output. #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] - pub enum ParlIoTxClockConfig { + pub enum ParlIoClkConfig { /// Selects `XTAL_CLK`. XtalClk, /// Selects `RC_FAST_CLK`. @@ -1961,9 +2282,9 @@ macro_rules! define_clock_tree_types { #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum SpiFunctionClockConfig { - #[default] /// Selects `XTAL_CLK`. Xtal, + #[default] /// Selects `PLL_F160M`. PllF160m, /// Selects `PLL_F120M`. @@ -1995,6 +2316,16 @@ macro_rules! define_clock_tree_types { /// Selects `RC_FAST_CLK`. RcFastClk, } + /// The list of clock signals that the `TWAI0_FUNCTION_CLOCK` multiplexer can output. + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum TwaiFunctionClockConfig { + /// Selects `XTAL_CLK`. + Xtal, + #[default] + /// Selects `PLL_F80M`. + PllF80m, + } #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum UartFunctionClockSclk { @@ -2029,10 +2360,10 @@ macro_rules! define_clock_tree_types { ); Self { sclk, div_num } } - pub(crate) fn sclk(self) -> UartFunctionClockSclk { + pub fn sclk(self) -> UartFunctionClockSclk { self.sclk } - pub(crate) fn div_num(self) -> u32 { + pub fn div_num(self) -> u32 { self.div_num as u32 } } @@ -2070,10 +2401,10 @@ macro_rules! define_clock_tree_types { integral, } } - pub(crate) fn fractional(self) -> u32 { + pub fn fractional(self) -> u32 { self.fractional as u32 } - pub(crate) fn integral(self) -> u32 { + pub fn integral(self) -> u32 { self.integral as u32 } } @@ -2086,20 +2417,27 @@ macro_rules! define_clock_tree_types { apb_clk: Option, lp_fast_clk: Option, lp_slow_clk: Option, + ble_lp_clk: Option, crypto_clk: Option, iomux_function_clock: Option, timg_calibration_clock: Option, + adc_function_clock: [Option; 1], i2c_function_clock: [Option; 1], - parl_io_rx_clock: [Option; 1], - parl_io_tx_clock: [Option; 1], + i2s_tx_clk: [Option; 1], + i2s_rx_clk: [Option; 1], + i2s_mclk_out: [Option; 1], + parl_io_rx_clock: [Option; 1], + parl_io_tx_clock: [Option; 1], rmt_sclk: [Option; 1], spi_function_clock: [Option; 1], timg_function_clock: [Option; 2], timg_wdt_clock: [Option; 2], + twai_function_clock: [Option; 2], uart_function_clock: [Option; 2], uart_baud_rate_generator: [Option; 2], pll_clk_refcount: u32, rc_fast_clk_refcount: u32, + #[cfg(use_xtal32k)] xtal32k_clk_refcount: u32, osc_slow_clk_refcount: u32, rc_slow_clk_refcount: u32, @@ -2116,16 +2454,22 @@ macro_rules! define_clock_tree_types { apb_clk_refcount: u32, lp_fast_clk_refcount: u32, lp_slow_clk_refcount: u32, + ble_lp_clk_refcount: u32, crypto_clk_refcount: u32, timg_calibration_clock_refcount: u32, + adc_function_clock_refcount: [u32; 1], sdm_function_clock_refcount: [u32; 1], i2c_function_clock_refcount: [u32; 1], + i2s_tx_clk_refcount: [u32; 1], + i2s_rx_clk_refcount: [u32; 1], + i2s_mclk_out_refcount: [u32; 1], parl_io_rx_clock_refcount: [u32; 1], parl_io_tx_clock_refcount: [u32; 1], rmt_sclk_refcount: [u32; 1], spi_function_clock_refcount: [u32; 1], timg_function_clock_refcount: [u32; 2], timg_wdt_clock_refcount: [u32; 2], + twai_function_clock_refcount: [u32; 2], uart_function_clock_refcount: [u32; 2], uart_baud_rate_generator_refcount: [u32; 2], } @@ -2162,6 +2506,10 @@ macro_rules! define_clock_tree_types { pub fn lp_slow_clk(&self) -> Option { self.lp_slow_clk } + /// Returns the current configuration of the BLE_LP_CLK clock tree node + pub fn ble_lp_clk(&self) -> Option { + self.ble_lp_clk + } /// Returns the current configuration of the CRYPTO_CLK clock tree node pub fn crypto_clk(&self) -> Option { self.crypto_clk @@ -2174,16 +2522,32 @@ macro_rules! define_clock_tree_types { pub fn timg_calibration_clock(&self) -> Option { self.timg_calibration_clock } + /// Returns the current configuration of the APB_SARADC_FUNCTION_CLOCK clock tree node + pub fn apb_saradc_function_clock(&self) -> Option { + self.adc_function_clock[AdcInstance::ApbSaradc as usize] + } /// Returns the current configuration of the I2C0_FUNCTION_CLOCK clock tree node pub fn i2c0_function_clock(&self) -> Option { self.i2c_function_clock[I2cInstance::I2c0 as usize] } + /// Returns the current configuration of the I2S0_TX_CLK clock tree node + pub fn i2s0_tx_clk(&self) -> Option { + self.i2s_tx_clk[I2sInstance::I2s0 as usize] + } + /// Returns the current configuration of the I2S0_RX_CLK clock tree node + pub fn i2s0_rx_clk(&self) -> Option { + self.i2s_rx_clk[I2sInstance::I2s0 as usize] + } + /// Returns the current configuration of the I2S0_MCLK_OUT clock tree node + pub fn i2s0_mclk_out(&self) -> Option { + self.i2s_mclk_out[I2sInstance::I2s0 as usize] + } /// Returns the current configuration of the PARL_IO_RX_CLOCK clock tree node - pub fn parl_io_rx_clock(&self) -> Option { + pub fn parl_io_rx_clock(&self) -> Option { self.parl_io_rx_clock[ParlIoInstance::ParlIo as usize] } /// Returns the current configuration of the PARL_IO_TX_CLOCK clock tree node - pub fn parl_io_tx_clock(&self) -> Option { + pub fn parl_io_tx_clock(&self) -> Option { self.parl_io_tx_clock[ParlIoInstance::ParlIo as usize] } /// Returns the current configuration of the RMT_SCLK clock tree node @@ -2210,6 +2574,14 @@ macro_rules! define_clock_tree_types { pub fn timg1_wdt_clock(&self) -> Option { self.timg_wdt_clock[TimgInstance::Timg1 as usize] } + /// Returns the current configuration of the TWAI0_FUNCTION_CLOCK clock tree node + pub fn twai0_function_clock(&self) -> Option { + self.twai_function_clock[TwaiInstance::Twai0 as usize] + } + /// Returns the current configuration of the TWAI1_FUNCTION_CLOCK clock tree node + pub fn twai1_function_clock(&self) -> Option { + self.twai_function_clock[TwaiInstance::Twai1 as usize] + } /// Returns the current configuration of the UART0_FUNCTION_CLOCK clock tree node pub fn uart0_function_clock(&self) -> Option { self.uart_function_clock[UartInstance::Uart0 as usize] @@ -2236,20 +2608,27 @@ macro_rules! define_clock_tree_types { apb_clk: None, lp_fast_clk: None, lp_slow_clk: None, + ble_lp_clk: None, crypto_clk: None, iomux_function_clock: None, timg_calibration_clock: None, + adc_function_clock: [None; 1], i2c_function_clock: [None; 1], + i2s_tx_clk: [None; 1], + i2s_rx_clk: [None; 1], + i2s_mclk_out: [None; 1], parl_io_rx_clock: [None; 1], parl_io_tx_clock: [None; 1], rmt_sclk: [None; 1], spi_function_clock: [None; 1], timg_function_clock: [None; 2], timg_wdt_clock: [None; 2], + twai_function_clock: [None; 2], uart_function_clock: [None; 2], uart_baud_rate_generator: [None; 2], pll_clk_refcount: 0, rc_fast_clk_refcount: 0, + #[cfg(use_xtal32k)] xtal32k_clk_refcount: 0, osc_slow_clk_refcount: 0, rc_slow_clk_refcount: 0, @@ -2266,16 +2645,22 @@ macro_rules! define_clock_tree_types { apb_clk_refcount: 0, lp_fast_clk_refcount: 0, lp_slow_clk_refcount: 0, + ble_lp_clk_refcount: 0, crypto_clk_refcount: 0, timg_calibration_clock_refcount: 0, + adc_function_clock_refcount: [0; 1], sdm_function_clock_refcount: [0; 1], i2c_function_clock_refcount: [0; 1], + i2s_tx_clk_refcount: [0; 1], + i2s_rx_clk_refcount: [0; 1], + i2s_mclk_out_refcount: [0; 1], parl_io_rx_clock_refcount: [0; 1], parl_io_tx_clock_refcount: [0; 1], rmt_sclk_refcount: [0; 1], spi_function_clock_refcount: [0; 1], timg_function_clock_refcount: [0; 2], timg_wdt_clock_refcount: [0; 2], + twai_function_clock_refcount: [0; 2], uart_function_clock_refcount: [0; 2], uart_baud_rate_generator_refcount: [0; 2], }); @@ -2293,14 +2678,24 @@ macro_rules! define_clock_tree_types { ::core::sync::atomic::AtomicU32::new(0); static LP_SLOW_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); + static BLE_LP_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(0); static CRYPTO_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); static IOMUX_FUNCTION_CLOCK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); static TIMG_CALIBRATION_CLOCK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); + static ADC_FUNCTION_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; static I2C_FUNCTION_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; + static I2S_TX_CLK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; + static I2S_RX_CLK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; + static I2S_MCLK_OUT_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; static PARL_IO_RX_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; static PARL_IO_TX_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = @@ -2313,42 +2708,219 @@ macro_rules! define_clock_tree_types { [const { ::core::sync::atomic::AtomicU32::new(0) }; 2]; static TIMG_WDT_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 2] = [const { ::core::sync::atomic::AtomicU32::new(0) }; 2]; + static TWAI_FUNCTION_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 2] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 2]; static UART_FUNCTION_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 2] = [const { ::core::sync::atomic::AtomicU32::new(0) }; 2]; static UART_BAUD_RATE_GENERATOR_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 2] = [const { ::core::sync::atomic::AtomicU32::new(0) }; 2]; - pub fn configure_xtal_clk(clocks: &mut ClockTree, config: XtalClkConfig) { - let old_config = clocks.xtal_clk.replace(config); - refresh_xtal_clk_downstream(clocks); - configure_xtal_clk_impl(clocks, old_config, config); + /// The clock sources of the device. + /// + /// A clock source is a node of the clock tree that other nodes derive their output + /// from. Ask a node which source it runs on with its `..._root_source` function. + #[derive(Debug, enumset::EnumSetType)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum ClockSource { + /// `XTAL_CLK`. + XtalClk, + /// `RC_FAST_CLK`. + RcFastClk, + #[cfg(use_xtal32k)] + /// `XTAL32K_CLK`. + Xtal32kClk, + /// `OSC_SLOW_CLK`. + OscSlowClk, + /// `RC_SLOW_CLK`. + RcSlowClk, } - pub fn xtal_clk_config(clocks: &mut ClockTree) -> Option { - clocks.xtal_clk + /// Returns the clock source that `XTAL_CLK` currently runs on. + pub fn xtal_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::XtalClk) } - fn request_xtal_clk(_clocks: &mut ClockTree) {} - fn release_xtal_clk(_clocks: &mut ClockTree) {} - #[allow(unused_variables)] - pub fn xtal_clk_config_frequency(clocks: &mut ClockTree, config: XtalClkConfig) -> u32 { - config.value() + /// Returns the clock source that `PLL_CLK` currently runs on. + pub fn pll_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) } - pub fn xtal_clk_frequency() -> u32 { - XTAL_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) + /// Returns the clock source that `RC_FAST_CLK` currently runs on. + pub fn rc_fast_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::RcFastClk) } - pub fn request_pll_clk(clocks: &mut ClockTree) { - trace!("Requesting PLL_CLK"); - if increment_reference_count(&mut clocks.pll_clk_refcount) { - trace!("Enabling PLL_CLK"); - request_xtal_clk(clocks); - enable_pll_clk_impl(clocks, true); - } + #[cfg(use_xtal32k)] + /// Returns the clock source that `XTAL32K_CLK` currently runs on. + pub fn xtal32k_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::Xtal32kClk) } - pub fn release_pll_clk(clocks: &mut ClockTree) { - trace!("Releasing PLL_CLK"); - if decrement_reference_count(&mut clocks.pll_clk_refcount) { - trace!("Disabling PLL_CLK"); - enable_pll_clk_impl(clocks, false); - release_xtal_clk(clocks); - } + /// Returns the clock source that `OSC_SLOW_CLK` currently runs on. + pub fn osc_slow_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::OscSlowClk) + } + /// Returns the clock source that `RC_SLOW_CLK` currently runs on. + pub fn rc_slow_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::RcSlowClk) + } + /// Returns the clock source that `PLL_F12M` currently runs on. + pub fn pll_f12m_root_source(clocks: &mut ClockTree) -> Option { + pll_clk_root_source(clocks) + } + /// Returns the clock source that `PLL_F20M` currently runs on. + pub fn pll_f20m_root_source(clocks: &mut ClockTree) -> Option { + pll_clk_root_source(clocks) + } + /// Returns the clock source that `PLL_F40M` currently runs on. + pub fn pll_f40m_root_source(clocks: &mut ClockTree) -> Option { + pll_clk_root_source(clocks) + } + /// Returns the clock source that `PLL_F48M` currently runs on. + pub fn pll_f48m_root_source(clocks: &mut ClockTree) -> Option { + pll_clk_root_source(clocks) + } + /// Returns the clock source that `PLL_F60M` currently runs on. + pub fn pll_f60m_root_source(clocks: &mut ClockTree) -> Option { + pll_clk_root_source(clocks) + } + /// Returns the clock source that `PLL_F80M` currently runs on. + pub fn pll_f80m_root_source(clocks: &mut ClockTree) -> Option { + pll_clk_root_source(clocks) + } + /// Returns the clock source that `PLL_F120M` currently runs on. + pub fn pll_f120m_root_source(clocks: &mut ClockTree) -> Option { + pll_clk_root_source(clocks) + } + /// Returns the clock source that `PLL_F160M` currently runs on. + pub fn pll_f160m_root_source(clocks: &mut ClockTree) -> Option { + pll_clk_root_source(clocks) + } + /// Returns the clock source that `PLL_F240M` currently runs on. + pub fn pll_f240m_root_source(clocks: &mut ClockTree) -> Option { + pll_clk_root_source(clocks) + } + /// Returns the clock source that `HP_ROOT_CLK` currently runs on. + pub fn hp_root_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.hp_root_clk?; + match config { + HpRootClkConfig::Xtal => xtal_clk_root_source(clocks), + HpRootClkConfig::RcFast => rc_fast_clk_root_source(clocks), + HpRootClkConfig::PllF160m => pll_f160m_root_source(clocks), + HpRootClkConfig::PllF240m => pll_f240m_root_source(clocks), + } + } + /// Returns the clock source that `CPU_CLK` currently runs on. + pub fn cpu_clk_root_source(clocks: &mut ClockTree) -> Option { + hp_root_clk_root_source(clocks) + } + /// Returns the clock source that `AHB_CLK` currently runs on. + pub fn ahb_clk_root_source(clocks: &mut ClockTree) -> Option { + hp_root_clk_root_source(clocks) + } + /// Returns the clock source that `APB_CLK` currently runs on. + pub fn apb_clk_root_source(clocks: &mut ClockTree) -> Option { + ahb_clk_root_source(clocks) + } + /// Returns the clock source that `XTAL_D2_CLK` currently runs on. + pub fn xtal_d2_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `LP_FAST_CLK` currently runs on. + pub fn lp_fast_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.lp_fast_clk?; + match config { + LpFastClkConfig::RcFast => rc_fast_clk_root_source(clocks), + LpFastClkConfig::XtalD2 => xtal_d2_clk_root_source(clocks), + LpFastClkConfig::Xtal => xtal_clk_root_source(clocks), + } + } + /// Returns the clock source that `LP_SLOW_CLK` currently runs on. + pub fn lp_slow_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.lp_slow_clk?; + match config { + LpSlowClkConfig::RcSlow => rc_slow_clk_root_source(clocks), + #[cfg(use_xtal32k)] + LpSlowClkConfig::Xtal32k => xtal32k_clk_root_source(clocks), + LpSlowClkConfig::OscSlow => osc_slow_clk_root_source(clocks), + } + } + /// Returns the clock source that `BLE_LP_XTAL_CLK` currently runs on. + pub fn ble_lp_xtal_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `BLE_LP_RC_SLOW_CLK` currently runs on. + pub fn ble_lp_rc_slow_clk_root_source(clocks: &mut ClockTree) -> Option { + rc_slow_clk_root_source(clocks) + } + /// Returns the clock source that `BLE_LP_CLK` currently runs on. + pub fn ble_lp_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.ble_lp_clk?; + match config { + BleLpClkConfig::Xtal => ble_lp_xtal_clk_root_source(clocks), + BleLpClkConfig::RcSlow => ble_lp_rc_slow_clk_root_source(clocks), + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => xtal32k_clk_root_source(clocks), + } + } + /// Returns the clock source that `CRYPTO_PLL_DIV` currently runs on. + pub fn crypto_pll_div_root_source(clocks: &mut ClockTree) -> Option { + pll_clk_root_source(clocks) + } + /// Returns the clock source that `CRYPTO_CLK` currently runs on. + pub fn crypto_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.crypto_clk?; + match config { + CryptoClkConfig::Xtal => xtal_clk_root_source(clocks), + CryptoClkConfig::Fosc => rc_fast_clk_root_source(clocks), + CryptoClkConfig::PllF480m => crypto_pll_div_root_source(clocks), + } + } + /// Returns the clock source that `IOMUX_FUNCTION_CLOCK` currently runs on. + pub fn iomux_function_clock_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.iomux_function_clock?; + match config { + IomuxFunctionClockConfig::XtalClk => xtal_clk_root_source(clocks), + IomuxFunctionClockConfig::RcFastClk => rc_fast_clk_root_source(clocks), + IomuxFunctionClockConfig::PllF80m => pll_f80m_root_source(clocks), + } + } + /// Returns the clock source that `TIMG_CALIBRATION_CLOCK` currently runs on. + pub fn timg_calibration_clock_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.timg_calibration_clock?; + match config { + TimgCalibrationClockConfig::OscSlowClk => osc_slow_clk_root_source(clocks), + TimgCalibrationClockConfig::RcSlowClk => rc_slow_clk_root_source(clocks), + TimgCalibrationClockConfig::RcFastDivClk => rc_fast_clk_root_source(clocks), + #[cfg(use_xtal32k)] + TimgCalibrationClockConfig::Xtal32kClk => xtal32k_clk_root_source(clocks), + } + } + pub fn configure_xtal_clk(clocks: &mut ClockTree, config: XtalClkConfig) { + let old_config = clocks.xtal_clk.replace(config); + refresh_xtal_clk_downstream(clocks); + configure_xtal_clk_impl(clocks, old_config, config); + } + pub fn xtal_clk_config(clocks: &mut ClockTree) -> Option { + clocks.xtal_clk + } + fn request_xtal_clk(_clocks: &mut ClockTree) {} + fn release_xtal_clk(_clocks: &mut ClockTree) {} + pub fn xtal_clk_config_frequency(config: XtalClkConfig) -> u32 { + config.value() + } + pub fn xtal_clk_frequency() -> u32 { + XTAL_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn request_pll_clk(clocks: &mut ClockTree) { + trace!("Requesting PLL_CLK"); + if increment_reference_count(&mut clocks.pll_clk_refcount) { + trace!("Enabling PLL_CLK"); + request_xtal_clk(clocks); + enable_pll_clk_impl(clocks, true); + } + } + pub fn release_pll_clk(clocks: &mut ClockTree) { + trace!("Releasing PLL_CLK"); + if decrement_reference_count(&mut clocks.pll_clk_refcount) { + trace!("Disabling PLL_CLK"); + enable_pll_clk_impl(clocks, false); + release_xtal_clk(clocks); + } } pub fn pll_clk_frequency() -> u32 { 480000000 @@ -2370,9 +2942,31 @@ macro_rules! define_clock_tree_types { enable_rc_fast_clk_impl(clocks, false); } } - pub fn rc_fast_clk_frequency() -> u32 { + static RC_FAST_CLK_FREQUENCY: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(rc_fast_clk_nominal_frequency()); + pub const fn rc_fast_clk_nominal_frequency() -> u32 { 20000000 } + pub fn rc_fast_clk_frequency() -> u32 { + RC_FAST_CLK_FREQUENCY.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn set_rc_fast_clk_frequency(clocks: &mut ClockTree, frequency: u32) { + if !(10000000..=30000000).contains(&frequency) { + warn!( + "Ignoring out-of-range RC_FAST_CLK frequency: {} Hz", + frequency + ); + return; + } + debug!( + "Updating RC_FAST_CLK frequency to {} Hz (nominal {} Hz)", + frequency, + rc_fast_clk_nominal_frequency() + ); + RC_FAST_CLK_FREQUENCY.store(frequency, ::core::sync::atomic::Ordering::Release); + refresh_rc_fast_clk_downstream(clocks); + } + #[cfg(use_xtal32k)] pub fn request_xtal32k_clk(clocks: &mut ClockTree) { trace!("Requesting XTAL32K_CLK"); if increment_reference_count(&mut clocks.xtal32k_clk_refcount) { @@ -2380,6 +2974,7 @@ macro_rules! define_clock_tree_types { enable_xtal32k_clk_impl(clocks, true); } } + #[cfg(use_xtal32k)] pub fn release_xtal32k_clk(clocks: &mut ClockTree) { trace!("Releasing XTAL32K_CLK"); if decrement_reference_count(&mut clocks.xtal32k_clk_refcount) { @@ -2387,6 +2982,7 @@ macro_rules! define_clock_tree_types { enable_xtal32k_clk_impl(clocks, false); } } + #[cfg(use_xtal32k)] pub fn xtal32k_clk_frequency() -> u32 { 32768 } @@ -2421,9 +3017,30 @@ macro_rules! define_clock_tree_types { enable_rc_slow_clk_impl(clocks, false); } } - pub fn rc_slow_clk_frequency() -> u32 { + static RC_SLOW_CLK_FREQUENCY: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(rc_slow_clk_nominal_frequency()); + pub const fn rc_slow_clk_nominal_frequency() -> u32 { 130000 } + pub fn rc_slow_clk_frequency() -> u32 { + RC_SLOW_CLK_FREQUENCY.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn set_rc_slow_clk_frequency(clocks: &mut ClockTree, frequency: u32) { + if !(65000..=195000).contains(&frequency) { + warn!( + "Ignoring out-of-range RC_SLOW_CLK frequency: {} Hz", + frequency + ); + return; + } + debug!( + "Updating RC_SLOW_CLK frequency to {} Hz (nominal {} Hz)", + frequency, + rc_slow_clk_nominal_frequency() + ); + RC_SLOW_CLK_FREQUENCY.store(frequency, ::core::sync::atomic::Ordering::Release); + refresh_rc_slow_clk_downstream(clocks); + } pub fn request_pll_f12m(clocks: &mut ClockTree) { trace!("Requesting PLL_F12M"); if increment_reference_count(&mut clocks.pll_f12m_refcount) { @@ -2557,13 +3174,11 @@ macro_rules! define_clock_tree_types { pll_clk_frequency() } pub fn request_pll_f120m(clocks: &mut ClockTree) { - trace!("Requesting PLL_F120M"); trace!("Enabling PLL_F120M"); request_pll_clk(clocks); enable_pll_f120m_impl(clocks, true); } pub fn release_pll_f120m(clocks: &mut ClockTree) { - trace!("Releasing PLL_F120M"); trace!("Disabling PLL_F120M"); enable_pll_f120m_impl(clocks, false); release_pll_clk(clocks); @@ -2621,24 +3236,23 @@ macro_rules! define_clock_tree_types { pub fn configure_hp_root_clk(clocks: &mut ClockTree, new_selector: HpRootClkConfig) { let old_selector = clocks.hp_root_clk.replace(new_selector); refresh_hp_root_clk_downstream(clocks); - if clocks.hp_root_clk_refcount > 0 { + let active = clocks.hp_root_clk_refcount > 0; + if active { match new_selector { HpRootClkConfig::Xtal => request_xtal_clk(clocks), HpRootClkConfig::RcFast => request_rc_fast_clk(clocks), HpRootClkConfig::PllF160m => request_pll_f160m(clocks), HpRootClkConfig::PllF240m => request_pll_f240m(clocks), } - configure_hp_root_clk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - HpRootClkConfig::Xtal => release_xtal_clk(clocks), - HpRootClkConfig::RcFast => release_rc_fast_clk(clocks), - HpRootClkConfig::PllF160m => release_pll_f160m(clocks), - HpRootClkConfig::PllF240m => release_pll_f240m(clocks), - } + } + configure_hp_root_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + HpRootClkConfig::Xtal => release_xtal_clk(clocks), + HpRootClkConfig::RcFast => release_rc_fast_clk(clocks), + HpRootClkConfig::PllF160m => release_pll_f160m(clocks), + HpRootClkConfig::PllF240m => release_pll_f240m(clocks), } - } else { - configure_hp_root_clk_impl(clocks, old_selector, new_selector); } } pub fn hp_root_clk_config(clocks: &mut ClockTree) -> Option { @@ -2670,11 +3284,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn hp_root_clk_config_frequency( - clocks: &mut ClockTree, - config: HpRootClkConfig, - ) -> u32 { + pub fn hp_root_clk_config_frequency(config: HpRootClkConfig) -> u32 { match config { HpRootClkConfig::Xtal => xtal_clk_frequency(), HpRootClkConfig::RcFast => rc_fast_clk_frequency(), @@ -2686,12 +3296,7 @@ macro_rules! define_clock_tree_types { HP_ROOT_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn hp_root_clk_source_frequency(source: HpRootClkConfig) -> u32 { - match source { - HpRootClkConfig::Xtal => xtal_clk_frequency(), - HpRootClkConfig::RcFast => rc_fast_clk_frequency(), - HpRootClkConfig::PllF160m => pll_f160m_frequency(), - HpRootClkConfig::PllF240m => pll_f240m_frequency(), - } + hp_root_clk_config_frequency(source) } pub fn configure_cpu_clk(clocks: &mut ClockTree, config: CpuClkConfig) { let old_config = clocks.cpu_clk.replace(config); @@ -2717,8 +3322,7 @@ macro_rules! define_clock_tree_types { release_hp_root_clk(clocks); } } - #[allow(unused_variables)] - pub fn cpu_clk_config_frequency(clocks: &mut ClockTree, config: CpuClkConfig) -> u32 { + pub fn cpu_clk_config_frequency(config: CpuClkConfig) -> u32 { (hp_root_clk_frequency() / (config.divisor() + 1)) } pub fn cpu_clk_frequency() -> u32 { @@ -2736,19 +3340,16 @@ macro_rules! define_clock_tree_types { clocks.ahb_clk } pub fn request_ahb_clk(clocks: &mut ClockTree) { - trace!("Requesting AHB_CLK"); trace!("Enabling AHB_CLK"); request_hp_root_clk(clocks); enable_ahb_clk_impl(clocks, true); } pub fn release_ahb_clk(clocks: &mut ClockTree) { - trace!("Releasing AHB_CLK"); trace!("Disabling AHB_CLK"); enable_ahb_clk_impl(clocks, false); release_hp_root_clk(clocks); } - #[allow(unused_variables)] - pub fn ahb_clk_config_frequency(clocks: &mut ClockTree, config: AhbClkConfig) -> u32 { + pub fn ahb_clk_config_frequency(config: AhbClkConfig) -> u32 { (hp_root_clk_frequency() / (config.divisor() + 1)) } pub fn ahb_clk_frequency() -> u32 { @@ -2781,8 +3382,7 @@ macro_rules! define_clock_tree_types { release_ahb_clk(clocks); } } - #[allow(unused_variables)] - pub fn apb_clk_config_frequency(clocks: &mut ClockTree, config: ApbClkConfig) -> u32 { + pub fn apb_clk_config_frequency(config: ApbClkConfig) -> u32 { (ahb_clk_frequency() / (config.divisor() + 1)) } pub fn apb_clk_frequency() -> u32 { @@ -2792,13 +3392,11 @@ macro_rules! define_clock_tree_types { ahb_clk_frequency() } pub fn request_xtal_d2_clk(clocks: &mut ClockTree) { - trace!("Requesting XTAL_D2_CLK"); trace!("Enabling XTAL_D2_CLK"); request_xtal_clk(clocks); enable_xtal_d2_clk_impl(clocks, true); } pub fn release_xtal_d2_clk(clocks: &mut ClockTree) { - trace!("Releasing XTAL_D2_CLK"); trace!("Disabling XTAL_D2_CLK"); enable_xtal_d2_clk_impl(clocks, false); release_xtal_clk(clocks); @@ -2812,22 +3410,21 @@ macro_rules! define_clock_tree_types { pub fn configure_lp_fast_clk(clocks: &mut ClockTree, new_selector: LpFastClkConfig) { let old_selector = clocks.lp_fast_clk.replace(new_selector); refresh_lp_fast_clk_downstream(clocks); - if clocks.lp_fast_clk_refcount > 0 { + let active = clocks.lp_fast_clk_refcount > 0; + if active { match new_selector { LpFastClkConfig::RcFast => request_rc_fast_clk(clocks), LpFastClkConfig::XtalD2 => request_xtal_d2_clk(clocks), LpFastClkConfig::Xtal => request_xtal_clk(clocks), } - configure_lp_fast_clk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - LpFastClkConfig::RcFast => release_rc_fast_clk(clocks), - LpFastClkConfig::XtalD2 => release_xtal_d2_clk(clocks), - LpFastClkConfig::Xtal => release_xtal_clk(clocks), - } + } + configure_lp_fast_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + LpFastClkConfig::RcFast => release_rc_fast_clk(clocks), + LpFastClkConfig::XtalD2 => release_xtal_d2_clk(clocks), + LpFastClkConfig::Xtal => release_xtal_clk(clocks), } - } else { - configure_lp_fast_clk_impl(clocks, old_selector, new_selector); } } pub fn lp_fast_clk_config(clocks: &mut ClockTree) -> Option { @@ -2857,11 +3454,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn lp_fast_clk_config_frequency( - clocks: &mut ClockTree, - config: LpFastClkConfig, - ) -> u32 { + pub fn lp_fast_clk_config_frequency(config: LpFastClkConfig) -> u32 { match config { LpFastClkConfig::RcFast => rc_fast_clk_frequency(), LpFastClkConfig::XtalD2 => xtal_d2_clk_frequency(), @@ -2872,31 +3465,28 @@ macro_rules! define_clock_tree_types { LP_FAST_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn lp_fast_clk_source_frequency(source: LpFastClkConfig) -> u32 { - match source { - LpFastClkConfig::RcFast => rc_fast_clk_frequency(), - LpFastClkConfig::XtalD2 => xtal_d2_clk_frequency(), - LpFastClkConfig::Xtal => xtal_clk_frequency(), - } + lp_fast_clk_config_frequency(source) } pub fn configure_lp_slow_clk(clocks: &mut ClockTree, new_selector: LpSlowClkConfig) { let old_selector = clocks.lp_slow_clk.replace(new_selector); refresh_lp_slow_clk_downstream(clocks); - if clocks.lp_slow_clk_refcount > 0 { + let active = clocks.lp_slow_clk_refcount > 0; + if active { match new_selector { LpSlowClkConfig::RcSlow => request_rc_slow_clk(clocks), + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => request_xtal32k_clk(clocks), LpSlowClkConfig::OscSlow => request_osc_slow_clk(clocks), } - configure_lp_slow_clk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - LpSlowClkConfig::RcSlow => release_rc_slow_clk(clocks), - LpSlowClkConfig::Xtal32k => release_xtal32k_clk(clocks), - LpSlowClkConfig::OscSlow => release_osc_slow_clk(clocks), - } + } + configure_lp_slow_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + LpSlowClkConfig::RcSlow => release_rc_slow_clk(clocks), + #[cfg(use_xtal32k)] + LpSlowClkConfig::Xtal32k => release_xtal32k_clk(clocks), + LpSlowClkConfig::OscSlow => release_osc_slow_clk(clocks), } - } else { - configure_lp_slow_clk_impl(clocks, old_selector, new_selector); } } pub fn lp_slow_clk_config(clocks: &mut ClockTree) -> Option { @@ -2908,6 +3498,7 @@ macro_rules! define_clock_tree_types { trace!("Enabling LP_SLOW_CLK"); match unwrap!(clocks.lp_slow_clk) { LpSlowClkConfig::RcSlow => request_rc_slow_clk(clocks), + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => request_xtal32k_clk(clocks), LpSlowClkConfig::OscSlow => request_osc_slow_clk(clocks), } @@ -2921,18 +3512,16 @@ macro_rules! define_clock_tree_types { enable_lp_slow_clk_impl(clocks, false); match unwrap!(clocks.lp_slow_clk) { LpSlowClkConfig::RcSlow => release_rc_slow_clk(clocks), + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => release_xtal32k_clk(clocks), LpSlowClkConfig::OscSlow => release_osc_slow_clk(clocks), } } } - #[allow(unused_variables)] - pub fn lp_slow_clk_config_frequency( - clocks: &mut ClockTree, - config: LpSlowClkConfig, - ) -> u32 { + pub fn lp_slow_clk_config_frequency(config: LpSlowClkConfig) -> u32 { match config { LpSlowClkConfig::RcSlow => rc_slow_clk_frequency(), + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => xtal32k_clk_frequency(), LpSlowClkConfig::OscSlow => osc_slow_clk_frequency(), } @@ -2941,31 +3530,139 @@ macro_rules! define_clock_tree_types { LP_SLOW_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn lp_slow_clk_source_frequency(source: LpSlowClkConfig) -> u32 { - match source { - LpSlowClkConfig::RcSlow => rc_slow_clk_frequency(), - LpSlowClkConfig::Xtal32k => xtal32k_clk_frequency(), - LpSlowClkConfig::OscSlow => osc_slow_clk_frequency(), + lp_slow_clk_config_frequency(source) + } + pub fn request_ble_lp_xtal_clk(clocks: &mut ClockTree) { + trace!("Enabling BLE_LP_XTAL_CLK"); + request_xtal_clk(clocks); + enable_ble_lp_xtal_clk_impl(clocks, true); + } + pub fn release_ble_lp_xtal_clk(clocks: &mut ClockTree) { + trace!("Disabling BLE_LP_XTAL_CLK"); + enable_ble_lp_xtal_clk_impl(clocks, false); + release_xtal_clk(clocks); + } + pub fn ble_lp_xtal_clk_frequency() -> u32 { + 100000 + } + pub fn ble_lp_xtal_clk_source_frequency() -> u32 { + xtal_clk_frequency() + } + pub fn request_ble_lp_rc_slow_clk(clocks: &mut ClockTree) { + trace!("Enabling BLE_LP_RC_SLOW_CLK"); + request_rc_slow_clk(clocks); + enable_ble_lp_rc_slow_clk_impl(clocks, true); + } + pub fn release_ble_lp_rc_slow_clk(clocks: &mut ClockTree) { + trace!("Disabling BLE_LP_RC_SLOW_CLK"); + enable_ble_lp_rc_slow_clk_impl(clocks, false); + release_rc_slow_clk(clocks); + } + pub fn ble_lp_rc_slow_clk_frequency() -> u32 { + (rc_slow_clk_frequency() / 5) + } + pub fn ble_lp_rc_slow_clk_source_frequency() -> u32 { + rc_slow_clk_frequency() + } + pub fn configure_ble_lp_clk(clocks: &mut ClockTree, new_selector: BleLpClkConfig) { + let old_selector = clocks.ble_lp_clk.replace(new_selector); + refresh_ble_lp_clk_downstream(clocks); + let active = clocks.ble_lp_clk_refcount > 0; + if active { + match new_selector { + BleLpClkConfig::Xtal => request_ble_lp_xtal_clk(clocks), + BleLpClkConfig::RcSlow => request_ble_lp_rc_slow_clk(clocks), + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => request_xtal32k_clk(clocks), + } + } + configure_ble_lp_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + BleLpClkConfig::Xtal => release_ble_lp_xtal_clk(clocks), + BleLpClkConfig::RcSlow => release_ble_lp_rc_slow_clk(clocks), + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => release_xtal32k_clk(clocks), + } } } + pub fn ble_lp_clk_config(clocks: &mut ClockTree) -> Option { + clocks.ble_lp_clk + } + pub fn request_ble_lp_clk(clocks: &mut ClockTree) { + trace!("Requesting BLE_LP_CLK"); + if increment_reference_count(&mut clocks.ble_lp_clk_refcount) { + trace!("Enabling BLE_LP_CLK"); + match unwrap!(clocks.ble_lp_clk) { + BleLpClkConfig::Xtal => request_ble_lp_xtal_clk(clocks), + BleLpClkConfig::RcSlow => request_ble_lp_rc_slow_clk(clocks), + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => request_xtal32k_clk(clocks), + } + enable_ble_lp_clk_impl(clocks, true); + } + } + pub fn release_ble_lp_clk(clocks: &mut ClockTree) { + trace!("Releasing BLE_LP_CLK"); + if decrement_reference_count(&mut clocks.ble_lp_clk_refcount) { + trace!("Disabling BLE_LP_CLK"); + enable_ble_lp_clk_impl(clocks, false); + match unwrap!(clocks.ble_lp_clk) { + BleLpClkConfig::Xtal => release_ble_lp_xtal_clk(clocks), + BleLpClkConfig::RcSlow => release_ble_lp_rc_slow_clk(clocks), + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => release_xtal32k_clk(clocks), + } + } + } + pub fn ble_lp_clk_config_frequency(config: BleLpClkConfig) -> u32 { + match config { + BleLpClkConfig::Xtal => ble_lp_xtal_clk_frequency(), + BleLpClkConfig::RcSlow => ble_lp_rc_slow_clk_frequency(), + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => xtal32k_clk_frequency(), + } + } + pub fn ble_lp_clk_frequency() -> u32 { + BLE_LP_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn ble_lp_clk_source_frequency(source: BleLpClkConfig) -> u32 { + ble_lp_clk_config_frequency(source) + } + pub fn request_crypto_pll_div(clocks: &mut ClockTree) { + trace!("Enabling CRYPTO_PLL_DIV"); + request_pll_clk(clocks); + enable_crypto_pll_div_impl(clocks, true); + } + pub fn release_crypto_pll_div(clocks: &mut ClockTree) { + trace!("Disabling CRYPTO_PLL_DIV"); + enable_crypto_pll_div_impl(clocks, false); + release_pll_clk(clocks); + } + pub fn crypto_pll_div_frequency() -> u32 { + (pll_clk_frequency() / 3) + } + pub fn crypto_pll_div_source_frequency() -> u32 { + pll_clk_frequency() + } pub fn configure_crypto_clk(clocks: &mut ClockTree, new_selector: CryptoClkConfig) { let old_selector = clocks.crypto_clk.replace(new_selector); refresh_crypto_clk_downstream(clocks); - if clocks.crypto_clk_refcount > 0 { + let active = clocks.crypto_clk_refcount > 0; + if active { match new_selector { CryptoClkConfig::Xtal => request_xtal_clk(clocks), CryptoClkConfig::Fosc => request_rc_fast_clk(clocks), - CryptoClkConfig::PllF480m => request_pll_clk(clocks), + CryptoClkConfig::PllF480m => request_crypto_pll_div(clocks), } - configure_crypto_clk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - CryptoClkConfig::Xtal => release_xtal_clk(clocks), - CryptoClkConfig::Fosc => release_rc_fast_clk(clocks), - CryptoClkConfig::PllF480m => release_pll_clk(clocks), - } + } + configure_crypto_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + CryptoClkConfig::Xtal => release_xtal_clk(clocks), + CryptoClkConfig::Fosc => release_rc_fast_clk(clocks), + CryptoClkConfig::PllF480m => release_crypto_pll_div(clocks), } - } else { - configure_crypto_clk_impl(clocks, old_selector, new_selector); } } pub fn crypto_clk_config(clocks: &mut ClockTree) -> Option { @@ -2978,7 +3675,7 @@ macro_rules! define_clock_tree_types { match unwrap!(clocks.crypto_clk) { CryptoClkConfig::Xtal => request_xtal_clk(clocks), CryptoClkConfig::Fosc => request_rc_fast_clk(clocks), - CryptoClkConfig::PllF480m => request_pll_clk(clocks), + CryptoClkConfig::PllF480m => request_crypto_pll_div(clocks), } enable_crypto_clk_impl(clocks, true); } @@ -2991,27 +3688,22 @@ macro_rules! define_clock_tree_types { match unwrap!(clocks.crypto_clk) { CryptoClkConfig::Xtal => release_xtal_clk(clocks), CryptoClkConfig::Fosc => release_rc_fast_clk(clocks), - CryptoClkConfig::PllF480m => release_pll_clk(clocks), + CryptoClkConfig::PllF480m => release_crypto_pll_div(clocks), } } } - #[allow(unused_variables)] - pub fn crypto_clk_config_frequency(clocks: &mut ClockTree, config: CryptoClkConfig) -> u32 { + pub fn crypto_clk_config_frequency(config: CryptoClkConfig) -> u32 { match config { CryptoClkConfig::Xtal => xtal_clk_frequency(), CryptoClkConfig::Fosc => rc_fast_clk_frequency(), - CryptoClkConfig::PllF480m => pll_clk_frequency(), + CryptoClkConfig::PllF480m => crypto_pll_div_frequency(), } } pub fn crypto_clk_frequency() -> u32 { CRYPTO_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn crypto_clk_source_frequency(source: CryptoClkConfig) -> u32 { - match source { - CryptoClkConfig::Xtal => xtal_clk_frequency(), - CryptoClkConfig::Fosc => rc_fast_clk_frequency(), - CryptoClkConfig::PllF480m => pll_clk_frequency(), - } + crypto_clk_config_frequency(source) } pub fn configure_iomux_function_clock( clocks: &mut ClockTree, @@ -3040,11 +3732,7 @@ macro_rules! define_clock_tree_types { } fn request_iomux_function_clock(_clocks: &mut ClockTree) {} fn release_iomux_function_clock(_clocks: &mut ClockTree) {} - #[allow(unused_variables)] - pub fn iomux_function_clock_config_frequency( - clocks: &mut ClockTree, - config: IomuxFunctionClockConfig, - ) -> u32 { + pub fn iomux_function_clock_config_frequency(config: IomuxFunctionClockConfig) -> u32 { match config { IomuxFunctionClockConfig::XtalClk => xtal_clk_frequency(), IomuxFunctionClockConfig::RcFastClk => rc_fast_clk_frequency(), @@ -3055,11 +3743,7 @@ macro_rules! define_clock_tree_types { IOMUX_FUNCTION_CLOCK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn iomux_function_clock_source_frequency(source: IomuxFunctionClockConfig) -> u32 { - match source { - IomuxFunctionClockConfig::XtalClk => xtal_clk_frequency(), - IomuxFunctionClockConfig::RcFastClk => rc_fast_clk_frequency(), - IomuxFunctionClockConfig::PllF80m => pll_f80m_frequency(), - } + iomux_function_clock_config_frequency(source) } pub fn configure_timg_calibration_clock( clocks: &mut ClockTree, @@ -3067,24 +3751,25 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.timg_calibration_clock.replace(new_selector); refresh_timg_calibration_clock_downstream(clocks); - if clocks.timg_calibration_clock_refcount > 0 { + let active = clocks.timg_calibration_clock_refcount > 0; + if active { match new_selector { TimgCalibrationClockConfig::OscSlowClk => request_osc_slow_clk(clocks), TimgCalibrationClockConfig::RcSlowClk => request_rc_slow_clk(clocks), TimgCalibrationClockConfig::RcFastDivClk => request_rc_fast_clk(clocks), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => request_xtal32k_clk(clocks), } - configure_timg_calibration_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - TimgCalibrationClockConfig::OscSlowClk => release_osc_slow_clk(clocks), - TimgCalibrationClockConfig::RcSlowClk => release_rc_slow_clk(clocks), - TimgCalibrationClockConfig::RcFastDivClk => release_rc_fast_clk(clocks), - TimgCalibrationClockConfig::Xtal32kClk => release_xtal32k_clk(clocks), - } + } + configure_timg_calibration_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + TimgCalibrationClockConfig::OscSlowClk => release_osc_slow_clk(clocks), + TimgCalibrationClockConfig::RcSlowClk => release_rc_slow_clk(clocks), + TimgCalibrationClockConfig::RcFastDivClk => release_rc_fast_clk(clocks), + #[cfg(use_xtal32k)] + TimgCalibrationClockConfig::Xtal32kClk => release_xtal32k_clk(clocks), } - } else { - configure_timg_calibration_clock_impl(clocks, old_selector, new_selector); } } pub fn timg_calibration_clock_config( @@ -3101,6 +3786,7 @@ macro_rules! define_clock_tree_types { TimgCalibrationClockConfig::OscSlowClk => request_osc_slow_clk(clocks), TimgCalibrationClockConfig::RcSlowClk => request_rc_slow_clk(clocks), TimgCalibrationClockConfig::RcFastDivClk => request_rc_fast_clk(clocks), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => request_xtal32k_clk(clocks), } enable_timg_calibration_clock_impl(clocks, true); @@ -3116,19 +3802,17 @@ macro_rules! define_clock_tree_types { TimgCalibrationClockConfig::OscSlowClk => release_osc_slow_clk(clocks), TimgCalibrationClockConfig::RcSlowClk => release_rc_slow_clk(clocks), TimgCalibrationClockConfig::RcFastDivClk => release_rc_fast_clk(clocks), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => release_xtal32k_clk(clocks), } } } - #[allow(unused_variables)] - pub fn timg_calibration_clock_config_frequency( - clocks: &mut ClockTree, - config: TimgCalibrationClockConfig, - ) -> u32 { + pub fn timg_calibration_clock_config_frequency(config: TimgCalibrationClockConfig) -> u32 { match config { TimgCalibrationClockConfig::OscSlowClk => osc_slow_clk_frequency(), TimgCalibrationClockConfig::RcSlowClk => rc_slow_clk_frequency(), TimgCalibrationClockConfig::RcFastDivClk => rc_fast_clk_frequency(), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => xtal32k_clk_frequency(), } } @@ -3136,11 +3820,78 @@ macro_rules! define_clock_tree_types { TIMG_CALIBRATION_CLOCK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn timg_calibration_clock_source_frequency(source: TimgCalibrationClockConfig) -> u32 { - match source { - TimgCalibrationClockConfig::OscSlowClk => osc_slow_clk_frequency(), - TimgCalibrationClockConfig::RcSlowClk => rc_slow_clk_frequency(), - TimgCalibrationClockConfig::RcFastDivClk => rc_fast_clk_frequency(), - TimgCalibrationClockConfig::Xtal32kClk => xtal32k_clk_frequency(), + timg_calibration_clock_config_frequency(source) + } + impl AdcInstance { + pub fn configure_function_clock( + self, + clocks: &mut ClockTree, + new_selector: AdcFunctionClockConfig, + ) { + let old_selector = clocks.adc_function_clock[self as usize].replace(new_selector); + refresh_adc_function_clock_downstream(clocks, self); + let active = clocks.adc_function_clock_refcount[self as usize] > 0; + if active { + match new_selector { + AdcFunctionClockConfig::Xtal => request_xtal_clk(clocks), + AdcFunctionClockConfig::RcFast => request_rc_fast_clk(clocks), + AdcFunctionClockConfig::PllF80m => request_pll_f80m(clocks), + } + } + self.configure_function_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + AdcFunctionClockConfig::Xtal => release_xtal_clk(clocks), + AdcFunctionClockConfig::RcFast => release_rc_fast_clk(clocks), + AdcFunctionClockConfig::PllF80m => release_pll_f80m(clocks), + } + } + } + pub fn function_clock_config( + self, + clocks: &mut ClockTree, + ) -> Option { + clocks.adc_function_clock[self as usize] + } + pub fn request_function_clock(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::FUNCTION_CLOCK", self); + if increment_reference_count(&mut clocks.adc_function_clock_refcount[self as usize]) + { + trace!("Enabling {:?}::FUNCTION_CLOCK", self); + match unwrap!(clocks.adc_function_clock[self as usize]) { + AdcFunctionClockConfig::Xtal => request_xtal_clk(clocks), + AdcFunctionClockConfig::RcFast => request_rc_fast_clk(clocks), + AdcFunctionClockConfig::PllF80m => request_pll_f80m(clocks), + } + self.enable_function_clock_impl(clocks, true); + } + } + pub fn release_function_clock(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::FUNCTION_CLOCK", self); + if decrement_reference_count(&mut clocks.adc_function_clock_refcount[self as usize]) + { + trace!("Disabling {:?}::FUNCTION_CLOCK", self); + self.enable_function_clock_impl(clocks, false); + match unwrap!(clocks.adc_function_clock[self as usize]) { + AdcFunctionClockConfig::Xtal => release_xtal_clk(clocks), + AdcFunctionClockConfig::RcFast => release_rc_fast_clk(clocks), + AdcFunctionClockConfig::PllF80m => release_pll_f80m(clocks), + } + } + } + pub fn function_clock_config_frequency(config: AdcFunctionClockConfig) -> u32 { + match config { + AdcFunctionClockConfig::Xtal => xtal_clk_frequency(), + AdcFunctionClockConfig::RcFast => rc_fast_clk_frequency(), + AdcFunctionClockConfig::PllF80m => pll_f80m_frequency(), + } + } + pub fn function_clock_frequency(self) -> u32 { + ADC_FUNCTION_CLOCK_FREQ_CACHE[self as usize] + .load(::core::sync::atomic::Ordering::Acquire) + } + pub fn function_clock_source_frequency(source: AdcFunctionClockConfig) -> u32 { + Self::function_clock_config_frequency(source) } } impl SdmInstance { @@ -3177,20 +3928,19 @@ macro_rules! define_clock_tree_types { ) { let old_config = clocks.i2c_function_clock[self as usize].replace(config); refresh_i2c_function_clock_downstream(clocks, self); - if clocks.i2c_function_clock_refcount[self as usize] > 0 { + let active = clocks.i2c_function_clock_refcount[self as usize] > 0; + if active { match config.sclk { I2cFunctionClockSclk::Xtal => request_xtal_clk(clocks), I2cFunctionClockSclk::RcFast => request_rc_fast_clk(clocks), } - self.configure_function_clock_impl(clocks, old_config, config); - if let Some(old_config) = old_config { - match old_config.sclk { - I2cFunctionClockSclk::Xtal => release_xtal_clk(clocks), - I2cFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), - } + } + self.configure_function_clock_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + I2cFunctionClockSclk::Xtal => release_xtal_clk(clocks), + I2cFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_config, config); } } pub fn function_clock_config( @@ -3223,11 +3973,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: I2cFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: I2cFunctionClockConfig) -> u32 { (match config.sclk { I2cFunctionClockSclk::Xtal => xtal_clk_frequency(), I2cFunctionClockSclk::RcFast => rc_fast_clk_frequency(), @@ -3244,33 +3990,224 @@ macro_rules! define_clock_tree_types { } } } - impl ParlIoInstance { - pub fn configure_rx_clock( + impl I2sInstance { + pub fn configure_tx_clk(self, clocks: &mut ClockTree, config: I2sClkConfig) { + let old_config = clocks.i2s_tx_clk[self as usize].replace(config); + refresh_i2s_tx_clk_downstream(clocks, self); + let active = clocks.i2s_tx_clk_refcount[self as usize] > 0; + if active { + match config.sclk { + I2sClkSclk::Xtal => request_xtal_clk(clocks), + I2sClkSclk::PllF240m => request_pll_f240m(clocks), + I2sClkSclk::PllF160m => request_pll_f160m(clocks), + } + } + self.configure_tx_clk_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + I2sClkSclk::Xtal => release_xtal_clk(clocks), + I2sClkSclk::PllF240m => release_pll_f240m(clocks), + I2sClkSclk::PllF160m => release_pll_f160m(clocks), + } + } + } + pub fn tx_clk_config(self, clocks: &mut ClockTree) -> Option { + clocks.i2s_tx_clk[self as usize] + } + pub fn request_tx_clk(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::TX_CLK", self); + if increment_reference_count(&mut clocks.i2s_tx_clk_refcount[self as usize]) { + trace!("Enabling {:?}::TX_CLK", self); + crate::rtc_cntl::WakeLock::acquire(); + match unwrap!(clocks.i2s_tx_clk[self as usize]).sclk { + I2sClkSclk::Xtal => request_xtal_clk(clocks), + I2sClkSclk::PllF240m => request_pll_f240m(clocks), + I2sClkSclk::PllF160m => request_pll_f160m(clocks), + } + self.enable_tx_clk_impl(clocks, true); + } + } + pub fn release_tx_clk(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::TX_CLK", self); + if decrement_reference_count(&mut clocks.i2s_tx_clk_refcount[self as usize]) { + trace!("Disabling {:?}::TX_CLK", self); + crate::rtc_cntl::WakeLock::release(); + self.enable_tx_clk_impl(clocks, false); + match unwrap!(clocks.i2s_tx_clk[self as usize]).sclk { + I2sClkSclk::Xtal => release_xtal_clk(clocks), + I2sClkSclk::PllF240m => release_pll_f240m(clocks), + I2sClkSclk::PllF160m => release_pll_f160m(clocks), + } + } + } + pub fn tx_clk_config_frequency(config: I2sClkConfig) -> u32 { + (((match config.sclk { + I2sClkSclk::Xtal => xtal_clk_frequency(), + I2sClkSclk::PllF240m => pll_f240m_frequency(), + I2sClkSclk::PllF160m => pll_f160m_frequency(), + } as u64) + * (config.div_a() as u64)) + / (((config.div_num() * config.div_a()) + config.div_b()) as u64)) + as u32 + } + pub fn tx_clk_frequency(self) -> u32 { + I2S_TX_CLK_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) + } + pub fn tx_clk_source_frequency(sclk: I2sClkSclk) -> u32 { + match sclk { + I2sClkSclk::Xtal => xtal_clk_frequency(), + I2sClkSclk::PllF240m => pll_f240m_frequency(), + I2sClkSclk::PllF160m => pll_f160m_frequency(), + } + } + pub fn configure_rx_clk(self, clocks: &mut ClockTree, config: I2sClkConfig) { + let old_config = clocks.i2s_rx_clk[self as usize].replace(config); + refresh_i2s_rx_clk_downstream(clocks, self); + let active = clocks.i2s_rx_clk_refcount[self as usize] > 0; + if active { + match config.sclk { + I2sClkSclk::Xtal => request_xtal_clk(clocks), + I2sClkSclk::PllF240m => request_pll_f240m(clocks), + I2sClkSclk::PllF160m => request_pll_f160m(clocks), + } + } + self.configure_rx_clk_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + I2sClkSclk::Xtal => release_xtal_clk(clocks), + I2sClkSclk::PllF240m => release_pll_f240m(clocks), + I2sClkSclk::PllF160m => release_pll_f160m(clocks), + } + } + } + pub fn rx_clk_config(self, clocks: &mut ClockTree) -> Option { + clocks.i2s_rx_clk[self as usize] + } + pub fn request_rx_clk(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::RX_CLK", self); + if increment_reference_count(&mut clocks.i2s_rx_clk_refcount[self as usize]) { + trace!("Enabling {:?}::RX_CLK", self); + crate::rtc_cntl::WakeLock::acquire(); + match unwrap!(clocks.i2s_rx_clk[self as usize]).sclk { + I2sClkSclk::Xtal => request_xtal_clk(clocks), + I2sClkSclk::PllF240m => request_pll_f240m(clocks), + I2sClkSclk::PllF160m => request_pll_f160m(clocks), + } + self.enable_rx_clk_impl(clocks, true); + } + } + pub fn release_rx_clk(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::RX_CLK", self); + if decrement_reference_count(&mut clocks.i2s_rx_clk_refcount[self as usize]) { + trace!("Disabling {:?}::RX_CLK", self); + crate::rtc_cntl::WakeLock::release(); + self.enable_rx_clk_impl(clocks, false); + match unwrap!(clocks.i2s_rx_clk[self as usize]).sclk { + I2sClkSclk::Xtal => release_xtal_clk(clocks), + I2sClkSclk::PllF240m => release_pll_f240m(clocks), + I2sClkSclk::PllF160m => release_pll_f160m(clocks), + } + } + } + pub fn rx_clk_config_frequency(config: I2sClkConfig) -> u32 { + (((match config.sclk { + I2sClkSclk::Xtal => xtal_clk_frequency(), + I2sClkSclk::PllF240m => pll_f240m_frequency(), + I2sClkSclk::PllF160m => pll_f160m_frequency(), + } as u64) + * (config.div_a() as u64)) + / (((config.div_num() * config.div_a()) + config.div_b()) as u64)) + as u32 + } + pub fn rx_clk_frequency(self) -> u32 { + I2S_RX_CLK_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) + } + pub fn rx_clk_source_frequency(sclk: I2sClkSclk) -> u32 { + match sclk { + I2sClkSclk::Xtal => xtal_clk_frequency(), + I2sClkSclk::PllF240m => pll_f240m_frequency(), + I2sClkSclk::PllF160m => pll_f160m_frequency(), + } + } + pub fn configure_mclk_out( self, clocks: &mut ClockTree, - new_selector: ParlIoRxClockConfig, + new_selector: I2sMclkOutConfig, ) { + let old_selector = clocks.i2s_mclk_out[self as usize].replace(new_selector); + refresh_i2s_mclk_out_downstream(clocks, self); + let active = clocks.i2s_mclk_out_refcount[self as usize] > 0; + if active { + match new_selector { + I2sMclkOutConfig::Tx => self.request_tx_clk(clocks), + I2sMclkOutConfig::Rx => self.request_rx_clk(clocks), + } + } + self.configure_mclk_out_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + I2sMclkOutConfig::Tx => self.release_tx_clk(clocks), + I2sMclkOutConfig::Rx => self.release_rx_clk(clocks), + } + } + } + pub fn mclk_out_config(self, clocks: &mut ClockTree) -> Option { + clocks.i2s_mclk_out[self as usize] + } + pub fn request_mclk_out(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::MCLK_OUT", self); + if increment_reference_count(&mut clocks.i2s_mclk_out_refcount[self as usize]) { + trace!("Enabling {:?}::MCLK_OUT", self); + match unwrap!(clocks.i2s_mclk_out[self as usize]) { + I2sMclkOutConfig::Tx => self.request_tx_clk(clocks), + I2sMclkOutConfig::Rx => self.request_rx_clk(clocks), + } + self.enable_mclk_out_impl(clocks, true); + } + } + pub fn release_mclk_out(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::MCLK_OUT", self); + if decrement_reference_count(&mut clocks.i2s_mclk_out_refcount[self as usize]) { + trace!("Disabling {:?}::MCLK_OUT", self); + self.enable_mclk_out_impl(clocks, false); + match unwrap!(clocks.i2s_mclk_out[self as usize]) { + I2sMclkOutConfig::Tx => self.release_tx_clk(clocks), + I2sMclkOutConfig::Rx => self.release_rx_clk(clocks), + } + } + } + pub fn mclk_out_config_frequency(self, config: I2sMclkOutConfig) -> u32 { + match config { + I2sMclkOutConfig::Tx => self.tx_clk_frequency(), + I2sMclkOutConfig::Rx => self.rx_clk_frequency(), + } + } + pub fn mclk_out_frequency(self) -> u32 { + I2S_MCLK_OUT_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) + } + } + impl ParlIoInstance { + pub fn configure_rx_clock(self, clocks: &mut ClockTree, new_selector: ParlIoClkConfig) { let old_selector = clocks.parl_io_rx_clock[self as usize].replace(new_selector); refresh_parl_io_rx_clock_downstream(clocks, self); - if clocks.parl_io_rx_clock_refcount[self as usize] > 0 { + let active = clocks.parl_io_rx_clock_refcount[self as usize] > 0; + if active { match new_selector { - ParlIoRxClockConfig::XtalClk => request_xtal_clk(clocks), - ParlIoRxClockConfig::RcFastClk => request_rc_fast_clk(clocks), - ParlIoRxClockConfig::PllF240m => request_pll_f240m(clocks), + ParlIoClkConfig::XtalClk => request_xtal_clk(clocks), + ParlIoClkConfig::RcFastClk => request_rc_fast_clk(clocks), + ParlIoClkConfig::PllF240m => request_pll_f240m(clocks), } - self.configure_rx_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - ParlIoRxClockConfig::XtalClk => release_xtal_clk(clocks), - ParlIoRxClockConfig::RcFastClk => release_rc_fast_clk(clocks), - ParlIoRxClockConfig::PllF240m => release_pll_f240m(clocks), - } + } + self.configure_rx_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + ParlIoClkConfig::XtalClk => release_xtal_clk(clocks), + ParlIoClkConfig::RcFastClk => release_rc_fast_clk(clocks), + ParlIoClkConfig::PllF240m => release_pll_f240m(clocks), } - } else { - self.configure_rx_clock_impl(clocks, old_selector, new_selector); } } - pub fn rx_clock_config(self, clocks: &mut ClockTree) -> Option { + pub fn rx_clock_config(self, clocks: &mut ClockTree) -> Option { clocks.parl_io_rx_clock[self as usize] } pub fn request_rx_clock(self, clocks: &mut ClockTree) { @@ -3278,9 +4215,9 @@ macro_rules! define_clock_tree_types { if increment_reference_count(&mut clocks.parl_io_rx_clock_refcount[self as usize]) { trace!("Enabling {:?}::RX_CLOCK", self); match unwrap!(clocks.parl_io_rx_clock[self as usize]) { - ParlIoRxClockConfig::XtalClk => request_xtal_clk(clocks), - ParlIoRxClockConfig::RcFastClk => request_rc_fast_clk(clocks), - ParlIoRxClockConfig::PllF240m => request_pll_f240m(clocks), + ParlIoClkConfig::XtalClk => request_xtal_clk(clocks), + ParlIoClkConfig::RcFastClk => request_rc_fast_clk(clocks), + ParlIoClkConfig::PllF240m => request_pll_f240m(clocks), } self.enable_rx_clock_impl(clocks, true); } @@ -3291,60 +4228,47 @@ macro_rules! define_clock_tree_types { trace!("Disabling {:?}::RX_CLOCK", self); self.enable_rx_clock_impl(clocks, false); match unwrap!(clocks.parl_io_rx_clock[self as usize]) { - ParlIoRxClockConfig::XtalClk => release_xtal_clk(clocks), - ParlIoRxClockConfig::RcFastClk => release_rc_fast_clk(clocks), - ParlIoRxClockConfig::PllF240m => release_pll_f240m(clocks), + ParlIoClkConfig::XtalClk => release_xtal_clk(clocks), + ParlIoClkConfig::RcFastClk => release_rc_fast_clk(clocks), + ParlIoClkConfig::PllF240m => release_pll_f240m(clocks), } } } - #[allow(unused_variables)] - pub fn rx_clock_config_frequency( - clocks: &mut ClockTree, - config: ParlIoRxClockConfig, - ) -> u32 { + pub fn rx_clock_config_frequency(config: ParlIoClkConfig) -> u32 { match config { - ParlIoRxClockConfig::XtalClk => xtal_clk_frequency(), - ParlIoRxClockConfig::RcFastClk => rc_fast_clk_frequency(), - ParlIoRxClockConfig::PllF240m => pll_f240m_frequency(), + ParlIoClkConfig::XtalClk => xtal_clk_frequency(), + ParlIoClkConfig::RcFastClk => rc_fast_clk_frequency(), + ParlIoClkConfig::PllF240m => pll_f240m_frequency(), } } pub fn rx_clock_frequency(self) -> u32 { PARL_IO_RX_CLOCK_FREQ_CACHE[self as usize] .load(::core::sync::atomic::Ordering::Acquire) } - pub fn rx_clock_source_frequency(source: ParlIoRxClockConfig) -> u32 { - match source { - ParlIoRxClockConfig::XtalClk => xtal_clk_frequency(), - ParlIoRxClockConfig::RcFastClk => rc_fast_clk_frequency(), - ParlIoRxClockConfig::PllF240m => pll_f240m_frequency(), - } + pub fn rx_clock_source_frequency(source: ParlIoClkConfig) -> u32 { + Self::rx_clock_config_frequency(source) } - pub fn configure_tx_clock( - self, - clocks: &mut ClockTree, - new_selector: ParlIoTxClockConfig, - ) { + pub fn configure_tx_clock(self, clocks: &mut ClockTree, new_selector: ParlIoClkConfig) { let old_selector = clocks.parl_io_tx_clock[self as usize].replace(new_selector); refresh_parl_io_tx_clock_downstream(clocks, self); - if clocks.parl_io_tx_clock_refcount[self as usize] > 0 { + let active = clocks.parl_io_tx_clock_refcount[self as usize] > 0; + if active { match new_selector { - ParlIoTxClockConfig::XtalClk => request_xtal_clk(clocks), - ParlIoTxClockConfig::RcFastClk => request_rc_fast_clk(clocks), - ParlIoTxClockConfig::PllF240m => request_pll_f240m(clocks), + ParlIoClkConfig::XtalClk => request_xtal_clk(clocks), + ParlIoClkConfig::RcFastClk => request_rc_fast_clk(clocks), + ParlIoClkConfig::PllF240m => request_pll_f240m(clocks), } - self.configure_tx_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - ParlIoTxClockConfig::XtalClk => release_xtal_clk(clocks), - ParlIoTxClockConfig::RcFastClk => release_rc_fast_clk(clocks), - ParlIoTxClockConfig::PllF240m => release_pll_f240m(clocks), - } + } + self.configure_tx_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + ParlIoClkConfig::XtalClk => release_xtal_clk(clocks), + ParlIoClkConfig::RcFastClk => release_rc_fast_clk(clocks), + ParlIoClkConfig::PllF240m => release_pll_f240m(clocks), } - } else { - self.configure_tx_clock_impl(clocks, old_selector, new_selector); } } - pub fn tx_clock_config(self, clocks: &mut ClockTree) -> Option { + pub fn tx_clock_config(self, clocks: &mut ClockTree) -> Option { clocks.parl_io_tx_clock[self as usize] } pub fn request_tx_clock(self, clocks: &mut ClockTree) { @@ -3352,9 +4276,9 @@ macro_rules! define_clock_tree_types { if increment_reference_count(&mut clocks.parl_io_tx_clock_refcount[self as usize]) { trace!("Enabling {:?}::TX_CLOCK", self); match unwrap!(clocks.parl_io_tx_clock[self as usize]) { - ParlIoTxClockConfig::XtalClk => request_xtal_clk(clocks), - ParlIoTxClockConfig::RcFastClk => request_rc_fast_clk(clocks), - ParlIoTxClockConfig::PllF240m => request_pll_f240m(clocks), + ParlIoClkConfig::XtalClk => request_xtal_clk(clocks), + ParlIoClkConfig::RcFastClk => request_rc_fast_clk(clocks), + ParlIoClkConfig::PllF240m => request_pll_f240m(clocks), } self.enable_tx_clock_impl(clocks, true); } @@ -3365,55 +4289,46 @@ macro_rules! define_clock_tree_types { trace!("Disabling {:?}::TX_CLOCK", self); self.enable_tx_clock_impl(clocks, false); match unwrap!(clocks.parl_io_tx_clock[self as usize]) { - ParlIoTxClockConfig::XtalClk => release_xtal_clk(clocks), - ParlIoTxClockConfig::RcFastClk => release_rc_fast_clk(clocks), - ParlIoTxClockConfig::PllF240m => release_pll_f240m(clocks), + ParlIoClkConfig::XtalClk => release_xtal_clk(clocks), + ParlIoClkConfig::RcFastClk => release_rc_fast_clk(clocks), + ParlIoClkConfig::PllF240m => release_pll_f240m(clocks), } } } - #[allow(unused_variables)] - pub fn tx_clock_config_frequency( - clocks: &mut ClockTree, - config: ParlIoTxClockConfig, - ) -> u32 { + pub fn tx_clock_config_frequency(config: ParlIoClkConfig) -> u32 { match config { - ParlIoTxClockConfig::XtalClk => xtal_clk_frequency(), - ParlIoTxClockConfig::RcFastClk => rc_fast_clk_frequency(), - ParlIoTxClockConfig::PllF240m => pll_f240m_frequency(), + ParlIoClkConfig::XtalClk => xtal_clk_frequency(), + ParlIoClkConfig::RcFastClk => rc_fast_clk_frequency(), + ParlIoClkConfig::PllF240m => pll_f240m_frequency(), } } pub fn tx_clock_frequency(self) -> u32 { PARL_IO_TX_CLOCK_FREQ_CACHE[self as usize] .load(::core::sync::atomic::Ordering::Acquire) } - pub fn tx_clock_source_frequency(source: ParlIoTxClockConfig) -> u32 { - match source { - ParlIoTxClockConfig::XtalClk => xtal_clk_frequency(), - ParlIoTxClockConfig::RcFastClk => rc_fast_clk_frequency(), - ParlIoTxClockConfig::PllF240m => pll_f240m_frequency(), - } + pub fn tx_clock_source_frequency(source: ParlIoClkConfig) -> u32 { + Self::tx_clock_config_frequency(source) } } impl RmtInstance { pub fn configure_sclk(self, clocks: &mut ClockTree, new_selector: RmtSclkConfig) { let old_selector = clocks.rmt_sclk[self as usize].replace(new_selector); refresh_rmt_sclk_downstream(clocks, self); - if clocks.rmt_sclk_refcount[self as usize] > 0 { + let active = clocks.rmt_sclk_refcount[self as usize] > 0; + if active { match new_selector { RmtSclkConfig::XtalClk => request_xtal_clk(clocks), RmtSclkConfig::RcFastClk => request_rc_fast_clk(clocks), RmtSclkConfig::PllF80m => request_pll_f80m(clocks), } - self.configure_sclk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - RmtSclkConfig::XtalClk => release_xtal_clk(clocks), - RmtSclkConfig::RcFastClk => release_rc_fast_clk(clocks), - RmtSclkConfig::PllF80m => release_pll_f80m(clocks), - } + } + self.configure_sclk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + RmtSclkConfig::XtalClk => release_xtal_clk(clocks), + RmtSclkConfig::RcFastClk => release_rc_fast_clk(clocks), + RmtSclkConfig::PllF80m => release_pll_f80m(clocks), } - } else { - self.configure_sclk_impl(clocks, old_selector, new_selector); } } pub fn sclk_config(self, clocks: &mut ClockTree) -> Option { @@ -3443,8 +4358,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn sclk_config_frequency(clocks: &mut ClockTree, config: RmtSclkConfig) -> u32 { + pub fn sclk_config_frequency(config: RmtSclkConfig) -> u32 { match config { RmtSclkConfig::XtalClk => xtal_clk_frequency(), RmtSclkConfig::RcFastClk => rc_fast_clk_frequency(), @@ -3455,11 +4369,7 @@ macro_rules! define_clock_tree_types { RMT_SCLK_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) } pub fn sclk_source_frequency(source: RmtSclkConfig) -> u32 { - match source { - RmtSclkConfig::XtalClk => xtal_clk_frequency(), - RmtSclkConfig::RcFastClk => rc_fast_clk_frequency(), - RmtSclkConfig::PllF80m => pll_f80m_frequency(), - } + Self::sclk_config_frequency(source) } } impl SpiInstance { @@ -3470,24 +4380,23 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.spi_function_clock[self as usize].replace(new_selector); refresh_spi_function_clock_downstream(clocks, self); - if clocks.spi_function_clock_refcount[self as usize] > 0 { + let active = clocks.spi_function_clock_refcount[self as usize] > 0; + if active { match new_selector { SpiFunctionClockConfig::Xtal => request_xtal_clk(clocks), SpiFunctionClockConfig::PllF160m => request_pll_f160m(clocks), SpiFunctionClockConfig::PllF120m => request_pll_f120m(clocks), SpiFunctionClockConfig::RcFast => request_rc_fast_clk(clocks), } - self.configure_function_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - SpiFunctionClockConfig::Xtal => release_xtal_clk(clocks), - SpiFunctionClockConfig::PllF160m => release_pll_f160m(clocks), - SpiFunctionClockConfig::PllF120m => release_pll_f120m(clocks), - SpiFunctionClockConfig::RcFast => release_rc_fast_clk(clocks), - } + } + self.configure_function_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + SpiFunctionClockConfig::Xtal => release_xtal_clk(clocks), + SpiFunctionClockConfig::PllF160m => release_pll_f160m(clocks), + SpiFunctionClockConfig::PllF120m => release_pll_f120m(clocks), + SpiFunctionClockConfig::RcFast => release_rc_fast_clk(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_selector, new_selector); } } pub fn function_clock_config( @@ -3524,11 +4433,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: SpiFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: SpiFunctionClockConfig) -> u32 { match config { SpiFunctionClockConfig::Xtal => xtal_clk_frequency(), SpiFunctionClockConfig::PllF160m => pll_f160m_frequency(), @@ -3541,12 +4446,7 @@ macro_rules! define_clock_tree_types { .load(::core::sync::atomic::Ordering::Acquire) } pub fn function_clock_source_frequency(source: SpiFunctionClockConfig) -> u32 { - match source { - SpiFunctionClockConfig::Xtal => xtal_clk_frequency(), - SpiFunctionClockConfig::PllF160m => pll_f160m_frequency(), - SpiFunctionClockConfig::PllF120m => pll_f120m_frequency(), - SpiFunctionClockConfig::RcFast => rc_fast_clk_frequency(), - } + Self::function_clock_config_frequency(source) } } impl TimgInstance { @@ -3557,22 +4457,21 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.timg_function_clock[self as usize].replace(new_selector); refresh_timg_function_clock_downstream(clocks, self); - if clocks.timg_function_clock_refcount[self as usize] > 0 { + let active = clocks.timg_function_clock_refcount[self as usize] > 0; + if active { match new_selector { TimgFunctionClockConfig::XtalClk => request_xtal_clk(clocks), TimgFunctionClockConfig::RcFastClk => request_rc_fast_clk(clocks), TimgFunctionClockConfig::PllF80m => request_pll_f80m(clocks), } - self.configure_function_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - TimgFunctionClockConfig::XtalClk => release_xtal_clk(clocks), - TimgFunctionClockConfig::RcFastClk => release_rc_fast_clk(clocks), - TimgFunctionClockConfig::PllF80m => release_pll_f80m(clocks), - } + } + self.configure_function_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + TimgFunctionClockConfig::XtalClk => release_xtal_clk(clocks), + TimgFunctionClockConfig::RcFastClk => release_rc_fast_clk(clocks), + TimgFunctionClockConfig::PllF80m => release_pll_f80m(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_selector, new_selector); } } pub fn function_clock_config( @@ -3609,11 +4508,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: TimgFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: TimgFunctionClockConfig) -> u32 { match config { TimgFunctionClockConfig::XtalClk => xtal_clk_frequency(), TimgFunctionClockConfig::RcFastClk => rc_fast_clk_frequency(), @@ -3625,11 +4520,7 @@ macro_rules! define_clock_tree_types { .load(::core::sync::atomic::Ordering::Acquire) } pub fn function_clock_source_frequency(source: TimgFunctionClockConfig) -> u32 { - match source { - TimgFunctionClockConfig::XtalClk => xtal_clk_frequency(), - TimgFunctionClockConfig::RcFastClk => rc_fast_clk_frequency(), - TimgFunctionClockConfig::PllF80m => pll_f80m_frequency(), - } + Self::function_clock_config_frequency(source) } pub fn configure_wdt_clock( self, @@ -3638,22 +4529,21 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.timg_wdt_clock[self as usize].replace(new_selector); refresh_timg_wdt_clock_downstream(clocks, self); - if clocks.timg_wdt_clock_refcount[self as usize] > 0 { + let active = clocks.timg_wdt_clock_refcount[self as usize] > 0; + if active { match new_selector { TimgWdtClockConfig::XtalClk => request_xtal_clk(clocks), TimgWdtClockConfig::PllF80m => request_pll_f80m(clocks), TimgWdtClockConfig::RcFastClk => request_rc_fast_clk(clocks), } - self.configure_wdt_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - TimgWdtClockConfig::XtalClk => release_xtal_clk(clocks), - TimgWdtClockConfig::PllF80m => release_pll_f80m(clocks), - TimgWdtClockConfig::RcFastClk => release_rc_fast_clk(clocks), - } + } + self.configure_wdt_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + TimgWdtClockConfig::XtalClk => release_xtal_clk(clocks), + TimgWdtClockConfig::PllF80m => release_pll_f80m(clocks), + TimgWdtClockConfig::RcFastClk => release_rc_fast_clk(clocks), } - } else { - self.configure_wdt_clock_impl(clocks, old_selector, new_selector); } } pub fn wdt_clock_config(self, clocks: &mut ClockTree) -> Option { @@ -3683,11 +4573,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn wdt_clock_config_frequency( - clocks: &mut ClockTree, - config: TimgWdtClockConfig, - ) -> u32 { + pub fn wdt_clock_config_frequency(config: TimgWdtClockConfig) -> u32 { match config { TimgWdtClockConfig::XtalClk => xtal_clk_frequency(), TimgWdtClockConfig::PllF80m => pll_f80m_frequency(), @@ -3699,12 +4585,77 @@ macro_rules! define_clock_tree_types { .load(::core::sync::atomic::Ordering::Acquire) } pub fn wdt_clock_source_frequency(source: TimgWdtClockConfig) -> u32 { - match source { - TimgWdtClockConfig::XtalClk => xtal_clk_frequency(), - TimgWdtClockConfig::PllF80m => pll_f80m_frequency(), - TimgWdtClockConfig::RcFastClk => rc_fast_clk_frequency(), + Self::wdt_clock_config_frequency(source) + } + } + impl TwaiInstance { + pub fn configure_function_clock( + self, + clocks: &mut ClockTree, + new_selector: TwaiFunctionClockConfig, + ) { + let old_selector = clocks.twai_function_clock[self as usize].replace(new_selector); + refresh_twai_function_clock_downstream(clocks, self); + let active = clocks.twai_function_clock_refcount[self as usize] > 0; + if active { + match new_selector { + TwaiFunctionClockConfig::Xtal => request_xtal_clk(clocks), + TwaiFunctionClockConfig::PllF80m => request_pll_f80m(clocks), + } + } + self.configure_function_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + TwaiFunctionClockConfig::Xtal => release_xtal_clk(clocks), + TwaiFunctionClockConfig::PllF80m => release_pll_f80m(clocks), + } + } + } + pub fn function_clock_config( + self, + clocks: &mut ClockTree, + ) -> Option { + clocks.twai_function_clock[self as usize] + } + pub fn request_function_clock(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::FUNCTION_CLOCK", self); + if increment_reference_count( + &mut clocks.twai_function_clock_refcount[self as usize], + ) { + trace!("Enabling {:?}::FUNCTION_CLOCK", self); + match unwrap!(clocks.twai_function_clock[self as usize]) { + TwaiFunctionClockConfig::Xtal => request_xtal_clk(clocks), + TwaiFunctionClockConfig::PllF80m => request_pll_f80m(clocks), + } + self.enable_function_clock_impl(clocks, true); } } + pub fn release_function_clock(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::FUNCTION_CLOCK", self); + if decrement_reference_count( + &mut clocks.twai_function_clock_refcount[self as usize], + ) { + trace!("Disabling {:?}::FUNCTION_CLOCK", self); + self.enable_function_clock_impl(clocks, false); + match unwrap!(clocks.twai_function_clock[self as usize]) { + TwaiFunctionClockConfig::Xtal => release_xtal_clk(clocks), + TwaiFunctionClockConfig::PllF80m => release_pll_f80m(clocks), + } + } + } + pub fn function_clock_config_frequency(config: TwaiFunctionClockConfig) -> u32 { + match config { + TwaiFunctionClockConfig::Xtal => xtal_clk_frequency(), + TwaiFunctionClockConfig::PllF80m => pll_f80m_frequency(), + } + } + pub fn function_clock_frequency(self) -> u32 { + TWAI_FUNCTION_CLOCK_FREQ_CACHE[self as usize] + .load(::core::sync::atomic::Ordering::Acquire) + } + pub fn function_clock_source_frequency(source: TwaiFunctionClockConfig) -> u32 { + Self::function_clock_config_frequency(source) + } } impl UartInstance { pub fn configure_function_clock( @@ -3714,22 +4665,21 @@ macro_rules! define_clock_tree_types { ) { let old_config = clocks.uart_function_clock[self as usize].replace(config); refresh_uart_function_clock_downstream(clocks, self); - if clocks.uart_function_clock_refcount[self as usize] > 0 { + let active = clocks.uart_function_clock_refcount[self as usize] > 0; + if active { match config.sclk { UartFunctionClockSclk::Xtal => request_xtal_clk(clocks), UartFunctionClockSclk::PllF80m => request_pll_f80m(clocks), UartFunctionClockSclk::RcFast => request_rc_fast_clk(clocks), } - self.configure_function_clock_impl(clocks, old_config, config); - if let Some(old_config) = old_config { - match old_config.sclk { - UartFunctionClockSclk::Xtal => release_xtal_clk(clocks), - UartFunctionClockSclk::PllF80m => release_pll_f80m(clocks), - UartFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), - } + } + self.configure_function_clock_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + UartFunctionClockSclk::Xtal => release_xtal_clk(clocks), + UartFunctionClockSclk::PllF80m => release_pll_f80m(clocks), + UartFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_config, config); } } pub fn function_clock_config( @@ -3766,11 +4716,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: UartFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: UartFunctionClockConfig) -> u32 { (match config.sclk { UartFunctionClockSclk::Xtal => xtal_clk_frequency(), UartFunctionClockSclk::PllF80m => pll_f80m_frequency(), @@ -3823,10 +4769,8 @@ macro_rules! define_clock_tree_types { self.release_function_clock(clocks); } } - #[allow(unused_variables)] pub fn baud_rate_generator_config_frequency( self, - clocks: &mut ClockTree, config: UartBaudRateGeneratorConfig, ) -> u32 { ((self.function_clock_frequency() * 16) @@ -3862,6 +4806,8 @@ macro_rules! define_clock_tree_types { pub lp_fast_clk: Option, /// `LP_SLOW_CLK` configuration. pub lp_slow_clk: Option, + /// `BLE_LP_CLK` configuration. + pub ble_lp_clk: Option, /// `CRYPTO_CLK` configuration. pub crypto_clk: Option, /// `IOMUX_FUNCTION_CLOCK` configuration. @@ -3892,6 +4838,9 @@ macro_rules! define_clock_tree_types { if let Some(config) = self.lp_slow_clk { configure_lp_slow_clk(clocks, config); } + if let Some(config) = self.ble_lp_clk { + configure_ble_lp_clk(clocks, config); + } if let Some(config) = self.crypto_clk { configure_crypto_clk(clocks, config); } @@ -3916,17 +4865,25 @@ macro_rules! define_clock_tree_types { fn refresh_xtal_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.xtal_clk { XTAL_CLK_FREQ_CACHE.store( - xtal_clk_config_frequency(clocks, config), + xtal_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } refresh_hp_root_clk_downstream(clocks); refresh_lp_fast_clk_downstream(clocks); + refresh_ble_lp_clk_downstream(clocks); refresh_crypto_clk_downstream(clocks); refresh_iomux_function_clock_downstream(clocks); + for child_instance in [AdcInstance::ApbSaradc] { + refresh_adc_function_clock_downstream(clocks, child_instance); + } for child_instance in [I2cInstance::I2c0] { refresh_i2c_function_clock_downstream(clocks, child_instance); } + for child_instance in [I2sInstance::I2s0] { + refresh_i2s_tx_clk_downstream(clocks, child_instance); + refresh_i2s_rx_clk_downstream(clocks, child_instance); + } for child_instance in [ParlIoInstance::ParlIo] { refresh_parl_io_rx_clock_downstream(clocks, child_instance); refresh_parl_io_tx_clock_downstream(clocks, child_instance); @@ -3941,14 +4898,52 @@ macro_rules! define_clock_tree_types { refresh_timg_function_clock_downstream(clocks, child_instance); refresh_timg_wdt_clock_downstream(clocks, child_instance); } + for child_instance in [TwaiInstance::Twai0, TwaiInstance::Twai1] { + refresh_twai_function_clock_downstream(clocks, child_instance); + } for child_instance in [UartInstance::Uart0, UartInstance::Uart1] { refresh_uart_function_clock_downstream(clocks, child_instance); } } + fn refresh_rc_fast_clk_downstream(clocks: &mut ClockTree) { + refresh_hp_root_clk_downstream(clocks); + refresh_lp_fast_clk_downstream(clocks); + refresh_crypto_clk_downstream(clocks); + refresh_iomux_function_clock_downstream(clocks); + refresh_timg_calibration_clock_downstream(clocks); + for child_instance in [AdcInstance::ApbSaradc] { + refresh_adc_function_clock_downstream(clocks, child_instance); + } + for child_instance in [I2cInstance::I2c0] { + refresh_i2c_function_clock_downstream(clocks, child_instance); + } + for child_instance in [ParlIoInstance::ParlIo] { + refresh_parl_io_rx_clock_downstream(clocks, child_instance); + refresh_parl_io_tx_clock_downstream(clocks, child_instance); + } + for child_instance in [RmtInstance::Rmt] { + refresh_rmt_sclk_downstream(clocks, child_instance); + } + for child_instance in [SpiInstance::Spi2] { + refresh_spi_function_clock_downstream(clocks, child_instance); + } + for child_instance in [TimgInstance::Timg0, TimgInstance::Timg1] { + refresh_timg_function_clock_downstream(clocks, child_instance); + refresh_timg_wdt_clock_downstream(clocks, child_instance); + } + for child_instance in [UartInstance::Uart0, UartInstance::Uart1] { + refresh_uart_function_clock_downstream(clocks, child_instance); + } + } + fn refresh_rc_slow_clk_downstream(clocks: &mut ClockTree) { + refresh_lp_slow_clk_downstream(clocks); + refresh_ble_lp_clk_downstream(clocks); + refresh_timg_calibration_clock_downstream(clocks); + } fn refresh_hp_root_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.hp_root_clk { HP_ROOT_CLK_FREQ_CACHE.store( - hp_root_clk_config_frequency(clocks, config), + hp_root_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3958,7 +4953,7 @@ macro_rules! define_clock_tree_types { fn refresh_cpu_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.cpu_clk { CPU_CLK_FREQ_CACHE.store( - cpu_clk_config_frequency(clocks, config), + cpu_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3966,7 +4961,7 @@ macro_rules! define_clock_tree_types { fn refresh_ahb_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.ahb_clk { AHB_CLK_FREQ_CACHE.store( - ahb_clk_config_frequency(clocks, config), + ahb_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3975,7 +4970,7 @@ macro_rules! define_clock_tree_types { fn refresh_apb_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.apb_clk { APB_CLK_FREQ_CACHE.store( - apb_clk_config_frequency(clocks, config), + apb_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3983,7 +4978,7 @@ macro_rules! define_clock_tree_types { fn refresh_lp_fast_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.lp_fast_clk { LP_FAST_CLK_FREQ_CACHE.store( - lp_fast_clk_config_frequency(clocks, config), + lp_fast_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3991,7 +4986,15 @@ macro_rules! define_clock_tree_types { fn refresh_lp_slow_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.lp_slow_clk { LP_SLOW_CLK_FREQ_CACHE.store( - lp_slow_clk_config_frequency(clocks, config), + lp_slow_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + fn refresh_ble_lp_clk_downstream(clocks: &mut ClockTree) { + if let Some(config) = clocks.ble_lp_clk { + BLE_LP_CLK_FREQ_CACHE.store( + ble_lp_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3999,7 +5002,7 @@ macro_rules! define_clock_tree_types { fn refresh_crypto_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.crypto_clk { CRYPTO_CLK_FREQ_CACHE.store( - crypto_clk_config_frequency(clocks, config), + crypto_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4007,7 +5010,7 @@ macro_rules! define_clock_tree_types { fn refresh_iomux_function_clock_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.iomux_function_clock { IOMUX_FUNCTION_CLOCK_FREQ_CACHE.store( - iomux_function_clock_config_frequency(clocks, config), + iomux_function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4015,7 +5018,15 @@ macro_rules! define_clock_tree_types { fn refresh_timg_calibration_clock_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.timg_calibration_clock { TIMG_CALIBRATION_CLOCK_FREQ_CACHE.store( - timg_calibration_clock_config_frequency(clocks, config), + timg_calibration_clock_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + fn refresh_adc_function_clock_downstream(clocks: &mut ClockTree, instance: AdcInstance) { + if let Some(config) = clocks.adc_function_clock[instance as usize] { + ADC_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( + AdcInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4023,7 +5034,33 @@ macro_rules! define_clock_tree_types { fn refresh_i2c_function_clock_downstream(clocks: &mut ClockTree, instance: I2cInstance) { if let Some(config) = clocks.i2c_function_clock[instance as usize] { I2C_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - I2cInstance::function_clock_config_frequency(clocks, config), + I2cInstance::function_clock_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + fn refresh_i2s_tx_clk_downstream(clocks: &mut ClockTree, instance: I2sInstance) { + if let Some(config) = clocks.i2s_tx_clk[instance as usize] { + I2S_TX_CLK_FREQ_CACHE[instance as usize].store( + I2sInstance::tx_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + refresh_i2s_mclk_out_downstream(clocks, instance); + } + fn refresh_i2s_rx_clk_downstream(clocks: &mut ClockTree, instance: I2sInstance) { + if let Some(config) = clocks.i2s_rx_clk[instance as usize] { + I2S_RX_CLK_FREQ_CACHE[instance as usize].store( + I2sInstance::rx_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + refresh_i2s_mclk_out_downstream(clocks, instance); + } + fn refresh_i2s_mclk_out_downstream(clocks: &mut ClockTree, instance: I2sInstance) { + if let Some(config) = clocks.i2s_mclk_out[instance as usize] { + I2S_MCLK_OUT_FREQ_CACHE[instance as usize].store( + instance.mclk_out_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4031,7 +5068,7 @@ macro_rules! define_clock_tree_types { fn refresh_parl_io_rx_clock_downstream(clocks: &mut ClockTree, instance: ParlIoInstance) { if let Some(config) = clocks.parl_io_rx_clock[instance as usize] { PARL_IO_RX_CLOCK_FREQ_CACHE[instance as usize].store( - ParlIoInstance::rx_clock_config_frequency(clocks, config), + ParlIoInstance::rx_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4039,7 +5076,7 @@ macro_rules! define_clock_tree_types { fn refresh_parl_io_tx_clock_downstream(clocks: &mut ClockTree, instance: ParlIoInstance) { if let Some(config) = clocks.parl_io_tx_clock[instance as usize] { PARL_IO_TX_CLOCK_FREQ_CACHE[instance as usize].store( - ParlIoInstance::tx_clock_config_frequency(clocks, config), + ParlIoInstance::tx_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4047,7 +5084,7 @@ macro_rules! define_clock_tree_types { fn refresh_rmt_sclk_downstream(clocks: &mut ClockTree, instance: RmtInstance) { if let Some(config) = clocks.rmt_sclk[instance as usize] { RMT_SCLK_FREQ_CACHE[instance as usize].store( - RmtInstance::sclk_config_frequency(clocks, config), + RmtInstance::sclk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4055,7 +5092,7 @@ macro_rules! define_clock_tree_types { fn refresh_spi_function_clock_downstream(clocks: &mut ClockTree, instance: SpiInstance) { if let Some(config) = clocks.spi_function_clock[instance as usize] { SPI_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - SpiInstance::function_clock_config_frequency(clocks, config), + SpiInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4063,7 +5100,7 @@ macro_rules! define_clock_tree_types { fn refresh_timg_function_clock_downstream(clocks: &mut ClockTree, instance: TimgInstance) { if let Some(config) = clocks.timg_function_clock[instance as usize] { TIMG_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - TimgInstance::function_clock_config_frequency(clocks, config), + TimgInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4071,7 +5108,15 @@ macro_rules! define_clock_tree_types { fn refresh_timg_wdt_clock_downstream(clocks: &mut ClockTree, instance: TimgInstance) { if let Some(config) = clocks.timg_wdt_clock[instance as usize] { TIMG_WDT_CLOCK_FREQ_CACHE[instance as usize].store( - TimgInstance::wdt_clock_config_frequency(clocks, config), + TimgInstance::wdt_clock_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + fn refresh_twai_function_clock_downstream(clocks: &mut ClockTree, instance: TwaiInstance) { + if let Some(config) = clocks.twai_function_clock[instance as usize] { + TWAI_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( + TwaiInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4079,7 +5124,7 @@ macro_rules! define_clock_tree_types { fn refresh_uart_function_clock_downstream(clocks: &mut ClockTree, instance: UartInstance) { if let Some(config) = clocks.uart_function_clock[instance as usize] { UART_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - UartInstance::function_clock_config_frequency(clocks, config), + UartInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4091,7 +5136,7 @@ macro_rules! define_clock_tree_types { ) { if let Some(config) = clocks.uart_baud_rate_generator[instance as usize] { UART_BAUD_RATE_GENERATOR_FREQ_CACHE[instance as usize].store( - instance.baud_rate_generator_config_frequency(clocks, config), + instance.baud_rate_generator_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4142,6 +5187,10 @@ macro_rules! implement_peripheral_clocks { Timg0, /// TIMG1 peripheral clock signal Timg1, + /// TWAI0 peripheral clock signal + Twai0, + /// TWAI1 peripheral clock signal + Twai1, /// UART0 peripheral clock signal Uart0, /// UART1 peripheral clock signal @@ -4177,6 +5226,8 @@ macro_rules! implement_peripheral_clocks { Self::Systimer, Self::Timg0, Self::Timg1, + Self::Twai0, + Self::Twai1, Self::Uart0, Self::Uart1, Self::Uhci0, @@ -4267,6 +5318,16 @@ macro_rules! implement_peripheral_clocks { .conf() .modify(|_, w| w.clk_en().bit(enable)); } + Peripheral::Twai0 => { + crate::peripherals::SYSTEM::regs() + .twai0_conf() + .modify(|_, w| w.twai0_clk_en().bit(enable)); + } + Peripheral::Twai1 => { + crate::peripherals::SYSTEM::regs() + .twai1_conf() + .modify(|_, w| w.twai1_clk_en().bit(enable)); + } Peripheral::Uart0 => { crate::peripherals::SYSTEM::regs() .uart(0) @@ -4373,6 +5434,16 @@ macro_rules! implement_peripheral_clocks { .conf() .modify(|_, w| w.rst_en().bit(reset)); } + Peripheral::Twai0 => { + crate::peripherals::SYSTEM::regs() + .twai0_conf() + .modify(|_, w| w.twai0_rst_en().bit(reset)); + } + Peripheral::Twai1 => { + crate::peripherals::SYSTEM::regs() + .twai1_conf() + .modify(|_, w| w.twai1_rst_en().bit(reset)); + } Peripheral::Uart0 => { crate::peripherals::SYSTEM::regs() .uart(0) @@ -4588,6 +5659,84 @@ macro_rules! for_each_spi_slave { Spi2, FSPICLK, FSPID, FSPIQ, FSPICS0))); }; } +/// This macro can be used to generate code for each PCNT unit. +/// +/// For an explanation on the general syntax, as well as usage of individual/repeated +/// matchers, refer to [the crate-level documentation][crate#for_each-macros]. +/// +/// This macro has four options for its "Individual matcher" case: +/// +/// - `names`: `($instance:ident)` +/// - `all`: `($peri:ident, $variant:ident, $sys:ident, $regs:ident, $unit:literal, +/// $interrupt:ident, $sig_ch0:ident, $sig_ch1:ident, $ctrl_ch0:ident, $ctrl_ch1:ident)` +/// - `interrupt`: `($interrupt:ident)` (repeated: one ident per unique IRQ) +/// - `regs`: `($regs:ident)` (repeated: one ident per register block) +/// +/// Macro fragments: +/// +/// - `$peri`: unit singleton name (`PCNT0_UNIT0`, `PCNT1_UNIT0`, …) +/// - `$variant`: `AnyPcntUnit` enum variant (`Pcnt0Unit0`, `Pcnt1Unit0`, …) +/// - `$sys`: `esp_hal::system::Peripheral` variant for clocks +/// - `$regs`: register-block singleton (`PCNT`, `PCNT1`) +/// - `$unit`: hardware unit index within that register block +/// - `$interrupt`: shared peripheral interrupt +/// - `$sig_ch0`, `$sig_ch1`, `$ctrl_ch0`, `$ctrl_ch1`: GPIO matrix input signals +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! for_each_pcnt_unit { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _for_each_inner_pcnt_unit { $(($pattern) => $code;)* ($other : tt) + => {} } _for_each_inner_pcnt_unit!((PCNT0_UNIT0)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT2)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT3)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT0, Pcnt0Unit0, Pcnt, PCNT, 0, PCNT, + PCNT0_SIG_CH0, PCNT0_SIG_CH1, PCNT0_CTRL_CH0, PCNT0_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT1, Pcnt0Unit1, Pcnt, PCNT, 1, PCNT, + PCNT1_SIG_CH0, PCNT1_SIG_CH1, PCNT1_CTRL_CH0, PCNT1_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT2, Pcnt0Unit2, Pcnt, PCNT, 2, PCNT, + PCNT2_SIG_CH0, PCNT2_SIG_CH1, PCNT2_CTRL_CH0, PCNT2_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT3, Pcnt0Unit3, Pcnt, PCNT, 3, PCNT, + PCNT3_SIG_CH0, PCNT3_SIG_CH1, PCNT3_CTRL_CH0, PCNT3_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT)); _for_each_inner_pcnt_unit!((PCNT)); + _for_each_inner_pcnt_unit!((names(PCNT0_UNIT0), (PCNT0_UNIT1), (PCNT0_UNIT2), + (PCNT0_UNIT3))); _for_each_inner_pcnt_unit!((all(PCNT0_UNIT0, Pcnt0Unit0, Pcnt, + PCNT, 0, PCNT, PCNT0_SIG_CH0, PCNT0_SIG_CH1, PCNT0_CTRL_CH0, PCNT0_CTRL_CH1), + (PCNT0_UNIT1, Pcnt0Unit1, Pcnt, PCNT, 1, PCNT, PCNT1_SIG_CH0, PCNT1_SIG_CH1, + PCNT1_CTRL_CH0, PCNT1_CTRL_CH1), (PCNT0_UNIT2, Pcnt0Unit2, Pcnt, PCNT, 2, PCNT, + PCNT2_SIG_CH0, PCNT2_SIG_CH1, PCNT2_CTRL_CH0, PCNT2_CTRL_CH1), (PCNT0_UNIT3, + Pcnt0Unit3, Pcnt, PCNT, 3, PCNT, PCNT3_SIG_CH0, PCNT3_SIG_CH1, PCNT3_CTRL_CH0, + PCNT3_CTRL_CH1))); _for_each_inner_pcnt_unit!((interrupt(PCNT))); + _for_each_inner_pcnt_unit!((regs(PCNT))); + }; +} +/// This macro can be used to generate code for each peripheral instance of the CAN FD driver. +/// +/// For an explanation on the general syntax, as well as usage of individual/repeated +/// matchers, refer to [the crate-level documentation][crate#for_each-macros]. +/// +/// This macro has one option for its "Individual matcher" case: +/// +/// Syntax: `($instance:ident, $sys:ident, $rx:ident, $tx:ident)` +/// +/// Macro fragments: +/// +/// - `$instance`: the name of the CAN FD instance +/// - `$sys`: the name of the instance as it is in the `esp_hal::system::Peripheral` enum. +/// - `$rx`, `$tx`: signal names. +/// +/// Example data: `(TWAI0, Twai0, TWAI0_RX, TWAI0_TX)` +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! for_each_canfd { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _for_each_inner_canfd { $(($pattern) => $code;)* ($other : tt) => {} + } _for_each_inner_canfd!((TWAI0, Twai0, TWAI0_RX, TWAI0_TX)); + _for_each_inner_canfd!((TWAI1, Twai1, TWAI1_RX, TWAI1_TX)); + _for_each_inner_canfd!((all(TWAI0, Twai0, TWAI0_RX, TWAI0_TX), (TWAI1, Twai1, + TWAI1_RX, TWAI1_TX))); + }; +} #[macro_export] #[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] macro_rules! for_each_peripheral { @@ -4771,6 +5920,14 @@ macro_rules! for_each_peripheral { DMA_CH2 <= virtual(DMA_IN_CH2 : { bind_dma_in_interrupt, enable_dma_in_interrupt, disable_dma_in_interrupt }, DMA_OUT_CH2 : { bind_dma_out_interrupt, enable_dma_out_interrupt, disable_dma_out_interrupt }) (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT0_UNIT0 peripheral singleton"] PCNT0_UNIT0 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT0_UNIT1 peripheral singleton"] PCNT0_UNIT1 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT0_UNIT2 peripheral singleton"] PCNT0_UNIT2 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT0_UNIT3 peripheral singleton"] PCNT0_UNIT3 <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "SDM_CH0 peripheral singleton"] SDM_CH0 <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "SDM_CH1 peripheral singleton"] SDM_CH1 <= virtual() (unstable))); @@ -4785,26 +5942,27 @@ macro_rules! for_each_peripheral { "APB_SARADC peripheral singleton"] APB_SARADC <= APB_SARADC() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "CACHE peripheral singleton"] CACHE <= CACHE() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "CLINT peripheral singleton"] CLINT <= CLINT() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "DMA peripheral singleton"] DMA - <= DMA() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "DS peripheral singleton"] DS <= DS() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "ECC peripheral singleton"] ECC - <= ECC() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "ECDSA peripheral singleton"] ECDSA <= ECDSA() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "EFUSE peripheral singleton"] - EFUSE <= EFUSE() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "ETM peripheral singleton"] ETM <= SOC_ETM() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "GPIO peripheral singleton"] - GPIO <= GPIO() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "GPIO_SD peripheral singleton"] GPIO_SD <= GPIO_EXT() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "HMAC peripheral singleton"] - HMAC <= HMAC() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "HP_APM peripheral singleton"] HP_APM <= HP_APM() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "HP_SYS peripheral singleton"] - HP_SYS <= HP_SYS() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "HUK peripheral singleton"] HUK <= HUK() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = + "CLIC peripheral singleton"] CLIC <= CLIC() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "CLINT peripheral singleton"] + CLINT <= CLINT() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "DMA peripheral singleton"] DMA <= DMA() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "DS peripheral singleton"] DS <= + DS() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "ECC peripheral singleton"] ECC <= ECC() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "ECDSA peripheral singleton"] + ECDSA <= ECDSA() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "EFUSE peripheral singleton"] EFUSE <= EFUSE() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "ETM peripheral singleton"] ETM + <= SOC_ETM() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "GPIO peripheral singleton"] GPIO <= GPIO() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "GPIO_SD peripheral singleton"] + GPIO_SD <= GPIO_EXT() (unstable))); _for_each_inner_peripheral!((@ peri_type + #[doc = "HMAC peripheral singleton"] HMAC <= HMAC() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "HP_APM peripheral singleton"] + HP_APM <= HP_APM() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "HP_SYS peripheral singleton"] HP_SYS <= HP_SYS() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "HUK peripheral singleton"] HUK + <= HUK() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "I2C_ANA_MST peripheral singleton"] I2C_ANA_MST <= I2C_ANA_MST() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "I2C0 peripheral singleton"] I2C0 <= I2C0(I2C_EXT0 : { bind_peri_interrupt, enable_peri_interrupt, @@ -4857,8 +6015,9 @@ macro_rules! for_each_peripheral { disable_tx_interrupt }) (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "PAU peripheral singleton"] PAU <= PAU() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "PCNT peripheral singleton"] - PCNT <= PCNT() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "PCR peripheral singleton"] PCR <= PCR() (unstable))); + PCNT <= PCNT(PCNT : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt }) (unstable))); _for_each_inner_peripheral!((@ peri_type + #[doc = "PCR peripheral singleton"] PCR <= PCR() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "PMU peripheral singleton"] PMU <= PMU() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "PVT_MONITOR peripheral singleton"] PVT_MONITOR <= PVT() (unstable))); @@ -4885,6 +6044,14 @@ macro_rules! for_each_peripheral { "TIMG0 peripheral singleton"] TIMG0 <= TIMG0() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "TIMG1 peripheral singleton"] TIMG1 <= TIMG1() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "TWAI0 peripheral singleton"] TWAI0 <= TWAI0(TWAI0 : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }, TWAI0_TIMER : { + bind_timer_interrupt, enable_timer_interrupt, disable_timer_interrupt }) + (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "TWAI1 peripheral singleton"] TWAI1 <= TWAI1(TWAI1 : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }, TWAI1_TIMER : { + bind_timer_interrupt, enable_timer_interrupt, disable_timer_interrupt }) + (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "UART0 peripheral singleton"] UART0 <= UART0(UART0 : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }))); _for_each_inner_peripheral!((@ peri_type #[doc = "UART1 peripheral singleton"] @@ -4937,6 +6104,10 @@ macro_rules! for_each_peripheral { _for_each_inner_peripheral!((DMA_CH0(unstable))); _for_each_inner_peripheral!((DMA_CH1(unstable))); _for_each_inner_peripheral!((DMA_CH2(unstable))); + _for_each_inner_peripheral!((PCNT0_UNIT0(unstable))); + _for_each_inner_peripheral!((PCNT0_UNIT1(unstable))); + _for_each_inner_peripheral!((PCNT0_UNIT2(unstable))); + _for_each_inner_peripheral!((PCNT0_UNIT3(unstable))); _for_each_inner_peripheral!((SDM_CH0(unstable))); _for_each_inner_peripheral!((SDM_CH1(unstable))); _for_each_inner_peripheral!((SDM_CH2(unstable))); @@ -5002,6 +6173,8 @@ macro_rules! for_each_peripheral { _for_each_inner_peripheral!((TEE(unstable))); _for_each_inner_peripheral!((TIMG0(unstable))); _for_each_inner_peripheral!((TIMG1(unstable))); + _for_each_inner_peripheral!((TWAI0(unstable))); + _for_each_inner_peripheral!((TWAI1(unstable))); _for_each_inner_peripheral!((UART0)); _for_each_inner_peripheral!((UART1)); _for_each_inner_peripheral!((UHCI0(unstable))); _for_each_inner_peripheral!((USB_DEVICE(unstable))); @@ -5180,36 +6353,42 @@ macro_rules! for_each_peripheral { bind_dma_in_interrupt, enable_dma_in_interrupt, disable_dma_in_interrupt }, DMA_OUT_CH2 : { bind_dma_out_interrupt, enable_dma_out_interrupt, disable_dma_out_interrupt }) (unstable)), (@ peri_type #[doc = - "SDM_CH0 peripheral singleton"] SDM_CH0 <= virtual() (unstable)), (@ peri_type - #[doc = "SDM_CH1 peripheral singleton"] SDM_CH1 <= virtual() (unstable)), (@ - peri_type #[doc = "SDM_CH2 peripheral singleton"] SDM_CH2 <= virtual() - (unstable)), (@ peri_type #[doc = "SDM_CH3 peripheral singleton"] SDM_CH3 <= - virtual() (unstable)), (@ peri_type #[doc = "AES peripheral singleton"] AES <= - AES(AES : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) - (unstable)), (@ peri_type #[doc = "ASSIST_DEBUG peripheral singleton"] - ASSIST_DEBUG <= ASSIST_DEBUG() (unstable)), (@ peri_type #[doc = - "APB_SARADC peripheral singleton"] APB_SARADC <= APB_SARADC() (unstable)), (@ - peri_type #[doc = "CACHE peripheral singleton"] CACHE <= CACHE() (unstable)), (@ - peri_type #[doc = "CLINT peripheral singleton"] CLINT <= CLINT() (unstable)), (@ - peri_type #[doc = "DMA peripheral singleton"] DMA <= DMA() (unstable)), (@ - peri_type #[doc = "DS peripheral singleton"] DS <= DS() (unstable)), (@ peri_type - #[doc = "ECC peripheral singleton"] ECC <= ECC() (unstable)), (@ peri_type #[doc - = "ECDSA peripheral singleton"] ECDSA <= ECDSA() (unstable)), (@ peri_type #[doc - = "EFUSE peripheral singleton"] EFUSE <= EFUSE() (unstable)), (@ peri_type #[doc - = "ETM peripheral singleton"] ETM <= SOC_ETM() (unstable)), (@ peri_type #[doc = - "GPIO peripheral singleton"] GPIO <= GPIO() (unstable)), (@ peri_type #[doc = - "GPIO_SD peripheral singleton"] GPIO_SD <= GPIO_EXT() (unstable)), (@ peri_type - #[doc = "HMAC peripheral singleton"] HMAC <= HMAC() (unstable)), (@ peri_type - #[doc = "HP_APM peripheral singleton"] HP_APM <= HP_APM() (unstable)), (@ - peri_type #[doc = "HP_SYS peripheral singleton"] HP_SYS <= HP_SYS() (unstable)), - (@ peri_type #[doc = "HUK peripheral singleton"] HUK <= HUK() (unstable)), (@ - peri_type #[doc = "I2C_ANA_MST peripheral singleton"] I2C_ANA_MST <= - I2C_ANA_MST() (unstable)), (@ peri_type #[doc = "I2C0 peripheral singleton"] I2C0 - <= I2C0(I2C_EXT0 : { bind_peri_interrupt, enable_peri_interrupt, - disable_peri_interrupt })), (@ peri_type #[doc = "I2S0 peripheral singleton"] - I2S0 <= I2S0(I2S0 : { bind_peri_interrupt, enable_peri_interrupt, - disable_peri_interrupt }) (unstable)), (@ peri_type #[doc = - "IEEE802154 peripheral singleton"] IEEE802154 <= IEEE802154(ZB_MAC : { + "PCNT0_UNIT0 peripheral singleton"] PCNT0_UNIT0 <= virtual() (unstable)), (@ + peri_type #[doc = "PCNT0_UNIT1 peripheral singleton"] PCNT0_UNIT1 <= virtual() + (unstable)), (@ peri_type #[doc = "PCNT0_UNIT2 peripheral singleton"] PCNT0_UNIT2 + <= virtual() (unstable)), (@ peri_type #[doc = + "PCNT0_UNIT3 peripheral singleton"] PCNT0_UNIT3 <= virtual() (unstable)), (@ + peri_type #[doc = "SDM_CH0 peripheral singleton"] SDM_CH0 <= virtual() + (unstable)), (@ peri_type #[doc = "SDM_CH1 peripheral singleton"] SDM_CH1 <= + virtual() (unstable)), (@ peri_type #[doc = "SDM_CH2 peripheral singleton"] + SDM_CH2 <= virtual() (unstable)), (@ peri_type #[doc = + "SDM_CH3 peripheral singleton"] SDM_CH3 <= virtual() (unstable)), (@ peri_type + #[doc = "AES peripheral singleton"] AES <= AES(AES : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc + = "ASSIST_DEBUG peripheral singleton"] ASSIST_DEBUG <= ASSIST_DEBUG() + (unstable)), (@ peri_type #[doc = "APB_SARADC peripheral singleton"] APB_SARADC + <= APB_SARADC() (unstable)), (@ peri_type #[doc = "CACHE peripheral singleton"] + CACHE <= CACHE() (unstable)), (@ peri_type #[doc = "CLIC peripheral singleton"] + CLIC <= CLIC() (unstable)), (@ peri_type #[doc = "CLINT peripheral singleton"] + CLINT <= CLINT() (unstable)), (@ peri_type #[doc = "DMA peripheral singleton"] + DMA <= DMA() (unstable)), (@ peri_type #[doc = "DS peripheral singleton"] DS <= + DS() (unstable)), (@ peri_type #[doc = "ECC peripheral singleton"] ECC <= ECC() + (unstable)), (@ peri_type #[doc = "ECDSA peripheral singleton"] ECDSA <= ECDSA() + (unstable)), (@ peri_type #[doc = "EFUSE peripheral singleton"] EFUSE <= EFUSE() + (unstable)), (@ peri_type #[doc = "ETM peripheral singleton"] ETM <= SOC_ETM() + (unstable)), (@ peri_type #[doc = "GPIO peripheral singleton"] GPIO <= GPIO() + (unstable)), (@ peri_type #[doc = "GPIO_SD peripheral singleton"] GPIO_SD <= + GPIO_EXT() (unstable)), (@ peri_type #[doc = "HMAC peripheral singleton"] HMAC <= + HMAC() (unstable)), (@ peri_type #[doc = "HP_APM peripheral singleton"] HP_APM <= + HP_APM() (unstable)), (@ peri_type #[doc = "HP_SYS peripheral singleton"] HP_SYS + <= HP_SYS() (unstable)), (@ peri_type #[doc = "HUK peripheral singleton"] HUK <= + HUK() (unstable)), (@ peri_type #[doc = "I2C_ANA_MST peripheral singleton"] + I2C_ANA_MST <= I2C_ANA_MST() (unstable)), (@ peri_type #[doc = + "I2C0 peripheral singleton"] I2C0 <= I2C0(I2C_EXT0 : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt })), (@ peri_type #[doc = + "I2S0 peripheral singleton"] I2S0 <= I2S0(I2S0 : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc + = "IEEE802154 peripheral singleton"] IEEE802154 <= IEEE802154(ZB_MAC : { bind_mac_interrupt, enable_mac_interrupt, disable_mac_interrupt }) (unstable)), (@ peri_type #[doc = "INTERRUPT_CORE0 peripheral singleton"] INTERRUPT_CORE0 <= INTERRUPT_CORE0() (unstable)), (@ peri_type #[doc = @@ -5243,8 +6422,9 @@ macro_rules! for_each_peripheral { disable_rx_interrupt }, PARL_IO_TX : { bind_tx_interrupt, enable_tx_interrupt, disable_tx_interrupt }) (unstable)), (@ peri_type #[doc = "PAU peripheral singleton"] PAU <= PAU() (unstable)), (@ peri_type #[doc = - "PCNT peripheral singleton"] PCNT <= PCNT() (unstable)), (@ peri_type #[doc = - "PCR peripheral singleton"] PCR <= PCR() (unstable)), (@ peri_type #[doc = + "PCNT peripheral singleton"] PCNT <= PCNT(PCNT : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc + = "PCR peripheral singleton"] PCR <= PCR() (unstable)), (@ peri_type #[doc = "PMU peripheral singleton"] PMU <= PMU() (unstable)), (@ peri_type #[doc = "PVT_MONITOR peripheral singleton"] PVT_MONITOR <= PVT() (unstable)), (@ peri_type #[doc = "RMT peripheral singleton"] RMT <= RMT() (unstable)), (@ @@ -5263,6 +6443,13 @@ macro_rules! for_each_peripheral { (unstable)), (@ peri_type #[doc = "TEE peripheral singleton"] TEE <= TEE() (unstable)), (@ peri_type #[doc = "TIMG0 peripheral singleton"] TIMG0 <= TIMG0() (unstable)), (@ peri_type #[doc = "TIMG1 peripheral singleton"] TIMG1 <= TIMG1() + (unstable)), (@ peri_type #[doc = "TWAI0 peripheral singleton"] TWAI0 <= + TWAI0(TWAI0 : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt }, TWAI0_TIMER : { bind_timer_interrupt, + enable_timer_interrupt, disable_timer_interrupt }) (unstable)), (@ peri_type + #[doc = "TWAI1 peripheral singleton"] TWAI1 <= TWAI1(TWAI1 : { + bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }, TWAI1_TIMER + : { bind_timer_interrupt, enable_timer_interrupt, disable_timer_interrupt }) (unstable)), (@ peri_type #[doc = "UART0 peripheral singleton"] UART0 <= UART0(UART0 : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt })), (@ peri_type #[doc = "UART1 peripheral singleton"] @@ -5295,28 +6482,30 @@ macro_rules! for_each_peripheral { (GPIO7), (GPIO8), (GPIO9), (GPIO10), (GPIO11), (GPIO12), (GPIO13), (GPIO14), (GPIO15), (GPIO16), (GPIO17), (GPIO18), (GPIO19), (GPIO20), (GPIO21), (GPIO22), (GPIO23), (GPIO24), (GPIO25), (GPIO26), (GPIO27), (GPIO28), (DMA_CH0(unstable)), - (DMA_CH1(unstable)), (DMA_CH2(unstable)), (SDM_CH0(unstable)), - (SDM_CH1(unstable)), (SDM_CH2(unstable)), (SDM_CH3(unstable)), (AES(unstable)), - (ASSIST_DEBUG(unstable)), (APB_SARADC(unstable)), (CACHE(unstable)), - (CLINT(unstable)), (DMA(unstable)), (DS(unstable)), (ECC(unstable)), - (ECDSA(unstable)), (ETM(unstable)), (GPIO(unstable)), (GPIO_SD(unstable)), - (HMAC(unstable)), (HP_APM(unstable)), (HP_SYS(unstable)), (HUK(unstable)), - (I2C_ANA_MST(unstable)), (I2C0), (I2S0(unstable)), (IEEE802154(unstable)), - (INTERRUPT_CORE0(unstable)), (INTPRI(unstable)), (IO_MUX(unstable)), - (KEYMNG(unstable)), (LP_ANA(unstable)), (LP_AON(unstable)), (LP_APM0(unstable)), - (LP_CLKRST(unstable)), (LP_GPIO(unstable)), (LP_I2C0(unstable)), - (LP_I2C_ANA_MST(unstable)), (LP_IO_MUX(unstable)), (LP_PERI(unstable)), - (LP_TEE(unstable)), (RTC_TIMER(unstable)), (LP_UART(unstable)), - (LP_WDT(unstable)), (LPWR(unstable)), (MCPWM0(unstable)), - (MEM_MONITOR(unstable)), (MODEM_LPCON(unstable)), (MODEM_SYSCON(unstable)), - (PARL_IO(unstable)), (PAU(unstable)), (PCNT(unstable)), (PCR(unstable)), - (PMU(unstable)), (PVT_MONITOR(unstable)), (RMT(unstable)), (RNG(unstable)), - (RSA(unstable)), (SHA(unstable)), (SLC(unstable)), (SPI0(unstable)), - (SPI1(unstable)), (SPI2), (SYSTEM(unstable)), (SYSTIMER(unstable)), - (TEE(unstable)), (TIMG0(unstable)), (TIMG1(unstable)), (UART0), (UART1), - (UHCI0(unstable)), (USB_DEVICE(unstable)), (ADC1(unstable)), (BT(unstable)), - (FLASH(unstable)), (GPIO_DEDICATED(unstable)), (LP_CORE(unstable)), (WIFI), - (PSRAM(unstable)), (FROM_CPU_INTR0(unstable)), (FROM_CPU_INTR1(unstable)), + (DMA_CH1(unstable)), (DMA_CH2(unstable)), (PCNT0_UNIT0(unstable)), + (PCNT0_UNIT1(unstable)), (PCNT0_UNIT2(unstable)), (PCNT0_UNIT3(unstable)), + (SDM_CH0(unstable)), (SDM_CH1(unstable)), (SDM_CH2(unstable)), + (SDM_CH3(unstable)), (AES(unstable)), (ASSIST_DEBUG(unstable)), + (APB_SARADC(unstable)), (CACHE(unstable)), (CLINT(unstable)), (DMA(unstable)), + (DS(unstable)), (ECC(unstable)), (ECDSA(unstable)), (ETM(unstable)), + (GPIO(unstable)), (GPIO_SD(unstable)), (HMAC(unstable)), (HP_APM(unstable)), + (HP_SYS(unstable)), (HUK(unstable)), (I2C_ANA_MST(unstable)), (I2C0), + (I2S0(unstable)), (IEEE802154(unstable)), (INTERRUPT_CORE0(unstable)), + (INTPRI(unstable)), (IO_MUX(unstable)), (KEYMNG(unstable)), (LP_ANA(unstable)), + (LP_AON(unstable)), (LP_APM0(unstable)), (LP_CLKRST(unstable)), + (LP_GPIO(unstable)), (LP_I2C0(unstable)), (LP_I2C_ANA_MST(unstable)), + (LP_IO_MUX(unstable)), (LP_PERI(unstable)), (LP_TEE(unstable)), + (RTC_TIMER(unstable)), (LP_UART(unstable)), (LP_WDT(unstable)), (LPWR(unstable)), + (MCPWM0(unstable)), (MEM_MONITOR(unstable)), (MODEM_LPCON(unstable)), + (MODEM_SYSCON(unstable)), (PARL_IO(unstable)), (PAU(unstable)), (PCNT(unstable)), + (PCR(unstable)), (PMU(unstable)), (PVT_MONITOR(unstable)), (RMT(unstable)), + (RNG(unstable)), (RSA(unstable)), (SHA(unstable)), (SLC(unstable)), + (SPI0(unstable)), (SPI1(unstable)), (SPI2), (SYSTEM(unstable)), + (SYSTIMER(unstable)), (TEE(unstable)), (TIMG0(unstable)), (TIMG1(unstable)), + (TWAI0(unstable)), (TWAI1(unstable)), (UART0), (UART1), (UHCI0(unstable)), + (USB_DEVICE(unstable)), (ADC1(unstable)), (BT(unstable)), (FLASH(unstable)), + (GPIO_DEDICATED(unstable)), (LP_CORE(unstable)), (WIFI), (PSRAM(unstable)), + (FROM_CPU_INTR0(unstable)), (FROM_CPU_INTR1(unstable)), (FROM_CPU_INTR2(unstable)), (FROM_CPU_INTR3(unstable)))); _for_each_inner_peripheral!((dma_eligible(SPI2, Spi2, 1, AhbGdmaChannel), (UHCI0, Uhci0, 2, AhbGdmaChannel), (I2S0, I2s0, 3, AhbGdmaChannel), (AES, Aes, 6, diff --git a/esp-metadata-generated/src/_generated_esp32c6.rs b/esp-metadata-generated/src/_generated_esp32c6.rs index faf0fa1fc5b..a970ad73831 100644 --- a/esp-metadata-generated/src/_generated_esp32c6.rs +++ b/esp-metadata-generated/src/_generated_esp32c6.rs @@ -88,6 +88,9 @@ macro_rules! property { ("gpio.func_in_sel_offset", str) => { stringify!(0) }; + ("gpio.need_soft_isolate_during_pd") => { + false + }; ("gpio.has_bank_1") => { false }; @@ -253,12 +256,6 @@ macro_rules! property { ("i2s.version", str) => { stringify!(2) }; - ("i2s.default_clock_source") => { - 2 - }; - ("i2s.default_clock_source", str) => { - stringify!(2) - }; ("i2s.mclk_divider_bit_width") => { 9 }; @@ -298,6 +295,15 @@ macro_rules! property { ("parl_io.version", str) => { stringify!(1) }; + ("parl_io.max_data_width") => { + 16 + }; + ("parl_io.max_data_width", str) => { + stringify!(16) + }; + ("parl_io.has_tx_cs") => { + false + }; ("rmt.ram_start") => { 1610638336 }; @@ -352,9 +358,48 @@ macro_rules! property { ("wifi.csi_supported") => { true }; + ("wifi.has_nan") => { + false + }; + ("wifi.has_ftm") => { + true + }; ("phy.combo_module") => { true }; + ("adc.controller") => { + "digital" + }; + ("adc.channel_count") => { + 7 + }; + ("adc.channel_count", str) => { + stringify!(7) + }; + ("adc.line_calibration") => { + true + }; + ("adc.curve_calibration") => { + true + }; + ("adc.basic_calibration") => { + true + }; + ("adc.calibration_v1_scheme_supported") => { + true + }; + ("adc.channel_compensation") => { + true + }; + ("adc.pcr_clock") => { + true + }; + ("adc.pcr_sar_clk_div") => { + false + }; + ("adc.sar_power_override") => { + true + }; ("ledc.version") => { 3 }; @@ -379,6 +424,9 @@ macro_rules! property { ("timergroup.timg_has_divcnt_rst") => { true }; + ("timergroup.wdt_has_conf_update") => { + true + }; ("timergroup.rc_fast_calibration_divider_min_rev") => { 1 }; @@ -523,6 +571,9 @@ macro_rules! property { ("soc.cpu_has_csr_pc") => { true }; + ("soc.cpu_has_zcmp_workaround") => { + false + }; ("soc.multi_core_enabled") => { false }; @@ -544,6 +595,12 @@ macro_rules! property { ("soc.cpu_mcause_mask", str) => { stringify!(31) }; + ("soc.cpu_pmp_granularity") => { + 4 + }; + ("soc.cpu_pmp_granularity", str) => { + stringify!(4) + }; ("clock_tree.soc_root_clk") => { [crate ::soc::clocks::SocRootClkConfig::Xtal, crate ::soc::clocks::SocRootClkConfig::RcFast, crate @@ -598,14 +655,19 @@ macro_rules! property { ::soc::clocks::LpFastClkConfig::XtalD2Clk] }; ("clock_tree.lp_slow_clk") => { - [crate ::soc::clocks::LpSlowClkConfig::Xtal32k, crate + [#[cfg(use_xtal32k)] crate ::soc::clocks::LpSlowClkConfig::Xtal32k, crate ::soc::clocks::LpSlowClkConfig::RcSlow, crate ::soc::clocks::LpSlowClkConfig::OscSlow] }; + ("clock_tree.ble_lp_clk") => { + [crate ::soc::clocks::BleLpClkConfig::Xtal, crate + ::soc::clocks::BleLpClkConfig::RcSlow, #[cfg(use_xtal32k)] crate + ::soc::clocks::BleLpClkConfig::Xtal32k] + }; ("clock_tree.timg_calibration_clock") => { [crate ::soc::clocks::TimgCalibrationClockConfig::RcSlowClk, crate - ::soc::clocks::TimgCalibrationClockConfig::RcFastDivClk, crate - ::soc::clocks::TimgCalibrationClockConfig::Xtal32kClk] + ::soc::clocks::TimgCalibrationClockConfig::RcFastDivClk, #[cfg(use_xtal32k)] + crate ::soc::clocks::TimgCalibrationClockConfig::Xtal32kClk] }; ("clock_tree.uart.function_clock.sclk") => { [crate ::soc::clocks::UartFunctionClockSclk::PllF80m, crate @@ -642,14 +704,44 @@ macro_rules! property { ::soc::clocks::McpwmFunctionClockConfig::XtalClk] }; ("clock_tree.parl_io.rx_clock") => { - [crate ::soc::clocks::ParlIoRxClockConfig::XtalClk, crate - ::soc::clocks::ParlIoRxClockConfig::RcFastClk, crate - ::soc::clocks::ParlIoRxClockConfig::PllF240m] + [crate ::soc::clocks::ParlIoClkConfig::XtalClk, crate + ::soc::clocks::ParlIoClkConfig::RcFastClk, crate + ::soc::clocks::ParlIoClkConfig::PllF240m] }; ("clock_tree.parl_io.tx_clock") => { - [crate ::soc::clocks::ParlIoTxClockConfig::XtalClk, crate - ::soc::clocks::ParlIoTxClockConfig::RcFastClk, crate - ::soc::clocks::ParlIoTxClockConfig::PllF240m] + [crate ::soc::clocks::ParlIoClkConfig::XtalClk, crate + ::soc::clocks::ParlIoClkConfig::RcFastClk, crate + ::soc::clocks::ParlIoClkConfig::PllF240m] + }; + ("clock_tree.i2s.tx_clk.sclk") => { + [crate ::soc::clocks::I2sClkSclk::Xtal, crate + ::soc::clocks::I2sClkSclk::PllF240m, crate ::soc::clocks::I2sClkSclk::PllF160m] + }; + ("clock_tree.i2s.tx_clk.div_num") => { + (1, 255) + }; + ("clock_tree.i2s.tx_clk.div_a") => { + (1, 511) + }; + ("clock_tree.i2s.tx_clk.div_b") => { + (0, 511) + }; + ("clock_tree.i2s.rx_clk.sclk") => { + [crate ::soc::clocks::I2sClkSclk::Xtal, crate + ::soc::clocks::I2sClkSclk::PllF240m, crate ::soc::clocks::I2sClkSclk::PllF160m] + }; + ("clock_tree.i2s.rx_clk.div_num") => { + (1, 255) + }; + ("clock_tree.i2s.rx_clk.div_a") => { + (1, 511) + }; + ("clock_tree.i2s.rx_clk.div_b") => { + (0, 511) + }; + ("clock_tree.i2s.mclk_out") => { + [crate ::soc::clocks::I2sMclkOutConfig::Tx, crate + ::soc::clocks::I2sMclkOutConfig::Rx] }; ("clock_tree.i2c.function_clock.sclk") => { [crate ::soc::clocks::I2cFunctionClockSclk::Xtal, crate @@ -658,11 +750,20 @@ macro_rules! property { ("clock_tree.i2c.function_clock.div_num") => { (0, 255) }; + ("clock_tree.tsens.sclk") => { + [crate ::soc::clocks::TsensSclkConfig::RcFast, crate + ::soc::clocks::TsensSclkConfig::Xtal] + }; ("clock_tree.spi.function_clock") => { [crate ::soc::clocks::SpiFunctionClockConfig::PllF80m, crate ::soc::clocks::SpiFunctionClockConfig::Xtal, crate ::soc::clocks::SpiFunctionClockConfig::RcFast] }; + ("clock_tree.adc.function_clock") => { + [crate ::soc::clocks::AdcFunctionClockConfig::Xtal, crate + ::soc::clocks::AdcFunctionClockConfig::PllF80m, crate + ::soc::clocks::AdcFunctionClockConfig::RcFast] + }; } #[macro_export] #[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] @@ -1163,21 +1264,21 @@ macro_rules! for_each_interrupt { ($($pattern:tt => $code:tt;)*) => { macro_rules! _for_each_inner_interrupt { $(($pattern) => $code;)* ($other : tt) => {} } _for_each_inner_interrupt!(([reserved 0] 0)); - _for_each_inner_interrupt!(([direct_bindable 0] 1)); - _for_each_inner_interrupt!(([direct_bindable 1] 2)); + _for_each_inner_interrupt!(([context_switch 0] 1)); + _for_each_inner_interrupt!(([direct_bindable 0] 2)); _for_each_inner_interrupt!(([reserved 1] 3)); _for_each_inner_interrupt!(([reserved 2] 4)); - _for_each_inner_interrupt!(([direct_bindable 2] 5)); - _for_each_inner_interrupt!(([direct_bindable 3] 6)); + _for_each_inner_interrupt!(([direct_bindable 1] 5)); + _for_each_inner_interrupt!(([direct_bindable 2] 6)); _for_each_inner_interrupt!(([reserved 3] 7)); - _for_each_inner_interrupt!(([direct_bindable 4] 8)); - _for_each_inner_interrupt!(([direct_bindable 5] 9)); - _for_each_inner_interrupt!(([direct_bindable 6] 10)); - _for_each_inner_interrupt!(([direct_bindable 7] 11)); - _for_each_inner_interrupt!(([direct_bindable 8] 12)); - _for_each_inner_interrupt!(([direct_bindable 9] 13)); - _for_each_inner_interrupt!(([direct_bindable 10] 14)); - _for_each_inner_interrupt!(([direct_bindable 11] 15)); + _for_each_inner_interrupt!(([direct_bindable 3] 8)); + _for_each_inner_interrupt!(([direct_bindable 4] 9)); + _for_each_inner_interrupt!(([direct_bindable 5] 10)); + _for_each_inner_interrupt!(([direct_bindable 6] 11)); + _for_each_inner_interrupt!(([direct_bindable 7] 12)); + _for_each_inner_interrupt!(([direct_bindable 8] 13)); + _for_each_inner_interrupt!(([direct_bindable 9] 14)); + _for_each_inner_interrupt!(([direct_bindable 10] 15)); _for_each_inner_interrupt!(([vector 0] 16)); _for_each_inner_interrupt!(([vector 1] 17)); _for_each_inner_interrupt!(([vector 2] 18)); _for_each_inner_interrupt!(([vector 3] 19)); _for_each_inner_interrupt!(([vector @@ -1189,12 +1290,12 @@ macro_rules! for_each_interrupt { _for_each_inner_interrupt!(([vector 12] 28)); _for_each_inner_interrupt!(([vector 13] 29)); _for_each_inner_interrupt!(([vector 14] 30)); _for_each_inner_interrupt!(([disabled 0] 31)); - _for_each_inner_interrupt!((all([reserved 0] 0), ([direct_bindable 0] 1), - ([direct_bindable 1] 2), ([reserved 1] 3), ([reserved 2] 4), ([direct_bindable 2] - 5), ([direct_bindable 3] 6), ([reserved 3] 7), ([direct_bindable 4] 8), - ([direct_bindable 5] 9), ([direct_bindable 6] 10), ([direct_bindable 7] 11), - ([direct_bindable 8] 12), ([direct_bindable 9] 13), ([direct_bindable 10] 14), - ([direct_bindable 11] 15), ([vector 0] 16), ([vector 1] 17), ([vector 2] 18), + _for_each_inner_interrupt!((all([reserved 0] 0), ([context_switch 0] 1), + ([direct_bindable 0] 2), ([reserved 1] 3), ([reserved 2] 4), ([direct_bindable 1] + 5), ([direct_bindable 2] 6), ([reserved 3] 7), ([direct_bindable 3] 8), + ([direct_bindable 4] 9), ([direct_bindable 5] 10), ([direct_bindable 6] 11), + ([direct_bindable 7] 12), ([direct_bindable 8] 13), ([direct_bindable 9] 14), + ([direct_bindable 10] 15), ([vector 0] 16), ([vector 1] 17), ([vector 2] 18), ([vector 3] 19), ([vector 4] 20), ([vector 5] 21), ([vector 6] 22), ([vector 7] 23), ([vector 8] 24), ([vector 9] 25), ([vector 10] 26), ([vector 11] 27), ([vector 12] 28), ([vector 13] 29), ([vector 14] 30), ([disabled 0] 31))); @@ -1206,17 +1307,16 @@ macro_rules! for_each_classified_interrupt { ($($pattern:tt => $code:tt;)*) => { macro_rules! _for_each_inner_classified_interrupt { $(($pattern) => $code;)* ($other : tt) => {} } _for_each_inner_classified_interrupt!(([direct_bindable 0] - 1)); _for_each_inner_classified_interrupt!(([direct_bindable 1] 2)); - _for_each_inner_classified_interrupt!(([direct_bindable 2] 5)); - _for_each_inner_classified_interrupt!(([direct_bindable 3] 6)); - _for_each_inner_classified_interrupt!(([direct_bindable 4] 8)); - _for_each_inner_classified_interrupt!(([direct_bindable 5] 9)); - _for_each_inner_classified_interrupt!(([direct_bindable 6] 10)); - _for_each_inner_classified_interrupt!(([direct_bindable 7] 11)); - _for_each_inner_classified_interrupt!(([direct_bindable 8] 12)); - _for_each_inner_classified_interrupt!(([direct_bindable 9] 13)); - _for_each_inner_classified_interrupt!(([direct_bindable 10] 14)); - _for_each_inner_classified_interrupt!(([direct_bindable 11] 15)); + 2)); _for_each_inner_classified_interrupt!(([direct_bindable 1] 5)); + _for_each_inner_classified_interrupt!(([direct_bindable 2] 6)); + _for_each_inner_classified_interrupt!(([direct_bindable 3] 8)); + _for_each_inner_classified_interrupt!(([direct_bindable 4] 9)); + _for_each_inner_classified_interrupt!(([direct_bindable 5] 10)); + _for_each_inner_classified_interrupt!(([direct_bindable 6] 11)); + _for_each_inner_classified_interrupt!(([direct_bindable 7] 12)); + _for_each_inner_classified_interrupt!(([direct_bindable 8] 13)); + _for_each_inner_classified_interrupt!(([direct_bindable 9] 14)); + _for_each_inner_classified_interrupt!(([direct_bindable 10] 15)); _for_each_inner_classified_interrupt!(([vector 0] 16)); _for_each_inner_classified_interrupt!(([vector 1] 17)); _for_each_inner_classified_interrupt!(([vector 2] 18)); @@ -1236,17 +1336,19 @@ macro_rules! for_each_classified_interrupt { _for_each_inner_classified_interrupt!(([reserved 1] 3)); _for_each_inner_classified_interrupt!(([reserved 2] 4)); _for_each_inner_classified_interrupt!(([reserved 3] 7)); - _for_each_inner_classified_interrupt!((direct_bindable([direct_bindable 0] 1), - ([direct_bindable 1] 2), ([direct_bindable 2] 5), ([direct_bindable 3] 6), - ([direct_bindable 4] 8), ([direct_bindable 5] 9), ([direct_bindable 6] 10), - ([direct_bindable 7] 11), ([direct_bindable 8] 12), ([direct_bindable 9] 13), - ([direct_bindable 10] 14), ([direct_bindable 11] 15))); + _for_each_inner_classified_interrupt!(([context_switch 0] 1)); + _for_each_inner_classified_interrupt!((direct_bindable([direct_bindable 0] 2), + ([direct_bindable 1] 5), ([direct_bindable 2] 6), ([direct_bindable 3] 8), + ([direct_bindable 4] 9), ([direct_bindable 5] 10), ([direct_bindable 6] 11), + ([direct_bindable 7] 12), ([direct_bindable 8] 13), ([direct_bindable 9] 14), + ([direct_bindable 10] 15))); _for_each_inner_classified_interrupt!((vector([vector 0] 16), ([vector 1] 17), ([vector 2] 18), ([vector 3] 19), ([vector 4] 20), ([vector 5] 21), ([vector 6] 22), ([vector 7] 23), ([vector 8] 24), ([vector 9] 25), ([vector 10] 26), ([vector 11] 27), ([vector 12] 28), ([vector 13] 29), ([vector 14] 30))); _for_each_inner_classified_interrupt!((reserved([reserved 0] 0), ([reserved 1] 3), ([reserved 2] 4), ([reserved 3] 7))); + _for_each_inner_classified_interrupt!((context_switch([context_switch 0] 1))); }; } #[macro_export] @@ -1318,6 +1420,7 @@ macro_rules! for_each_sw_interrupt { /// /// // XTAL32K_CLK /// +/// #[cfg(use_xtal32k)] /// fn enable_xtal32k_clk_impl(_clocks: &mut ClockTree, _en: bool) { /// todo!() /// } @@ -1576,6 +1679,32 @@ macro_rules! for_each_sw_interrupt { /// todo!() /// } /// +/// // BLE_LP_XTAL_CLK +/// +/// fn enable_ble_lp_xtal_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// // BLE_LP_RC_SLOW_CLK +/// +/// fn enable_ble_lp_rc_slow_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// // BLE_LP_CLK +/// +/// fn enable_ble_lp_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_ble_lp_clk_impl( +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: BleLpClkConfig, +/// ) { +/// todo!() +/// } +/// /// // TIMG_CALIBRATION_CLOCK /// /// fn enable_timg_calibration_clock_impl(_clocks: &mut ClockTree, _en: bool) { @@ -1590,6 +1719,22 @@ macro_rules! for_each_sw_interrupt { /// todo!() /// } /// +/// impl AdcInstance { +/// // ADC_FUNCTION_CLOCK +/// +/// fn enable_function_clock_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_function_clock_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: AdcFunctionClockConfig, +/// ) { +/// todo!() +/// } +/// } /// impl SdmInstance { /// // SDM_FUNCTION_CLOCK /// @@ -1613,6 +1758,52 @@ macro_rules! for_each_sw_interrupt { /// todo!() /// } /// } +/// impl I2sInstance { +/// // I2S_TX_CLK +/// +/// fn enable_tx_clk_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_tx_clk_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: I2sClkConfig, +/// ) { +/// todo!() +/// } +/// +/// // I2S_RX_CLK +/// +/// fn enable_rx_clk_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_rx_clk_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: I2sClkConfig, +/// ) { +/// todo!() +/// } +/// +/// // I2S_MCLK_OUT +/// +/// fn enable_mclk_out_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_mclk_out_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: I2sMclkOutConfig, +/// ) { +/// todo!() +/// } +/// } /// impl McpwmInstance { /// // MCPWM_FUNCTION_CLOCK /// @@ -1639,8 +1830,8 @@ macro_rules! for_each_sw_interrupt { /// fn configure_rx_clock_impl( /// self, /// _clocks: &mut ClockTree, -/// _old_config: Option, -/// _new_config: ParlIoRxClockConfig, +/// _old_config: Option, +/// _new_config: ParlIoClkConfig, /// ) { /// todo!() /// } @@ -1654,8 +1845,8 @@ macro_rules! for_each_sw_interrupt { /// fn configure_tx_clock_impl( /// self, /// _clocks: &mut ClockTree, -/// _old_config: Option, -/// _new_config: ParlIoTxClockConfig, +/// _old_config: Option, +/// _new_config: ParlIoClkConfig, /// ) { /// todo!() /// } @@ -1754,9 +1945,30 @@ macro_rules! for_each_sw_interrupt { /// todo!() /// } /// } +/// impl TsensInstance { +/// // TSENS_SCLK +/// +/// fn enable_sclk_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_sclk_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: TsensSclkConfig, +/// ) { +/// todo!() +/// } +/// } /// ``` macro_rules! define_clock_tree_types { () => { + #[derive(Clone, Copy, PartialEq, Eq, Debug)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum AdcInstance { + ApbSaradc = 0, + } #[derive(Clone, Copy, PartialEq, Eq, Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum SdmInstance { @@ -1769,6 +1981,11 @@ macro_rules! define_clock_tree_types { } #[derive(Clone, Copy, PartialEq, Eq, Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum I2sInstance { + I2s0 = 0, + } + #[derive(Clone, Copy, PartialEq, Eq, Debug)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum McpwmInstance { Mcpwm0 = 0, } @@ -1799,6 +2016,11 @@ macro_rules! define_clock_tree_types { Uart0 = 0, Uart1 = 1, } + #[derive(Clone, Copy, PartialEq, Eq, Debug)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum TsensInstance { + Tsens = 0, + } /// Selects the output frequency of `XTAL_CLK`. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] @@ -1844,7 +2066,7 @@ macro_rules! define_clock_tree_types { pub const fn new(divisor: HpRootClkDivisor) -> Self { Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -1920,7 +2142,7 @@ macro_rules! define_clock_tree_types { pub const fn new(divisor: CpuHsDivDivisor) -> Self { Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -1967,7 +2189,7 @@ macro_rules! define_clock_tree_types { pub const fn new(divisor: CpuLsDivDivisor) -> Self { Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -2005,7 +2227,7 @@ macro_rules! define_clock_tree_types { pub const fn new(divisor: AhbHsDivDivisor) -> Self { Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -2052,7 +2274,7 @@ macro_rules! define_clock_tree_types { pub const fn new(divisor: AhbLsDivDivisor) -> Self { Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -2090,7 +2312,7 @@ macro_rules! define_clock_tree_types { pub const fn new(divisor: ApbClkDivisor) -> Self { Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -2128,7 +2350,7 @@ macro_rules! define_clock_tree_types { pub const fn new(divisor: MspiFastHsClkDivisor) -> Self { Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -2166,7 +2388,7 @@ macro_rules! define_clock_tree_types { pub const fn new(divisor: MspiFastLsClkDivisor) -> Self { Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -2206,6 +2428,7 @@ macro_rules! define_clock_tree_types { #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum LpSlowClkConfig { + #[cfg(use_xtal32k)] /// Selects `XTAL32K_CLK`. Xtal32k, /// Selects `RC_SLOW_CLK`. @@ -2213,6 +2436,18 @@ macro_rules! define_clock_tree_types { /// Selects `OSC_SLOW_CLK`. OscSlow, } + /// The list of clock signals that the `BLE_LP_CLK` multiplexer can output. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum BleLpClkConfig { + /// Selects `BLE_LP_XTAL_CLK`. + Xtal, + /// Selects `BLE_LP_RC_SLOW_CLK`. + RcSlow, + #[cfg(use_xtal32k)] + /// Selects `XTAL32K_CLK`. + Xtal32k, + } /// The list of clock signals that the `TIMG_CALIBRATION_CLOCK` multiplexer can output. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] @@ -2221,9 +2456,22 @@ macro_rules! define_clock_tree_types { RcSlowClk, /// Selects `RC_FAST_CLK`. RcFastDivClk, + #[cfg(use_xtal32k)] /// Selects `XTAL32K_CLK`. Xtal32kClk, } + /// The list of clock signals that the `APB_SARADC_FUNCTION_CLOCK` multiplexer can output. + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum AdcFunctionClockConfig { + /// Selects `XTAL_CLK`. + Xtal, + #[default] + /// Selects `PLL_F80M`. + PllF80m, + /// Selects `RC_FAST_CLK`. + RcFast, + } #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum I2cFunctionClockSclk { @@ -2256,12 +2504,90 @@ macro_rules! define_clock_tree_types { ); Self { sclk, div_num } } - pub(crate) fn sclk(self) -> I2cFunctionClockSclk { + pub fn sclk(self) -> I2cFunctionClockSclk { + self.sclk + } + pub fn div_num(self) -> u32 { + self.div_num as u32 + } + } + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum I2sClkSclk { + /// Selects `XTAL_CLK`. + Xtal, + /// Selects `PLL_F240M`. + PllF240m, + #[default] + /// Selects `PLL_F160M`. + PllF160m, + } + /// Configures the `I2S0_TX_CLK` clock node. + /// + /// The output is calculated as `OUTPUT = (sclk * div_a) / (div_num * div_a + div_b)`. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub struct I2sClkConfig { + sclk: I2sClkSclk, + div_num: u32, + div_a: u32, + div_b: u32, + } + impl I2sClkConfig { + /// Creates a new configuration for the TX_CLK clock node. + /// + /// ## Panics + /// + /// Panics if the div_num value is outside the + /// valid range (1 ..= 255). + /// + /// Panics if the div_a value is outside the + /// valid range (1 ..= 511). + /// + /// Panics if the div_b value is outside the + /// valid range (0 ..= 511). + pub const fn new(sclk: I2sClkSclk, div_num: u32, div_a: u32, div_b: u32) -> Self { + ::core::assert!( + div_num >= 1 && div_num <= 255, + "`I2S0_TX_CLK` div_num must be between 1 and 255 (inclusive)." + ); + ::core::assert!( + div_a >= 1 && div_a <= 511, + "`I2S0_TX_CLK` div_a must be between 1 and 511 (inclusive)." + ); + ::core::assert!( + div_b <= 511, + "`I2S0_TX_CLK` div_b must be between 0 and 511 (inclusive)." + ); + Self { + sclk, + div_num, + div_a, + div_b, + } + } + pub fn sclk(self) -> I2sClkSclk { self.sclk } - pub(crate) fn div_num(self) -> u32 { + pub fn div_num(self) -> u32 { self.div_num as u32 } + pub fn div_a(self) -> u32 { + self.div_a as u32 + } + pub fn div_b(self) -> u32 { + self.div_b as u32 + } + } + /// The list of clock signals that the `I2S0_MCLK_OUT` multiplexer can output. + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum I2sMclkOutConfig { + /// Selects `TX_CLK`. + Tx, + #[default] + /// Selects `RX_CLK`. + Rx, } /// The list of clock signals that the `MCPWM0_FUNCTION_CLOCK` multiplexer can output. #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] @@ -2278,19 +2604,7 @@ macro_rules! define_clock_tree_types { /// The list of clock signals that the `PARL_IO_RX_CLOCK` multiplexer can output. #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] - pub enum ParlIoRxClockConfig { - /// Selects `XTAL_CLK`. - XtalClk, - /// Selects `RC_FAST_CLK`. - RcFastClk, - #[default] - /// Selects `PLL_F240M`. - PllF240m, - } - /// The list of clock signals that the `PARL_IO_TX_CLOCK` multiplexer can output. - #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] - #[cfg_attr(feature = "defmt", derive(defmt::Format))] - pub enum ParlIoTxClockConfig { + pub enum ParlIoClkConfig { /// Selects `XTAL_CLK`. XtalClk, /// Selects `RC_FAST_CLK`. @@ -2315,9 +2629,9 @@ macro_rules! define_clock_tree_types { #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum SpiFunctionClockConfig { + #[default] /// Selects `PLL_F80M`. PllF80m, - #[default] /// Selects `XTAL_CLK`. Xtal, /// Selects `RC_FAST_CLK`. @@ -2381,10 +2695,10 @@ macro_rules! define_clock_tree_types { ); Self { sclk, div_num } } - pub(crate) fn sclk(self) -> UartFunctionClockSclk { + pub fn sclk(self) -> UartFunctionClockSclk { self.sclk } - pub(crate) fn div_num(self) -> u32 { + pub fn div_num(self) -> u32 { self.div_num as u32 } } @@ -2422,13 +2736,23 @@ macro_rules! define_clock_tree_types { integral, } } - pub(crate) fn fractional(self) -> u32 { + pub fn fractional(self) -> u32 { self.fractional as u32 } - pub(crate) fn integral(self) -> u32 { + pub fn integral(self) -> u32 { self.integral as u32 } } + /// The list of clock signals that the `TSENS_SCLK` multiplexer can output. + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum TsensSclkConfig { + /// Selects `RC_FAST_CLK`. + RcFast, + #[default] + /// Selects `XTAL_CLK`. + Xtal, + } /// Represents the device's clock tree. pub struct ClockTree { xtal_clk: Option, @@ -2448,31 +2772,45 @@ macro_rules! define_clock_tree_types { ledc_sclk: Option, lp_fast_clk: Option, lp_slow_clk: Option, + ble_lp_clk: Option, timg_calibration_clock: Option, + adc_function_clock: [Option; 1], i2c_function_clock: [Option; 1], + i2s_tx_clk: [Option; 1], + i2s_rx_clk: [Option; 1], + i2s_mclk_out: [Option; 1], mcpwm_function_clock: [Option; 1], - parl_io_rx_clock: [Option; 1], - parl_io_tx_clock: [Option; 1], + parl_io_rx_clock: [Option; 1], + parl_io_tx_clock: [Option; 1], rmt_sclk: [Option; 1], spi_function_clock: [Option; 1], timg_function_clock: [Option; 2], timg_wdt_clock: [Option; 2], uart_function_clock: [Option; 2], uart_baud_rate_generator: [Option; 2], + tsens_sclk: [Option; 1], pll_clk_refcount: u32, rc_fast_clk_refcount: u32, + #[cfg(use_xtal32k)] xtal32k_clk_refcount: u32, + rc_slow_clk_refcount: u32, hp_root_clk_refcount: u32, mspi_fast_clk_refcount: u32, apb_clk_refcount: u32, pll_f48m_refcount: u32, pll_f80m_refcount: u32, + pll_f160m_refcount: u32, pll_f240m_refcount: u32, ledc_sclk_refcount: u32, lp_fast_clk_refcount: u32, + ble_lp_clk_refcount: u32, timg_calibration_clock_refcount: u32, + adc_function_clock_refcount: [u32; 1], sdm_function_clock_refcount: [u32; 1], i2c_function_clock_refcount: [u32; 1], + i2s_tx_clk_refcount: [u32; 1], + i2s_rx_clk_refcount: [u32; 1], + i2s_mclk_out_refcount: [u32; 1], mcpwm_function_clock_refcount: [u32; 1], parl_io_rx_clock_refcount: [u32; 1], parl_io_tx_clock_refcount: [u32; 1], @@ -2482,6 +2820,7 @@ macro_rules! define_clock_tree_types { timg_wdt_clock_refcount: [u32; 2], uart_function_clock_refcount: [u32; 2], uart_baud_rate_generator_refcount: [u32; 2], + tsens_sclk_refcount: [u32; 1], } impl ClockTree { /// Locks the clock tree for exclusive access. @@ -2556,24 +2895,44 @@ macro_rules! define_clock_tree_types { pub fn lp_slow_clk(&self) -> Option { self.lp_slow_clk } + /// Returns the current configuration of the BLE_LP_CLK clock tree node + pub fn ble_lp_clk(&self) -> Option { + self.ble_lp_clk + } /// Returns the current configuration of the TIMG_CALIBRATION_CLOCK clock tree node pub fn timg_calibration_clock(&self) -> Option { self.timg_calibration_clock } + /// Returns the current configuration of the APB_SARADC_FUNCTION_CLOCK clock tree node + pub fn apb_saradc_function_clock(&self) -> Option { + self.adc_function_clock[AdcInstance::ApbSaradc as usize] + } /// Returns the current configuration of the I2C0_FUNCTION_CLOCK clock tree node pub fn i2c0_function_clock(&self) -> Option { self.i2c_function_clock[I2cInstance::I2c0 as usize] } + /// Returns the current configuration of the I2S0_TX_CLK clock tree node + pub fn i2s0_tx_clk(&self) -> Option { + self.i2s_tx_clk[I2sInstance::I2s0 as usize] + } + /// Returns the current configuration of the I2S0_RX_CLK clock tree node + pub fn i2s0_rx_clk(&self) -> Option { + self.i2s_rx_clk[I2sInstance::I2s0 as usize] + } + /// Returns the current configuration of the I2S0_MCLK_OUT clock tree node + pub fn i2s0_mclk_out(&self) -> Option { + self.i2s_mclk_out[I2sInstance::I2s0 as usize] + } /// Returns the current configuration of the MCPWM0_FUNCTION_CLOCK clock tree node pub fn mcpwm0_function_clock(&self) -> Option { self.mcpwm_function_clock[McpwmInstance::Mcpwm0 as usize] } /// Returns the current configuration of the PARL_IO_RX_CLOCK clock tree node - pub fn parl_io_rx_clock(&self) -> Option { + pub fn parl_io_rx_clock(&self) -> Option { self.parl_io_rx_clock[ParlIoInstance::ParlIo as usize] } /// Returns the current configuration of the PARL_IO_TX_CLOCK clock tree node - pub fn parl_io_tx_clock(&self) -> Option { + pub fn parl_io_tx_clock(&self) -> Option { self.parl_io_tx_clock[ParlIoInstance::ParlIo as usize] } /// Returns the current configuration of the RMT_SCLK clock tree node @@ -2616,6 +2975,10 @@ macro_rules! define_clock_tree_types { pub fn uart1_baud_rate_generator(&self) -> Option { self.uart_baud_rate_generator[UartInstance::Uart1 as usize] } + /// Returns the current configuration of the TSENS_SCLK clock tree node + pub fn tsens_sclk(&self) -> Option { + self.tsens_sclk[TsensInstance::Tsens as usize] + } } static CLOCK_TREE: ::esp_sync::NonReentrantMutex = ::esp_sync::NonReentrantMutex::new(ClockTree { @@ -2636,8 +2999,13 @@ macro_rules! define_clock_tree_types { ledc_sclk: None, lp_fast_clk: None, lp_slow_clk: None, + ble_lp_clk: None, timg_calibration_clock: None, + adc_function_clock: [None; 1], i2c_function_clock: [None; 1], + i2s_tx_clk: [None; 1], + i2s_rx_clk: [None; 1], + i2s_mclk_out: [None; 1], mcpwm_function_clock: [None; 1], parl_io_rx_clock: [None; 1], parl_io_tx_clock: [None; 1], @@ -2647,20 +3015,29 @@ macro_rules! define_clock_tree_types { timg_wdt_clock: [None; 2], uart_function_clock: [None; 2], uart_baud_rate_generator: [None; 2], + tsens_sclk: [None; 1], pll_clk_refcount: 0, rc_fast_clk_refcount: 0, + #[cfg(use_xtal32k)] xtal32k_clk_refcount: 0, + rc_slow_clk_refcount: 0, hp_root_clk_refcount: 0, mspi_fast_clk_refcount: 0, apb_clk_refcount: 0, pll_f48m_refcount: 0, pll_f80m_refcount: 0, + pll_f160m_refcount: 0, pll_f240m_refcount: 0, ledc_sclk_refcount: 0, lp_fast_clk_refcount: 0, + ble_lp_clk_refcount: 0, timg_calibration_clock_refcount: 0, + adc_function_clock_refcount: [0; 1], sdm_function_clock_refcount: [0; 1], i2c_function_clock_refcount: [0; 1], + i2s_tx_clk_refcount: [0; 1], + i2s_rx_clk_refcount: [0; 1], + i2s_mclk_out_refcount: [0; 1], mcpwm_function_clock_refcount: [0; 1], parl_io_rx_clock_refcount: [0; 1], parl_io_tx_clock_refcount: [0; 1], @@ -2670,6 +3047,7 @@ macro_rules! define_clock_tree_types { timg_wdt_clock_refcount: [0; 2], uart_function_clock_refcount: [0; 2], uart_baud_rate_generator_refcount: [0; 2], + tsens_sclk_refcount: [0; 1], }); static XTAL_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); @@ -2683,10 +3061,20 @@ macro_rules! define_clock_tree_types { ::core::sync::atomic::AtomicU32::new(0); static LP_SLOW_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); + static BLE_LP_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(0); static TIMG_CALIBRATION_CLOCK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); + static ADC_FUNCTION_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; static I2C_FUNCTION_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; + static I2S_TX_CLK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; + static I2S_RX_CLK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; + static I2S_MCLK_OUT_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; static MCPWM_FUNCTION_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; static PARL_IO_RX_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = @@ -2705,6 +3093,8 @@ macro_rules! define_clock_tree_types { [const { ::core::sync::atomic::AtomicU32::new(0) }; 2]; static UART_BAUD_RATE_GENERATOR_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 2] = [const { ::core::sync::atomic::AtomicU32::new(0) }; 2]; + static TSENS_SCLK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; static HP_ROOT_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); static CPU_HS_DIV_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = @@ -2727,38 +3117,230 @@ macro_rules! define_clock_tree_types { ::core::sync::atomic::AtomicU32::new(0); static APB_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); - pub fn configure_xtal_clk(clocks: &mut ClockTree, config: XtalClkConfig) { - let old_config = clocks.xtal_clk.replace(config); - refresh_xtal_clk_downstream(clocks); - configure_xtal_clk_impl(clocks, old_config, config); + /// The clock sources of the device. + /// + /// A clock source is a node of the clock tree that other nodes derive their output + /// from. Ask a node which source it runs on with its `..._root_source` function. + #[derive(Debug, enumset::EnumSetType)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum ClockSource { + /// `XTAL_CLK`. + XtalClk, + /// `RC_FAST_CLK`. + RcFastClk, + #[cfg(use_xtal32k)] + /// `XTAL32K_CLK`. + Xtal32kClk, + /// `OSC_SLOW_CLK`. + OscSlowClk, + /// `RC_SLOW_CLK`. + RcSlowClk, } - pub fn xtal_clk_config(clocks: &mut ClockTree) -> Option { - clocks.xtal_clk + /// Returns the clock source that `XTAL_CLK` currently runs on. + pub fn xtal_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::XtalClk) } - fn request_xtal_clk(_clocks: &mut ClockTree) {} - fn release_xtal_clk(_clocks: &mut ClockTree) {} - #[allow(unused_variables)] - pub fn xtal_clk_config_frequency(clocks: &mut ClockTree, config: XtalClkConfig) -> u32 { - config.value() + /// Returns the clock source that `PLL_CLK` currently runs on. + pub fn pll_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) } - pub fn xtal_clk_frequency() -> u32 { - XTAL_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) + /// Returns the clock source that `RC_FAST_CLK` currently runs on. + pub fn rc_fast_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::RcFastClk) } - pub fn request_pll_clk(clocks: &mut ClockTree) { - trace!("Requesting PLL_CLK"); - if increment_reference_count(&mut clocks.pll_clk_refcount) { - trace!("Enabling PLL_CLK"); - request_xtal_clk(clocks); - enable_pll_clk_impl(clocks, true); - } + #[cfg(use_xtal32k)] + /// Returns the clock source that `XTAL32K_CLK` currently runs on. + pub fn xtal32k_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::Xtal32kClk) } - pub fn release_pll_clk(clocks: &mut ClockTree) { - trace!("Releasing PLL_CLK"); - if decrement_reference_count(&mut clocks.pll_clk_refcount) { - trace!("Disabling PLL_CLK"); - enable_pll_clk_impl(clocks, false); - release_xtal_clk(clocks); - } + /// Returns the clock source that `OSC_SLOW_CLK` currently runs on. + pub fn osc_slow_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::OscSlowClk) + } + /// Returns the clock source that `RC_SLOW_CLK` currently runs on. + pub fn rc_slow_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::RcSlowClk) + } + /// Returns the clock source that `SOC_ROOT_CLK` currently runs on. + pub fn soc_root_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.soc_root_clk?; + match config { + SocRootClkConfig::Xtal => xtal_clk_root_source(clocks), + SocRootClkConfig::RcFast => rc_fast_clk_root_source(clocks), + SocRootClkConfig::Pll => pll_clk_root_source(clocks), + } + } + /// Returns the clock source that `PLL_F48M` currently runs on. + pub fn pll_f48m_root_source(clocks: &mut ClockTree) -> Option { + pll_clk_root_source(clocks) + } + /// Returns the clock source that `PLL_F80M` currently runs on. + pub fn pll_f80m_root_source(clocks: &mut ClockTree) -> Option { + pll_clk_root_source(clocks) + } + /// Returns the clock source that `PLL_F160M` currently runs on. + pub fn pll_f160m_root_source(clocks: &mut ClockTree) -> Option { + pll_clk_root_source(clocks) + } + /// Returns the clock source that `PLL_F240M` currently runs on. + pub fn pll_f240m_root_source(clocks: &mut ClockTree) -> Option { + pll_clk_root_source(clocks) + } + /// Returns the clock source that `IOMUX_FUNCTION_CLOCK` currently runs on. + pub fn iomux_function_clock_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.iomux_function_clock?; + match config { + IomuxFunctionClockConfig::PllF80m => pll_f80m_root_source(clocks), + IomuxFunctionClockConfig::RcFastClk => rc_fast_clk_root_source(clocks), + IomuxFunctionClockConfig::XtalClk => xtal_clk_root_source(clocks), + } + } + /// Returns the clock source that `LEDC_SCLK` currently runs on. + pub fn ledc_sclk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.ledc_sclk?; + match config { + LedcSclkConfig::PllF80m => pll_f80m_root_source(clocks), + LedcSclkConfig::RcFastClk => rc_fast_clk_root_source(clocks), + LedcSclkConfig::XtalClk => xtal_clk_root_source(clocks), + } + } + /// Returns the clock source that `XTAL_D2_CLK` currently runs on. + pub fn xtal_d2_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `LP_FAST_CLK` currently runs on. + pub fn lp_fast_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.lp_fast_clk?; + match config { + LpFastClkConfig::RcFastClk => rc_fast_clk_root_source(clocks), + LpFastClkConfig::XtalD2Clk => xtal_d2_clk_root_source(clocks), + } + } + /// Returns the clock source that `LP_SLOW_CLK` currently runs on. + pub fn lp_slow_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.lp_slow_clk?; + match config { + #[cfg(use_xtal32k)] + LpSlowClkConfig::Xtal32k => xtal32k_clk_root_source(clocks), + LpSlowClkConfig::RcSlow => rc_slow_clk_root_source(clocks), + LpSlowClkConfig::OscSlow => osc_slow_clk_root_source(clocks), + } + } + /// Returns the clock source that `BLE_LP_XTAL_CLK` currently runs on. + pub fn ble_lp_xtal_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `BLE_LP_RC_SLOW_CLK` currently runs on. + pub fn ble_lp_rc_slow_clk_root_source(clocks: &mut ClockTree) -> Option { + rc_slow_clk_root_source(clocks) + } + /// Returns the clock source that `BLE_LP_CLK` currently runs on. + pub fn ble_lp_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.ble_lp_clk?; + match config { + BleLpClkConfig::Xtal => ble_lp_xtal_clk_root_source(clocks), + BleLpClkConfig::RcSlow => ble_lp_rc_slow_clk_root_source(clocks), + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => xtal32k_clk_root_source(clocks), + } + } + /// Returns the clock source that `TIMG_CALIBRATION_CLOCK` currently runs on. + pub fn timg_calibration_clock_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.timg_calibration_clock?; + match config { + TimgCalibrationClockConfig::RcSlowClk => lp_slow_clk_root_source(clocks), + TimgCalibrationClockConfig::RcFastDivClk => rc_fast_clk_root_source(clocks), + #[cfg(use_xtal32k)] + TimgCalibrationClockConfig::Xtal32kClk => xtal32k_clk_root_source(clocks), + } + } + /// Returns the clock source that `HP_ROOT_CLK` currently runs on. + pub fn hp_root_clk_root_source(clocks: &mut ClockTree) -> Option { + soc_root_clk_root_source(clocks) + } + /// Returns the clock source that `CPU_HS_DIV` currently runs on. + pub fn cpu_hs_div_root_source(clocks: &mut ClockTree) -> Option { + hp_root_clk_root_source(clocks) + } + /// Returns the clock source that `CPU_LS_DIV` currently runs on. + pub fn cpu_ls_div_root_source(clocks: &mut ClockTree) -> Option { + hp_root_clk_root_source(clocks) + } + /// Returns the clock source that `AHB_HS_DIV` currently runs on. + pub fn ahb_hs_div_root_source(clocks: &mut ClockTree) -> Option { + hp_root_clk_root_source(clocks) + } + /// Returns the clock source that `AHB_LS_DIV` currently runs on. + pub fn ahb_ls_div_root_source(clocks: &mut ClockTree) -> Option { + hp_root_clk_root_source(clocks) + } + /// Returns the clock source that `MSPI_FAST_HS_CLK` currently runs on. + pub fn mspi_fast_hs_clk_root_source(clocks: &mut ClockTree) -> Option { + hp_root_clk_root_source(clocks) + } + /// Returns the clock source that `MSPI_FAST_LS_CLK` currently runs on. + pub fn mspi_fast_ls_clk_root_source(clocks: &mut ClockTree) -> Option { + hp_root_clk_root_source(clocks) + } + /// Returns the clock source that `CPU_CLK` currently runs on. + pub fn cpu_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.cpu_clk?; + match config { + CpuClkConfig::Hs => cpu_hs_div_root_source(clocks), + CpuClkConfig::Ls => cpu_ls_div_root_source(clocks), + } + } + /// Returns the clock source that `AHB_CLK` currently runs on. + pub fn ahb_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.ahb_clk?; + match config { + AhbClkConfig::Hs => ahb_hs_div_root_source(clocks), + AhbClkConfig::Ls => ahb_ls_div_root_source(clocks), + } + } + /// Returns the clock source that `MSPI_FAST_CLK` currently runs on. + pub fn mspi_fast_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.mspi_fast_clk?; + match config { + MspiFastClkConfig::Hs => mspi_fast_hs_clk_root_source(clocks), + MspiFastClkConfig::Ls => mspi_fast_ls_clk_root_source(clocks), + } + } + /// Returns the clock source that `APB_CLK` currently runs on. + pub fn apb_clk_root_source(clocks: &mut ClockTree) -> Option { + ahb_clk_root_source(clocks) + } + pub fn configure_xtal_clk(clocks: &mut ClockTree, config: XtalClkConfig) { + let old_config = clocks.xtal_clk.replace(config); + refresh_xtal_clk_downstream(clocks); + configure_xtal_clk_impl(clocks, old_config, config); + } + pub fn xtal_clk_config(clocks: &mut ClockTree) -> Option { + clocks.xtal_clk + } + fn request_xtal_clk(_clocks: &mut ClockTree) {} + fn release_xtal_clk(_clocks: &mut ClockTree) {} + pub fn xtal_clk_config_frequency(config: XtalClkConfig) -> u32 { + config.value() + } + pub fn xtal_clk_frequency() -> u32 { + XTAL_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn request_pll_clk(clocks: &mut ClockTree) { + trace!("Requesting PLL_CLK"); + if increment_reference_count(&mut clocks.pll_clk_refcount) { + trace!("Enabling PLL_CLK"); + request_xtal_clk(clocks); + enable_pll_clk_impl(clocks, true); + } + } + pub fn release_pll_clk(clocks: &mut ClockTree) { + trace!("Releasing PLL_CLK"); + if decrement_reference_count(&mut clocks.pll_clk_refcount) { + trace!("Disabling PLL_CLK"); + enable_pll_clk_impl(clocks, false); + release_xtal_clk(clocks); + } } pub fn pll_clk_frequency() -> u32 { 480000000 @@ -2780,9 +3362,31 @@ macro_rules! define_clock_tree_types { enable_rc_fast_clk_impl(clocks, false); } } - pub fn rc_fast_clk_frequency() -> u32 { + static RC_FAST_CLK_FREQUENCY: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(rc_fast_clk_nominal_frequency()); + pub const fn rc_fast_clk_nominal_frequency() -> u32 { 17500000 } + pub fn rc_fast_clk_frequency() -> u32 { + RC_FAST_CLK_FREQUENCY.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn set_rc_fast_clk_frequency(clocks: &mut ClockTree, frequency: u32) { + if !(8750000..=26250000).contains(&frequency) { + warn!( + "Ignoring out-of-range RC_FAST_CLK frequency: {} Hz", + frequency + ); + return; + } + debug!( + "Updating RC_FAST_CLK frequency to {} Hz (nominal {} Hz)", + frequency, + rc_fast_clk_nominal_frequency() + ); + RC_FAST_CLK_FREQUENCY.store(frequency, ::core::sync::atomic::Ordering::Release); + refresh_rc_fast_clk_downstream(clocks); + } + #[cfg(use_xtal32k)] pub fn request_xtal32k_clk(clocks: &mut ClockTree) { trace!("Requesting XTAL32K_CLK"); if increment_reference_count(&mut clocks.xtal32k_clk_refcount) { @@ -2790,6 +3394,7 @@ macro_rules! define_clock_tree_types { enable_xtal32k_clk_impl(clocks, true); } } + #[cfg(use_xtal32k)] pub fn release_xtal32k_clk(clocks: &mut ClockTree) { trace!("Releasing XTAL32K_CLK"); if decrement_reference_count(&mut clocks.xtal32k_clk_refcount) { @@ -2797,16 +3402,15 @@ macro_rules! define_clock_tree_types { enable_xtal32k_clk_impl(clocks, false); } } + #[cfg(use_xtal32k)] pub fn xtal32k_clk_frequency() -> u32 { 32768 } pub fn request_osc_slow_clk(clocks: &mut ClockTree) { - trace!("Requesting OSC_SLOW_CLK"); trace!("Enabling OSC_SLOW_CLK"); enable_osc_slow_clk_impl(clocks, true); } pub fn release_osc_slow_clk(clocks: &mut ClockTree) { - trace!("Releasing OSC_SLOW_CLK"); trace!("Disabling OSC_SLOW_CLK"); enable_osc_slow_clk_impl(clocks, false); } @@ -2815,17 +3419,42 @@ macro_rules! define_clock_tree_types { } pub fn request_rc_slow_clk(clocks: &mut ClockTree) { trace!("Requesting RC_SLOW_CLK"); - trace!("Enabling RC_SLOW_CLK"); - enable_rc_slow_clk_impl(clocks, true); + if increment_reference_count(&mut clocks.rc_slow_clk_refcount) { + trace!("Enabling RC_SLOW_CLK"); + enable_rc_slow_clk_impl(clocks, true); + } } pub fn release_rc_slow_clk(clocks: &mut ClockTree) { trace!("Releasing RC_SLOW_CLK"); - trace!("Disabling RC_SLOW_CLK"); - enable_rc_slow_clk_impl(clocks, false); + if decrement_reference_count(&mut clocks.rc_slow_clk_refcount) { + trace!("Disabling RC_SLOW_CLK"); + enable_rc_slow_clk_impl(clocks, false); + } } - pub fn rc_slow_clk_frequency() -> u32 { + static RC_SLOW_CLK_FREQUENCY: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(rc_slow_clk_nominal_frequency()); + pub const fn rc_slow_clk_nominal_frequency() -> u32 { 136000 } + pub fn rc_slow_clk_frequency() -> u32 { + RC_SLOW_CLK_FREQUENCY.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn set_rc_slow_clk_frequency(clocks: &mut ClockTree, frequency: u32) { + if !(68000..=204000).contains(&frequency) { + warn!( + "Ignoring out-of-range RC_SLOW_CLK frequency: {} Hz", + frequency + ); + return; + } + debug!( + "Updating RC_SLOW_CLK frequency to {} Hz (nominal {} Hz)", + frequency, + rc_slow_clk_nominal_frequency() + ); + RC_SLOW_CLK_FREQUENCY.store(frequency, ::core::sync::atomic::Ordering::Release); + refresh_rc_slow_clk_downstream(clocks); + } pub fn configure_hp_root_clk(clocks: &mut ClockTree, config: HpRootClkConfig) { let old_config = clocks.hp_root_clk.replace(config); refresh_hp_root_clk_downstream(clocks); @@ -2850,11 +3479,7 @@ macro_rules! define_clock_tree_types { release_soc_root_clk(clocks); } } - #[allow(unused_variables)] - pub fn hp_root_clk_config_frequency( - clocks: &mut ClockTree, - config: HpRootClkConfig, - ) -> u32 { + pub fn hp_root_clk_config_frequency(config: HpRootClkConfig) -> u32 { (soc_root_clk_frequency() / config.divisor()) } pub fn hp_root_clk_frequency() -> u32 { @@ -2883,8 +3508,7 @@ macro_rules! define_clock_tree_types { } fn request_cpu_clk(_clocks: &mut ClockTree) {} fn release_cpu_clk(_clocks: &mut ClockTree) {} - #[allow(unused_variables)] - pub fn cpu_clk_config_frequency(clocks: &mut ClockTree, config: CpuClkConfig) -> u32 { + pub fn cpu_clk_config_frequency(config: CpuClkConfig) -> u32 { match config { CpuClkConfig::Hs => cpu_hs_div_frequency(), CpuClkConfig::Ls => cpu_ls_div_frequency(), @@ -2894,10 +3518,7 @@ macro_rules! define_clock_tree_types { CPU_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn cpu_clk_source_frequency(source: CpuClkConfig) -> u32 { - match source { - CpuClkConfig::Hs => cpu_hs_div_frequency(), - CpuClkConfig::Ls => cpu_ls_div_frequency(), - } + cpu_clk_config_frequency(source) } pub fn configure_ahb_clk(clocks: &mut ClockTree, new_selector: AhbClkConfig) { let old_selector = clocks.ahb_clk.replace(new_selector); @@ -2919,8 +3540,7 @@ macro_rules! define_clock_tree_types { } fn request_ahb_clk(_clocks: &mut ClockTree) {} fn release_ahb_clk(_clocks: &mut ClockTree) {} - #[allow(unused_variables)] - pub fn ahb_clk_config_frequency(clocks: &mut ClockTree, config: AhbClkConfig) -> u32 { + pub fn ahb_clk_config_frequency(config: AhbClkConfig) -> u32 { match config { AhbClkConfig::Hs => ahb_hs_div_frequency(), AhbClkConfig::Ls => ahb_ls_div_frequency(), @@ -2930,28 +3550,24 @@ macro_rules! define_clock_tree_types { AHB_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn ahb_clk_source_frequency(source: AhbClkConfig) -> u32 { - match source { - AhbClkConfig::Hs => ahb_hs_div_frequency(), - AhbClkConfig::Ls => ahb_ls_div_frequency(), - } + ahb_clk_config_frequency(source) } pub fn configure_mspi_fast_clk(clocks: &mut ClockTree, new_selector: MspiFastClkConfig) { let old_selector = clocks.mspi_fast_clk.replace(new_selector); refresh_mspi_fast_clk_downstream(clocks); - if clocks.mspi_fast_clk_refcount > 0 { + let active = clocks.mspi_fast_clk_refcount > 0; + if active { match new_selector { MspiFastClkConfig::Hs => request_mspi_fast_hs_clk(clocks), MspiFastClkConfig::Ls => request_mspi_fast_ls_clk(clocks), } - configure_mspi_fast_clk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - MspiFastClkConfig::Hs => release_mspi_fast_hs_clk(clocks), - MspiFastClkConfig::Ls => release_mspi_fast_ls_clk(clocks), - } + } + configure_mspi_fast_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + MspiFastClkConfig::Hs => release_mspi_fast_hs_clk(clocks), + MspiFastClkConfig::Ls => release_mspi_fast_ls_clk(clocks), } - } else { - configure_mspi_fast_clk_impl(clocks, old_selector, new_selector); } } pub fn mspi_fast_clk_config(clocks: &mut ClockTree) -> Option { @@ -2979,11 +3595,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn mspi_fast_clk_config_frequency( - clocks: &mut ClockTree, - config: MspiFastClkConfig, - ) -> u32 { + pub fn mspi_fast_clk_config_frequency(config: MspiFastClkConfig) -> u32 { match config { MspiFastClkConfig::Hs => mspi_fast_hs_clk_frequency(), MspiFastClkConfig::Ls => mspi_fast_ls_clk_frequency(), @@ -2993,10 +3605,7 @@ macro_rules! define_clock_tree_types { MSPI_FAST_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn mspi_fast_clk_source_frequency(source: MspiFastClkConfig) -> u32 { - match source { - MspiFastClkConfig::Hs => mspi_fast_hs_clk_frequency(), - MspiFastClkConfig::Ls => mspi_fast_ls_clk_frequency(), - } + mspi_fast_clk_config_frequency(source) } pub fn configure_soc_root_clk(clocks: &mut ClockTree, new_selector: SocRootClkConfig) { let old_selector = clocks.soc_root_clk.replace(new_selector); @@ -3042,7 +3651,6 @@ macro_rules! define_clock_tree_types { clocks.soc_root_clk } pub fn request_soc_root_clk(clocks: &mut ClockTree) { - trace!("Requesting SOC_ROOT_CLK"); trace!("Enabling SOC_ROOT_CLK"); match unwrap!(clocks.soc_root_clk) { SocRootClkConfig::Xtal => request_xtal_clk(clocks), @@ -3052,7 +3660,6 @@ macro_rules! define_clock_tree_types { enable_soc_root_clk_impl(clocks, true); } pub fn release_soc_root_clk(clocks: &mut ClockTree) { - trace!("Releasing SOC_ROOT_CLK"); trace!("Disabling SOC_ROOT_CLK"); enable_soc_root_clk_impl(clocks, false); match unwrap!(clocks.soc_root_clk) { @@ -3061,11 +3668,7 @@ macro_rules! define_clock_tree_types { SocRootClkConfig::Pll => release_pll_clk(clocks), } } - #[allow(unused_variables)] - pub fn soc_root_clk_config_frequency( - clocks: &mut ClockTree, - config: SocRootClkConfig, - ) -> u32 { + pub fn soc_root_clk_config_frequency(config: SocRootClkConfig) -> u32 { match config { SocRootClkConfig::Xtal => xtal_clk_frequency(), SocRootClkConfig::RcFast => rc_fast_clk_frequency(), @@ -3084,19 +3687,16 @@ macro_rules! define_clock_tree_types { clocks.cpu_hs_div } pub fn request_cpu_hs_div(clocks: &mut ClockTree) { - trace!("Requesting CPU_HS_DIV"); trace!("Enabling CPU_HS_DIV"); request_hp_root_clk(clocks); enable_cpu_hs_div_impl(clocks, true); } pub fn release_cpu_hs_div(clocks: &mut ClockTree) { - trace!("Releasing CPU_HS_DIV"); trace!("Disabling CPU_HS_DIV"); enable_cpu_hs_div_impl(clocks, false); release_hp_root_clk(clocks); } - #[allow(unused_variables)] - pub fn cpu_hs_div_config_frequency(clocks: &mut ClockTree, config: CpuHsDivConfig) -> u32 { + pub fn cpu_hs_div_config_frequency(config: CpuHsDivConfig) -> u32 { (hp_root_clk_frequency() / (config.divisor() + 1)) } pub fn cpu_hs_div_frequency() -> u32 { @@ -3114,19 +3714,16 @@ macro_rules! define_clock_tree_types { clocks.cpu_ls_div } pub fn request_cpu_ls_div(clocks: &mut ClockTree) { - trace!("Requesting CPU_LS_DIV"); trace!("Enabling CPU_LS_DIV"); request_hp_root_clk(clocks); enable_cpu_ls_div_impl(clocks, true); } pub fn release_cpu_ls_div(clocks: &mut ClockTree) { - trace!("Releasing CPU_LS_DIV"); trace!("Disabling CPU_LS_DIV"); enable_cpu_ls_div_impl(clocks, false); release_hp_root_clk(clocks); } - #[allow(unused_variables)] - pub fn cpu_ls_div_config_frequency(clocks: &mut ClockTree, config: CpuLsDivConfig) -> u32 { + pub fn cpu_ls_div_config_frequency(config: CpuLsDivConfig) -> u32 { (hp_root_clk_frequency() / (config.divisor() + 1)) } pub fn cpu_ls_div_frequency() -> u32 { @@ -3144,19 +3741,16 @@ macro_rules! define_clock_tree_types { clocks.ahb_hs_div } pub fn request_ahb_hs_div(clocks: &mut ClockTree) { - trace!("Requesting AHB_HS_DIV"); trace!("Enabling AHB_HS_DIV"); request_hp_root_clk(clocks); enable_ahb_hs_div_impl(clocks, true); } pub fn release_ahb_hs_div(clocks: &mut ClockTree) { - trace!("Releasing AHB_HS_DIV"); trace!("Disabling AHB_HS_DIV"); enable_ahb_hs_div_impl(clocks, false); release_hp_root_clk(clocks); } - #[allow(unused_variables)] - pub fn ahb_hs_div_config_frequency(clocks: &mut ClockTree, config: AhbHsDivConfig) -> u32 { + pub fn ahb_hs_div_config_frequency(config: AhbHsDivConfig) -> u32 { (hp_root_clk_frequency() / (config.divisor() + 1)) } pub fn ahb_hs_div_frequency() -> u32 { @@ -3174,19 +3768,16 @@ macro_rules! define_clock_tree_types { clocks.ahb_ls_div } pub fn request_ahb_ls_div(clocks: &mut ClockTree) { - trace!("Requesting AHB_LS_DIV"); trace!("Enabling AHB_LS_DIV"); request_hp_root_clk(clocks); enable_ahb_ls_div_impl(clocks, true); } pub fn release_ahb_ls_div(clocks: &mut ClockTree) { - trace!("Releasing AHB_LS_DIV"); trace!("Disabling AHB_LS_DIV"); enable_ahb_ls_div_impl(clocks, false); release_hp_root_clk(clocks); } - #[allow(unused_variables)] - pub fn ahb_ls_div_config_frequency(clocks: &mut ClockTree, config: AhbLsDivConfig) -> u32 { + pub fn ahb_ls_div_config_frequency(config: AhbLsDivConfig) -> u32 { (hp_root_clk_frequency() / (config.divisor() + 1)) } pub fn ahb_ls_div_frequency() -> u32 { @@ -3219,8 +3810,7 @@ macro_rules! define_clock_tree_types { release_ahb_clk(clocks); } } - #[allow(unused_variables)] - pub fn apb_clk_config_frequency(clocks: &mut ClockTree, config: ApbClkConfig) -> u32 { + pub fn apb_clk_config_frequency(config: ApbClkConfig) -> u32 { (ahb_clk_frequency() / (config.divisor() + 1)) } pub fn apb_clk_frequency() -> u32 { @@ -3238,22 +3828,16 @@ macro_rules! define_clock_tree_types { clocks.mspi_fast_hs_clk } pub fn request_mspi_fast_hs_clk(clocks: &mut ClockTree) { - trace!("Requesting MSPI_FAST_HS_CLK"); trace!("Enabling MSPI_FAST_HS_CLK"); request_hp_root_clk(clocks); enable_mspi_fast_hs_clk_impl(clocks, true); } pub fn release_mspi_fast_hs_clk(clocks: &mut ClockTree) { - trace!("Releasing MSPI_FAST_HS_CLK"); trace!("Disabling MSPI_FAST_HS_CLK"); enable_mspi_fast_hs_clk_impl(clocks, false); release_hp_root_clk(clocks); } - #[allow(unused_variables)] - pub fn mspi_fast_hs_clk_config_frequency( - clocks: &mut ClockTree, - config: MspiFastHsClkConfig, - ) -> u32 { + pub fn mspi_fast_hs_clk_config_frequency(config: MspiFastHsClkConfig) -> u32 { (hp_root_clk_frequency() / (config.divisor() + 1)) } pub fn mspi_fast_hs_clk_frequency() -> u32 { @@ -3271,22 +3855,16 @@ macro_rules! define_clock_tree_types { clocks.mspi_fast_ls_clk } pub fn request_mspi_fast_ls_clk(clocks: &mut ClockTree) { - trace!("Requesting MSPI_FAST_LS_CLK"); trace!("Enabling MSPI_FAST_LS_CLK"); request_hp_root_clk(clocks); enable_mspi_fast_ls_clk_impl(clocks, true); } pub fn release_mspi_fast_ls_clk(clocks: &mut ClockTree) { - trace!("Releasing MSPI_FAST_LS_CLK"); trace!("Disabling MSPI_FAST_LS_CLK"); enable_mspi_fast_ls_clk_impl(clocks, false); release_hp_root_clk(clocks); } - #[allow(unused_variables)] - pub fn mspi_fast_ls_clk_config_frequency( - clocks: &mut ClockTree, - config: MspiFastLsClkConfig, - ) -> u32 { + pub fn mspi_fast_ls_clk_config_frequency(config: MspiFastLsClkConfig) -> u32 { (hp_root_clk_frequency() / (config.divisor() + 1)) } pub fn mspi_fast_ls_clk_frequency() -> u32 { @@ -3341,15 +3919,19 @@ macro_rules! define_clock_tree_types { } pub fn request_pll_f160m(clocks: &mut ClockTree) { trace!("Requesting PLL_F160M"); - trace!("Enabling PLL_F160M"); - request_pll_clk(clocks); - enable_pll_f160m_impl(clocks, true); + if increment_reference_count(&mut clocks.pll_f160m_refcount) { + trace!("Enabling PLL_F160M"); + request_pll_clk(clocks); + enable_pll_f160m_impl(clocks, true); + } } pub fn release_pll_f160m(clocks: &mut ClockTree) { trace!("Releasing PLL_F160M"); - trace!("Disabling PLL_F160M"); - enable_pll_f160m_impl(clocks, false); - release_pll_clk(clocks); + if decrement_reference_count(&mut clocks.pll_f160m_refcount) { + trace!("Disabling PLL_F160M"); + enable_pll_f160m_impl(clocks, false); + release_pll_clk(clocks); + } } pub fn pll_f160m_frequency() -> u32 { 160000000 @@ -3406,11 +3988,7 @@ macro_rules! define_clock_tree_types { } fn request_iomux_function_clock(_clocks: &mut ClockTree) {} fn release_iomux_function_clock(_clocks: &mut ClockTree) {} - #[allow(unused_variables)] - pub fn iomux_function_clock_config_frequency( - clocks: &mut ClockTree, - config: IomuxFunctionClockConfig, - ) -> u32 { + pub fn iomux_function_clock_config_frequency(config: IomuxFunctionClockConfig) -> u32 { match config { IomuxFunctionClockConfig::PllF80m => pll_f80m_frequency(), IomuxFunctionClockConfig::RcFastClk => rc_fast_clk_frequency(), @@ -3421,31 +3999,26 @@ macro_rules! define_clock_tree_types { IOMUX_FUNCTION_CLOCK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn iomux_function_clock_source_frequency(source: IomuxFunctionClockConfig) -> u32 { - match source { - IomuxFunctionClockConfig::PllF80m => pll_f80m_frequency(), - IomuxFunctionClockConfig::RcFastClk => rc_fast_clk_frequency(), - IomuxFunctionClockConfig::XtalClk => xtal_clk_frequency(), - } + iomux_function_clock_config_frequency(source) } pub fn configure_ledc_sclk(clocks: &mut ClockTree, new_selector: LedcSclkConfig) { let old_selector = clocks.ledc_sclk.replace(new_selector); refresh_ledc_sclk_downstream(clocks); - if clocks.ledc_sclk_refcount > 0 { + let active = clocks.ledc_sclk_refcount > 0; + if active { match new_selector { LedcSclkConfig::PllF80m => request_pll_f80m(clocks), LedcSclkConfig::RcFastClk => request_rc_fast_clk(clocks), LedcSclkConfig::XtalClk => request_xtal_clk(clocks), } - configure_ledc_sclk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - LedcSclkConfig::PllF80m => release_pll_f80m(clocks), - LedcSclkConfig::RcFastClk => release_rc_fast_clk(clocks), - LedcSclkConfig::XtalClk => release_xtal_clk(clocks), - } + } + configure_ledc_sclk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + LedcSclkConfig::PllF80m => release_pll_f80m(clocks), + LedcSclkConfig::RcFastClk => release_rc_fast_clk(clocks), + LedcSclkConfig::XtalClk => release_xtal_clk(clocks), } - } else { - configure_ledc_sclk_impl(clocks, old_selector, new_selector); } } pub fn ledc_sclk_config(clocks: &mut ClockTree) -> Option { @@ -3475,8 +4048,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn ledc_sclk_config_frequency(clocks: &mut ClockTree, config: LedcSclkConfig) -> u32 { + pub fn ledc_sclk_config_frequency(config: LedcSclkConfig) -> u32 { match config { LedcSclkConfig::PllF80m => pll_f80m_frequency(), LedcSclkConfig::RcFastClk => rc_fast_clk_frequency(), @@ -3487,20 +4059,14 @@ macro_rules! define_clock_tree_types { LEDC_SCLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn ledc_sclk_source_frequency(source: LedcSclkConfig) -> u32 { - match source { - LedcSclkConfig::PllF80m => pll_f80m_frequency(), - LedcSclkConfig::RcFastClk => rc_fast_clk_frequency(), - LedcSclkConfig::XtalClk => xtal_clk_frequency(), - } + ledc_sclk_config_frequency(source) } pub fn request_xtal_d2_clk(clocks: &mut ClockTree) { - trace!("Requesting XTAL_D2_CLK"); trace!("Enabling XTAL_D2_CLK"); request_xtal_clk(clocks); enable_xtal_d2_clk_impl(clocks, true); } pub fn release_xtal_d2_clk(clocks: &mut ClockTree) { - trace!("Releasing XTAL_D2_CLK"); trace!("Disabling XTAL_D2_CLK"); enable_xtal_d2_clk_impl(clocks, false); release_xtal_clk(clocks); @@ -3514,20 +4080,19 @@ macro_rules! define_clock_tree_types { pub fn configure_lp_fast_clk(clocks: &mut ClockTree, new_selector: LpFastClkConfig) { let old_selector = clocks.lp_fast_clk.replace(new_selector); refresh_lp_fast_clk_downstream(clocks); - if clocks.lp_fast_clk_refcount > 0 { + let active = clocks.lp_fast_clk_refcount > 0; + if active { match new_selector { LpFastClkConfig::RcFastClk => request_rc_fast_clk(clocks), LpFastClkConfig::XtalD2Clk => request_xtal_d2_clk(clocks), } - configure_lp_fast_clk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - LpFastClkConfig::RcFastClk => release_rc_fast_clk(clocks), - LpFastClkConfig::XtalD2Clk => release_xtal_d2_clk(clocks), - } + } + configure_lp_fast_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + LpFastClkConfig::RcFastClk => release_rc_fast_clk(clocks), + LpFastClkConfig::XtalD2Clk => release_xtal_d2_clk(clocks), } - } else { - configure_lp_fast_clk_impl(clocks, old_selector, new_selector); } } pub fn lp_fast_clk_config(clocks: &mut ClockTree) -> Option { @@ -3555,11 +4120,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn lp_fast_clk_config_frequency( - clocks: &mut ClockTree, - config: LpFastClkConfig, - ) -> u32 { + pub fn lp_fast_clk_config_frequency(config: LpFastClkConfig) -> u32 { match config { LpFastClkConfig::RcFastClk => rc_fast_clk_frequency(), LpFastClkConfig::XtalD2Clk => xtal_d2_clk_frequency(), @@ -3569,15 +4130,13 @@ macro_rules! define_clock_tree_types { LP_FAST_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn lp_fast_clk_source_frequency(source: LpFastClkConfig) -> u32 { - match source { - LpFastClkConfig::RcFastClk => rc_fast_clk_frequency(), - LpFastClkConfig::XtalD2Clk => xtal_d2_clk_frequency(), - } + lp_fast_clk_config_frequency(source) } pub fn configure_lp_slow_clk(clocks: &mut ClockTree, new_selector: LpSlowClkConfig) { let old_selector = clocks.lp_slow_clk.replace(new_selector); refresh_lp_slow_clk_downstream(clocks); match new_selector { + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => request_xtal32k_clk(clocks), LpSlowClkConfig::RcSlow => request_rc_slow_clk(clocks), LpSlowClkConfig::OscSlow => request_osc_slow_clk(clocks), @@ -3585,6 +4144,7 @@ macro_rules! define_clock_tree_types { configure_lp_slow_clk_impl(clocks, old_selector, new_selector); if let Some(old_selector) = old_selector { match old_selector { + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => release_xtal32k_clk(clocks), LpSlowClkConfig::RcSlow => release_rc_slow_clk(clocks), LpSlowClkConfig::OscSlow => release_osc_slow_clk(clocks), @@ -3595,9 +4155,9 @@ macro_rules! define_clock_tree_types { clocks.lp_slow_clk } pub fn request_lp_slow_clk(clocks: &mut ClockTree) { - trace!("Requesting LP_SLOW_CLK"); trace!("Enabling LP_SLOW_CLK"); match unwrap!(clocks.lp_slow_clk) { + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => request_xtal32k_clk(clocks), LpSlowClkConfig::RcSlow => request_rc_slow_clk(clocks), LpSlowClkConfig::OscSlow => request_osc_slow_clk(clocks), @@ -3605,21 +4165,18 @@ macro_rules! define_clock_tree_types { enable_lp_slow_clk_impl(clocks, true); } pub fn release_lp_slow_clk(clocks: &mut ClockTree) { - trace!("Releasing LP_SLOW_CLK"); trace!("Disabling LP_SLOW_CLK"); enable_lp_slow_clk_impl(clocks, false); match unwrap!(clocks.lp_slow_clk) { + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => release_xtal32k_clk(clocks), LpSlowClkConfig::RcSlow => release_rc_slow_clk(clocks), LpSlowClkConfig::OscSlow => release_osc_slow_clk(clocks), } } - #[allow(unused_variables)] - pub fn lp_slow_clk_config_frequency( - clocks: &mut ClockTree, - config: LpSlowClkConfig, - ) -> u32 { + pub fn lp_slow_clk_config_frequency(config: LpSlowClkConfig) -> u32 { match config { + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => xtal32k_clk_frequency(), LpSlowClkConfig::RcSlow => rc_slow_clk_frequency(), LpSlowClkConfig::OscSlow => osc_slow_clk_frequency(), @@ -3629,34 +4186,128 @@ macro_rules! define_clock_tree_types { LP_SLOW_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn lp_slow_clk_source_frequency(source: LpSlowClkConfig) -> u32 { - match source { - LpSlowClkConfig::Xtal32k => xtal32k_clk_frequency(), - LpSlowClkConfig::RcSlow => rc_slow_clk_frequency(), - LpSlowClkConfig::OscSlow => osc_slow_clk_frequency(), + lp_slow_clk_config_frequency(source) + } + pub fn request_ble_lp_xtal_clk(clocks: &mut ClockTree) { + trace!("Enabling BLE_LP_XTAL_CLK"); + request_xtal_clk(clocks); + enable_ble_lp_xtal_clk_impl(clocks, true); + } + pub fn release_ble_lp_xtal_clk(clocks: &mut ClockTree) { + trace!("Disabling BLE_LP_XTAL_CLK"); + enable_ble_lp_xtal_clk_impl(clocks, false); + release_xtal_clk(clocks); + } + pub fn ble_lp_xtal_clk_frequency() -> u32 { + 100000 + } + pub fn ble_lp_xtal_clk_source_frequency() -> u32 { + xtal_clk_frequency() + } + pub fn request_ble_lp_rc_slow_clk(clocks: &mut ClockTree) { + trace!("Enabling BLE_LP_RC_SLOW_CLK"); + request_rc_slow_clk(clocks); + enable_ble_lp_rc_slow_clk_impl(clocks, true); + } + pub fn release_ble_lp_rc_slow_clk(clocks: &mut ClockTree) { + trace!("Disabling BLE_LP_RC_SLOW_CLK"); + enable_ble_lp_rc_slow_clk_impl(clocks, false); + release_rc_slow_clk(clocks); + } + pub fn ble_lp_rc_slow_clk_frequency() -> u32 { + (rc_slow_clk_frequency() / 5) + } + pub fn ble_lp_rc_slow_clk_source_frequency() -> u32 { + rc_slow_clk_frequency() + } + pub fn configure_ble_lp_clk(clocks: &mut ClockTree, new_selector: BleLpClkConfig) { + let old_selector = clocks.ble_lp_clk.replace(new_selector); + refresh_ble_lp_clk_downstream(clocks); + let active = clocks.ble_lp_clk_refcount > 0; + if active { + match new_selector { + BleLpClkConfig::Xtal => request_ble_lp_xtal_clk(clocks), + BleLpClkConfig::RcSlow => request_ble_lp_rc_slow_clk(clocks), + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => request_xtal32k_clk(clocks), + } + } + configure_ble_lp_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + BleLpClkConfig::Xtal => release_ble_lp_xtal_clk(clocks), + BleLpClkConfig::RcSlow => release_ble_lp_rc_slow_clk(clocks), + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => release_xtal32k_clk(clocks), + } + } + } + pub fn ble_lp_clk_config(clocks: &mut ClockTree) -> Option { + clocks.ble_lp_clk + } + pub fn request_ble_lp_clk(clocks: &mut ClockTree) { + trace!("Requesting BLE_LP_CLK"); + if increment_reference_count(&mut clocks.ble_lp_clk_refcount) { + trace!("Enabling BLE_LP_CLK"); + match unwrap!(clocks.ble_lp_clk) { + BleLpClkConfig::Xtal => request_ble_lp_xtal_clk(clocks), + BleLpClkConfig::RcSlow => request_ble_lp_rc_slow_clk(clocks), + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => request_xtal32k_clk(clocks), + } + enable_ble_lp_clk_impl(clocks, true); + } + } + pub fn release_ble_lp_clk(clocks: &mut ClockTree) { + trace!("Releasing BLE_LP_CLK"); + if decrement_reference_count(&mut clocks.ble_lp_clk_refcount) { + trace!("Disabling BLE_LP_CLK"); + enable_ble_lp_clk_impl(clocks, false); + match unwrap!(clocks.ble_lp_clk) { + BleLpClkConfig::Xtal => release_ble_lp_xtal_clk(clocks), + BleLpClkConfig::RcSlow => release_ble_lp_rc_slow_clk(clocks), + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => release_xtal32k_clk(clocks), + } } } + pub fn ble_lp_clk_config_frequency(config: BleLpClkConfig) -> u32 { + match config { + BleLpClkConfig::Xtal => ble_lp_xtal_clk_frequency(), + BleLpClkConfig::RcSlow => ble_lp_rc_slow_clk_frequency(), + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => xtal32k_clk_frequency(), + } + } + pub fn ble_lp_clk_frequency() -> u32 { + BLE_LP_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn ble_lp_clk_source_frequency(source: BleLpClkConfig) -> u32 { + ble_lp_clk_config_frequency(source) + } pub fn configure_timg_calibration_clock( clocks: &mut ClockTree, new_selector: TimgCalibrationClockConfig, ) { let old_selector = clocks.timg_calibration_clock.replace(new_selector); refresh_timg_calibration_clock_downstream(clocks); - if clocks.timg_calibration_clock_refcount > 0 { + let active = clocks.timg_calibration_clock_refcount > 0; + if active { match new_selector { TimgCalibrationClockConfig::RcSlowClk => request_lp_slow_clk(clocks), TimgCalibrationClockConfig::RcFastDivClk => request_rc_fast_clk(clocks), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => request_xtal32k_clk(clocks), } - configure_timg_calibration_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - TimgCalibrationClockConfig::RcSlowClk => release_lp_slow_clk(clocks), - TimgCalibrationClockConfig::RcFastDivClk => release_rc_fast_clk(clocks), - TimgCalibrationClockConfig::Xtal32kClk => release_xtal32k_clk(clocks), - } + } + configure_timg_calibration_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + TimgCalibrationClockConfig::RcSlowClk => release_lp_slow_clk(clocks), + TimgCalibrationClockConfig::RcFastDivClk => release_rc_fast_clk(clocks), + #[cfg(use_xtal32k)] + TimgCalibrationClockConfig::Xtal32kClk => release_xtal32k_clk(clocks), } - } else { - configure_timg_calibration_clock_impl(clocks, old_selector, new_selector); } } pub fn timg_calibration_clock_config( @@ -3672,6 +4323,7 @@ macro_rules! define_clock_tree_types { match unwrap!(clocks.timg_calibration_clock) { TimgCalibrationClockConfig::RcSlowClk => request_lp_slow_clk(clocks), TimgCalibrationClockConfig::RcFastDivClk => request_rc_fast_clk(clocks), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => request_xtal32k_clk(clocks), } enable_timg_calibration_clock_impl(clocks, true); @@ -3686,18 +4338,16 @@ macro_rules! define_clock_tree_types { match unwrap!(clocks.timg_calibration_clock) { TimgCalibrationClockConfig::RcSlowClk => release_lp_slow_clk(clocks), TimgCalibrationClockConfig::RcFastDivClk => release_rc_fast_clk(clocks), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => release_xtal32k_clk(clocks), } } } - #[allow(unused_variables)] - pub fn timg_calibration_clock_config_frequency( - clocks: &mut ClockTree, - config: TimgCalibrationClockConfig, - ) -> u32 { + pub fn timg_calibration_clock_config_frequency(config: TimgCalibrationClockConfig) -> u32 { match config { TimgCalibrationClockConfig::RcSlowClk => lp_slow_clk_frequency(), TimgCalibrationClockConfig::RcFastDivClk => rc_fast_clk_frequency(), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => xtal32k_clk_frequency(), } } @@ -3705,10 +4355,78 @@ macro_rules! define_clock_tree_types { TIMG_CALIBRATION_CLOCK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn timg_calibration_clock_source_frequency(source: TimgCalibrationClockConfig) -> u32 { - match source { - TimgCalibrationClockConfig::RcSlowClk => lp_slow_clk_frequency(), - TimgCalibrationClockConfig::RcFastDivClk => rc_fast_clk_frequency(), - TimgCalibrationClockConfig::Xtal32kClk => xtal32k_clk_frequency(), + timg_calibration_clock_config_frequency(source) + } + impl AdcInstance { + pub fn configure_function_clock( + self, + clocks: &mut ClockTree, + new_selector: AdcFunctionClockConfig, + ) { + let old_selector = clocks.adc_function_clock[self as usize].replace(new_selector); + refresh_adc_function_clock_downstream(clocks, self); + let active = clocks.adc_function_clock_refcount[self as usize] > 0; + if active { + match new_selector { + AdcFunctionClockConfig::Xtal => request_xtal_clk(clocks), + AdcFunctionClockConfig::PllF80m => request_pll_f80m(clocks), + AdcFunctionClockConfig::RcFast => request_rc_fast_clk(clocks), + } + } + self.configure_function_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + AdcFunctionClockConfig::Xtal => release_xtal_clk(clocks), + AdcFunctionClockConfig::PllF80m => release_pll_f80m(clocks), + AdcFunctionClockConfig::RcFast => release_rc_fast_clk(clocks), + } + } + } + pub fn function_clock_config( + self, + clocks: &mut ClockTree, + ) -> Option { + clocks.adc_function_clock[self as usize] + } + pub fn request_function_clock(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::FUNCTION_CLOCK", self); + if increment_reference_count(&mut clocks.adc_function_clock_refcount[self as usize]) + { + trace!("Enabling {:?}::FUNCTION_CLOCK", self); + match unwrap!(clocks.adc_function_clock[self as usize]) { + AdcFunctionClockConfig::Xtal => request_xtal_clk(clocks), + AdcFunctionClockConfig::PllF80m => request_pll_f80m(clocks), + AdcFunctionClockConfig::RcFast => request_rc_fast_clk(clocks), + } + self.enable_function_clock_impl(clocks, true); + } + } + pub fn release_function_clock(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::FUNCTION_CLOCK", self); + if decrement_reference_count(&mut clocks.adc_function_clock_refcount[self as usize]) + { + trace!("Disabling {:?}::FUNCTION_CLOCK", self); + self.enable_function_clock_impl(clocks, false); + match unwrap!(clocks.adc_function_clock[self as usize]) { + AdcFunctionClockConfig::Xtal => release_xtal_clk(clocks), + AdcFunctionClockConfig::PllF80m => release_pll_f80m(clocks), + AdcFunctionClockConfig::RcFast => release_rc_fast_clk(clocks), + } + } + } + pub fn function_clock_config_frequency(config: AdcFunctionClockConfig) -> u32 { + match config { + AdcFunctionClockConfig::Xtal => xtal_clk_frequency(), + AdcFunctionClockConfig::PllF80m => pll_f80m_frequency(), + AdcFunctionClockConfig::RcFast => rc_fast_clk_frequency(), + } + } + pub fn function_clock_frequency(self) -> u32 { + ADC_FUNCTION_CLOCK_FREQ_CACHE[self as usize] + .load(::core::sync::atomic::Ordering::Acquire) + } + pub fn function_clock_source_frequency(source: AdcFunctionClockConfig) -> u32 { + Self::function_clock_config_frequency(source) } } impl SdmInstance { @@ -3745,20 +4463,19 @@ macro_rules! define_clock_tree_types { ) { let old_config = clocks.i2c_function_clock[self as usize].replace(config); refresh_i2c_function_clock_downstream(clocks, self); - if clocks.i2c_function_clock_refcount[self as usize] > 0 { + let active = clocks.i2c_function_clock_refcount[self as usize] > 0; + if active { match config.sclk { I2cFunctionClockSclk::Xtal => request_xtal_clk(clocks), I2cFunctionClockSclk::RcFast => request_rc_fast_clk(clocks), } - self.configure_function_clock_impl(clocks, old_config, config); - if let Some(old_config) = old_config { - match old_config.sclk { - I2cFunctionClockSclk::Xtal => release_xtal_clk(clocks), - I2cFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), - } + } + self.configure_function_clock_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + I2cFunctionClockSclk::Xtal => release_xtal_clk(clocks), + I2cFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_config, config); } } pub fn function_clock_config( @@ -3793,11 +4510,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: I2cFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: I2cFunctionClockConfig) -> u32 { (match config.sclk { I2cFunctionClockSclk::Xtal => xtal_clk_frequency(), I2cFunctionClockSclk::RcFast => rc_fast_clk_frequency(), @@ -3814,6 +4527,202 @@ macro_rules! define_clock_tree_types { } } } + impl I2sInstance { + pub fn configure_tx_clk(self, clocks: &mut ClockTree, config: I2sClkConfig) { + let old_config = clocks.i2s_tx_clk[self as usize].replace(config); + refresh_i2s_tx_clk_downstream(clocks, self); + let active = clocks.i2s_tx_clk_refcount[self as usize] > 0; + if active { + match config.sclk { + I2sClkSclk::Xtal => request_xtal_clk(clocks), + I2sClkSclk::PllF240m => request_pll_f240m(clocks), + I2sClkSclk::PllF160m => request_pll_f160m(clocks), + } + } + self.configure_tx_clk_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + I2sClkSclk::Xtal => release_xtal_clk(clocks), + I2sClkSclk::PllF240m => release_pll_f240m(clocks), + I2sClkSclk::PllF160m => release_pll_f160m(clocks), + } + } + } + pub fn tx_clk_config(self, clocks: &mut ClockTree) -> Option { + clocks.i2s_tx_clk[self as usize] + } + pub fn request_tx_clk(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::TX_CLK", self); + if increment_reference_count(&mut clocks.i2s_tx_clk_refcount[self as usize]) { + trace!("Enabling {:?}::TX_CLK", self); + crate::rtc_cntl::WakeLock::acquire(); + match unwrap!(clocks.i2s_tx_clk[self as usize]).sclk { + I2sClkSclk::Xtal => request_xtal_clk(clocks), + I2sClkSclk::PllF240m => request_pll_f240m(clocks), + I2sClkSclk::PllF160m => request_pll_f160m(clocks), + } + self.enable_tx_clk_impl(clocks, true); + } + } + pub fn release_tx_clk(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::TX_CLK", self); + if decrement_reference_count(&mut clocks.i2s_tx_clk_refcount[self as usize]) { + trace!("Disabling {:?}::TX_CLK", self); + crate::rtc_cntl::WakeLock::release(); + self.enable_tx_clk_impl(clocks, false); + match unwrap!(clocks.i2s_tx_clk[self as usize]).sclk { + I2sClkSclk::Xtal => release_xtal_clk(clocks), + I2sClkSclk::PllF240m => release_pll_f240m(clocks), + I2sClkSclk::PllF160m => release_pll_f160m(clocks), + } + } + } + pub fn tx_clk_config_frequency(config: I2sClkConfig) -> u32 { + (((match config.sclk { + I2sClkSclk::Xtal => xtal_clk_frequency(), + I2sClkSclk::PllF240m => pll_f240m_frequency(), + I2sClkSclk::PllF160m => pll_f160m_frequency(), + } as u64) + * (config.div_a() as u64)) + / (((config.div_num() * config.div_a()) + config.div_b()) as u64)) + as u32 + } + pub fn tx_clk_frequency(self) -> u32 { + I2S_TX_CLK_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) + } + pub fn tx_clk_source_frequency(sclk: I2sClkSclk) -> u32 { + match sclk { + I2sClkSclk::Xtal => xtal_clk_frequency(), + I2sClkSclk::PllF240m => pll_f240m_frequency(), + I2sClkSclk::PllF160m => pll_f160m_frequency(), + } + } + pub fn configure_rx_clk(self, clocks: &mut ClockTree, config: I2sClkConfig) { + let old_config = clocks.i2s_rx_clk[self as usize].replace(config); + refresh_i2s_rx_clk_downstream(clocks, self); + let active = clocks.i2s_rx_clk_refcount[self as usize] > 0; + if active { + match config.sclk { + I2sClkSclk::Xtal => request_xtal_clk(clocks), + I2sClkSclk::PllF240m => request_pll_f240m(clocks), + I2sClkSclk::PllF160m => request_pll_f160m(clocks), + } + } + self.configure_rx_clk_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + I2sClkSclk::Xtal => release_xtal_clk(clocks), + I2sClkSclk::PllF240m => release_pll_f240m(clocks), + I2sClkSclk::PllF160m => release_pll_f160m(clocks), + } + } + } + pub fn rx_clk_config(self, clocks: &mut ClockTree) -> Option { + clocks.i2s_rx_clk[self as usize] + } + pub fn request_rx_clk(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::RX_CLK", self); + if increment_reference_count(&mut clocks.i2s_rx_clk_refcount[self as usize]) { + trace!("Enabling {:?}::RX_CLK", self); + crate::rtc_cntl::WakeLock::acquire(); + match unwrap!(clocks.i2s_rx_clk[self as usize]).sclk { + I2sClkSclk::Xtal => request_xtal_clk(clocks), + I2sClkSclk::PllF240m => request_pll_f240m(clocks), + I2sClkSclk::PllF160m => request_pll_f160m(clocks), + } + self.enable_rx_clk_impl(clocks, true); + } + } + pub fn release_rx_clk(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::RX_CLK", self); + if decrement_reference_count(&mut clocks.i2s_rx_clk_refcount[self as usize]) { + trace!("Disabling {:?}::RX_CLK", self); + crate::rtc_cntl::WakeLock::release(); + self.enable_rx_clk_impl(clocks, false); + match unwrap!(clocks.i2s_rx_clk[self as usize]).sclk { + I2sClkSclk::Xtal => release_xtal_clk(clocks), + I2sClkSclk::PllF240m => release_pll_f240m(clocks), + I2sClkSclk::PllF160m => release_pll_f160m(clocks), + } + } + } + pub fn rx_clk_config_frequency(config: I2sClkConfig) -> u32 { + (((match config.sclk { + I2sClkSclk::Xtal => xtal_clk_frequency(), + I2sClkSclk::PllF240m => pll_f240m_frequency(), + I2sClkSclk::PllF160m => pll_f160m_frequency(), + } as u64) + * (config.div_a() as u64)) + / (((config.div_num() * config.div_a()) + config.div_b()) as u64)) + as u32 + } + pub fn rx_clk_frequency(self) -> u32 { + I2S_RX_CLK_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) + } + pub fn rx_clk_source_frequency(sclk: I2sClkSclk) -> u32 { + match sclk { + I2sClkSclk::Xtal => xtal_clk_frequency(), + I2sClkSclk::PllF240m => pll_f240m_frequency(), + I2sClkSclk::PllF160m => pll_f160m_frequency(), + } + } + pub fn configure_mclk_out( + self, + clocks: &mut ClockTree, + new_selector: I2sMclkOutConfig, + ) { + let old_selector = clocks.i2s_mclk_out[self as usize].replace(new_selector); + refresh_i2s_mclk_out_downstream(clocks, self); + let active = clocks.i2s_mclk_out_refcount[self as usize] > 0; + if active { + match new_selector { + I2sMclkOutConfig::Tx => self.request_tx_clk(clocks), + I2sMclkOutConfig::Rx => self.request_rx_clk(clocks), + } + } + self.configure_mclk_out_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + I2sMclkOutConfig::Tx => self.release_tx_clk(clocks), + I2sMclkOutConfig::Rx => self.release_rx_clk(clocks), + } + } + } + pub fn mclk_out_config(self, clocks: &mut ClockTree) -> Option { + clocks.i2s_mclk_out[self as usize] + } + pub fn request_mclk_out(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::MCLK_OUT", self); + if increment_reference_count(&mut clocks.i2s_mclk_out_refcount[self as usize]) { + trace!("Enabling {:?}::MCLK_OUT", self); + match unwrap!(clocks.i2s_mclk_out[self as usize]) { + I2sMclkOutConfig::Tx => self.request_tx_clk(clocks), + I2sMclkOutConfig::Rx => self.request_rx_clk(clocks), + } + self.enable_mclk_out_impl(clocks, true); + } + } + pub fn release_mclk_out(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::MCLK_OUT", self); + if decrement_reference_count(&mut clocks.i2s_mclk_out_refcount[self as usize]) { + trace!("Disabling {:?}::MCLK_OUT", self); + self.enable_mclk_out_impl(clocks, false); + match unwrap!(clocks.i2s_mclk_out[self as usize]) { + I2sMclkOutConfig::Tx => self.release_tx_clk(clocks), + I2sMclkOutConfig::Rx => self.release_rx_clk(clocks), + } + } + } + pub fn mclk_out_config_frequency(self, config: I2sMclkOutConfig) -> u32 { + match config { + I2sMclkOutConfig::Tx => self.tx_clk_frequency(), + I2sMclkOutConfig::Rx => self.rx_clk_frequency(), + } + } + pub fn mclk_out_frequency(self) -> u32 { + I2S_MCLK_OUT_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) + } + } impl McpwmInstance { pub fn configure_function_clock( self, @@ -3822,22 +4731,21 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.mcpwm_function_clock[self as usize].replace(new_selector); refresh_mcpwm_function_clock_downstream(clocks, self); - if clocks.mcpwm_function_clock_refcount[self as usize] > 0 { + let active = clocks.mcpwm_function_clock_refcount[self as usize] > 0; + if active { match new_selector { McpwmFunctionClockConfig::PllF160m => request_pll_f160m(clocks), McpwmFunctionClockConfig::RcFastClk => request_rc_fast_clk(clocks), McpwmFunctionClockConfig::XtalClk => request_xtal_clk(clocks), } - self.configure_function_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - McpwmFunctionClockConfig::PllF160m => release_pll_f160m(clocks), - McpwmFunctionClockConfig::RcFastClk => release_rc_fast_clk(clocks), - McpwmFunctionClockConfig::XtalClk => release_xtal_clk(clocks), - } + } + self.configure_function_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + McpwmFunctionClockConfig::PllF160m => release_pll_f160m(clocks), + McpwmFunctionClockConfig::RcFastClk => release_rc_fast_clk(clocks), + McpwmFunctionClockConfig::XtalClk => release_xtal_clk(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_selector, new_selector); } } pub fn function_clock_config( @@ -3876,11 +4784,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: McpwmFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: McpwmFunctionClockConfig) -> u32 { match config { McpwmFunctionClockConfig::PllF160m => pll_f160m_frequency(), McpwmFunctionClockConfig::RcFastClk => rc_fast_clk_frequency(), @@ -3892,40 +4796,31 @@ macro_rules! define_clock_tree_types { .load(::core::sync::atomic::Ordering::Acquire) } pub fn function_clock_source_frequency(source: McpwmFunctionClockConfig) -> u32 { - match source { - McpwmFunctionClockConfig::PllF160m => pll_f160m_frequency(), - McpwmFunctionClockConfig::RcFastClk => rc_fast_clk_frequency(), - McpwmFunctionClockConfig::XtalClk => xtal_clk_frequency(), - } + Self::function_clock_config_frequency(source) } } impl ParlIoInstance { - pub fn configure_rx_clock( - self, - clocks: &mut ClockTree, - new_selector: ParlIoRxClockConfig, - ) { + pub fn configure_rx_clock(self, clocks: &mut ClockTree, new_selector: ParlIoClkConfig) { let old_selector = clocks.parl_io_rx_clock[self as usize].replace(new_selector); refresh_parl_io_rx_clock_downstream(clocks, self); - if clocks.parl_io_rx_clock_refcount[self as usize] > 0 { + let active = clocks.parl_io_rx_clock_refcount[self as usize] > 0; + if active { match new_selector { - ParlIoRxClockConfig::XtalClk => request_xtal_clk(clocks), - ParlIoRxClockConfig::RcFastClk => request_rc_fast_clk(clocks), - ParlIoRxClockConfig::PllF240m => request_pll_f240m(clocks), + ParlIoClkConfig::XtalClk => request_xtal_clk(clocks), + ParlIoClkConfig::RcFastClk => request_rc_fast_clk(clocks), + ParlIoClkConfig::PllF240m => request_pll_f240m(clocks), } - self.configure_rx_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - ParlIoRxClockConfig::XtalClk => release_xtal_clk(clocks), - ParlIoRxClockConfig::RcFastClk => release_rc_fast_clk(clocks), - ParlIoRxClockConfig::PllF240m => release_pll_f240m(clocks), - } + } + self.configure_rx_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + ParlIoClkConfig::XtalClk => release_xtal_clk(clocks), + ParlIoClkConfig::RcFastClk => release_rc_fast_clk(clocks), + ParlIoClkConfig::PllF240m => release_pll_f240m(clocks), } - } else { - self.configure_rx_clock_impl(clocks, old_selector, new_selector); } } - pub fn rx_clock_config(self, clocks: &mut ClockTree) -> Option { + pub fn rx_clock_config(self, clocks: &mut ClockTree) -> Option { clocks.parl_io_rx_clock[self as usize] } pub fn request_rx_clock(self, clocks: &mut ClockTree) { @@ -3934,9 +4829,9 @@ macro_rules! define_clock_tree_types { trace!("Enabling {:?}::RX_CLOCK", self); crate::rtc_cntl::WakeLock::acquire(); match unwrap!(clocks.parl_io_rx_clock[self as usize]) { - ParlIoRxClockConfig::XtalClk => request_xtal_clk(clocks), - ParlIoRxClockConfig::RcFastClk => request_rc_fast_clk(clocks), - ParlIoRxClockConfig::PllF240m => request_pll_f240m(clocks), + ParlIoClkConfig::XtalClk => request_xtal_clk(clocks), + ParlIoClkConfig::RcFastClk => request_rc_fast_clk(clocks), + ParlIoClkConfig::PllF240m => request_pll_f240m(clocks), } self.enable_rx_clock_impl(clocks, true); } @@ -3948,60 +4843,47 @@ macro_rules! define_clock_tree_types { crate::rtc_cntl::WakeLock::release(); self.enable_rx_clock_impl(clocks, false); match unwrap!(clocks.parl_io_rx_clock[self as usize]) { - ParlIoRxClockConfig::XtalClk => release_xtal_clk(clocks), - ParlIoRxClockConfig::RcFastClk => release_rc_fast_clk(clocks), - ParlIoRxClockConfig::PllF240m => release_pll_f240m(clocks), + ParlIoClkConfig::XtalClk => release_xtal_clk(clocks), + ParlIoClkConfig::RcFastClk => release_rc_fast_clk(clocks), + ParlIoClkConfig::PllF240m => release_pll_f240m(clocks), } } } - #[allow(unused_variables)] - pub fn rx_clock_config_frequency( - clocks: &mut ClockTree, - config: ParlIoRxClockConfig, - ) -> u32 { + pub fn rx_clock_config_frequency(config: ParlIoClkConfig) -> u32 { match config { - ParlIoRxClockConfig::XtalClk => xtal_clk_frequency(), - ParlIoRxClockConfig::RcFastClk => rc_fast_clk_frequency(), - ParlIoRxClockConfig::PllF240m => pll_f240m_frequency(), + ParlIoClkConfig::XtalClk => xtal_clk_frequency(), + ParlIoClkConfig::RcFastClk => rc_fast_clk_frequency(), + ParlIoClkConfig::PllF240m => pll_f240m_frequency(), } } pub fn rx_clock_frequency(self) -> u32 { PARL_IO_RX_CLOCK_FREQ_CACHE[self as usize] .load(::core::sync::atomic::Ordering::Acquire) } - pub fn rx_clock_source_frequency(source: ParlIoRxClockConfig) -> u32 { - match source { - ParlIoRxClockConfig::XtalClk => xtal_clk_frequency(), - ParlIoRxClockConfig::RcFastClk => rc_fast_clk_frequency(), - ParlIoRxClockConfig::PllF240m => pll_f240m_frequency(), - } + pub fn rx_clock_source_frequency(source: ParlIoClkConfig) -> u32 { + Self::rx_clock_config_frequency(source) } - pub fn configure_tx_clock( - self, - clocks: &mut ClockTree, - new_selector: ParlIoTxClockConfig, - ) { + pub fn configure_tx_clock(self, clocks: &mut ClockTree, new_selector: ParlIoClkConfig) { let old_selector = clocks.parl_io_tx_clock[self as usize].replace(new_selector); refresh_parl_io_tx_clock_downstream(clocks, self); - if clocks.parl_io_tx_clock_refcount[self as usize] > 0 { + let active = clocks.parl_io_tx_clock_refcount[self as usize] > 0; + if active { match new_selector { - ParlIoTxClockConfig::XtalClk => request_xtal_clk(clocks), - ParlIoTxClockConfig::RcFastClk => request_rc_fast_clk(clocks), - ParlIoTxClockConfig::PllF240m => request_pll_f240m(clocks), + ParlIoClkConfig::XtalClk => request_xtal_clk(clocks), + ParlIoClkConfig::RcFastClk => request_rc_fast_clk(clocks), + ParlIoClkConfig::PllF240m => request_pll_f240m(clocks), } - self.configure_tx_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - ParlIoTxClockConfig::XtalClk => release_xtal_clk(clocks), - ParlIoTxClockConfig::RcFastClk => release_rc_fast_clk(clocks), - ParlIoTxClockConfig::PllF240m => release_pll_f240m(clocks), - } + } + self.configure_tx_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + ParlIoClkConfig::XtalClk => release_xtal_clk(clocks), + ParlIoClkConfig::RcFastClk => release_rc_fast_clk(clocks), + ParlIoClkConfig::PllF240m => release_pll_f240m(clocks), } - } else { - self.configure_tx_clock_impl(clocks, old_selector, new_selector); } } - pub fn tx_clock_config(self, clocks: &mut ClockTree) -> Option { + pub fn tx_clock_config(self, clocks: &mut ClockTree) -> Option { clocks.parl_io_tx_clock[self as usize] } pub fn request_tx_clock(self, clocks: &mut ClockTree) { @@ -4010,9 +4892,9 @@ macro_rules! define_clock_tree_types { trace!("Enabling {:?}::TX_CLOCK", self); crate::rtc_cntl::WakeLock::acquire(); match unwrap!(clocks.parl_io_tx_clock[self as usize]) { - ParlIoTxClockConfig::XtalClk => request_xtal_clk(clocks), - ParlIoTxClockConfig::RcFastClk => request_rc_fast_clk(clocks), - ParlIoTxClockConfig::PllF240m => request_pll_f240m(clocks), + ParlIoClkConfig::XtalClk => request_xtal_clk(clocks), + ParlIoClkConfig::RcFastClk => request_rc_fast_clk(clocks), + ParlIoClkConfig::PllF240m => request_pll_f240m(clocks), } self.enable_tx_clock_impl(clocks, true); } @@ -4024,55 +4906,46 @@ macro_rules! define_clock_tree_types { crate::rtc_cntl::WakeLock::release(); self.enable_tx_clock_impl(clocks, false); match unwrap!(clocks.parl_io_tx_clock[self as usize]) { - ParlIoTxClockConfig::XtalClk => release_xtal_clk(clocks), - ParlIoTxClockConfig::RcFastClk => release_rc_fast_clk(clocks), - ParlIoTxClockConfig::PllF240m => release_pll_f240m(clocks), + ParlIoClkConfig::XtalClk => release_xtal_clk(clocks), + ParlIoClkConfig::RcFastClk => release_rc_fast_clk(clocks), + ParlIoClkConfig::PllF240m => release_pll_f240m(clocks), } } } - #[allow(unused_variables)] - pub fn tx_clock_config_frequency( - clocks: &mut ClockTree, - config: ParlIoTxClockConfig, - ) -> u32 { + pub fn tx_clock_config_frequency(config: ParlIoClkConfig) -> u32 { match config { - ParlIoTxClockConfig::XtalClk => xtal_clk_frequency(), - ParlIoTxClockConfig::RcFastClk => rc_fast_clk_frequency(), - ParlIoTxClockConfig::PllF240m => pll_f240m_frequency(), + ParlIoClkConfig::XtalClk => xtal_clk_frequency(), + ParlIoClkConfig::RcFastClk => rc_fast_clk_frequency(), + ParlIoClkConfig::PllF240m => pll_f240m_frequency(), } } pub fn tx_clock_frequency(self) -> u32 { PARL_IO_TX_CLOCK_FREQ_CACHE[self as usize] .load(::core::sync::atomic::Ordering::Acquire) } - pub fn tx_clock_source_frequency(source: ParlIoTxClockConfig) -> u32 { - match source { - ParlIoTxClockConfig::XtalClk => xtal_clk_frequency(), - ParlIoTxClockConfig::RcFastClk => rc_fast_clk_frequency(), - ParlIoTxClockConfig::PllF240m => pll_f240m_frequency(), - } + pub fn tx_clock_source_frequency(source: ParlIoClkConfig) -> u32 { + Self::tx_clock_config_frequency(source) } } impl RmtInstance { pub fn configure_sclk(self, clocks: &mut ClockTree, new_selector: RmtSclkConfig) { let old_selector = clocks.rmt_sclk[self as usize].replace(new_selector); refresh_rmt_sclk_downstream(clocks, self); - if clocks.rmt_sclk_refcount[self as usize] > 0 { + let active = clocks.rmt_sclk_refcount[self as usize] > 0; + if active { match new_selector { RmtSclkConfig::PllF80m => request_pll_f80m(clocks), RmtSclkConfig::RcFastClk => request_rc_fast_clk(clocks), RmtSclkConfig::XtalClk => request_xtal_clk(clocks), } - self.configure_sclk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - RmtSclkConfig::PllF80m => release_pll_f80m(clocks), - RmtSclkConfig::RcFastClk => release_rc_fast_clk(clocks), - RmtSclkConfig::XtalClk => release_xtal_clk(clocks), - } + } + self.configure_sclk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + RmtSclkConfig::PllF80m => release_pll_f80m(clocks), + RmtSclkConfig::RcFastClk => release_rc_fast_clk(clocks), + RmtSclkConfig::XtalClk => release_xtal_clk(clocks), } - } else { - self.configure_sclk_impl(clocks, old_selector, new_selector); } } pub fn sclk_config(self, clocks: &mut ClockTree) -> Option { @@ -4104,8 +4977,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn sclk_config_frequency(clocks: &mut ClockTree, config: RmtSclkConfig) -> u32 { + pub fn sclk_config_frequency(config: RmtSclkConfig) -> u32 { match config { RmtSclkConfig::PllF80m => pll_f80m_frequency(), RmtSclkConfig::RcFastClk => rc_fast_clk_frequency(), @@ -4116,11 +4988,7 @@ macro_rules! define_clock_tree_types { RMT_SCLK_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) } pub fn sclk_source_frequency(source: RmtSclkConfig) -> u32 { - match source { - RmtSclkConfig::PllF80m => pll_f80m_frequency(), - RmtSclkConfig::RcFastClk => rc_fast_clk_frequency(), - RmtSclkConfig::XtalClk => xtal_clk_frequency(), - } + Self::sclk_config_frequency(source) } } impl SpiInstance { @@ -4131,22 +4999,21 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.spi_function_clock[self as usize].replace(new_selector); refresh_spi_function_clock_downstream(clocks, self); - if clocks.spi_function_clock_refcount[self as usize] > 0 { + let active = clocks.spi_function_clock_refcount[self as usize] > 0; + if active { match new_selector { SpiFunctionClockConfig::PllF80m => request_pll_f80m(clocks), SpiFunctionClockConfig::Xtal => request_xtal_clk(clocks), SpiFunctionClockConfig::RcFast => request_rc_fast_clk(clocks), } - self.configure_function_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - SpiFunctionClockConfig::PllF80m => release_pll_f80m(clocks), - SpiFunctionClockConfig::Xtal => release_xtal_clk(clocks), - SpiFunctionClockConfig::RcFast => release_rc_fast_clk(clocks), - } + } + self.configure_function_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + SpiFunctionClockConfig::PllF80m => release_pll_f80m(clocks), + SpiFunctionClockConfig::Xtal => release_xtal_clk(clocks), + SpiFunctionClockConfig::RcFast => release_rc_fast_clk(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_selector, new_selector); } } pub fn function_clock_config( @@ -4183,11 +5050,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: SpiFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: SpiFunctionClockConfig) -> u32 { match config { SpiFunctionClockConfig::PllF80m => pll_f80m_frequency(), SpiFunctionClockConfig::Xtal => xtal_clk_frequency(), @@ -4199,11 +5062,7 @@ macro_rules! define_clock_tree_types { .load(::core::sync::atomic::Ordering::Acquire) } pub fn function_clock_source_frequency(source: SpiFunctionClockConfig) -> u32 { - match source { - SpiFunctionClockConfig::PllF80m => pll_f80m_frequency(), - SpiFunctionClockConfig::Xtal => xtal_clk_frequency(), - SpiFunctionClockConfig::RcFast => rc_fast_clk_frequency(), - } + Self::function_clock_config_frequency(source) } } impl TimgInstance { @@ -4214,22 +5073,21 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.timg_function_clock[self as usize].replace(new_selector); refresh_timg_function_clock_downstream(clocks, self); - if clocks.timg_function_clock_refcount[self as usize] > 0 { + let active = clocks.timg_function_clock_refcount[self as usize] > 0; + if active { match new_selector { TimgFunctionClockConfig::XtalClk => request_xtal_clk(clocks), TimgFunctionClockConfig::RcFastClk => request_rc_fast_clk(clocks), TimgFunctionClockConfig::PllF80m => request_pll_f80m(clocks), } - self.configure_function_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - TimgFunctionClockConfig::XtalClk => release_xtal_clk(clocks), - TimgFunctionClockConfig::RcFastClk => release_rc_fast_clk(clocks), - TimgFunctionClockConfig::PllF80m => release_pll_f80m(clocks), - } + } + self.configure_function_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + TimgFunctionClockConfig::XtalClk => release_xtal_clk(clocks), + TimgFunctionClockConfig::RcFastClk => release_rc_fast_clk(clocks), + TimgFunctionClockConfig::PllF80m => release_pll_f80m(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_selector, new_selector); } } pub fn function_clock_config( @@ -4266,11 +5124,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: TimgFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: TimgFunctionClockConfig) -> u32 { match config { TimgFunctionClockConfig::XtalClk => xtal_clk_frequency(), TimgFunctionClockConfig::RcFastClk => rc_fast_clk_frequency(), @@ -4282,11 +5136,7 @@ macro_rules! define_clock_tree_types { .load(::core::sync::atomic::Ordering::Acquire) } pub fn function_clock_source_frequency(source: TimgFunctionClockConfig) -> u32 { - match source { - TimgFunctionClockConfig::XtalClk => xtal_clk_frequency(), - TimgFunctionClockConfig::RcFastClk => rc_fast_clk_frequency(), - TimgFunctionClockConfig::PllF80m => pll_f80m_frequency(), - } + Self::function_clock_config_frequency(source) } pub fn configure_wdt_clock( self, @@ -4295,22 +5145,21 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.timg_wdt_clock[self as usize].replace(new_selector); refresh_timg_wdt_clock_downstream(clocks, self); - if clocks.timg_wdt_clock_refcount[self as usize] > 0 { + let active = clocks.timg_wdt_clock_refcount[self as usize] > 0; + if active { match new_selector { TimgWdtClockConfig::XtalClk => request_xtal_clk(clocks), TimgWdtClockConfig::PllF80m => request_pll_f80m(clocks), TimgWdtClockConfig::RcFastClk => request_rc_fast_clk(clocks), } - self.configure_wdt_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - TimgWdtClockConfig::XtalClk => release_xtal_clk(clocks), - TimgWdtClockConfig::PllF80m => release_pll_f80m(clocks), - TimgWdtClockConfig::RcFastClk => release_rc_fast_clk(clocks), - } + } + self.configure_wdt_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + TimgWdtClockConfig::XtalClk => release_xtal_clk(clocks), + TimgWdtClockConfig::PllF80m => release_pll_f80m(clocks), + TimgWdtClockConfig::RcFastClk => release_rc_fast_clk(clocks), } - } else { - self.configure_wdt_clock_impl(clocks, old_selector, new_selector); } } pub fn wdt_clock_config(self, clocks: &mut ClockTree) -> Option { @@ -4340,11 +5189,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn wdt_clock_config_frequency( - clocks: &mut ClockTree, - config: TimgWdtClockConfig, - ) -> u32 { + pub fn wdt_clock_config_frequency(config: TimgWdtClockConfig) -> u32 { match config { TimgWdtClockConfig::XtalClk => xtal_clk_frequency(), TimgWdtClockConfig::PllF80m => pll_f80m_frequency(), @@ -4356,11 +5201,7 @@ macro_rules! define_clock_tree_types { .load(::core::sync::atomic::Ordering::Acquire) } pub fn wdt_clock_source_frequency(source: TimgWdtClockConfig) -> u32 { - match source { - TimgWdtClockConfig::XtalClk => xtal_clk_frequency(), - TimgWdtClockConfig::PllF80m => pll_f80m_frequency(), - TimgWdtClockConfig::RcFastClk => rc_fast_clk_frequency(), - } + Self::wdt_clock_config_frequency(source) } } impl UartInstance { @@ -4371,22 +5212,21 @@ macro_rules! define_clock_tree_types { ) { let old_config = clocks.uart_function_clock[self as usize].replace(config); refresh_uart_function_clock_downstream(clocks, self); - if clocks.uart_function_clock_refcount[self as usize] > 0 { + let active = clocks.uart_function_clock_refcount[self as usize] > 0; + if active { match config.sclk { UartFunctionClockSclk::PllF80m => request_pll_f80m(clocks), UartFunctionClockSclk::RcFast => request_rc_fast_clk(clocks), UartFunctionClockSclk::Xtal => request_xtal_clk(clocks), } - self.configure_function_clock_impl(clocks, old_config, config); - if let Some(old_config) = old_config { - match old_config.sclk { - UartFunctionClockSclk::PllF80m => release_pll_f80m(clocks), - UartFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), - UartFunctionClockSclk::Xtal => release_xtal_clk(clocks), - } + } + self.configure_function_clock_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + UartFunctionClockSclk::PllF80m => release_pll_f80m(clocks), + UartFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), + UartFunctionClockSclk::Xtal => release_xtal_clk(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_config, config); } } pub fn function_clock_config( @@ -4425,11 +5265,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: UartFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: UartFunctionClockConfig) -> u32 { (match config.sclk { UartFunctionClockSclk::PllF80m => pll_f80m_frequency(), UartFunctionClockSclk::RcFast => rc_fast_clk_frequency(), @@ -4482,10 +5318,8 @@ macro_rules! define_clock_tree_types { self.release_function_clock(clocks); } } - #[allow(unused_variables)] pub fn baud_rate_generator_config_frequency( self, - clocks: &mut ClockTree, config: UartBaudRateGeneratorConfig, ) -> u32 { ((self.function_clock_frequency() * 16) @@ -4496,6 +5330,63 @@ macro_rules! define_clock_tree_types { .load(::core::sync::atomic::Ordering::Acquire) } } + impl TsensInstance { + pub fn configure_sclk(self, clocks: &mut ClockTree, new_selector: TsensSclkConfig) { + let old_selector = clocks.tsens_sclk[self as usize].replace(new_selector); + refresh_tsens_sclk_downstream(clocks, self); + let active = clocks.tsens_sclk_refcount[self as usize] > 0; + if active { + match new_selector { + TsensSclkConfig::RcFast => request_rc_fast_clk(clocks), + TsensSclkConfig::Xtal => request_xtal_clk(clocks), + } + } + self.configure_sclk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + TsensSclkConfig::RcFast => release_rc_fast_clk(clocks), + TsensSclkConfig::Xtal => release_xtal_clk(clocks), + } + } + } + pub fn sclk_config(self, clocks: &mut ClockTree) -> Option { + clocks.tsens_sclk[self as usize] + } + pub fn request_sclk(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::SCLK", self); + if increment_reference_count(&mut clocks.tsens_sclk_refcount[self as usize]) { + trace!("Enabling {:?}::SCLK", self); + match unwrap!(clocks.tsens_sclk[self as usize]) { + TsensSclkConfig::RcFast => request_rc_fast_clk(clocks), + TsensSclkConfig::Xtal => request_xtal_clk(clocks), + } + self.enable_sclk_impl(clocks, true); + } + } + pub fn release_sclk(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::SCLK", self); + if decrement_reference_count(&mut clocks.tsens_sclk_refcount[self as usize]) { + trace!("Disabling {:?}::SCLK", self); + self.enable_sclk_impl(clocks, false); + match unwrap!(clocks.tsens_sclk[self as usize]) { + TsensSclkConfig::RcFast => release_rc_fast_clk(clocks), + TsensSclkConfig::Xtal => release_xtal_clk(clocks), + } + } + } + pub fn sclk_config_frequency(config: TsensSclkConfig) -> u32 { + match config { + TsensSclkConfig::RcFast => rc_fast_clk_frequency(), + TsensSclkConfig::Xtal => xtal_clk_frequency(), + } + } + pub fn sclk_frequency(self) -> u32 { + TSENS_SCLK_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) + } + pub fn sclk_source_frequency(source: TsensSclkConfig) -> u32 { + Self::sclk_config_frequency(source) + } + } /// Clock tree configuration. /// /// The fields of this struct are optional, with the following caveats: @@ -4533,6 +5424,8 @@ macro_rules! define_clock_tree_types { pub lp_fast_clk: Option, /// `LP_SLOW_CLK` configuration. pub lp_slow_clk: Option, + /// `BLE_LP_CLK` configuration. + pub ble_lp_clk: Option, /// `TIMG_CALIBRATION_CLOCK` configuration. pub timg_calibration_clock: Option, } @@ -4556,6 +5449,9 @@ macro_rules! define_clock_tree_types { if let Some(config) = self.lp_slow_clk { configure_lp_slow_clk(clocks, config); } + if let Some(config) = self.ble_lp_clk { + configure_ble_lp_clk(clocks, config); + } if let Some(config) = self.timg_calibration_clock { configure_timg_calibration_clock(clocks, config); } @@ -4595,7 +5491,7 @@ macro_rules! define_clock_tree_types { fn refresh_xtal_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.xtal_clk { XTAL_CLK_FREQ_CACHE.store( - xtal_clk_config_frequency(clocks, config), + xtal_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4603,6 +5499,50 @@ macro_rules! define_clock_tree_types { refresh_iomux_function_clock_downstream(clocks); refresh_ledc_sclk_downstream(clocks); refresh_lp_fast_clk_downstream(clocks); + refresh_ble_lp_clk_downstream(clocks); + for child_instance in [AdcInstance::ApbSaradc] { + refresh_adc_function_clock_downstream(clocks, child_instance); + } + for child_instance in [I2cInstance::I2c0] { + refresh_i2c_function_clock_downstream(clocks, child_instance); + } + for child_instance in [I2sInstance::I2s0] { + refresh_i2s_tx_clk_downstream(clocks, child_instance); + refresh_i2s_rx_clk_downstream(clocks, child_instance); + } + for child_instance in [McpwmInstance::Mcpwm0] { + refresh_mcpwm_function_clock_downstream(clocks, child_instance); + } + for child_instance in [ParlIoInstance::ParlIo] { + refresh_parl_io_rx_clock_downstream(clocks, child_instance); + refresh_parl_io_tx_clock_downstream(clocks, child_instance); + } + for child_instance in [RmtInstance::Rmt] { + refresh_rmt_sclk_downstream(clocks, child_instance); + } + for child_instance in [SpiInstance::Spi2] { + refresh_spi_function_clock_downstream(clocks, child_instance); + } + for child_instance in [TimgInstance::Timg0, TimgInstance::Timg1] { + refresh_timg_function_clock_downstream(clocks, child_instance); + refresh_timg_wdt_clock_downstream(clocks, child_instance); + } + for child_instance in [UartInstance::Uart0, UartInstance::Uart1] { + refresh_uart_function_clock_downstream(clocks, child_instance); + } + for child_instance in [TsensInstance::Tsens] { + refresh_tsens_sclk_downstream(clocks, child_instance); + } + } + fn refresh_rc_fast_clk_downstream(clocks: &mut ClockTree) { + refresh_soc_root_clk_downstream(clocks); + refresh_iomux_function_clock_downstream(clocks); + refresh_ledc_sclk_downstream(clocks); + refresh_lp_fast_clk_downstream(clocks); + refresh_timg_calibration_clock_downstream(clocks); + for child_instance in [AdcInstance::ApbSaradc] { + refresh_adc_function_clock_downstream(clocks, child_instance); + } for child_instance in [I2cInstance::I2c0] { refresh_i2c_function_clock_downstream(clocks, child_instance); } @@ -4626,11 +5566,18 @@ macro_rules! define_clock_tree_types { for child_instance in [UartInstance::Uart0, UartInstance::Uart1] { refresh_uart_function_clock_downstream(clocks, child_instance); } + for child_instance in [TsensInstance::Tsens] { + refresh_tsens_sclk_downstream(clocks, child_instance); + } + } + fn refresh_rc_slow_clk_downstream(clocks: &mut ClockTree) { + refresh_lp_slow_clk_downstream(clocks); + refresh_ble_lp_clk_downstream(clocks); } fn refresh_soc_root_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.soc_root_clk { SOC_ROOT_CLK_FREQ_CACHE.store( - soc_root_clk_config_frequency(clocks, config), + soc_root_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4639,7 +5586,7 @@ macro_rules! define_clock_tree_types { fn refresh_iomux_function_clock_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.iomux_function_clock { IOMUX_FUNCTION_CLOCK_FREQ_CACHE.store( - iomux_function_clock_config_frequency(clocks, config), + iomux_function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4647,7 +5594,7 @@ macro_rules! define_clock_tree_types { fn refresh_ledc_sclk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.ledc_sclk { LEDC_SCLK_FREQ_CACHE.store( - ledc_sclk_config_frequency(clocks, config), + ledc_sclk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4655,7 +5602,7 @@ macro_rules! define_clock_tree_types { fn refresh_lp_fast_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.lp_fast_clk { LP_FAST_CLK_FREQ_CACHE.store( - lp_fast_clk_config_frequency(clocks, config), + lp_fast_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4663,16 +5610,32 @@ macro_rules! define_clock_tree_types { fn refresh_lp_slow_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.lp_slow_clk { LP_SLOW_CLK_FREQ_CACHE.store( - lp_slow_clk_config_frequency(clocks, config), + lp_slow_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } refresh_timg_calibration_clock_downstream(clocks); } + fn refresh_ble_lp_clk_downstream(clocks: &mut ClockTree) { + if let Some(config) = clocks.ble_lp_clk { + BLE_LP_CLK_FREQ_CACHE.store( + ble_lp_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } fn refresh_timg_calibration_clock_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.timg_calibration_clock { TIMG_CALIBRATION_CLOCK_FREQ_CACHE.store( - timg_calibration_clock_config_frequency(clocks, config), + timg_calibration_clock_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + fn refresh_adc_function_clock_downstream(clocks: &mut ClockTree, instance: AdcInstance) { + if let Some(config) = clocks.adc_function_clock[instance as usize] { + ADC_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( + AdcInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4680,7 +5643,33 @@ macro_rules! define_clock_tree_types { fn refresh_i2c_function_clock_downstream(clocks: &mut ClockTree, instance: I2cInstance) { if let Some(config) = clocks.i2c_function_clock[instance as usize] { I2C_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - I2cInstance::function_clock_config_frequency(clocks, config), + I2cInstance::function_clock_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + fn refresh_i2s_tx_clk_downstream(clocks: &mut ClockTree, instance: I2sInstance) { + if let Some(config) = clocks.i2s_tx_clk[instance as usize] { + I2S_TX_CLK_FREQ_CACHE[instance as usize].store( + I2sInstance::tx_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + refresh_i2s_mclk_out_downstream(clocks, instance); + } + fn refresh_i2s_rx_clk_downstream(clocks: &mut ClockTree, instance: I2sInstance) { + if let Some(config) = clocks.i2s_rx_clk[instance as usize] { + I2S_RX_CLK_FREQ_CACHE[instance as usize].store( + I2sInstance::rx_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + refresh_i2s_mclk_out_downstream(clocks, instance); + } + fn refresh_i2s_mclk_out_downstream(clocks: &mut ClockTree, instance: I2sInstance) { + if let Some(config) = clocks.i2s_mclk_out[instance as usize] { + I2S_MCLK_OUT_FREQ_CACHE[instance as usize].store( + instance.mclk_out_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4691,7 +5680,7 @@ macro_rules! define_clock_tree_types { ) { if let Some(config) = clocks.mcpwm_function_clock[instance as usize] { MCPWM_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - McpwmInstance::function_clock_config_frequency(clocks, config), + McpwmInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4699,7 +5688,7 @@ macro_rules! define_clock_tree_types { fn refresh_parl_io_rx_clock_downstream(clocks: &mut ClockTree, instance: ParlIoInstance) { if let Some(config) = clocks.parl_io_rx_clock[instance as usize] { PARL_IO_RX_CLOCK_FREQ_CACHE[instance as usize].store( - ParlIoInstance::rx_clock_config_frequency(clocks, config), + ParlIoInstance::rx_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4707,7 +5696,7 @@ macro_rules! define_clock_tree_types { fn refresh_parl_io_tx_clock_downstream(clocks: &mut ClockTree, instance: ParlIoInstance) { if let Some(config) = clocks.parl_io_tx_clock[instance as usize] { PARL_IO_TX_CLOCK_FREQ_CACHE[instance as usize].store( - ParlIoInstance::tx_clock_config_frequency(clocks, config), + ParlIoInstance::tx_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4715,7 +5704,7 @@ macro_rules! define_clock_tree_types { fn refresh_rmt_sclk_downstream(clocks: &mut ClockTree, instance: RmtInstance) { if let Some(config) = clocks.rmt_sclk[instance as usize] { RMT_SCLK_FREQ_CACHE[instance as usize].store( - RmtInstance::sclk_config_frequency(clocks, config), + RmtInstance::sclk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4723,7 +5712,7 @@ macro_rules! define_clock_tree_types { fn refresh_spi_function_clock_downstream(clocks: &mut ClockTree, instance: SpiInstance) { if let Some(config) = clocks.spi_function_clock[instance as usize] { SPI_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - SpiInstance::function_clock_config_frequency(clocks, config), + SpiInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4731,7 +5720,7 @@ macro_rules! define_clock_tree_types { fn refresh_timg_function_clock_downstream(clocks: &mut ClockTree, instance: TimgInstance) { if let Some(config) = clocks.timg_function_clock[instance as usize] { TIMG_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - TimgInstance::function_clock_config_frequency(clocks, config), + TimgInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4739,7 +5728,7 @@ macro_rules! define_clock_tree_types { fn refresh_timg_wdt_clock_downstream(clocks: &mut ClockTree, instance: TimgInstance) { if let Some(config) = clocks.timg_wdt_clock[instance as usize] { TIMG_WDT_CLOCK_FREQ_CACHE[instance as usize].store( - TimgInstance::wdt_clock_config_frequency(clocks, config), + TimgInstance::wdt_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4747,7 +5736,7 @@ macro_rules! define_clock_tree_types { fn refresh_uart_function_clock_downstream(clocks: &mut ClockTree, instance: UartInstance) { if let Some(config) = clocks.uart_function_clock[instance as usize] { UART_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - UartInstance::function_clock_config_frequency(clocks, config), + UartInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4759,7 +5748,15 @@ macro_rules! define_clock_tree_types { ) { if let Some(config) = clocks.uart_baud_rate_generator[instance as usize] { UART_BAUD_RATE_GENERATOR_FREQ_CACHE[instance as usize].store( - instance.baud_rate_generator_config_frequency(clocks, config), + instance.baud_rate_generator_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + fn refresh_tsens_sclk_downstream(clocks: &mut ClockTree, instance: TsensInstance) { + if let Some(config) = clocks.tsens_sclk[instance as usize] { + TSENS_SCLK_FREQ_CACHE[instance as usize].store( + TsensInstance::sclk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4767,7 +5764,7 @@ macro_rules! define_clock_tree_types { fn refresh_hp_root_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.hp_root_clk { HP_ROOT_CLK_FREQ_CACHE.store( - hp_root_clk_config_frequency(clocks, config), + hp_root_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4781,7 +5778,7 @@ macro_rules! define_clock_tree_types { fn refresh_cpu_hs_div_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.cpu_hs_div { CPU_HS_DIV_FREQ_CACHE.store( - cpu_hs_div_config_frequency(clocks, config), + cpu_hs_div_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4790,7 +5787,7 @@ macro_rules! define_clock_tree_types { fn refresh_cpu_ls_div_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.cpu_ls_div { CPU_LS_DIV_FREQ_CACHE.store( - cpu_ls_div_config_frequency(clocks, config), + cpu_ls_div_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4799,7 +5796,7 @@ macro_rules! define_clock_tree_types { fn refresh_ahb_hs_div_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.ahb_hs_div { AHB_HS_DIV_FREQ_CACHE.store( - ahb_hs_div_config_frequency(clocks, config), + ahb_hs_div_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4808,7 +5805,7 @@ macro_rules! define_clock_tree_types { fn refresh_ahb_ls_div_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.ahb_ls_div { AHB_LS_DIV_FREQ_CACHE.store( - ahb_ls_div_config_frequency(clocks, config), + ahb_ls_div_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4817,7 +5814,7 @@ macro_rules! define_clock_tree_types { fn refresh_mspi_fast_hs_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.mspi_fast_hs_clk { MSPI_FAST_HS_CLK_FREQ_CACHE.store( - mspi_fast_hs_clk_config_frequency(clocks, config), + mspi_fast_hs_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4826,7 +5823,7 @@ macro_rules! define_clock_tree_types { fn refresh_mspi_fast_ls_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.mspi_fast_ls_clk { MSPI_FAST_LS_CLK_FREQ_CACHE.store( - mspi_fast_ls_clk_config_frequency(clocks, config), + mspi_fast_ls_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4835,7 +5832,7 @@ macro_rules! define_clock_tree_types { fn refresh_cpu_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.cpu_clk { CPU_CLK_FREQ_CACHE.store( - cpu_clk_config_frequency(clocks, config), + cpu_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4843,7 +5840,7 @@ macro_rules! define_clock_tree_types { fn refresh_ahb_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.ahb_clk { AHB_CLK_FREQ_CACHE.store( - ahb_clk_config_frequency(clocks, config), + ahb_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4852,7 +5849,7 @@ macro_rules! define_clock_tree_types { fn refresh_mspi_fast_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.mspi_fast_clk { MSPI_FAST_CLK_FREQ_CACHE.store( - mspi_fast_clk_config_frequency(clocks, config), + mspi_fast_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4860,7 +5857,7 @@ macro_rules! define_clock_tree_types { fn refresh_apb_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.apb_clk { APB_CLK_FREQ_CACHE.store( - apb_clk_config_frequency(clocks, config), + apb_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -5493,6 +6490,57 @@ macro_rules! for_each_spi_slave { Spi2, FSPICLK, FSPID, FSPIQ, FSPICS0))); }; } +/// This macro can be used to generate code for each PCNT unit. +/// +/// For an explanation on the general syntax, as well as usage of individual/repeated +/// matchers, refer to [the crate-level documentation][crate#for_each-macros]. +/// +/// This macro has four options for its "Individual matcher" case: +/// +/// - `names`: `($instance:ident)` +/// - `all`: `($peri:ident, $variant:ident, $sys:ident, $regs:ident, $unit:literal, +/// $interrupt:ident, $sig_ch0:ident, $sig_ch1:ident, $ctrl_ch0:ident, $ctrl_ch1:ident)` +/// - `interrupt`: `($interrupt:ident)` (repeated: one ident per unique IRQ) +/// - `regs`: `($regs:ident)` (repeated: one ident per register block) +/// +/// Macro fragments: +/// +/// - `$peri`: unit singleton name (`PCNT0_UNIT0`, `PCNT1_UNIT0`, …) +/// - `$variant`: `AnyPcntUnit` enum variant (`Pcnt0Unit0`, `Pcnt1Unit0`, …) +/// - `$sys`: `esp_hal::system::Peripheral` variant for clocks +/// - `$regs`: register-block singleton (`PCNT`, `PCNT1`) +/// - `$unit`: hardware unit index within that register block +/// - `$interrupt`: shared peripheral interrupt +/// - `$sig_ch0`, `$sig_ch1`, `$ctrl_ch0`, `$ctrl_ch1`: GPIO matrix input signals +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! for_each_pcnt_unit { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _for_each_inner_pcnt_unit { $(($pattern) => $code;)* ($other : tt) + => {} } _for_each_inner_pcnt_unit!((PCNT0_UNIT0)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT2)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT3)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT0, Pcnt0Unit0, Pcnt, PCNT, 0, PCNT, + PCNT0_SIG_CH0, PCNT0_SIG_CH1, PCNT0_CTRL_CH0, PCNT0_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT1, Pcnt0Unit1, Pcnt, PCNT, 1, PCNT, + PCNT1_SIG_CH0, PCNT1_SIG_CH1, PCNT1_CTRL_CH0, PCNT1_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT2, Pcnt0Unit2, Pcnt, PCNT, 2, PCNT, + PCNT2_SIG_CH0, PCNT2_SIG_CH1, PCNT2_CTRL_CH0, PCNT2_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT3, Pcnt0Unit3, Pcnt, PCNT, 3, PCNT, + PCNT3_SIG_CH0, PCNT3_SIG_CH1, PCNT3_CTRL_CH0, PCNT3_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT)); _for_each_inner_pcnt_unit!((PCNT)); + _for_each_inner_pcnt_unit!((names(PCNT0_UNIT0), (PCNT0_UNIT1), (PCNT0_UNIT2), + (PCNT0_UNIT3))); _for_each_inner_pcnt_unit!((all(PCNT0_UNIT0, Pcnt0Unit0, Pcnt, + PCNT, 0, PCNT, PCNT0_SIG_CH0, PCNT0_SIG_CH1, PCNT0_CTRL_CH0, PCNT0_CTRL_CH1), + (PCNT0_UNIT1, Pcnt0Unit1, Pcnt, PCNT, 1, PCNT, PCNT1_SIG_CH0, PCNT1_SIG_CH1, + PCNT1_CTRL_CH0, PCNT1_CTRL_CH1), (PCNT0_UNIT2, Pcnt0Unit2, Pcnt, PCNT, 2, PCNT, + PCNT2_SIG_CH0, PCNT2_SIG_CH1, PCNT2_CTRL_CH0, PCNT2_CTRL_CH1), (PCNT0_UNIT3, + Pcnt0Unit3, Pcnt, PCNT, 3, PCNT, PCNT3_SIG_CH0, PCNT3_SIG_CH1, PCNT3_CTRL_CH0, + PCNT3_CTRL_CH1))); _for_each_inner_pcnt_unit!((interrupt(PCNT))); + _for_each_inner_pcnt_unit!((regs(PCNT))); + }; +} #[macro_export] #[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] macro_rules! for_each_peripheral { @@ -5658,6 +6706,14 @@ macro_rules! for_each_peripheral { DMA_CH2 <= virtual(DMA_IN_CH2 : { bind_dma_in_interrupt, enable_dma_in_interrupt, disable_dma_in_interrupt }, DMA_OUT_CH2 : { bind_dma_out_interrupt, enable_dma_out_interrupt, disable_dma_out_interrupt }) (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT0_UNIT0 peripheral singleton"] PCNT0_UNIT0 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT0_UNIT1 peripheral singleton"] PCNT0_UNIT1 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT0_UNIT2 peripheral singleton"] PCNT0_UNIT2 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT0_UNIT3 peripheral singleton"] PCNT0_UNIT3 <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "SDM_CH0 peripheral singleton"] SDM_CH0 <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "SDM_CH1 peripheral singleton"] SDM_CH1 <= virtual() (unstable))); @@ -5672,23 +6728,24 @@ macro_rules! for_each_peripheral { "ASSIST_DEBUG peripheral singleton"] ASSIST_DEBUG <= ASSIST_DEBUG() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "ATOMIC peripheral singleton"] ATOMIC <= ATOMIC() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "DMA peripheral singleton"] DMA <= DMA() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "DS peripheral singleton"] DS <= - DS() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "ECC peripheral singleton"] ECC <= ECC() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "EFUSE peripheral singleton"] - EFUSE <= EFUSE() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "EXTMEM peripheral singleton"] EXTMEM <= EXTMEM() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "GPIO peripheral singleton"] - GPIO <= GPIO() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "GPIO_SD peripheral singleton"] GPIO_SD <= GPIO_SD() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "HINF peripheral singleton"] - HINF <= HINF() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "HMAC peripheral singleton"] HMAC <= HMAC() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "HP_APM peripheral singleton"] - HP_APM <= HP_APM() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "HP_SYS peripheral singleton"] HP_SYS <= HP_SYS() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = + "CLINT peripheral singleton"] CLINT <= CLINT() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "DMA peripheral singleton"] DMA + <= DMA() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "DS peripheral singleton"] DS <= DS() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "ECC peripheral singleton"] ECC + <= ECC() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "EFUSE peripheral singleton"] EFUSE <= EFUSE() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "EXTMEM peripheral singleton"] + EXTMEM <= EXTMEM() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "GPIO peripheral singleton"] GPIO <= GPIO() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "GPIO_SD peripheral singleton"] + GPIO_SD <= GPIO_SD() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc + = "HINF peripheral singleton"] HINF <= HINF() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "HMAC peripheral singleton"] + HMAC <= HMAC() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "HP_APM peripheral singleton"] HP_APM <= HP_APM() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "HP_SYS peripheral singleton"] + HP_SYS <= HP_SYS() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "I2C_ANA_MST peripheral singleton"] I2C_ANA_MST <= I2C_ANA_MST() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "I2C0 peripheral singleton"] I2C0 <= I2C0(I2C_EXT0 : { bind_peri_interrupt, enable_peri_interrupt, @@ -5742,47 +6799,49 @@ macro_rules! for_each_peripheral { disable_peri_interrupt }) (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "PAU peripheral singleton"] PAU <= PAU() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "PCNT peripheral singleton"] - PCNT <= PCNT() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "PCR peripheral singleton"] PCR <= PCR() (unstable))); + PCNT <= PCNT(PCNT : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt }) (unstable))); _for_each_inner_peripheral!((@ peri_type + #[doc = "PCR peripheral singleton"] PCR <= PCR() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "PLIC_MX peripheral singleton"] PLIC_MX <= PLIC_MX() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc - = "PMU peripheral singleton"] PMU <= PMU() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "RMT peripheral singleton"] RMT - <= RMT() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "RNG peripheral singleton"] RNG <= LP_PERI() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "RSA peripheral singleton"] RSA - <= RSA(RSA : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt - }) (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "SHA peripheral singleton"] SHA <= SHA(SHA : { bind_peri_interrupt, + = "PLIC_UX peripheral singleton"] PLIC_UX <= PLIC_UX() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "PMU peripheral singleton"] PMU + <= PMU() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "RMT peripheral singleton"] RMT <= RMT() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "RNG peripheral singleton"] RNG + <= LP_PERI() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "RSA peripheral singleton"] RSA <= RSA(RSA : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "SLCHOST peripheral singleton"] - SLCHOST <= SLCHOST() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc - = "ETM peripheral singleton"] ETM <= SOC_ETM() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "SPI0 peripheral singleton"] - SPI0 <= SPI0() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "SPI1 peripheral singleton"] SPI1 <= SPI1() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "SPI2 peripheral singleton"] - SPI2 <= SPI2(SPI2 : { bind_peri_interrupt, enable_peri_interrupt, - disable_peri_interrupt }))); _for_each_inner_peripheral!((@ peri_type #[doc = - "SYSTEM peripheral singleton"] SYSTEM <= PCR() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "SYSTIMER peripheral singleton"] - SYSTIMER <= SYSTIMER() (unstable))); _for_each_inner_peripheral!((@ peri_type - #[doc = "TEE peripheral singleton"] TEE <= TEE() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "TIMG0 peripheral singleton"] - TIMG0 <= TIMG0() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "TIMG1 peripheral singleton"] TIMG1 <= TIMG1() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "TRACE0 peripheral singleton"] - TRACE0 <= TRACE() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "TWAI0 peripheral singleton"] TWAI0 <= TWAI0() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "TWAI1 peripheral singleton"] - TWAI1 <= TWAI1() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "UART0 peripheral singleton"] UART0 <= UART0(UART0 : { bind_peri_interrupt, + _for_each_inner_peripheral!((@ peri_type #[doc = "SHA peripheral singleton"] SHA + <= SHA(SHA : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt + }) (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "SLCHOST peripheral singleton"] SLCHOST <= SLCHOST() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "ETM peripheral singleton"] ETM + <= SOC_ETM() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "SPI0 peripheral singleton"] SPI0 <= SPI0() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "SPI1 peripheral singleton"] + SPI1 <= SPI1() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "SPI2 peripheral singleton"] SPI2 <= SPI2(SPI2 : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }))); - _for_each_inner_peripheral!((@ peri_type #[doc = "UART1 peripheral singleton"] - UART1 <= UART1(UART1 : { bind_peri_interrupt, enable_peri_interrupt, + _for_each_inner_peripheral!((@ peri_type #[doc = "SYSTEM peripheral singleton"] + SYSTEM <= PCR() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "SYSTIMER peripheral singleton"] SYSTIMER <= SYSTIMER() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "TEE peripheral singleton"] TEE + <= TEE() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "TIMG0 peripheral singleton"] TIMG0 <= TIMG0() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "TIMG1 peripheral singleton"] + TIMG1 <= TIMG1() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "TRACE0 peripheral singleton"] TRACE0 <= TRACE() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "TWAI0 peripheral singleton"] + TWAI0 <= TWAI0() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "TWAI1 peripheral singleton"] TWAI1 <= TWAI1() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "UART0 peripheral singleton"] + UART0 <= UART0(UART0 : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }))); _for_each_inner_peripheral!((@ peri_type #[doc = - "UHCI0 peripheral singleton"] UHCI0 <= UHCI0() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = + "UART1 peripheral singleton"] UART1 <= UART1(UART1 : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }))); + _for_each_inner_peripheral!((@ peri_type #[doc = "UHCI0 peripheral singleton"] + UHCI0 <= UHCI0() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "USB_DEVICE peripheral singleton"] USB_DEVICE <= USB_DEVICE(USB_DEVICE : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = @@ -5831,6 +6890,10 @@ macro_rules! for_each_peripheral { _for_each_inner_peripheral!((DMA_CH0(unstable))); _for_each_inner_peripheral!((DMA_CH1(unstable))); _for_each_inner_peripheral!((DMA_CH2(unstable))); + _for_each_inner_peripheral!((PCNT0_UNIT0(unstable))); + _for_each_inner_peripheral!((PCNT0_UNIT1(unstable))); + _for_each_inner_peripheral!((PCNT0_UNIT2(unstable))); + _for_each_inner_peripheral!((PCNT0_UNIT3(unstable))); _for_each_inner_peripheral!((SDM_CH0(unstable))); _for_each_inner_peripheral!((SDM_CH1(unstable))); _for_each_inner_peripheral!((SDM_CH2(unstable))); @@ -5909,7 +6972,6 @@ macro_rules! for_each_peripheral { _for_each_inner_peripheral!((LP_CORE(unstable))); _for_each_inner_peripheral!((TSENS(unstable))); _for_each_inner_peripheral!((WIFI)); - _for_each_inner_peripheral!((FROM_CPU_INTR0(unstable))); _for_each_inner_peripheral!((FROM_CPU_INTR1(unstable))); _for_each_inner_peripheral!((FROM_CPU_INTR2(unstable))); _for_each_inner_peripheral!((FROM_CPU_INTR3(unstable))); @@ -6058,34 +7120,41 @@ macro_rules! for_each_peripheral { bind_dma_in_interrupt, enable_dma_in_interrupt, disable_dma_in_interrupt }, DMA_OUT_CH2 : { bind_dma_out_interrupt, enable_dma_out_interrupt, disable_dma_out_interrupt }) (unstable)), (@ peri_type #[doc = - "SDM_CH0 peripheral singleton"] SDM_CH0 <= virtual() (unstable)), (@ peri_type - #[doc = "SDM_CH1 peripheral singleton"] SDM_CH1 <= virtual() (unstable)), (@ - peri_type #[doc = "SDM_CH2 peripheral singleton"] SDM_CH2 <= virtual() - (unstable)), (@ peri_type #[doc = "SDM_CH3 peripheral singleton"] SDM_CH3 <= - virtual() (unstable)), (@ peri_type #[doc = "AES peripheral singleton"] AES <= - AES(AES : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) - (unstable)), (@ peri_type #[doc = "APB_SARADC peripheral singleton"] APB_SARADC - <= APB_SARADC() (unstable)), (@ peri_type #[doc = - "ASSIST_DEBUG peripheral singleton"] ASSIST_DEBUG <= ASSIST_DEBUG() (unstable)), - (@ peri_type #[doc = "ATOMIC peripheral singleton"] ATOMIC <= ATOMIC() - (unstable)), (@ peri_type #[doc = "DMA peripheral singleton"] DMA <= DMA() - (unstable)), (@ peri_type #[doc = "DS peripheral singleton"] DS <= DS() - (unstable)), (@ peri_type #[doc = "ECC peripheral singleton"] ECC <= ECC() - (unstable)), (@ peri_type #[doc = "EFUSE peripheral singleton"] EFUSE <= EFUSE() - (unstable)), (@ peri_type #[doc = "EXTMEM peripheral singleton"] EXTMEM <= - EXTMEM() (unstable)), (@ peri_type #[doc = "GPIO peripheral singleton"] GPIO <= - GPIO() (unstable)), (@ peri_type #[doc = "GPIO_SD peripheral singleton"] GPIO_SD - <= GPIO_SD() (unstable)), (@ peri_type #[doc = "HINF peripheral singleton"] HINF - <= HINF() (unstable)), (@ peri_type #[doc = "HMAC peripheral singleton"] HMAC <= - HMAC() (unstable)), (@ peri_type #[doc = "HP_APM peripheral singleton"] HP_APM <= - HP_APM() (unstable)), (@ peri_type #[doc = "HP_SYS peripheral singleton"] HP_SYS - <= HP_SYS() (unstable)), (@ peri_type #[doc = "I2C_ANA_MST peripheral singleton"] - I2C_ANA_MST <= I2C_ANA_MST() (unstable)), (@ peri_type #[doc = - "I2C0 peripheral singleton"] I2C0 <= I2C0(I2C_EXT0 : { bind_peri_interrupt, - enable_peri_interrupt, disable_peri_interrupt })), (@ peri_type #[doc = - "I2S0 peripheral singleton"] I2S0 <= I2S0(I2S0 : { bind_peri_interrupt, + "PCNT0_UNIT0 peripheral singleton"] PCNT0_UNIT0 <= virtual() (unstable)), (@ + peri_type #[doc = "PCNT0_UNIT1 peripheral singleton"] PCNT0_UNIT1 <= virtual() + (unstable)), (@ peri_type #[doc = "PCNT0_UNIT2 peripheral singleton"] PCNT0_UNIT2 + <= virtual() (unstable)), (@ peri_type #[doc = + "PCNT0_UNIT3 peripheral singleton"] PCNT0_UNIT3 <= virtual() (unstable)), (@ + peri_type #[doc = "SDM_CH0 peripheral singleton"] SDM_CH0 <= virtual() + (unstable)), (@ peri_type #[doc = "SDM_CH1 peripheral singleton"] SDM_CH1 <= + virtual() (unstable)), (@ peri_type #[doc = "SDM_CH2 peripheral singleton"] + SDM_CH2 <= virtual() (unstable)), (@ peri_type #[doc = + "SDM_CH3 peripheral singleton"] SDM_CH3 <= virtual() (unstable)), (@ peri_type + #[doc = "AES peripheral singleton"] AES <= AES(AES : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc - = "IEEE802154 peripheral singleton"] IEEE802154 <= IEEE802154(ZB_MAC : { + = "APB_SARADC peripheral singleton"] APB_SARADC <= APB_SARADC() (unstable)), (@ + peri_type #[doc = "ASSIST_DEBUG peripheral singleton"] ASSIST_DEBUG <= + ASSIST_DEBUG() (unstable)), (@ peri_type #[doc = "ATOMIC peripheral singleton"] + ATOMIC <= ATOMIC() (unstable)), (@ peri_type #[doc = + "CLINT peripheral singleton"] CLINT <= CLINT() (unstable)), (@ peri_type #[doc = + "DMA peripheral singleton"] DMA <= DMA() (unstable)), (@ peri_type #[doc = + "DS peripheral singleton"] DS <= DS() (unstable)), (@ peri_type #[doc = + "ECC peripheral singleton"] ECC <= ECC() (unstable)), (@ peri_type #[doc = + "EFUSE peripheral singleton"] EFUSE <= EFUSE() (unstable)), (@ peri_type #[doc = + "EXTMEM peripheral singleton"] EXTMEM <= EXTMEM() (unstable)), (@ peri_type #[doc + = "GPIO peripheral singleton"] GPIO <= GPIO() (unstable)), (@ peri_type #[doc = + "GPIO_SD peripheral singleton"] GPIO_SD <= GPIO_SD() (unstable)), (@ peri_type + #[doc = "HINF peripheral singleton"] HINF <= HINF() (unstable)), (@ peri_type + #[doc = "HMAC peripheral singleton"] HMAC <= HMAC() (unstable)), (@ peri_type + #[doc = "HP_APM peripheral singleton"] HP_APM <= HP_APM() (unstable)), (@ + peri_type #[doc = "HP_SYS peripheral singleton"] HP_SYS <= HP_SYS() (unstable)), + (@ peri_type #[doc = "I2C_ANA_MST peripheral singleton"] I2C_ANA_MST <= + I2C_ANA_MST() (unstable)), (@ peri_type #[doc = "I2C0 peripheral singleton"] I2C0 + <= I2C0(I2C_EXT0 : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt })), (@ peri_type #[doc = "I2S0 peripheral singleton"] + I2S0 <= I2S0(I2S0 : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt }) (unstable)), (@ peri_type #[doc = + "IEEE802154 peripheral singleton"] IEEE802154 <= IEEE802154(ZB_MAC : { bind_mac_interrupt, enable_mac_interrupt, disable_mac_interrupt }) (unstable)), (@ peri_type #[doc = "INTERRUPT_CORE0 peripheral singleton"] INTERRUPT_CORE0 <= INTERRUPT_CORE0() (unstable)), (@ peri_type #[doc = @@ -6118,51 +7187,54 @@ macro_rules! for_each_peripheral { peri_type #[doc = "PARL_IO peripheral singleton"] PARL_IO <= PARL_IO(PARL_IO : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc = "PAU peripheral singleton"] PAU <= PAU() - (unstable)), (@ peri_type #[doc = "PCNT peripheral singleton"] PCNT <= PCNT() + (unstable)), (@ peri_type #[doc = "PCNT peripheral singleton"] PCNT <= PCNT(PCNT + : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc = "PCR peripheral singleton"] PCR <= PCR() (unstable)), (@ peri_type #[doc = "PLIC_MX peripheral singleton"] PLIC_MX <= - PLIC_MX() (unstable)), (@ peri_type #[doc = "PMU peripheral singleton"] PMU <= - PMU() (unstable)), (@ peri_type #[doc = "RMT peripheral singleton"] RMT <= RMT() - (unstable)), (@ peri_type #[doc = "RNG peripheral singleton"] RNG <= LP_PERI() - (unstable)), (@ peri_type #[doc = "RSA peripheral singleton"] RSA <= RSA(RSA : { - bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) - (unstable)), (@ peri_type #[doc = "SHA peripheral singleton"] SHA <= SHA(SHA : { - bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) - (unstable)), (@ peri_type #[doc = "SLCHOST peripheral singleton"] SLCHOST <= - SLCHOST() (unstable)), (@ peri_type #[doc = "ETM peripheral singleton"] ETM <= - SOC_ETM() (unstable)), (@ peri_type #[doc = "SPI0 peripheral singleton"] SPI0 <= - SPI0() (unstable)), (@ peri_type #[doc = "SPI1 peripheral singleton"] SPI1 <= - SPI1() (unstable)), (@ peri_type #[doc = "SPI2 peripheral singleton"] SPI2 <= - SPI2(SPI2 : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt - })), (@ peri_type #[doc = "SYSTEM peripheral singleton"] SYSTEM <= PCR() - (unstable)), (@ peri_type #[doc = "SYSTIMER peripheral singleton"] SYSTIMER <= - SYSTIMER() (unstable)), (@ peri_type #[doc = "TEE peripheral singleton"] TEE <= - TEE() (unstable)), (@ peri_type #[doc = "TIMG0 peripheral singleton"] TIMG0 <= - TIMG0() (unstable)), (@ peri_type #[doc = "TIMG1 peripheral singleton"] TIMG1 <= - TIMG1() (unstable)), (@ peri_type #[doc = "TRACE0 peripheral singleton"] TRACE0 - <= TRACE() (unstable)), (@ peri_type #[doc = "TWAI0 peripheral singleton"] TWAI0 - <= TWAI0() (unstable)), (@ peri_type #[doc = "TWAI1 peripheral singleton"] TWAI1 - <= TWAI1() (unstable)), (@ peri_type #[doc = "UART0 peripheral singleton"] UART0 - <= UART0(UART0 : { bind_peri_interrupt, enable_peri_interrupt, - disable_peri_interrupt })), (@ peri_type #[doc = "UART1 peripheral singleton"] - UART1 <= UART1(UART1 : { bind_peri_interrupt, enable_peri_interrupt, - disable_peri_interrupt })), (@ peri_type #[doc = "UHCI0 peripheral singleton"] - UHCI0 <= UHCI0() (unstable)), (@ peri_type #[doc = - "USB_DEVICE peripheral singleton"] USB_DEVICE <= USB_DEVICE(USB_DEVICE : { - bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) - (unstable)), (@ peri_type #[doc = "ADC1 peripheral singleton"] ADC1 <= virtual() - (unstable)), (@ peri_type #[doc = "BT peripheral singleton"] BT <= - virtual(LP_TIMER : { bind_lp_timer_interrupt, enable_lp_timer_interrupt, - disable_lp_timer_interrupt }, BT_MAC : { bind_mac_interrupt, - enable_mac_interrupt, disable_mac_interrupt }) (unstable)), (@ peri_type #[doc = - "FLASH peripheral singleton"] FLASH <= virtual() (unstable)), (@ peri_type #[doc - = "GPIO_DEDICATED peripheral singleton"] GPIO_DEDICATED <= virtual() (unstable)), - (@ peri_type #[doc = "LP_CORE peripheral singleton"] LP_CORE <= virtual() - (unstable)), (@ peri_type #[doc = "TSENS peripheral singleton"] TSENS <= - virtual() (unstable)), (@ peri_type #[doc = "WIFI peripheral singleton"] WIFI <= - virtual(WIFI_BB : { bind_bb_interrupt, enable_bb_interrupt, disable_bb_interrupt - }, WIFI_MAC : { bind_mac_interrupt, enable_mac_interrupt, disable_mac_interrupt - }, MODEM_PERI_TIMEOUT : { bind_modem_peri_timeout_interrupt, + PLIC_MX() (unstable)), (@ peri_type #[doc = "PLIC_UX peripheral singleton"] + PLIC_UX <= PLIC_UX() (unstable)), (@ peri_type #[doc = + "PMU peripheral singleton"] PMU <= PMU() (unstable)), (@ peri_type #[doc = + "RMT peripheral singleton"] RMT <= RMT() (unstable)), (@ peri_type #[doc = + "RNG peripheral singleton"] RNG <= LP_PERI() (unstable)), (@ peri_type #[doc = + "RSA peripheral singleton"] RSA <= RSA(RSA : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc + = "SHA peripheral singleton"] SHA <= SHA(SHA : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc + = "SLCHOST peripheral singleton"] SLCHOST <= SLCHOST() (unstable)), (@ peri_type + #[doc = "ETM peripheral singleton"] ETM <= SOC_ETM() (unstable)), (@ peri_type + #[doc = "SPI0 peripheral singleton"] SPI0 <= SPI0() (unstable)), (@ peri_type + #[doc = "SPI1 peripheral singleton"] SPI1 <= SPI1() (unstable)), (@ peri_type + #[doc = "SPI2 peripheral singleton"] SPI2 <= SPI2(SPI2 : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt })), (@ peri_type #[doc = + "SYSTEM peripheral singleton"] SYSTEM <= PCR() (unstable)), (@ peri_type #[doc = + "SYSTIMER peripheral singleton"] SYSTIMER <= SYSTIMER() (unstable)), (@ peri_type + #[doc = "TEE peripheral singleton"] TEE <= TEE() (unstable)), (@ peri_type #[doc + = "TIMG0 peripheral singleton"] TIMG0 <= TIMG0() (unstable)), (@ peri_type #[doc + = "TIMG1 peripheral singleton"] TIMG1 <= TIMG1() (unstable)), (@ peri_type #[doc + = "TRACE0 peripheral singleton"] TRACE0 <= TRACE() (unstable)), (@ peri_type + #[doc = "TWAI0 peripheral singleton"] TWAI0 <= TWAI0() (unstable)), (@ peri_type + #[doc = "TWAI1 peripheral singleton"] TWAI1 <= TWAI1() (unstable)), (@ peri_type + #[doc = "UART0 peripheral singleton"] UART0 <= UART0(UART0 : { + bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt })), (@ + peri_type #[doc = "UART1 peripheral singleton"] UART1 <= UART1(UART1 : { + bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt })), (@ + peri_type #[doc = "UHCI0 peripheral singleton"] UHCI0 <= UHCI0() (unstable)), (@ + peri_type #[doc = "USB_DEVICE peripheral singleton"] USB_DEVICE <= + USB_DEVICE(USB_DEVICE : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt }) (unstable)), (@ peri_type #[doc = + "ADC1 peripheral singleton"] ADC1 <= virtual() (unstable)), (@ peri_type #[doc = + "BT peripheral singleton"] BT <= virtual(LP_TIMER : { bind_lp_timer_interrupt, + enable_lp_timer_interrupt, disable_lp_timer_interrupt }, BT_MAC : { + bind_mac_interrupt, enable_mac_interrupt, disable_mac_interrupt }) (unstable)), + (@ peri_type #[doc = "FLASH peripheral singleton"] FLASH <= virtual() + (unstable)), (@ peri_type #[doc = "GPIO_DEDICATED peripheral singleton"] + GPIO_DEDICATED <= virtual() (unstable)), (@ peri_type #[doc = + "LP_CORE peripheral singleton"] LP_CORE <= virtual() (unstable)), (@ peri_type + #[doc = "TSENS peripheral singleton"] TSENS <= virtual() (unstable)), (@ + peri_type #[doc = "WIFI peripheral singleton"] WIFI <= virtual(WIFI_BB : { + bind_bb_interrupt, enable_bb_interrupt, disable_bb_interrupt }, WIFI_MAC : { + bind_mac_interrupt, enable_mac_interrupt, disable_mac_interrupt }, + MODEM_PERI_TIMEOUT : { bind_modem_peri_timeout_interrupt, enable_modem_peri_timeout_interrupt, disable_modem_peri_timeout_interrupt }, WIFI_PWR : { bind_pwr_interrupt, enable_pwr_interrupt, disable_pwr_interrupt })), (@ peri_type #[doc = "FROM_CPU_INTR0 peripheral singleton"] FROM_CPU_INTR0 <= @@ -6177,28 +7249,29 @@ macro_rules! for_each_peripheral { (GPIO15), (GPIO16), (GPIO17), (GPIO18), (GPIO19), (GPIO20), (GPIO21), (GPIO22), (GPIO23), (GPIO24), (GPIO25), (GPIO26), (GPIO27), (GPIO28), (GPIO29), (GPIO30), (DMA_CH0(unstable)), (DMA_CH1(unstable)), (DMA_CH2(unstable)), - (SDM_CH0(unstable)), (SDM_CH1(unstable)), (SDM_CH2(unstable)), - (SDM_CH3(unstable)), (AES(unstable)), (APB_SARADC(unstable)), - (ASSIST_DEBUG(unstable)), (ATOMIC(unstable)), (DMA(unstable)), (DS(unstable)), - (ECC(unstable)), (EXTMEM(unstable)), (GPIO(unstable)), (GPIO_SD(unstable)), - (HINF(unstable)), (HMAC(unstable)), (HP_APM(unstable)), (HP_SYS(unstable)), - (I2C_ANA_MST(unstable)), (I2C0), (I2S0(unstable)), (IEEE802154(unstable)), - (INTERRUPT_CORE0(unstable)), (INTPRI(unstable)), (IO_MUX(unstable)), - (LEDC(unstable)), (LP_ANA(unstable)), (LP_AON(unstable)), (LP_APM(unstable)), - (LP_APM0(unstable)), (LP_CLKRST(unstable)), (LP_I2C0(unstable)), - (LP_I2C_ANA_MST(unstable)), (LP_IO(unstable)), (LP_PERI(unstable)), - (LP_TEE(unstable)), (RTC_TIMER(unstable)), (LP_UART(unstable)), - (LP_WDT(unstable)), (LPWR(unstable)), (MCPWM0(unstable)), - (MEM_MONITOR(unstable)), (MODEM_LPCON(unstable)), (MODEM_SYSCON(unstable)), - (OTP_DEBUG(unstable)), (PARL_IO(unstable)), (PAU(unstable)), (PCNT(unstable)), - (PCR(unstable)), (PLIC_MX(unstable)), (PMU(unstable)), (RMT(unstable)), - (RNG(unstable)), (RSA(unstable)), (SHA(unstable)), (SLCHOST(unstable)), - (ETM(unstable)), (SPI0(unstable)), (SPI1(unstable)), (SPI2), (SYSTEM(unstable)), - (SYSTIMER(unstable)), (TEE(unstable)), (TIMG0(unstable)), (TIMG1(unstable)), - (TRACE0(unstable)), (TWAI0(unstable)), (TWAI1(unstable)), (UART0), (UART1), - (UHCI0(unstable)), (USB_DEVICE(unstable)), (ADC1(unstable)), (BT(unstable)), - (FLASH(unstable)), (GPIO_DEDICATED(unstable)), (LP_CORE(unstable)), - (TSENS(unstable)), (WIFI), (FROM_CPU_INTR0(unstable)), + (PCNT0_UNIT0(unstable)), (PCNT0_UNIT1(unstable)), (PCNT0_UNIT2(unstable)), + (PCNT0_UNIT3(unstable)), (SDM_CH0(unstable)), (SDM_CH1(unstable)), + (SDM_CH2(unstable)), (SDM_CH3(unstable)), (AES(unstable)), + (APB_SARADC(unstable)), (ASSIST_DEBUG(unstable)), (ATOMIC(unstable)), + (DMA(unstable)), (DS(unstable)), (ECC(unstable)), (EXTMEM(unstable)), + (GPIO(unstable)), (GPIO_SD(unstable)), (HINF(unstable)), (HMAC(unstable)), + (HP_APM(unstable)), (HP_SYS(unstable)), (I2C_ANA_MST(unstable)), (I2C0), + (I2S0(unstable)), (IEEE802154(unstable)), (INTERRUPT_CORE0(unstable)), + (INTPRI(unstable)), (IO_MUX(unstable)), (LEDC(unstable)), (LP_ANA(unstable)), + (LP_AON(unstable)), (LP_APM(unstable)), (LP_APM0(unstable)), + (LP_CLKRST(unstable)), (LP_I2C0(unstable)), (LP_I2C_ANA_MST(unstable)), + (LP_IO(unstable)), (LP_PERI(unstable)), (LP_TEE(unstable)), + (RTC_TIMER(unstable)), (LP_UART(unstable)), (LP_WDT(unstable)), (LPWR(unstable)), + (MCPWM0(unstable)), (MEM_MONITOR(unstable)), (MODEM_LPCON(unstable)), + (MODEM_SYSCON(unstable)), (OTP_DEBUG(unstable)), (PARL_IO(unstable)), + (PAU(unstable)), (PCNT(unstable)), (PCR(unstable)), (PLIC_MX(unstable)), + (PMU(unstable)), (RMT(unstable)), (RNG(unstable)), (RSA(unstable)), + (SHA(unstable)), (SLCHOST(unstable)), (ETM(unstable)), (SPI0(unstable)), + (SPI1(unstable)), (SPI2), (SYSTEM(unstable)), (SYSTIMER(unstable)), + (TEE(unstable)), (TIMG0(unstable)), (TIMG1(unstable)), (TRACE0(unstable)), + (TWAI0(unstable)), (TWAI1(unstable)), (UART0), (UART1), (UHCI0(unstable)), + (USB_DEVICE(unstable)), (ADC1(unstable)), (BT(unstable)), (FLASH(unstable)), + (GPIO_DEDICATED(unstable)), (LP_CORE(unstable)), (TSENS(unstable)), (WIFI), (FROM_CPU_INTR1(unstable)), (FROM_CPU_INTR2(unstable)), (FROM_CPU_INTR3(unstable)))); _for_each_inner_peripheral!((dma_eligible(SPI2, Spi2, 0, AhbGdmaChannel), (UHCI0, Uhci0, 2, AhbGdmaChannel), (I2S0, I2s0, 3, diff --git a/esp-metadata-generated/src/_generated_esp32c61.rs b/esp-metadata-generated/src/_generated_esp32c61.rs index 4a7771ddf6f..083f691129b 100644 --- a/esp-metadata-generated/src/_generated_esp32c61.rs +++ b/esp-metadata-generated/src/_generated_esp32c61.rs @@ -88,6 +88,9 @@ macro_rules! property { ("gpio.func_in_sel_offset", str) => { stringify!(0) }; + ("gpio.need_soft_isolate_during_pd") => { + false + }; ("gpio.has_bank_1") => { false }; @@ -235,12 +238,6 @@ macro_rules! property { ("i2s.version", str) => { stringify!(3) }; - ("i2s.default_clock_source") => { - 2 - }; - ("i2s.default_clock_source", str) => { - stringify!(2) - }; ("i2s.mclk_divider_bit_width") => { 9 }; @@ -292,15 +289,57 @@ macro_rules! property { ("wifi.csi_supported") => { true }; + ("wifi.has_nan") => { + true + }; + ("wifi.has_ftm") => { + true + }; ("phy.combo_module") => { true }; + ("adc.controller") => { + "digital" + }; + ("adc.channel_count") => { + 4 + }; + ("adc.channel_count", str) => { + stringify!(4) + }; + ("adc.line_calibration") => { + true + }; + ("adc.curve_calibration") => { + true + }; + ("adc.basic_calibration") => { + true + }; + ("adc.calibration_v1_scheme_supported") => { + true + }; + ("adc.channel_compensation") => { + true + }; + ("adc.pcr_clock") => { + true + }; + ("adc.pcr_sar_clk_div") => { + true + }; + ("adc.sar_power_override") => { + true + }; ("timergroup.timg_has_timer1") => { false }; ("timergroup.timg_has_divcnt_rst") => { true }; + ("timergroup.wdt_has_conf_update") => { + true + }; ("timergroup.rc_fast_calibration_divider_min_rev") => { 0 }; @@ -332,7 +371,7 @@ macro_rules! property { stringify!(16) }; ("rng.trng_supported") => { - false + true }; ("rng.is_lp_sys") => { true @@ -433,6 +472,9 @@ macro_rules! property { ("soc.cpu_has_csr_pc") => { false }; + ("soc.cpu_has_zcmp_workaround") => { + false + }; ("soc.multi_core_enabled") => { false }; @@ -454,6 +496,12 @@ macro_rules! property { ("soc.cpu_mcause_mask", str) => { stringify!(31) }; + ("soc.cpu_pmp_granularity") => { + 128 + }; + ("soc.cpu_pmp_granularity", str) => { + stringify!(128) + }; ("clock_tree.hp_root_clk") => { [crate ::soc::clocks::HpRootClkConfig::Xtal, crate ::soc::clocks::HpRootClkConfig::RcFast, crate @@ -474,15 +522,25 @@ macro_rules! property { ::soc::clocks::LpFastClkConfig::Xtal] }; ("clock_tree.lp_slow_clk") => { - [crate ::soc::clocks::LpSlowClkConfig::RcSlow, crate + [crate ::soc::clocks::LpSlowClkConfig::RcSlow, #[cfg(use_xtal32k)] crate ::soc::clocks::LpSlowClkConfig::Xtal32k, crate ::soc::clocks::LpSlowClkConfig::OscSlow] }; + ("clock_tree.ble_lp_clk") => { + [crate ::soc::clocks::BleLpClkConfig::Xtal, crate + ::soc::clocks::BleLpClkConfig::RcSlow, #[cfg(use_xtal32k)] crate + ::soc::clocks::BleLpClkConfig::Xtal32k] + }; + ("clock_tree.crypto_clk") => { + [crate ::soc::clocks::CryptoClkConfig::Xtal, crate + ::soc::clocks::CryptoClkConfig::RcFast, crate + ::soc::clocks::CryptoClkConfig::PllF480m] + }; ("clock_tree.timg_calibration_clock") => { [crate ::soc::clocks::TimgCalibrationClockConfig::OscSlowClk, crate ::soc::clocks::TimgCalibrationClockConfig::RcSlowClk, crate - ::soc::clocks::TimgCalibrationClockConfig::RcFastDivClk, crate - ::soc::clocks::TimgCalibrationClockConfig::Xtal32kClk] + ::soc::clocks::TimgCalibrationClockConfig::RcFastDivClk, #[cfg(use_xtal32k)] + crate ::soc::clocks::TimgCalibrationClockConfig::Xtal32kClk] }; ("clock_tree.uart.function_clock.sclk") => { [crate ::soc::clocks::UartFunctionClockSclk::Xtal, crate @@ -520,6 +578,41 @@ macro_rules! property { ::soc::clocks::SpiFunctionClockConfig::PllF160m, crate ::soc::clocks::SpiFunctionClockConfig::RcFast] }; + ("clock_tree.adc.function_clock") => { + [crate ::soc::clocks::AdcFunctionClockConfig::Xtal, crate + ::soc::clocks::AdcFunctionClockConfig::RcFast, crate + ::soc::clocks::AdcFunctionClockConfig::PllF80m] + }; + ("clock_tree.i2s.tx_clk.sclk") => { + [crate ::soc::clocks::I2sClkSclk::Xtal, crate + ::soc::clocks::I2sClkSclk::PllF120m, crate ::soc::clocks::I2sClkSclk::PllF160m] + }; + ("clock_tree.i2s.tx_clk.div_num") => { + (1, 255) + }; + ("clock_tree.i2s.tx_clk.div_a") => { + (1, 511) + }; + ("clock_tree.i2s.tx_clk.div_b") => { + (0, 511) + }; + ("clock_tree.i2s.rx_clk.sclk") => { + [crate ::soc::clocks::I2sClkSclk::Xtal, crate + ::soc::clocks::I2sClkSclk::PllF120m, crate ::soc::clocks::I2sClkSclk::PllF160m] + }; + ("clock_tree.i2s.rx_clk.div_num") => { + (1, 255) + }; + ("clock_tree.i2s.rx_clk.div_a") => { + (1, 511) + }; + ("clock_tree.i2s.rx_clk.div_b") => { + (0, 511) + }; + ("clock_tree.i2s.mclk_out") => { + [crate ::soc::clocks::I2sMclkOutConfig::Tx, crate + ::soc::clocks::I2sMclkOutConfig::Rx] + }; } #[macro_export] #[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] @@ -817,7 +910,7 @@ macro_rules! for_each_classified_interrupt { 2), ([reserved 2] 3), ([reserved 3] 4), ([reserved 4] 5), ([reserved 5] 6), ([reserved 6] 7), ([reserved 7] 8), ([reserved 8] 9), ([reserved 9] 10), ([reserved 10] 11), ([reserved 11] 12), ([reserved 12] 13), ([reserved 13] 14), - ([reserved 14] 15))); + ([reserved 14] 15))); _for_each_inner_classified_interrupt!((context_switch)); }; } #[macro_export] @@ -880,6 +973,7 @@ macro_rules! for_each_sw_interrupt { /// /// // XTAL32K_CLK /// +/// #[cfg(use_xtal32k)] /// fn enable_xtal32k_clk_impl(_clocks: &mut ClockTree, _en: bool) { /// todo!() /// } @@ -1028,6 +1122,52 @@ macro_rules! for_each_sw_interrupt { /// todo!() /// } /// +/// // BLE_LP_XTAL_CLK +/// +/// fn enable_ble_lp_xtal_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// // BLE_LP_RC_SLOW_CLK +/// +/// fn enable_ble_lp_rc_slow_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// // BLE_LP_CLK +/// +/// fn enable_ble_lp_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_ble_lp_clk_impl( +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: BleLpClkConfig, +/// ) { +/// todo!() +/// } +/// +/// // CRYPTO_PLL_DIV +/// +/// fn enable_crypto_pll_div_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// // CRYPTO_CLK +/// +/// fn enable_crypto_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_crypto_clk_impl( +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: CryptoClkConfig, +/// ) { +/// todo!() +/// } +/// /// // TIMG_CALIBRATION_CLOCK /// /// fn enable_timg_calibration_clock_impl(_clocks: &mut ClockTree, _en: bool) { @@ -1042,6 +1182,22 @@ macro_rules! for_each_sw_interrupt { /// todo!() /// } /// +/// impl AdcInstance { +/// // ADC_FUNCTION_CLOCK +/// +/// fn enable_function_clock_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_function_clock_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: AdcFunctionClockConfig, +/// ) { +/// todo!() +/// } +/// } /// impl I2cInstance { /// // I2C_FUNCTION_CLOCK /// @@ -1058,6 +1214,52 @@ macro_rules! for_each_sw_interrupt { /// todo!() /// } /// } +/// impl I2sInstance { +/// // I2S_TX_CLK +/// +/// fn enable_tx_clk_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_tx_clk_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: I2sClkConfig, +/// ) { +/// todo!() +/// } +/// +/// // I2S_RX_CLK +/// +/// fn enable_rx_clk_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_rx_clk_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: I2sClkConfig, +/// ) { +/// todo!() +/// } +/// +/// // I2S_MCLK_OUT +/// +/// fn enable_mclk_out_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_mclk_out_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: I2sMclkOutConfig, +/// ) { +/// todo!() +/// } +/// } /// impl SpiInstance { /// // SPI_FUNCTION_CLOCK /// @@ -1139,6 +1341,11 @@ macro_rules! for_each_sw_interrupt { /// ``` macro_rules! define_clock_tree_types { () => { + #[derive(Clone, Copy, PartialEq, Eq, Debug)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum AdcInstance { + ApbSaradc = 0, + } #[derive(Clone, Copy, PartialEq, Eq, Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum I2cInstance { @@ -1146,6 +1353,11 @@ macro_rules! define_clock_tree_types { } #[derive(Clone, Copy, PartialEq, Eq, Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum I2sInstance { + I2s0 = 0, + } + #[derive(Clone, Copy, PartialEq, Eq, Debug)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum SpiInstance { Spi2 = 0, } @@ -1209,7 +1421,7 @@ macro_rules! define_clock_tree_types { ); Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -1235,7 +1447,7 @@ macro_rules! define_clock_tree_types { ); Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -1261,7 +1473,7 @@ macro_rules! define_clock_tree_types { ); Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -1282,11 +1494,35 @@ macro_rules! define_clock_tree_types { pub enum LpSlowClkConfig { /// Selects `RC_SLOW_CLK`. RcSlow, + #[cfg(use_xtal32k)] /// Selects `XTAL32K_CLK`. Xtal32k, /// Selects `OSC_SLOW_CLK`. OscSlow, } + /// The list of clock signals that the `BLE_LP_CLK` multiplexer can output. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum BleLpClkConfig { + /// Selects `BLE_LP_XTAL_CLK`. + Xtal, + /// Selects `BLE_LP_RC_SLOW_CLK`. + RcSlow, + #[cfg(use_xtal32k)] + /// Selects `XTAL32K_CLK`. + Xtal32k, + } + /// The list of clock signals that the `CRYPTO_CLK` multiplexer can output. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum CryptoClkConfig { + /// Selects `XTAL_CLK`. + Xtal, + /// Selects `RC_FAST_CLK`. + RcFast, + /// Selects `CRYPTO_PLL_DIV`. + PllF480m, + } /// The list of clock signals that the `TIMG_CALIBRATION_CLOCK` multiplexer can output. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] @@ -1297,9 +1533,22 @@ macro_rules! define_clock_tree_types { RcSlowClk, /// Selects `RC_FAST_CLK`. RcFastDivClk, + #[cfg(use_xtal32k)] /// Selects `XTAL32K_CLK`. Xtal32kClk, } + /// The list of clock signals that the `APB_SARADC_FUNCTION_CLOCK` multiplexer can output. + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum AdcFunctionClockConfig { + /// Selects `XTAL_CLK`. + Xtal, + /// Selects `RC_FAST_CLK`. + RcFast, + #[default] + /// Selects `PLL_F80M`. + PllF80m, + } #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum I2cFunctionClockSclk { @@ -1332,20 +1581,98 @@ macro_rules! define_clock_tree_types { ); Self { sclk, div_num } } - pub(crate) fn sclk(self) -> I2cFunctionClockSclk { + pub fn sclk(self) -> I2cFunctionClockSclk { + self.sclk + } + pub fn div_num(self) -> u32 { + self.div_num as u32 + } + } + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum I2sClkSclk { + /// Selects `XTAL_CLK`. + Xtal, + /// Selects `PLL_F120M`. + PllF120m, + #[default] + /// Selects `PLL_F160M`. + PllF160m, + } + /// Configures the `I2S0_TX_CLK` clock node. + /// + /// The output is calculated as `OUTPUT = (sclk * div_a) / (div_num * div_a + div_b)`. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub struct I2sClkConfig { + sclk: I2sClkSclk, + div_num: u32, + div_a: u32, + div_b: u32, + } + impl I2sClkConfig { + /// Creates a new configuration for the TX_CLK clock node. + /// + /// ## Panics + /// + /// Panics if the div_num value is outside the + /// valid range (1 ..= 255). + /// + /// Panics if the div_a value is outside the + /// valid range (1 ..= 511). + /// + /// Panics if the div_b value is outside the + /// valid range (0 ..= 511). + pub const fn new(sclk: I2sClkSclk, div_num: u32, div_a: u32, div_b: u32) -> Self { + ::core::assert!( + div_num >= 1 && div_num <= 255, + "`I2S0_TX_CLK` div_num must be between 1 and 255 (inclusive)." + ); + ::core::assert!( + div_a >= 1 && div_a <= 511, + "`I2S0_TX_CLK` div_a must be between 1 and 511 (inclusive)." + ); + ::core::assert!( + div_b <= 511, + "`I2S0_TX_CLK` div_b must be between 0 and 511 (inclusive)." + ); + Self { + sclk, + div_num, + div_a, + div_b, + } + } + pub fn sclk(self) -> I2sClkSclk { self.sclk } - pub(crate) fn div_num(self) -> u32 { + pub fn div_num(self) -> u32 { self.div_num as u32 } + pub fn div_a(self) -> u32 { + self.div_a as u32 + } + pub fn div_b(self) -> u32 { + self.div_b as u32 + } + } + /// The list of clock signals that the `I2S0_MCLK_OUT` multiplexer can output. + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum I2sMclkOutConfig { + /// Selects `TX_CLK`. + Tx, + #[default] + /// Selects `RX_CLK`. + Rx, } /// The list of clock signals that the `SPI2_FUNCTION_CLOCK` multiplexer can output. #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum SpiFunctionClockConfig { - #[default] /// Selects `XTAL_CLK`. Xtal, + #[default] /// Selects `PLL_F160M`. PllF160m, /// Selects `RC_FAST_CLK`. @@ -1409,10 +1736,10 @@ macro_rules! define_clock_tree_types { ); Self { sclk, div_num } } - pub(crate) fn sclk(self) -> UartFunctionClockSclk { + pub fn sclk(self) -> UartFunctionClockSclk { self.sclk } - pub(crate) fn div_num(self) -> u32 { + pub fn div_num(self) -> u32 { self.div_num as u32 } } @@ -1450,10 +1777,10 @@ macro_rules! define_clock_tree_types { integral, } } - pub(crate) fn fractional(self) -> u32 { + pub fn fractional(self) -> u32 { self.fractional as u32 } - pub(crate) fn integral(self) -> u32 { + pub fn integral(self) -> u32 { self.integral as u32 } } @@ -1466,8 +1793,14 @@ macro_rules! define_clock_tree_types { apb_clk: Option, lp_fast_clk: Option, lp_slow_clk: Option, + ble_lp_clk: Option, + crypto_clk: Option, timg_calibration_clock: Option, + adc_function_clock: [Option; 1], i2c_function_clock: [Option; 1], + i2s_tx_clk: [Option; 1], + i2s_rx_clk: [Option; 1], + i2s_mclk_out: [Option; 1], spi_function_clock: [Option; 1], timg_function_clock: [Option; 2], timg_wdt_clock: [Option; 2], @@ -1475,6 +1808,7 @@ macro_rules! define_clock_tree_types { uart_baud_rate_generator: [Option; 3], rc_fast_clk_refcount: u32, pll_clk_refcount: u32, + #[cfg(use_xtal32k)] xtal32k_clk_refcount: u32, osc_slow_clk_refcount: u32, rc_slow_clk_refcount: u32, @@ -1490,8 +1824,14 @@ macro_rules! define_clock_tree_types { apb_clk_refcount: u32, lp_fast_clk_refcount: u32, lp_slow_clk_refcount: u32, + ble_lp_clk_refcount: u32, + crypto_clk_refcount: u32, timg_calibration_clock_refcount: u32, + adc_function_clock_refcount: [u32; 1], i2c_function_clock_refcount: [u32; 1], + i2s_tx_clk_refcount: [u32; 1], + i2s_rx_clk_refcount: [u32; 1], + i2s_mclk_out_refcount: [u32; 1], spi_function_clock_refcount: [u32; 1], timg_function_clock_refcount: [u32; 2], timg_wdt_clock_refcount: [u32; 2], @@ -1531,14 +1871,38 @@ macro_rules! define_clock_tree_types { pub fn lp_slow_clk(&self) -> Option { self.lp_slow_clk } + /// Returns the current configuration of the BLE_LP_CLK clock tree node + pub fn ble_lp_clk(&self) -> Option { + self.ble_lp_clk + } + /// Returns the current configuration of the CRYPTO_CLK clock tree node + pub fn crypto_clk(&self) -> Option { + self.crypto_clk + } /// Returns the current configuration of the TIMG_CALIBRATION_CLOCK clock tree node pub fn timg_calibration_clock(&self) -> Option { self.timg_calibration_clock } + /// Returns the current configuration of the APB_SARADC_FUNCTION_CLOCK clock tree node + pub fn apb_saradc_function_clock(&self) -> Option { + self.adc_function_clock[AdcInstance::ApbSaradc as usize] + } /// Returns the current configuration of the I2C0_FUNCTION_CLOCK clock tree node pub fn i2c0_function_clock(&self) -> Option { self.i2c_function_clock[I2cInstance::I2c0 as usize] } + /// Returns the current configuration of the I2S0_TX_CLK clock tree node + pub fn i2s0_tx_clk(&self) -> Option { + self.i2s_tx_clk[I2sInstance::I2s0 as usize] + } + /// Returns the current configuration of the I2S0_RX_CLK clock tree node + pub fn i2s0_rx_clk(&self) -> Option { + self.i2s_rx_clk[I2sInstance::I2s0 as usize] + } + /// Returns the current configuration of the I2S0_MCLK_OUT clock tree node + pub fn i2s0_mclk_out(&self) -> Option { + self.i2s_mclk_out[I2sInstance::I2s0 as usize] + } /// Returns the current configuration of the SPI2_FUNCTION_CLOCK clock tree node pub fn spi2_function_clock(&self) -> Option { self.spi_function_clock[SpiInstance::Spi2 as usize] @@ -1593,8 +1957,14 @@ macro_rules! define_clock_tree_types { apb_clk: None, lp_fast_clk: None, lp_slow_clk: None, + ble_lp_clk: None, + crypto_clk: None, timg_calibration_clock: None, + adc_function_clock: [None; 1], i2c_function_clock: [None; 1], + i2s_tx_clk: [None; 1], + i2s_rx_clk: [None; 1], + i2s_mclk_out: [None; 1], spi_function_clock: [None; 1], timg_function_clock: [None; 2], timg_wdt_clock: [None; 2], @@ -1602,6 +1972,7 @@ macro_rules! define_clock_tree_types { uart_baud_rate_generator: [None; 3], rc_fast_clk_refcount: 0, pll_clk_refcount: 0, + #[cfg(use_xtal32k)] xtal32k_clk_refcount: 0, osc_slow_clk_refcount: 0, rc_slow_clk_refcount: 0, @@ -1617,8 +1988,14 @@ macro_rules! define_clock_tree_types { apb_clk_refcount: 0, lp_fast_clk_refcount: 0, lp_slow_clk_refcount: 0, + ble_lp_clk_refcount: 0, + crypto_clk_refcount: 0, timg_calibration_clock_refcount: 0, + adc_function_clock_refcount: [0; 1], i2c_function_clock_refcount: [0; 1], + i2s_tx_clk_refcount: [0; 1], + i2s_rx_clk_refcount: [0; 1], + i2s_mclk_out_refcount: [0; 1], spi_function_clock_refcount: [0; 1], timg_function_clock_refcount: [0; 2], timg_wdt_clock_refcount: [0; 2], @@ -1639,10 +2016,22 @@ macro_rules! define_clock_tree_types { ::core::sync::atomic::AtomicU32::new(0); static LP_SLOW_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); + static BLE_LP_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(0); + static CRYPTO_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(0); static TIMG_CALIBRATION_CLOCK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); + static ADC_FUNCTION_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; static I2C_FUNCTION_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; + static I2S_TX_CLK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; + static I2S_RX_CLK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; + static I2S_MCLK_OUT_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; static SPI_FUNCTION_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; static TIMG_FUNCTION_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 2] = @@ -1653,6 +2042,164 @@ macro_rules! define_clock_tree_types { [const { ::core::sync::atomic::AtomicU32::new(0) }; 3]; static UART_BAUD_RATE_GENERATOR_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 3] = [const { ::core::sync::atomic::AtomicU32::new(0) }; 3]; + /// The clock sources of the device. + /// + /// A clock source is a node of the clock tree that other nodes derive their output + /// from. Ask a node which source it runs on with its `..._root_source` function. + #[derive(Debug, enumset::EnumSetType)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum ClockSource { + /// `XTAL_CLK`. + XtalClk, + /// `RC_FAST_CLK`. + RcFastClk, + #[cfg(use_xtal32k)] + /// `XTAL32K_CLK`. + Xtal32kClk, + /// `OSC_SLOW_CLK`. + OscSlowClk, + /// `RC_SLOW_CLK`. + RcSlowClk, + } + /// Returns the clock source that `XTAL_CLK` currently runs on. + pub fn xtal_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::XtalClk) + } + /// Returns the clock source that `RC_FAST_CLK` currently runs on. + pub fn rc_fast_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::RcFastClk) + } + /// Returns the clock source that `PLL_CLK` currently runs on. + pub fn pll_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + #[cfg(use_xtal32k)] + /// Returns the clock source that `XTAL32K_CLK` currently runs on. + pub fn xtal32k_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::Xtal32kClk) + } + /// Returns the clock source that `OSC_SLOW_CLK` currently runs on. + pub fn osc_slow_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::OscSlowClk) + } + /// Returns the clock source that `RC_SLOW_CLK` currently runs on. + pub fn rc_slow_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::RcSlowClk) + } + /// Returns the clock source that `PLL_F20M` currently runs on. + pub fn pll_f20m_root_source(clocks: &mut ClockTree) -> Option { + pll_clk_root_source(clocks) + } + /// Returns the clock source that `PLL_F40M` currently runs on. + pub fn pll_f40m_root_source(clocks: &mut ClockTree) -> Option { + pll_clk_root_source(clocks) + } + /// Returns the clock source that `PLL_F48M` currently runs on. + pub fn pll_f48m_root_source(clocks: &mut ClockTree) -> Option { + pll_clk_root_source(clocks) + } + /// Returns the clock source that `PLL_F60M` currently runs on. + pub fn pll_f60m_root_source(clocks: &mut ClockTree) -> Option { + pll_clk_root_source(clocks) + } + /// Returns the clock source that `PLL_F80M` currently runs on. + pub fn pll_f80m_root_source(clocks: &mut ClockTree) -> Option { + pll_clk_root_source(clocks) + } + /// Returns the clock source that `PLL_F120M` currently runs on. + pub fn pll_f120m_root_source(clocks: &mut ClockTree) -> Option { + pll_clk_root_source(clocks) + } + /// Returns the clock source that `PLL_F160M` currently runs on. + pub fn pll_f160m_root_source(clocks: &mut ClockTree) -> Option { + pll_clk_root_source(clocks) + } + /// Returns the clock source that `HP_ROOT_CLK` currently runs on. + pub fn hp_root_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.hp_root_clk?; + match config { + HpRootClkConfig::Xtal => xtal_clk_root_source(clocks), + HpRootClkConfig::RcFast => rc_fast_clk_root_source(clocks), + HpRootClkConfig::PllF160m => pll_f160m_root_source(clocks), + } + } + /// Returns the clock source that `CPU_CLK` currently runs on. + pub fn cpu_clk_root_source(clocks: &mut ClockTree) -> Option { + hp_root_clk_root_source(clocks) + } + /// Returns the clock source that `AHB_CLK` currently runs on. + pub fn ahb_clk_root_source(clocks: &mut ClockTree) -> Option { + hp_root_clk_root_source(clocks) + } + /// Returns the clock source that `APB_CLK` currently runs on. + pub fn apb_clk_root_source(clocks: &mut ClockTree) -> Option { + ahb_clk_root_source(clocks) + } + /// Returns the clock source that `XTAL_D2_CLK` currently runs on. + pub fn xtal_d2_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `LP_FAST_CLK` currently runs on. + pub fn lp_fast_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.lp_fast_clk?; + match config { + LpFastClkConfig::RcFast => rc_fast_clk_root_source(clocks), + LpFastClkConfig::XtalD2 => xtal_d2_clk_root_source(clocks), + LpFastClkConfig::Xtal => xtal_clk_root_source(clocks), + } + } + /// Returns the clock source that `LP_SLOW_CLK` currently runs on. + pub fn lp_slow_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.lp_slow_clk?; + match config { + LpSlowClkConfig::RcSlow => rc_slow_clk_root_source(clocks), + #[cfg(use_xtal32k)] + LpSlowClkConfig::Xtal32k => xtal32k_clk_root_source(clocks), + LpSlowClkConfig::OscSlow => osc_slow_clk_root_source(clocks), + } + } + /// Returns the clock source that `BLE_LP_XTAL_CLK` currently runs on. + pub fn ble_lp_xtal_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `BLE_LP_RC_SLOW_CLK` currently runs on. + pub fn ble_lp_rc_slow_clk_root_source(clocks: &mut ClockTree) -> Option { + rc_slow_clk_root_source(clocks) + } + /// Returns the clock source that `BLE_LP_CLK` currently runs on. + pub fn ble_lp_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.ble_lp_clk?; + match config { + BleLpClkConfig::Xtal => ble_lp_xtal_clk_root_source(clocks), + BleLpClkConfig::RcSlow => ble_lp_rc_slow_clk_root_source(clocks), + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => xtal32k_clk_root_source(clocks), + } + } + /// Returns the clock source that `CRYPTO_PLL_DIV` currently runs on. + pub fn crypto_pll_div_root_source(clocks: &mut ClockTree) -> Option { + pll_clk_root_source(clocks) + } + /// Returns the clock source that `CRYPTO_CLK` currently runs on. + pub fn crypto_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.crypto_clk?; + match config { + CryptoClkConfig::Xtal => xtal_clk_root_source(clocks), + CryptoClkConfig::RcFast => rc_fast_clk_root_source(clocks), + CryptoClkConfig::PllF480m => crypto_pll_div_root_source(clocks), + } + } + /// Returns the clock source that `TIMG_CALIBRATION_CLOCK` currently runs on. + pub fn timg_calibration_clock_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.timg_calibration_clock?; + match config { + TimgCalibrationClockConfig::OscSlowClk => osc_slow_clk_root_source(clocks), + TimgCalibrationClockConfig::RcSlowClk => rc_slow_clk_root_source(clocks), + TimgCalibrationClockConfig::RcFastDivClk => rc_fast_clk_root_source(clocks), + #[cfg(use_xtal32k)] + TimgCalibrationClockConfig::Xtal32kClk => xtal32k_clk_root_source(clocks), + } + } pub fn configure_xtal_clk(clocks: &mut ClockTree, config: XtalClkConfig) { let old_config = clocks.xtal_clk.replace(config); refresh_xtal_clk_downstream(clocks); @@ -1663,8 +2210,7 @@ macro_rules! define_clock_tree_types { } fn request_xtal_clk(_clocks: &mut ClockTree) {} fn release_xtal_clk(_clocks: &mut ClockTree) {} - #[allow(unused_variables)] - pub fn xtal_clk_config_frequency(clocks: &mut ClockTree, config: XtalClkConfig) -> u32 { + pub fn xtal_clk_config_frequency(config: XtalClkConfig) -> u32 { config.value() } pub fn xtal_clk_frequency() -> u32 { @@ -1684,10 +2230,31 @@ macro_rules! define_clock_tree_types { enable_rc_fast_clk_impl(clocks, false); } } - pub fn rc_fast_clk_frequency() -> u32 { + static RC_FAST_CLK_FREQUENCY: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(rc_fast_clk_nominal_frequency()); + pub const fn rc_fast_clk_nominal_frequency() -> u32 { 17500000 } - pub fn request_pll_clk(clocks: &mut ClockTree) { + pub fn rc_fast_clk_frequency() -> u32 { + RC_FAST_CLK_FREQUENCY.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn set_rc_fast_clk_frequency(clocks: &mut ClockTree, frequency: u32) { + if !(8750000..=26250000).contains(&frequency) { + warn!( + "Ignoring out-of-range RC_FAST_CLK frequency: {} Hz", + frequency + ); + return; + } + debug!( + "Updating RC_FAST_CLK frequency to {} Hz (nominal {} Hz)", + frequency, + rc_fast_clk_nominal_frequency() + ); + RC_FAST_CLK_FREQUENCY.store(frequency, ::core::sync::atomic::Ordering::Release); + refresh_rc_fast_clk_downstream(clocks); + } + pub fn request_pll_clk(clocks: &mut ClockTree) { trace!("Requesting PLL_CLK"); if increment_reference_count(&mut clocks.pll_clk_refcount) { trace!("Enabling PLL_CLK"); @@ -1709,6 +2276,7 @@ macro_rules! define_clock_tree_types { pub fn pll_clk_source_frequency() -> u32 { xtal_clk_frequency() } + #[cfg(use_xtal32k)] pub fn request_xtal32k_clk(clocks: &mut ClockTree) { trace!("Requesting XTAL32K_CLK"); if increment_reference_count(&mut clocks.xtal32k_clk_refcount) { @@ -1716,6 +2284,7 @@ macro_rules! define_clock_tree_types { enable_xtal32k_clk_impl(clocks, true); } } + #[cfg(use_xtal32k)] pub fn release_xtal32k_clk(clocks: &mut ClockTree) { trace!("Releasing XTAL32K_CLK"); if decrement_reference_count(&mut clocks.xtal32k_clk_refcount) { @@ -1723,6 +2292,7 @@ macro_rules! define_clock_tree_types { enable_xtal32k_clk_impl(clocks, false); } } + #[cfg(use_xtal32k)] pub fn xtal32k_clk_frequency() -> u32 { 32768 } @@ -1757,9 +2327,30 @@ macro_rules! define_clock_tree_types { enable_rc_slow_clk_impl(clocks, false); } } - pub fn rc_slow_clk_frequency() -> u32 { + static RC_SLOW_CLK_FREQUENCY: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(rc_slow_clk_nominal_frequency()); + pub const fn rc_slow_clk_nominal_frequency() -> u32 { 136000 } + pub fn rc_slow_clk_frequency() -> u32 { + RC_SLOW_CLK_FREQUENCY.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn set_rc_slow_clk_frequency(clocks: &mut ClockTree, frequency: u32) { + if !(68000..=204000).contains(&frequency) { + warn!( + "Ignoring out-of-range RC_SLOW_CLK frequency: {} Hz", + frequency + ); + return; + } + debug!( + "Updating RC_SLOW_CLK frequency to {} Hz (nominal {} Hz)", + frequency, + rc_slow_clk_nominal_frequency() + ); + RC_SLOW_CLK_FREQUENCY.store(frequency, ::core::sync::atomic::Ordering::Release); + refresh_rc_slow_clk_downstream(clocks); + } pub fn request_pll_f20m(clocks: &mut ClockTree) { trace!("Requesting PLL_F20M"); if increment_reference_count(&mut clocks.pll_f20m_refcount) { @@ -1917,22 +2508,21 @@ macro_rules! define_clock_tree_types { pub fn configure_hp_root_clk(clocks: &mut ClockTree, new_selector: HpRootClkConfig) { let old_selector = clocks.hp_root_clk.replace(new_selector); refresh_hp_root_clk_downstream(clocks); - if clocks.hp_root_clk_refcount > 0 { + let active = clocks.hp_root_clk_refcount > 0; + if active { match new_selector { HpRootClkConfig::Xtal => request_xtal_clk(clocks), HpRootClkConfig::RcFast => request_rc_fast_clk(clocks), HpRootClkConfig::PllF160m => request_pll_f160m(clocks), } - configure_hp_root_clk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - HpRootClkConfig::Xtal => release_xtal_clk(clocks), - HpRootClkConfig::RcFast => release_rc_fast_clk(clocks), - HpRootClkConfig::PllF160m => release_pll_f160m(clocks), - } + } + configure_hp_root_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + HpRootClkConfig::Xtal => release_xtal_clk(clocks), + HpRootClkConfig::RcFast => release_rc_fast_clk(clocks), + HpRootClkConfig::PllF160m => release_pll_f160m(clocks), } - } else { - configure_hp_root_clk_impl(clocks, old_selector, new_selector); } } pub fn hp_root_clk_config(clocks: &mut ClockTree) -> Option { @@ -1962,11 +2552,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn hp_root_clk_config_frequency( - clocks: &mut ClockTree, - config: HpRootClkConfig, - ) -> u32 { + pub fn hp_root_clk_config_frequency(config: HpRootClkConfig) -> u32 { match config { HpRootClkConfig::Xtal => xtal_clk_frequency(), HpRootClkConfig::RcFast => rc_fast_clk_frequency(), @@ -1977,11 +2563,7 @@ macro_rules! define_clock_tree_types { HP_ROOT_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn hp_root_clk_source_frequency(source: HpRootClkConfig) -> u32 { - match source { - HpRootClkConfig::Xtal => xtal_clk_frequency(), - HpRootClkConfig::RcFast => rc_fast_clk_frequency(), - HpRootClkConfig::PllF160m => pll_f160m_frequency(), - } + hp_root_clk_config_frequency(source) } pub fn configure_cpu_clk(clocks: &mut ClockTree, config: CpuClkConfig) { let old_config = clocks.cpu_clk.replace(config); @@ -2007,8 +2589,7 @@ macro_rules! define_clock_tree_types { release_hp_root_clk(clocks); } } - #[allow(unused_variables)] - pub fn cpu_clk_config_frequency(clocks: &mut ClockTree, config: CpuClkConfig) -> u32 { + pub fn cpu_clk_config_frequency(config: CpuClkConfig) -> u32 { (hp_root_clk_frequency() / (config.divisor() + 1)) } pub fn cpu_clk_frequency() -> u32 { @@ -2026,19 +2607,16 @@ macro_rules! define_clock_tree_types { clocks.ahb_clk } pub fn request_ahb_clk(clocks: &mut ClockTree) { - trace!("Requesting AHB_CLK"); trace!("Enabling AHB_CLK"); request_hp_root_clk(clocks); enable_ahb_clk_impl(clocks, true); } pub fn release_ahb_clk(clocks: &mut ClockTree) { - trace!("Releasing AHB_CLK"); trace!("Disabling AHB_CLK"); enable_ahb_clk_impl(clocks, false); release_hp_root_clk(clocks); } - #[allow(unused_variables)] - pub fn ahb_clk_config_frequency(clocks: &mut ClockTree, config: AhbClkConfig) -> u32 { + pub fn ahb_clk_config_frequency(config: AhbClkConfig) -> u32 { (hp_root_clk_frequency() / (config.divisor() + 1)) } pub fn ahb_clk_frequency() -> u32 { @@ -2071,8 +2649,7 @@ macro_rules! define_clock_tree_types { release_ahb_clk(clocks); } } - #[allow(unused_variables)] - pub fn apb_clk_config_frequency(clocks: &mut ClockTree, config: ApbClkConfig) -> u32 { + pub fn apb_clk_config_frequency(config: ApbClkConfig) -> u32 { (ahb_clk_frequency() / (config.divisor() + 1)) } pub fn apb_clk_frequency() -> u32 { @@ -2082,13 +2659,11 @@ macro_rules! define_clock_tree_types { ahb_clk_frequency() } pub fn request_xtal_d2_clk(clocks: &mut ClockTree) { - trace!("Requesting XTAL_D2_CLK"); trace!("Enabling XTAL_D2_CLK"); request_xtal_clk(clocks); enable_xtal_d2_clk_impl(clocks, true); } pub fn release_xtal_d2_clk(clocks: &mut ClockTree) { - trace!("Releasing XTAL_D2_CLK"); trace!("Disabling XTAL_D2_CLK"); enable_xtal_d2_clk_impl(clocks, false); release_xtal_clk(clocks); @@ -2102,22 +2677,21 @@ macro_rules! define_clock_tree_types { pub fn configure_lp_fast_clk(clocks: &mut ClockTree, new_selector: LpFastClkConfig) { let old_selector = clocks.lp_fast_clk.replace(new_selector); refresh_lp_fast_clk_downstream(clocks); - if clocks.lp_fast_clk_refcount > 0 { + let active = clocks.lp_fast_clk_refcount > 0; + if active { match new_selector { LpFastClkConfig::RcFast => request_rc_fast_clk(clocks), LpFastClkConfig::XtalD2 => request_xtal_d2_clk(clocks), LpFastClkConfig::Xtal => request_xtal_clk(clocks), } - configure_lp_fast_clk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - LpFastClkConfig::RcFast => release_rc_fast_clk(clocks), - LpFastClkConfig::XtalD2 => release_xtal_d2_clk(clocks), - LpFastClkConfig::Xtal => release_xtal_clk(clocks), - } + } + configure_lp_fast_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + LpFastClkConfig::RcFast => release_rc_fast_clk(clocks), + LpFastClkConfig::XtalD2 => release_xtal_d2_clk(clocks), + LpFastClkConfig::Xtal => release_xtal_clk(clocks), } - } else { - configure_lp_fast_clk_impl(clocks, old_selector, new_selector); } } pub fn lp_fast_clk_config(clocks: &mut ClockTree) -> Option { @@ -2147,11 +2721,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn lp_fast_clk_config_frequency( - clocks: &mut ClockTree, - config: LpFastClkConfig, - ) -> u32 { + pub fn lp_fast_clk_config_frequency(config: LpFastClkConfig) -> u32 { match config { LpFastClkConfig::RcFast => rc_fast_clk_frequency(), LpFastClkConfig::XtalD2 => xtal_d2_clk_frequency(), @@ -2162,31 +2732,28 @@ macro_rules! define_clock_tree_types { LP_FAST_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn lp_fast_clk_source_frequency(source: LpFastClkConfig) -> u32 { - match source { - LpFastClkConfig::RcFast => rc_fast_clk_frequency(), - LpFastClkConfig::XtalD2 => xtal_d2_clk_frequency(), - LpFastClkConfig::Xtal => xtal_clk_frequency(), - } + lp_fast_clk_config_frequency(source) } pub fn configure_lp_slow_clk(clocks: &mut ClockTree, new_selector: LpSlowClkConfig) { let old_selector = clocks.lp_slow_clk.replace(new_selector); refresh_lp_slow_clk_downstream(clocks); - if clocks.lp_slow_clk_refcount > 0 { + let active = clocks.lp_slow_clk_refcount > 0; + if active { match new_selector { LpSlowClkConfig::RcSlow => request_rc_slow_clk(clocks), + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => request_xtal32k_clk(clocks), LpSlowClkConfig::OscSlow => request_osc_slow_clk(clocks), } - configure_lp_slow_clk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - LpSlowClkConfig::RcSlow => release_rc_slow_clk(clocks), - LpSlowClkConfig::Xtal32k => release_xtal32k_clk(clocks), - LpSlowClkConfig::OscSlow => release_osc_slow_clk(clocks), - } + } + configure_lp_slow_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + LpSlowClkConfig::RcSlow => release_rc_slow_clk(clocks), + #[cfg(use_xtal32k)] + LpSlowClkConfig::Xtal32k => release_xtal32k_clk(clocks), + LpSlowClkConfig::OscSlow => release_osc_slow_clk(clocks), } - } else { - configure_lp_slow_clk_impl(clocks, old_selector, new_selector); } } pub fn lp_slow_clk_config(clocks: &mut ClockTree) -> Option { @@ -2198,6 +2765,7 @@ macro_rules! define_clock_tree_types { trace!("Enabling LP_SLOW_CLK"); match unwrap!(clocks.lp_slow_clk) { LpSlowClkConfig::RcSlow => request_rc_slow_clk(clocks), + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => request_xtal32k_clk(clocks), LpSlowClkConfig::OscSlow => request_osc_slow_clk(clocks), } @@ -2211,18 +2779,16 @@ macro_rules! define_clock_tree_types { enable_lp_slow_clk_impl(clocks, false); match unwrap!(clocks.lp_slow_clk) { LpSlowClkConfig::RcSlow => release_rc_slow_clk(clocks), + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => release_xtal32k_clk(clocks), LpSlowClkConfig::OscSlow => release_osc_slow_clk(clocks), } } } - #[allow(unused_variables)] - pub fn lp_slow_clk_config_frequency( - clocks: &mut ClockTree, - config: LpSlowClkConfig, - ) -> u32 { + pub fn lp_slow_clk_config_frequency(config: LpSlowClkConfig) -> u32 { match config { LpSlowClkConfig::RcSlow => rc_slow_clk_frequency(), + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => xtal32k_clk_frequency(), LpSlowClkConfig::OscSlow => osc_slow_clk_frequency(), } @@ -2231,36 +2797,206 @@ macro_rules! define_clock_tree_types { LP_SLOW_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn lp_slow_clk_source_frequency(source: LpSlowClkConfig) -> u32 { - match source { - LpSlowClkConfig::RcSlow => rc_slow_clk_frequency(), - LpSlowClkConfig::Xtal32k => xtal32k_clk_frequency(), - LpSlowClkConfig::OscSlow => osc_slow_clk_frequency(), + lp_slow_clk_config_frequency(source) + } + pub fn request_ble_lp_xtal_clk(clocks: &mut ClockTree) { + trace!("Enabling BLE_LP_XTAL_CLK"); + request_xtal_clk(clocks); + enable_ble_lp_xtal_clk_impl(clocks, true); + } + pub fn release_ble_lp_xtal_clk(clocks: &mut ClockTree) { + trace!("Disabling BLE_LP_XTAL_CLK"); + enable_ble_lp_xtal_clk_impl(clocks, false); + release_xtal_clk(clocks); + } + pub fn ble_lp_xtal_clk_frequency() -> u32 { + 100000 + } + pub fn ble_lp_xtal_clk_source_frequency() -> u32 { + xtal_clk_frequency() + } + pub fn request_ble_lp_rc_slow_clk(clocks: &mut ClockTree) { + trace!("Enabling BLE_LP_RC_SLOW_CLK"); + request_rc_slow_clk(clocks); + enable_ble_lp_rc_slow_clk_impl(clocks, true); + } + pub fn release_ble_lp_rc_slow_clk(clocks: &mut ClockTree) { + trace!("Disabling BLE_LP_RC_SLOW_CLK"); + enable_ble_lp_rc_slow_clk_impl(clocks, false); + release_rc_slow_clk(clocks); + } + pub fn ble_lp_rc_slow_clk_frequency() -> u32 { + (rc_slow_clk_frequency() / 5) + } + pub fn ble_lp_rc_slow_clk_source_frequency() -> u32 { + rc_slow_clk_frequency() + } + pub fn configure_ble_lp_clk(clocks: &mut ClockTree, new_selector: BleLpClkConfig) { + let old_selector = clocks.ble_lp_clk.replace(new_selector); + refresh_ble_lp_clk_downstream(clocks); + let active = clocks.ble_lp_clk_refcount > 0; + if active { + match new_selector { + BleLpClkConfig::Xtal => request_ble_lp_xtal_clk(clocks), + BleLpClkConfig::RcSlow => request_ble_lp_rc_slow_clk(clocks), + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => request_xtal32k_clk(clocks), + } + } + configure_ble_lp_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + BleLpClkConfig::Xtal => release_ble_lp_xtal_clk(clocks), + BleLpClkConfig::RcSlow => release_ble_lp_rc_slow_clk(clocks), + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => release_xtal32k_clk(clocks), + } + } + } + pub fn ble_lp_clk_config(clocks: &mut ClockTree) -> Option { + clocks.ble_lp_clk + } + pub fn request_ble_lp_clk(clocks: &mut ClockTree) { + trace!("Requesting BLE_LP_CLK"); + if increment_reference_count(&mut clocks.ble_lp_clk_refcount) { + trace!("Enabling BLE_LP_CLK"); + match unwrap!(clocks.ble_lp_clk) { + BleLpClkConfig::Xtal => request_ble_lp_xtal_clk(clocks), + BleLpClkConfig::RcSlow => request_ble_lp_rc_slow_clk(clocks), + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => request_xtal32k_clk(clocks), + } + enable_ble_lp_clk_impl(clocks, true); + } + } + pub fn release_ble_lp_clk(clocks: &mut ClockTree) { + trace!("Releasing BLE_LP_CLK"); + if decrement_reference_count(&mut clocks.ble_lp_clk_refcount) { + trace!("Disabling BLE_LP_CLK"); + enable_ble_lp_clk_impl(clocks, false); + match unwrap!(clocks.ble_lp_clk) { + BleLpClkConfig::Xtal => release_ble_lp_xtal_clk(clocks), + BleLpClkConfig::RcSlow => release_ble_lp_rc_slow_clk(clocks), + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => release_xtal32k_clk(clocks), + } } } + pub fn ble_lp_clk_config_frequency(config: BleLpClkConfig) -> u32 { + match config { + BleLpClkConfig::Xtal => ble_lp_xtal_clk_frequency(), + BleLpClkConfig::RcSlow => ble_lp_rc_slow_clk_frequency(), + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => xtal32k_clk_frequency(), + } + } + pub fn ble_lp_clk_frequency() -> u32 { + BLE_LP_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn ble_lp_clk_source_frequency(source: BleLpClkConfig) -> u32 { + ble_lp_clk_config_frequency(source) + } + pub fn request_crypto_pll_div(clocks: &mut ClockTree) { + trace!("Enabling CRYPTO_PLL_DIV"); + request_pll_clk(clocks); + enable_crypto_pll_div_impl(clocks, true); + } + pub fn release_crypto_pll_div(clocks: &mut ClockTree) { + trace!("Disabling CRYPTO_PLL_DIV"); + enable_crypto_pll_div_impl(clocks, false); + release_pll_clk(clocks); + } + pub fn crypto_pll_div_frequency() -> u32 { + (pll_clk_frequency() / 3) + } + pub fn crypto_pll_div_source_frequency() -> u32 { + pll_clk_frequency() + } + pub fn configure_crypto_clk(clocks: &mut ClockTree, new_selector: CryptoClkConfig) { + let old_selector = clocks.crypto_clk.replace(new_selector); + refresh_crypto_clk_downstream(clocks); + let active = clocks.crypto_clk_refcount > 0; + if active { + match new_selector { + CryptoClkConfig::Xtal => request_xtal_clk(clocks), + CryptoClkConfig::RcFast => request_rc_fast_clk(clocks), + CryptoClkConfig::PllF480m => request_crypto_pll_div(clocks), + } + } + configure_crypto_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + CryptoClkConfig::Xtal => release_xtal_clk(clocks), + CryptoClkConfig::RcFast => release_rc_fast_clk(clocks), + CryptoClkConfig::PllF480m => release_crypto_pll_div(clocks), + } + } + } + pub fn crypto_clk_config(clocks: &mut ClockTree) -> Option { + clocks.crypto_clk + } + pub fn request_crypto_clk(clocks: &mut ClockTree) { + trace!("Requesting CRYPTO_CLK"); + if increment_reference_count(&mut clocks.crypto_clk_refcount) { + trace!("Enabling CRYPTO_CLK"); + match unwrap!(clocks.crypto_clk) { + CryptoClkConfig::Xtal => request_xtal_clk(clocks), + CryptoClkConfig::RcFast => request_rc_fast_clk(clocks), + CryptoClkConfig::PllF480m => request_crypto_pll_div(clocks), + } + enable_crypto_clk_impl(clocks, true); + } + } + pub fn release_crypto_clk(clocks: &mut ClockTree) { + trace!("Releasing CRYPTO_CLK"); + if decrement_reference_count(&mut clocks.crypto_clk_refcount) { + trace!("Disabling CRYPTO_CLK"); + enable_crypto_clk_impl(clocks, false); + match unwrap!(clocks.crypto_clk) { + CryptoClkConfig::Xtal => release_xtal_clk(clocks), + CryptoClkConfig::RcFast => release_rc_fast_clk(clocks), + CryptoClkConfig::PllF480m => release_crypto_pll_div(clocks), + } + } + } + pub fn crypto_clk_config_frequency(config: CryptoClkConfig) -> u32 { + match config { + CryptoClkConfig::Xtal => xtal_clk_frequency(), + CryptoClkConfig::RcFast => rc_fast_clk_frequency(), + CryptoClkConfig::PllF480m => crypto_pll_div_frequency(), + } + } + pub fn crypto_clk_frequency() -> u32 { + CRYPTO_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn crypto_clk_source_frequency(source: CryptoClkConfig) -> u32 { + crypto_clk_config_frequency(source) + } pub fn configure_timg_calibration_clock( clocks: &mut ClockTree, new_selector: TimgCalibrationClockConfig, ) { let old_selector = clocks.timg_calibration_clock.replace(new_selector); refresh_timg_calibration_clock_downstream(clocks); - if clocks.timg_calibration_clock_refcount > 0 { + let active = clocks.timg_calibration_clock_refcount > 0; + if active { match new_selector { TimgCalibrationClockConfig::OscSlowClk => request_osc_slow_clk(clocks), TimgCalibrationClockConfig::RcSlowClk => request_rc_slow_clk(clocks), TimgCalibrationClockConfig::RcFastDivClk => request_rc_fast_clk(clocks), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => request_xtal32k_clk(clocks), } - configure_timg_calibration_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - TimgCalibrationClockConfig::OscSlowClk => release_osc_slow_clk(clocks), - TimgCalibrationClockConfig::RcSlowClk => release_rc_slow_clk(clocks), - TimgCalibrationClockConfig::RcFastDivClk => release_rc_fast_clk(clocks), - TimgCalibrationClockConfig::Xtal32kClk => release_xtal32k_clk(clocks), - } + } + configure_timg_calibration_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + TimgCalibrationClockConfig::OscSlowClk => release_osc_slow_clk(clocks), + TimgCalibrationClockConfig::RcSlowClk => release_rc_slow_clk(clocks), + TimgCalibrationClockConfig::RcFastDivClk => release_rc_fast_clk(clocks), + #[cfg(use_xtal32k)] + TimgCalibrationClockConfig::Xtal32kClk => release_xtal32k_clk(clocks), } - } else { - configure_timg_calibration_clock_impl(clocks, old_selector, new_selector); } } pub fn timg_calibration_clock_config( @@ -2277,6 +3013,7 @@ macro_rules! define_clock_tree_types { TimgCalibrationClockConfig::OscSlowClk => request_osc_slow_clk(clocks), TimgCalibrationClockConfig::RcSlowClk => request_rc_slow_clk(clocks), TimgCalibrationClockConfig::RcFastDivClk => request_rc_fast_clk(clocks), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => request_xtal32k_clk(clocks), } enable_timg_calibration_clock_impl(clocks, true); @@ -2292,19 +3029,17 @@ macro_rules! define_clock_tree_types { TimgCalibrationClockConfig::OscSlowClk => release_osc_slow_clk(clocks), TimgCalibrationClockConfig::RcSlowClk => release_rc_slow_clk(clocks), TimgCalibrationClockConfig::RcFastDivClk => release_rc_fast_clk(clocks), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => release_xtal32k_clk(clocks), } } } - #[allow(unused_variables)] - pub fn timg_calibration_clock_config_frequency( - clocks: &mut ClockTree, - config: TimgCalibrationClockConfig, - ) -> u32 { + pub fn timg_calibration_clock_config_frequency(config: TimgCalibrationClockConfig) -> u32 { match config { TimgCalibrationClockConfig::OscSlowClk => osc_slow_clk_frequency(), TimgCalibrationClockConfig::RcSlowClk => rc_slow_clk_frequency(), TimgCalibrationClockConfig::RcFastDivClk => rc_fast_clk_frequency(), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => xtal32k_clk_frequency(), } } @@ -2312,11 +3047,78 @@ macro_rules! define_clock_tree_types { TIMG_CALIBRATION_CLOCK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn timg_calibration_clock_source_frequency(source: TimgCalibrationClockConfig) -> u32 { - match source { - TimgCalibrationClockConfig::OscSlowClk => osc_slow_clk_frequency(), - TimgCalibrationClockConfig::RcSlowClk => rc_slow_clk_frequency(), - TimgCalibrationClockConfig::RcFastDivClk => rc_fast_clk_frequency(), - TimgCalibrationClockConfig::Xtal32kClk => xtal32k_clk_frequency(), + timg_calibration_clock_config_frequency(source) + } + impl AdcInstance { + pub fn configure_function_clock( + self, + clocks: &mut ClockTree, + new_selector: AdcFunctionClockConfig, + ) { + let old_selector = clocks.adc_function_clock[self as usize].replace(new_selector); + refresh_adc_function_clock_downstream(clocks, self); + let active = clocks.adc_function_clock_refcount[self as usize] > 0; + if active { + match new_selector { + AdcFunctionClockConfig::Xtal => request_xtal_clk(clocks), + AdcFunctionClockConfig::RcFast => request_rc_fast_clk(clocks), + AdcFunctionClockConfig::PllF80m => request_pll_f80m(clocks), + } + } + self.configure_function_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + AdcFunctionClockConfig::Xtal => release_xtal_clk(clocks), + AdcFunctionClockConfig::RcFast => release_rc_fast_clk(clocks), + AdcFunctionClockConfig::PllF80m => release_pll_f80m(clocks), + } + } + } + pub fn function_clock_config( + self, + clocks: &mut ClockTree, + ) -> Option { + clocks.adc_function_clock[self as usize] + } + pub fn request_function_clock(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::FUNCTION_CLOCK", self); + if increment_reference_count(&mut clocks.adc_function_clock_refcount[self as usize]) + { + trace!("Enabling {:?}::FUNCTION_CLOCK", self); + match unwrap!(clocks.adc_function_clock[self as usize]) { + AdcFunctionClockConfig::Xtal => request_xtal_clk(clocks), + AdcFunctionClockConfig::RcFast => request_rc_fast_clk(clocks), + AdcFunctionClockConfig::PllF80m => request_pll_f80m(clocks), + } + self.enable_function_clock_impl(clocks, true); + } + } + pub fn release_function_clock(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::FUNCTION_CLOCK", self); + if decrement_reference_count(&mut clocks.adc_function_clock_refcount[self as usize]) + { + trace!("Disabling {:?}::FUNCTION_CLOCK", self); + self.enable_function_clock_impl(clocks, false); + match unwrap!(clocks.adc_function_clock[self as usize]) { + AdcFunctionClockConfig::Xtal => release_xtal_clk(clocks), + AdcFunctionClockConfig::RcFast => release_rc_fast_clk(clocks), + AdcFunctionClockConfig::PllF80m => release_pll_f80m(clocks), + } + } + } + pub fn function_clock_config_frequency(config: AdcFunctionClockConfig) -> u32 { + match config { + AdcFunctionClockConfig::Xtal => xtal_clk_frequency(), + AdcFunctionClockConfig::RcFast => rc_fast_clk_frequency(), + AdcFunctionClockConfig::PllF80m => pll_f80m_frequency(), + } + } + pub fn function_clock_frequency(self) -> u32 { + ADC_FUNCTION_CLOCK_FREQ_CACHE[self as usize] + .load(::core::sync::atomic::Ordering::Acquire) + } + pub fn function_clock_source_frequency(source: AdcFunctionClockConfig) -> u32 { + Self::function_clock_config_frequency(source) } } impl I2cInstance { @@ -2327,20 +3129,19 @@ macro_rules! define_clock_tree_types { ) { let old_config = clocks.i2c_function_clock[self as usize].replace(config); refresh_i2c_function_clock_downstream(clocks, self); - if clocks.i2c_function_clock_refcount[self as usize] > 0 { + let active = clocks.i2c_function_clock_refcount[self as usize] > 0; + if active { match config.sclk { I2cFunctionClockSclk::Xtal => request_xtal_clk(clocks), I2cFunctionClockSclk::RcFast => request_rc_fast_clk(clocks), } - self.configure_function_clock_impl(clocks, old_config, config); - if let Some(old_config) = old_config { - match old_config.sclk { - I2cFunctionClockSclk::Xtal => release_xtal_clk(clocks), - I2cFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), - } + } + self.configure_function_clock_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + I2cFunctionClockSclk::Xtal => release_xtal_clk(clocks), + I2cFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_config, config); } } pub fn function_clock_config( @@ -2373,11 +3174,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: I2cFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: I2cFunctionClockConfig) -> u32 { (match config.sclk { I2cFunctionClockSclk::Xtal => xtal_clk_frequency(), I2cFunctionClockSclk::RcFast => rc_fast_clk_frequency(), @@ -2394,6 +3191,202 @@ macro_rules! define_clock_tree_types { } } } + impl I2sInstance { + pub fn configure_tx_clk(self, clocks: &mut ClockTree, config: I2sClkConfig) { + let old_config = clocks.i2s_tx_clk[self as usize].replace(config); + refresh_i2s_tx_clk_downstream(clocks, self); + let active = clocks.i2s_tx_clk_refcount[self as usize] > 0; + if active { + match config.sclk { + I2sClkSclk::Xtal => request_xtal_clk(clocks), + I2sClkSclk::PllF120m => request_pll_f120m(clocks), + I2sClkSclk::PllF160m => request_pll_f160m(clocks), + } + } + self.configure_tx_clk_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + I2sClkSclk::Xtal => release_xtal_clk(clocks), + I2sClkSclk::PllF120m => release_pll_f120m(clocks), + I2sClkSclk::PllF160m => release_pll_f160m(clocks), + } + } + } + pub fn tx_clk_config(self, clocks: &mut ClockTree) -> Option { + clocks.i2s_tx_clk[self as usize] + } + pub fn request_tx_clk(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::TX_CLK", self); + if increment_reference_count(&mut clocks.i2s_tx_clk_refcount[self as usize]) { + trace!("Enabling {:?}::TX_CLK", self); + crate::rtc_cntl::WakeLock::acquire(); + match unwrap!(clocks.i2s_tx_clk[self as usize]).sclk { + I2sClkSclk::Xtal => request_xtal_clk(clocks), + I2sClkSclk::PllF120m => request_pll_f120m(clocks), + I2sClkSclk::PllF160m => request_pll_f160m(clocks), + } + self.enable_tx_clk_impl(clocks, true); + } + } + pub fn release_tx_clk(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::TX_CLK", self); + if decrement_reference_count(&mut clocks.i2s_tx_clk_refcount[self as usize]) { + trace!("Disabling {:?}::TX_CLK", self); + crate::rtc_cntl::WakeLock::release(); + self.enable_tx_clk_impl(clocks, false); + match unwrap!(clocks.i2s_tx_clk[self as usize]).sclk { + I2sClkSclk::Xtal => release_xtal_clk(clocks), + I2sClkSclk::PllF120m => release_pll_f120m(clocks), + I2sClkSclk::PllF160m => release_pll_f160m(clocks), + } + } + } + pub fn tx_clk_config_frequency(config: I2sClkConfig) -> u32 { + (((match config.sclk { + I2sClkSclk::Xtal => xtal_clk_frequency(), + I2sClkSclk::PllF120m => pll_f120m_frequency(), + I2sClkSclk::PllF160m => pll_f160m_frequency(), + } as u64) + * (config.div_a() as u64)) + / (((config.div_num() * config.div_a()) + config.div_b()) as u64)) + as u32 + } + pub fn tx_clk_frequency(self) -> u32 { + I2S_TX_CLK_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) + } + pub fn tx_clk_source_frequency(sclk: I2sClkSclk) -> u32 { + match sclk { + I2sClkSclk::Xtal => xtal_clk_frequency(), + I2sClkSclk::PllF120m => pll_f120m_frequency(), + I2sClkSclk::PllF160m => pll_f160m_frequency(), + } + } + pub fn configure_rx_clk(self, clocks: &mut ClockTree, config: I2sClkConfig) { + let old_config = clocks.i2s_rx_clk[self as usize].replace(config); + refresh_i2s_rx_clk_downstream(clocks, self); + let active = clocks.i2s_rx_clk_refcount[self as usize] > 0; + if active { + match config.sclk { + I2sClkSclk::Xtal => request_xtal_clk(clocks), + I2sClkSclk::PllF120m => request_pll_f120m(clocks), + I2sClkSclk::PllF160m => request_pll_f160m(clocks), + } + } + self.configure_rx_clk_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + I2sClkSclk::Xtal => release_xtal_clk(clocks), + I2sClkSclk::PllF120m => release_pll_f120m(clocks), + I2sClkSclk::PllF160m => release_pll_f160m(clocks), + } + } + } + pub fn rx_clk_config(self, clocks: &mut ClockTree) -> Option { + clocks.i2s_rx_clk[self as usize] + } + pub fn request_rx_clk(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::RX_CLK", self); + if increment_reference_count(&mut clocks.i2s_rx_clk_refcount[self as usize]) { + trace!("Enabling {:?}::RX_CLK", self); + crate::rtc_cntl::WakeLock::acquire(); + match unwrap!(clocks.i2s_rx_clk[self as usize]).sclk { + I2sClkSclk::Xtal => request_xtal_clk(clocks), + I2sClkSclk::PllF120m => request_pll_f120m(clocks), + I2sClkSclk::PllF160m => request_pll_f160m(clocks), + } + self.enable_rx_clk_impl(clocks, true); + } + } + pub fn release_rx_clk(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::RX_CLK", self); + if decrement_reference_count(&mut clocks.i2s_rx_clk_refcount[self as usize]) { + trace!("Disabling {:?}::RX_CLK", self); + crate::rtc_cntl::WakeLock::release(); + self.enable_rx_clk_impl(clocks, false); + match unwrap!(clocks.i2s_rx_clk[self as usize]).sclk { + I2sClkSclk::Xtal => release_xtal_clk(clocks), + I2sClkSclk::PllF120m => release_pll_f120m(clocks), + I2sClkSclk::PllF160m => release_pll_f160m(clocks), + } + } + } + pub fn rx_clk_config_frequency(config: I2sClkConfig) -> u32 { + (((match config.sclk { + I2sClkSclk::Xtal => xtal_clk_frequency(), + I2sClkSclk::PllF120m => pll_f120m_frequency(), + I2sClkSclk::PllF160m => pll_f160m_frequency(), + } as u64) + * (config.div_a() as u64)) + / (((config.div_num() * config.div_a()) + config.div_b()) as u64)) + as u32 + } + pub fn rx_clk_frequency(self) -> u32 { + I2S_RX_CLK_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) + } + pub fn rx_clk_source_frequency(sclk: I2sClkSclk) -> u32 { + match sclk { + I2sClkSclk::Xtal => xtal_clk_frequency(), + I2sClkSclk::PllF120m => pll_f120m_frequency(), + I2sClkSclk::PllF160m => pll_f160m_frequency(), + } + } + pub fn configure_mclk_out( + self, + clocks: &mut ClockTree, + new_selector: I2sMclkOutConfig, + ) { + let old_selector = clocks.i2s_mclk_out[self as usize].replace(new_selector); + refresh_i2s_mclk_out_downstream(clocks, self); + let active = clocks.i2s_mclk_out_refcount[self as usize] > 0; + if active { + match new_selector { + I2sMclkOutConfig::Tx => self.request_tx_clk(clocks), + I2sMclkOutConfig::Rx => self.request_rx_clk(clocks), + } + } + self.configure_mclk_out_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + I2sMclkOutConfig::Tx => self.release_tx_clk(clocks), + I2sMclkOutConfig::Rx => self.release_rx_clk(clocks), + } + } + } + pub fn mclk_out_config(self, clocks: &mut ClockTree) -> Option { + clocks.i2s_mclk_out[self as usize] + } + pub fn request_mclk_out(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::MCLK_OUT", self); + if increment_reference_count(&mut clocks.i2s_mclk_out_refcount[self as usize]) { + trace!("Enabling {:?}::MCLK_OUT", self); + match unwrap!(clocks.i2s_mclk_out[self as usize]) { + I2sMclkOutConfig::Tx => self.request_tx_clk(clocks), + I2sMclkOutConfig::Rx => self.request_rx_clk(clocks), + } + self.enable_mclk_out_impl(clocks, true); + } + } + pub fn release_mclk_out(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::MCLK_OUT", self); + if decrement_reference_count(&mut clocks.i2s_mclk_out_refcount[self as usize]) { + trace!("Disabling {:?}::MCLK_OUT", self); + self.enable_mclk_out_impl(clocks, false); + match unwrap!(clocks.i2s_mclk_out[self as usize]) { + I2sMclkOutConfig::Tx => self.release_tx_clk(clocks), + I2sMclkOutConfig::Rx => self.release_rx_clk(clocks), + } + } + } + pub fn mclk_out_config_frequency(self, config: I2sMclkOutConfig) -> u32 { + match config { + I2sMclkOutConfig::Tx => self.tx_clk_frequency(), + I2sMclkOutConfig::Rx => self.rx_clk_frequency(), + } + } + pub fn mclk_out_frequency(self) -> u32 { + I2S_MCLK_OUT_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) + } + } impl SpiInstance { pub fn configure_function_clock( self, @@ -2402,22 +3395,21 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.spi_function_clock[self as usize].replace(new_selector); refresh_spi_function_clock_downstream(clocks, self); - if clocks.spi_function_clock_refcount[self as usize] > 0 { + let active = clocks.spi_function_clock_refcount[self as usize] > 0; + if active { match new_selector { SpiFunctionClockConfig::Xtal => request_xtal_clk(clocks), SpiFunctionClockConfig::PllF160m => request_pll_f160m(clocks), SpiFunctionClockConfig::RcFast => request_rc_fast_clk(clocks), } - self.configure_function_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - SpiFunctionClockConfig::Xtal => release_xtal_clk(clocks), - SpiFunctionClockConfig::PllF160m => release_pll_f160m(clocks), - SpiFunctionClockConfig::RcFast => release_rc_fast_clk(clocks), - } + } + self.configure_function_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + SpiFunctionClockConfig::Xtal => release_xtal_clk(clocks), + SpiFunctionClockConfig::PllF160m => release_pll_f160m(clocks), + SpiFunctionClockConfig::RcFast => release_rc_fast_clk(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_selector, new_selector); } } pub fn function_clock_config( @@ -2452,11 +3444,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: SpiFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: SpiFunctionClockConfig) -> u32 { match config { SpiFunctionClockConfig::Xtal => xtal_clk_frequency(), SpiFunctionClockConfig::PllF160m => pll_f160m_frequency(), @@ -2468,11 +3456,7 @@ macro_rules! define_clock_tree_types { .load(::core::sync::atomic::Ordering::Acquire) } pub fn function_clock_source_frequency(source: SpiFunctionClockConfig) -> u32 { - match source { - SpiFunctionClockConfig::Xtal => xtal_clk_frequency(), - SpiFunctionClockConfig::PllF160m => pll_f160m_frequency(), - SpiFunctionClockConfig::RcFast => rc_fast_clk_frequency(), - } + Self::function_clock_config_frequency(source) } } impl TimgInstance { @@ -2483,22 +3467,21 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.timg_function_clock[self as usize].replace(new_selector); refresh_timg_function_clock_downstream(clocks, self); - if clocks.timg_function_clock_refcount[self as usize] > 0 { + let active = clocks.timg_function_clock_refcount[self as usize] > 0; + if active { match new_selector { TimgFunctionClockConfig::XtalClk => request_xtal_clk(clocks), TimgFunctionClockConfig::RcFastClk => request_rc_fast_clk(clocks), TimgFunctionClockConfig::PllF80m => request_pll_f80m(clocks), } - self.configure_function_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - TimgFunctionClockConfig::XtalClk => release_xtal_clk(clocks), - TimgFunctionClockConfig::RcFastClk => release_rc_fast_clk(clocks), - TimgFunctionClockConfig::PllF80m => release_pll_f80m(clocks), - } + } + self.configure_function_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + TimgFunctionClockConfig::XtalClk => release_xtal_clk(clocks), + TimgFunctionClockConfig::RcFastClk => release_rc_fast_clk(clocks), + TimgFunctionClockConfig::PllF80m => release_pll_f80m(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_selector, new_selector); } } pub fn function_clock_config( @@ -2535,11 +3518,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: TimgFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: TimgFunctionClockConfig) -> u32 { match config { TimgFunctionClockConfig::XtalClk => xtal_clk_frequency(), TimgFunctionClockConfig::RcFastClk => rc_fast_clk_frequency(), @@ -2551,11 +3530,7 @@ macro_rules! define_clock_tree_types { .load(::core::sync::atomic::Ordering::Acquire) } pub fn function_clock_source_frequency(source: TimgFunctionClockConfig) -> u32 { - match source { - TimgFunctionClockConfig::XtalClk => xtal_clk_frequency(), - TimgFunctionClockConfig::RcFastClk => rc_fast_clk_frequency(), - TimgFunctionClockConfig::PllF80m => pll_f80m_frequency(), - } + Self::function_clock_config_frequency(source) } pub fn configure_wdt_clock( self, @@ -2564,22 +3539,21 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.timg_wdt_clock[self as usize].replace(new_selector); refresh_timg_wdt_clock_downstream(clocks, self); - if clocks.timg_wdt_clock_refcount[self as usize] > 0 { + let active = clocks.timg_wdt_clock_refcount[self as usize] > 0; + if active { match new_selector { TimgWdtClockConfig::XtalClk => request_xtal_clk(clocks), TimgWdtClockConfig::RcFastClk => request_rc_fast_clk(clocks), TimgWdtClockConfig::PllF80m => request_pll_f80m(clocks), } - self.configure_wdt_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - TimgWdtClockConfig::XtalClk => release_xtal_clk(clocks), - TimgWdtClockConfig::RcFastClk => release_rc_fast_clk(clocks), - TimgWdtClockConfig::PllF80m => release_pll_f80m(clocks), - } + } + self.configure_wdt_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + TimgWdtClockConfig::XtalClk => release_xtal_clk(clocks), + TimgWdtClockConfig::RcFastClk => release_rc_fast_clk(clocks), + TimgWdtClockConfig::PllF80m => release_pll_f80m(clocks), } - } else { - self.configure_wdt_clock_impl(clocks, old_selector, new_selector); } } pub fn wdt_clock_config(self, clocks: &mut ClockTree) -> Option { @@ -2609,11 +3583,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn wdt_clock_config_frequency( - clocks: &mut ClockTree, - config: TimgWdtClockConfig, - ) -> u32 { + pub fn wdt_clock_config_frequency(config: TimgWdtClockConfig) -> u32 { match config { TimgWdtClockConfig::XtalClk => xtal_clk_frequency(), TimgWdtClockConfig::RcFastClk => rc_fast_clk_frequency(), @@ -2625,11 +3595,7 @@ macro_rules! define_clock_tree_types { .load(::core::sync::atomic::Ordering::Acquire) } pub fn wdt_clock_source_frequency(source: TimgWdtClockConfig) -> u32 { - match source { - TimgWdtClockConfig::XtalClk => xtal_clk_frequency(), - TimgWdtClockConfig::RcFastClk => rc_fast_clk_frequency(), - TimgWdtClockConfig::PllF80m => pll_f80m_frequency(), - } + Self::wdt_clock_config_frequency(source) } } impl UartInstance { @@ -2640,22 +3606,21 @@ macro_rules! define_clock_tree_types { ) { let old_config = clocks.uart_function_clock[self as usize].replace(config); refresh_uart_function_clock_downstream(clocks, self); - if clocks.uart_function_clock_refcount[self as usize] > 0 { + let active = clocks.uart_function_clock_refcount[self as usize] > 0; + if active { match config.sclk { UartFunctionClockSclk::Xtal => request_xtal_clk(clocks), UartFunctionClockSclk::PllF80m => request_pll_f80m(clocks), UartFunctionClockSclk::RcFast => request_rc_fast_clk(clocks), } - self.configure_function_clock_impl(clocks, old_config, config); - if let Some(old_config) = old_config { - match old_config.sclk { - UartFunctionClockSclk::Xtal => release_xtal_clk(clocks), - UartFunctionClockSclk::PllF80m => release_pll_f80m(clocks), - UartFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), - } + } + self.configure_function_clock_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + UartFunctionClockSclk::Xtal => release_xtal_clk(clocks), + UartFunctionClockSclk::PllF80m => release_pll_f80m(clocks), + UartFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_config, config); } } pub fn function_clock_config( @@ -2692,11 +3657,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: UartFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: UartFunctionClockConfig) -> u32 { (match config.sclk { UartFunctionClockSclk::Xtal => xtal_clk_frequency(), UartFunctionClockSclk::PllF80m => pll_f80m_frequency(), @@ -2749,10 +3710,8 @@ macro_rules! define_clock_tree_types { self.release_function_clock(clocks); } } - #[allow(unused_variables)] pub fn baud_rate_generator_config_frequency( self, - clocks: &mut ClockTree, config: UartBaudRateGeneratorConfig, ) -> u32 { ((self.function_clock_frequency() * 16) @@ -2788,6 +3747,10 @@ macro_rules! define_clock_tree_types { pub lp_fast_clk: Option, /// `LP_SLOW_CLK` configuration. pub lp_slow_clk: Option, + /// `BLE_LP_CLK` configuration. + pub ble_lp_clk: Option, + /// `CRYPTO_CLK` configuration. + pub crypto_clk: Option, /// `TIMG_CALIBRATION_CLOCK` configuration. pub timg_calibration_clock: Option, } @@ -2814,6 +3777,12 @@ macro_rules! define_clock_tree_types { if let Some(config) = self.lp_slow_clk { configure_lp_slow_clk(clocks, config); } + if let Some(config) = self.ble_lp_clk { + configure_ble_lp_clk(clocks, config); + } + if let Some(config) = self.crypto_clk { + configure_crypto_clk(clocks, config); + } if let Some(config) = self.timg_calibration_clock { configure_timg_calibration_clock(clocks, config); } @@ -2832,15 +3801,24 @@ macro_rules! define_clock_tree_types { fn refresh_xtal_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.xtal_clk { XTAL_CLK_FREQ_CACHE.store( - xtal_clk_config_frequency(clocks, config), + xtal_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } refresh_hp_root_clk_downstream(clocks); refresh_lp_fast_clk_downstream(clocks); + refresh_ble_lp_clk_downstream(clocks); + refresh_crypto_clk_downstream(clocks); + for child_instance in [AdcInstance::ApbSaradc] { + refresh_adc_function_clock_downstream(clocks, child_instance); + } for child_instance in [I2cInstance::I2c0] { refresh_i2c_function_clock_downstream(clocks, child_instance); } + for child_instance in [I2sInstance::I2s0] { + refresh_i2s_tx_clk_downstream(clocks, child_instance); + refresh_i2s_rx_clk_downstream(clocks, child_instance); + } for child_instance in [SpiInstance::Spi2] { refresh_spi_function_clock_downstream(clocks, child_instance); } @@ -2856,10 +3834,41 @@ macro_rules! define_clock_tree_types { refresh_uart_function_clock_downstream(clocks, child_instance); } } + fn refresh_rc_fast_clk_downstream(clocks: &mut ClockTree) { + refresh_hp_root_clk_downstream(clocks); + refresh_lp_fast_clk_downstream(clocks); + refresh_crypto_clk_downstream(clocks); + refresh_timg_calibration_clock_downstream(clocks); + for child_instance in [AdcInstance::ApbSaradc] { + refresh_adc_function_clock_downstream(clocks, child_instance); + } + for child_instance in [I2cInstance::I2c0] { + refresh_i2c_function_clock_downstream(clocks, child_instance); + } + for child_instance in [SpiInstance::Spi2] { + refresh_spi_function_clock_downstream(clocks, child_instance); + } + for child_instance in [TimgInstance::Timg0, TimgInstance::Timg1] { + refresh_timg_function_clock_downstream(clocks, child_instance); + refresh_timg_wdt_clock_downstream(clocks, child_instance); + } + for child_instance in [ + UartInstance::Uart0, + UartInstance::Uart1, + UartInstance::Uart2, + ] { + refresh_uart_function_clock_downstream(clocks, child_instance); + } + } + fn refresh_rc_slow_clk_downstream(clocks: &mut ClockTree) { + refresh_lp_slow_clk_downstream(clocks); + refresh_ble_lp_clk_downstream(clocks); + refresh_timg_calibration_clock_downstream(clocks); + } fn refresh_hp_root_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.hp_root_clk { HP_ROOT_CLK_FREQ_CACHE.store( - hp_root_clk_config_frequency(clocks, config), + hp_root_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -2869,7 +3878,7 @@ macro_rules! define_clock_tree_types { fn refresh_cpu_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.cpu_clk { CPU_CLK_FREQ_CACHE.store( - cpu_clk_config_frequency(clocks, config), + cpu_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -2877,7 +3886,7 @@ macro_rules! define_clock_tree_types { fn refresh_ahb_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.ahb_clk { AHB_CLK_FREQ_CACHE.store( - ahb_clk_config_frequency(clocks, config), + ahb_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -2886,7 +3895,7 @@ macro_rules! define_clock_tree_types { fn refresh_apb_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.apb_clk { APB_CLK_FREQ_CACHE.store( - apb_clk_config_frequency(clocks, config), + apb_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -2894,7 +3903,7 @@ macro_rules! define_clock_tree_types { fn refresh_lp_fast_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.lp_fast_clk { LP_FAST_CLK_FREQ_CACHE.store( - lp_fast_clk_config_frequency(clocks, config), + lp_fast_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -2902,7 +3911,23 @@ macro_rules! define_clock_tree_types { fn refresh_lp_slow_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.lp_slow_clk { LP_SLOW_CLK_FREQ_CACHE.store( - lp_slow_clk_config_frequency(clocks, config), + lp_slow_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + fn refresh_ble_lp_clk_downstream(clocks: &mut ClockTree) { + if let Some(config) = clocks.ble_lp_clk { + BLE_LP_CLK_FREQ_CACHE.store( + ble_lp_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + fn refresh_crypto_clk_downstream(clocks: &mut ClockTree) { + if let Some(config) = clocks.crypto_clk { + CRYPTO_CLK_FREQ_CACHE.store( + crypto_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -2910,7 +3935,15 @@ macro_rules! define_clock_tree_types { fn refresh_timg_calibration_clock_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.timg_calibration_clock { TIMG_CALIBRATION_CLOCK_FREQ_CACHE.store( - timg_calibration_clock_config_frequency(clocks, config), + timg_calibration_clock_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + fn refresh_adc_function_clock_downstream(clocks: &mut ClockTree, instance: AdcInstance) { + if let Some(config) = clocks.adc_function_clock[instance as usize] { + ADC_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( + AdcInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -2918,7 +3951,33 @@ macro_rules! define_clock_tree_types { fn refresh_i2c_function_clock_downstream(clocks: &mut ClockTree, instance: I2cInstance) { if let Some(config) = clocks.i2c_function_clock[instance as usize] { I2C_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - I2cInstance::function_clock_config_frequency(clocks, config), + I2cInstance::function_clock_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + fn refresh_i2s_tx_clk_downstream(clocks: &mut ClockTree, instance: I2sInstance) { + if let Some(config) = clocks.i2s_tx_clk[instance as usize] { + I2S_TX_CLK_FREQ_CACHE[instance as usize].store( + I2sInstance::tx_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + refresh_i2s_mclk_out_downstream(clocks, instance); + } + fn refresh_i2s_rx_clk_downstream(clocks: &mut ClockTree, instance: I2sInstance) { + if let Some(config) = clocks.i2s_rx_clk[instance as usize] { + I2S_RX_CLK_FREQ_CACHE[instance as usize].store( + I2sInstance::rx_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + refresh_i2s_mclk_out_downstream(clocks, instance); + } + fn refresh_i2s_mclk_out_downstream(clocks: &mut ClockTree, instance: I2sInstance) { + if let Some(config) = clocks.i2s_mclk_out[instance as usize] { + I2S_MCLK_OUT_FREQ_CACHE[instance as usize].store( + instance.mclk_out_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -2926,7 +3985,7 @@ macro_rules! define_clock_tree_types { fn refresh_spi_function_clock_downstream(clocks: &mut ClockTree, instance: SpiInstance) { if let Some(config) = clocks.spi_function_clock[instance as usize] { SPI_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - SpiInstance::function_clock_config_frequency(clocks, config), + SpiInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -2934,7 +3993,7 @@ macro_rules! define_clock_tree_types { fn refresh_timg_function_clock_downstream(clocks: &mut ClockTree, instance: TimgInstance) { if let Some(config) = clocks.timg_function_clock[instance as usize] { TIMG_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - TimgInstance::function_clock_config_frequency(clocks, config), + TimgInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -2942,7 +4001,7 @@ macro_rules! define_clock_tree_types { fn refresh_timg_wdt_clock_downstream(clocks: &mut ClockTree, instance: TimgInstance) { if let Some(config) = clocks.timg_wdt_clock[instance as usize] { TIMG_WDT_CLOCK_FREQ_CACHE[instance as usize].store( - TimgInstance::wdt_clock_config_frequency(clocks, config), + TimgInstance::wdt_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -2950,7 +4009,7 @@ macro_rules! define_clock_tree_types { fn refresh_uart_function_clock_downstream(clocks: &mut ClockTree, instance: UartInstance) { if let Some(config) = clocks.uart_function_clock[instance as usize] { UART_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - UartInstance::function_clock_config_frequency(clocks, config), + UartInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -2962,7 +4021,7 @@ macro_rules! define_clock_tree_types { ) { if let Some(config) = clocks.uart_baud_rate_generator[instance as usize] { UART_BAUD_RATE_GENERATOR_FREQ_CACHE[instance as usize].store( - instance.baud_rate_generator_config_frequency(clocks, config), + instance.baud_rate_generator_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3557,23 +4616,25 @@ macro_rules! for_each_peripheral { "APB_SARADC peripheral singleton"] APB_SARADC <= APB_SARADC() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "ASSIST_DEBUG peripheral singleton"] ASSIST_DEBUG <= ASSIST_DEBUG() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "CACHE peripheral singleton"] + CACHE <= CACHE() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "CLIC peripheral singleton"] CLIC <= CLIC() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "CLINT peripheral singleton"] CLINT <= CLINT() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "CACHE peripheral singleton"] CACHE <= CACHE() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "DMA peripheral singleton"] DMA - <= DMA() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "ECC peripheral singleton"] ECC <= ECC() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "ECDSA peripheral singleton"] - ECDSA <= ECDSA() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "EFUSE peripheral singleton"] EFUSE <= EFUSE() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "ETM peripheral singleton"] ETM - <= SOC_ETM() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "GPIO peripheral singleton"] GPIO <= GPIO() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "GPIO_SD peripheral singleton"] - GPIO_SD <= GPIO_EXT() (unstable))); _for_each_inner_peripheral!((@ peri_type - #[doc = "HP_APM peripheral singleton"] HP_APM <= HP_APM() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "HP_SYS peripheral singleton"] - HP_SYS <= HP_SYS() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "DMA peripheral singleton"] DMA <= DMA() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "ECC peripheral singleton"] ECC + <= ECC() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "ECDSA peripheral singleton"] ECDSA <= ECDSA() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "EFUSE peripheral singleton"] + EFUSE <= EFUSE() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "ETM peripheral singleton"] ETM <= SOC_ETM() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "GPIO peripheral singleton"] + GPIO <= GPIO() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "GPIO_SD peripheral singleton"] GPIO_SD <= GPIO_EXT() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "HP_APM peripheral singleton"] + HP_APM <= HP_APM() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "HP_SYS peripheral singleton"] HP_SYS <= HP_SYS() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "I2C_ANA_MST peripheral singleton"] I2C_ANA_MST <= I2C_ANA_MST() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "I2C0 peripheral singleton"] I2C0 <= I2C0(I2C_EXT0 : { bind_peri_interrupt, enable_peri_interrupt, @@ -3685,8 +4746,8 @@ macro_rules! for_each_peripheral { _for_each_inner_peripheral!((DMA_CH1(unstable))); _for_each_inner_peripheral!((APB_SARADC(unstable))); _for_each_inner_peripheral!((ASSIST_DEBUG(unstable))); - _for_each_inner_peripheral!((CLINT(unstable))); _for_each_inner_peripheral!((CACHE(unstable))); + _for_each_inner_peripheral!((CLINT(unstable))); _for_each_inner_peripheral!((DMA(unstable))); _for_each_inner_peripheral!((ECC(unstable))); _for_each_inner_peripheral!((ECDSA(unstable))); @@ -3892,9 +4953,10 @@ macro_rules! for_each_peripheral { disable_dma_out_interrupt }) (unstable)), (@ peri_type #[doc = "APB_SARADC peripheral singleton"] APB_SARADC <= APB_SARADC() (unstable)), (@ peri_type #[doc = "ASSIST_DEBUG peripheral singleton"] ASSIST_DEBUG <= - ASSIST_DEBUG() (unstable)), (@ peri_type #[doc = "CLINT peripheral singleton"] - CLINT <= CLINT() (unstable)), (@ peri_type #[doc = "CACHE peripheral singleton"] - CACHE <= CACHE() (unstable)), (@ peri_type #[doc = "DMA peripheral singleton"] + ASSIST_DEBUG() (unstable)), (@ peri_type #[doc = "CACHE peripheral singleton"] + CACHE <= CACHE() (unstable)), (@ peri_type #[doc = "CLIC peripheral singleton"] + CLIC <= CLIC() (unstable)), (@ peri_type #[doc = "CLINT peripheral singleton"] + CLINT <= CLINT() (unstable)), (@ peri_type #[doc = "DMA peripheral singleton"] DMA <= DMA() (unstable)), (@ peri_type #[doc = "ECC peripheral singleton"] ECC <= ECC() (unstable)), (@ peri_type #[doc = "ECDSA peripheral singleton"] ECDSA <= ECDSA() (unstable)), (@ peri_type #[doc = "EFUSE peripheral singleton"] EFUSE <= @@ -3979,7 +5041,7 @@ macro_rules! for_each_peripheral { (GPIO15), (GPIO16), (GPIO17), (GPIO18), (GPIO19), (GPIO20), (GPIO21), (GPIO22), (GPIO23), (GPIO24), (GPIO25), (GPIO26), (GPIO27), (GPIO28), (GPIO29), (DMA_CH0(unstable)), (DMA_CH1(unstable)), (APB_SARADC(unstable)), - (ASSIST_DEBUG(unstable)), (CLINT(unstable)), (CACHE(unstable)), (DMA(unstable)), + (ASSIST_DEBUG(unstable)), (CACHE(unstable)), (CLINT(unstable)), (DMA(unstable)), (ECC(unstable)), (ECDSA(unstable)), (EFUSE(unstable)), (ETM(unstable)), (GPIO(unstable)), (GPIO_SD(unstable)), (HP_APM(unstable)), (HP_SYS(unstable)), (I2C_ANA_MST(unstable)), (I2C0), (I2S0(unstable)), (INTERRUPT_CORE0(unstable)), diff --git a/esp-metadata-generated/src/_generated_esp32h2.rs b/esp-metadata-generated/src/_generated_esp32h2.rs index 7fff8fad998..501b8b73980 100644 --- a/esp-metadata-generated/src/_generated_esp32h2.rs +++ b/esp-metadata-generated/src/_generated_esp32h2.rs @@ -88,6 +88,9 @@ macro_rules! property { ("gpio.func_in_sel_offset", str) => { stringify!(0) }; + ("gpio.need_soft_isolate_during_pd") => { + false + }; ("gpio.has_bank_1") => { false }; @@ -238,12 +241,6 @@ macro_rules! property { ("i2s.version", str) => { stringify!(3) }; - ("i2s.default_clock_source") => { - 1 - }; - ("i2s.default_clock_source", str) => { - stringify!(1) - }; ("i2s.mclk_divider_bit_width") => { 9 }; @@ -283,6 +280,15 @@ macro_rules! property { ("parl_io.version", str) => { stringify!(2) }; + ("parl_io.max_data_width") => { + 8 + }; + ("parl_io.max_data_width", str) => { + stringify!(8) + }; + ("parl_io.has_tx_cs") => { + false + }; ("rmt.ram_start") => { 1610642432 }; @@ -325,6 +331,39 @@ macro_rules! property { ("phy.combo_module") => { false }; + ("adc.controller") => { + "digital" + }; + ("adc.channel_count") => { + 5 + }; + ("adc.channel_count", str) => { + stringify!(5) + }; + ("adc.line_calibration") => { + true + }; + ("adc.curve_calibration") => { + true + }; + ("adc.basic_calibration") => { + true + }; + ("adc.calibration_v1_scheme_supported") => { + true + }; + ("adc.channel_compensation") => { + true + }; + ("adc.pcr_clock") => { + true + }; + ("adc.pcr_sar_clk_div") => { + true + }; + ("adc.sar_power_override") => { + true + }; ("ledc.version") => { 3 }; @@ -349,6 +388,9 @@ macro_rules! property { ("timergroup.timg_has_divcnt_rst") => { true }; + ("timergroup.wdt_has_conf_update") => { + true + }; ("timergroup.rc_fast_calibration_divider_min_rev") => { 2 }; @@ -487,6 +529,9 @@ macro_rules! property { ("soc.cpu_has_csr_pc") => { true }; + ("soc.cpu_has_zcmp_workaround") => { + false + }; ("soc.multi_core_enabled") => { false }; @@ -508,6 +553,12 @@ macro_rules! property { ("soc.cpu_mcause_mask", str) => { stringify!(31) }; + ("soc.cpu_pmp_granularity") => { + 4 + }; + ("soc.cpu_pmp_granularity", str) => { + stringify!(4) + }; ("clock_tree.iomux_function_clock") => { [crate ::soc::clocks::IomuxFunctionClockConfig::XtalClk, crate ::soc::clocks::IomuxFunctionClockConfig::PllF48m] @@ -528,19 +579,30 @@ macro_rules! property { (0, 255) }; ("clock_tree.lp_fast_clk") => { - [crate ::soc::clocks::LpFastClkConfig::RcFastClk, crate + [crate ::soc::clocks::LpFastClkConfig::RcFastClk, #[cfg(use_xtal32k)] crate ::soc::clocks::LpFastClkConfig::PllLpClk, crate ::soc::clocks::LpFastClkConfig::XtalD2Clk] }; ("clock_tree.lp_slow_clk") => { - [crate ::soc::clocks::LpSlowClkConfig::Xtal32k, crate + [#[cfg(use_xtal32k)] crate ::soc::clocks::LpSlowClkConfig::Xtal32k, crate ::soc::clocks::LpSlowClkConfig::RcSlow, crate ::soc::clocks::LpSlowClkConfig::OscSlow] }; + ("clock_tree.ble_lp_clk") => { + [crate ::soc::clocks::BleLpClkConfig::Xtal, crate + ::soc::clocks::BleLpClkConfig::RcSlow, #[cfg(use_xtal32k)] crate + ::soc::clocks::BleLpClkConfig::Xtal32k] + }; + ("clock_tree.crypto_clk") => { + [crate ::soc::clocks::CryptoClkConfig::Xtal, crate + ::soc::clocks::CryptoClkConfig::RcFast, crate + ::soc::clocks::CryptoClkConfig::PllF64m, crate + ::soc::clocks::CryptoClkConfig::PllF96m] + }; ("clock_tree.timg_calibration_clock") => { [crate ::soc::clocks::TimgCalibrationClockConfig::RcSlowClk, crate - ::soc::clocks::TimgCalibrationClockConfig::RcFastDivClk, crate - ::soc::clocks::TimgCalibrationClockConfig::Xtal32kClk] + ::soc::clocks::TimgCalibrationClockConfig::RcFastDivClk, #[cfg(use_xtal32k)] + crate ::soc::clocks::TimgCalibrationClockConfig::Xtal32kClk] }; ("clock_tree.uart.function_clock.sclk") => { [crate ::soc::clocks::UartFunctionClockSclk::PllF48m, crate @@ -576,14 +638,44 @@ macro_rules! property { ::soc::clocks::McpwmFunctionClockConfig::XtalClk] }; ("clock_tree.parl_io.rx_clock") => { - [crate ::soc::clocks::ParlIoRxClockConfig::XtalClk, crate - ::soc::clocks::ParlIoRxClockConfig::RcFastClk, crate - ::soc::clocks::ParlIoRxClockConfig::PllF96m] + [crate ::soc::clocks::ParlIoClkConfig::XtalClk, crate + ::soc::clocks::ParlIoClkConfig::RcFastClk, crate + ::soc::clocks::ParlIoClkConfig::PllF96m] }; ("clock_tree.parl_io.tx_clock") => { - [crate ::soc::clocks::ParlIoTxClockConfig::XtalClk, crate - ::soc::clocks::ParlIoTxClockConfig::RcFastClk, crate - ::soc::clocks::ParlIoTxClockConfig::PllF96m] + [crate ::soc::clocks::ParlIoClkConfig::XtalClk, crate + ::soc::clocks::ParlIoClkConfig::RcFastClk, crate + ::soc::clocks::ParlIoClkConfig::PllF96m] + }; + ("clock_tree.i2s.tx_clk.sclk") => { + [crate ::soc::clocks::I2sClkSclk::Xtal, crate ::soc::clocks::I2sClkSclk::PllF96m, + crate ::soc::clocks::I2sClkSclk::PllF64m] + }; + ("clock_tree.i2s.tx_clk.div_num") => { + (1, 255) + }; + ("clock_tree.i2s.tx_clk.div_a") => { + (1, 511) + }; + ("clock_tree.i2s.tx_clk.div_b") => { + (0, 511) + }; + ("clock_tree.i2s.rx_clk.sclk") => { + [crate ::soc::clocks::I2sClkSclk::Xtal, crate ::soc::clocks::I2sClkSclk::PllF96m, + crate ::soc::clocks::I2sClkSclk::PllF64m] + }; + ("clock_tree.i2s.rx_clk.div_num") => { + (1, 255) + }; + ("clock_tree.i2s.rx_clk.div_a") => { + (1, 511) + }; + ("clock_tree.i2s.rx_clk.div_b") => { + (0, 511) + }; + ("clock_tree.i2s.mclk_out") => { + [crate ::soc::clocks::I2sMclkOutConfig::Tx, crate + ::soc::clocks::I2sMclkOutConfig::Rx] }; ("clock_tree.i2c.function_clock.sclk") => { [crate ::soc::clocks::I2cFunctionClockSclk::Xtal, crate @@ -597,6 +689,11 @@ macro_rules! property { ::soc::clocks::SpiFunctionClockConfig::PllF48m, crate ::soc::clocks::SpiFunctionClockConfig::RcFast] }; + ("clock_tree.adc.function_clock") => { + [crate ::soc::clocks::AdcFunctionClockConfig::Xtal, crate + ::soc::clocks::AdcFunctionClockConfig::PllF96m, crate + ::soc::clocks::AdcFunctionClockConfig::RcFast] + }; } #[macro_export] #[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] @@ -1188,6 +1285,7 @@ macro_rules! for_each_classified_interrupt { ([vector 11] 27), ([vector 12] 28), ([vector 13] 29), ([vector 14] 30))); _for_each_inner_classified_interrupt!((reserved([reserved 0] 0), ([reserved 1] 3), ([reserved 2] 4), ([reserved 3] 7))); + _for_each_inner_classified_interrupt!((context_switch)); }; } #[macro_export] @@ -1281,6 +1379,7 @@ macro_rules! for_each_sw_interrupt { /// /// // XTAL32K_CLK /// +/// #[cfg(use_xtal32k)] /// fn enable_xtal32k_clk_impl(_clocks: &mut ClockTree, _en: bool) { /// todo!() /// } @@ -1299,6 +1398,7 @@ macro_rules! for_each_sw_interrupt { /// /// // PLL_LP_CLK /// +/// #[cfg(use_xtal32k)] /// fn enable_pll_lp_clk_impl(_clocks: &mut ClockTree, _en: bool) { /// todo!() /// } @@ -1385,6 +1485,46 @@ macro_rules! for_each_sw_interrupt { /// todo!() /// } /// +/// // BLE_LP_XTAL_CLK +/// +/// fn enable_ble_lp_xtal_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// // BLE_LP_RC_SLOW_CLK +/// +/// fn enable_ble_lp_rc_slow_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// // BLE_LP_CLK +/// +/// fn enable_ble_lp_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_ble_lp_clk_impl( +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: BleLpClkConfig, +/// ) { +/// todo!() +/// } +/// +/// // CRYPTO_CLK +/// +/// fn enable_crypto_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_crypto_clk_impl( +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: CryptoClkConfig, +/// ) { +/// todo!() +/// } +/// /// // TIMG_CALIBRATION_CLOCK /// /// fn enable_timg_calibration_clock_impl(_clocks: &mut ClockTree, _en: bool) { @@ -1399,6 +1539,22 @@ macro_rules! for_each_sw_interrupt { /// todo!() /// } /// +/// impl AdcInstance { +/// // ADC_FUNCTION_CLOCK +/// +/// fn enable_function_clock_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_function_clock_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: AdcFunctionClockConfig, +/// ) { +/// todo!() +/// } +/// } /// impl SdmInstance { /// // SDM_FUNCTION_CLOCK /// @@ -1422,6 +1578,52 @@ macro_rules! for_each_sw_interrupt { /// todo!() /// } /// } +/// impl I2sInstance { +/// // I2S_TX_CLK +/// +/// fn enable_tx_clk_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_tx_clk_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: I2sClkConfig, +/// ) { +/// todo!() +/// } +/// +/// // I2S_RX_CLK +/// +/// fn enable_rx_clk_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_rx_clk_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: I2sClkConfig, +/// ) { +/// todo!() +/// } +/// +/// // I2S_MCLK_OUT +/// +/// fn enable_mclk_out_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_mclk_out_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: I2sMclkOutConfig, +/// ) { +/// todo!() +/// } +/// } /// impl McpwmInstance { /// // MCPWM_FUNCTION_CLOCK /// @@ -1448,8 +1650,8 @@ macro_rules! for_each_sw_interrupt { /// fn configure_rx_clock_impl( /// self, /// _clocks: &mut ClockTree, -/// _old_config: Option, -/// _new_config: ParlIoRxClockConfig, +/// _old_config: Option, +/// _new_config: ParlIoClkConfig, /// ) { /// todo!() /// } @@ -1463,8 +1665,8 @@ macro_rules! for_each_sw_interrupt { /// fn configure_tx_clock_impl( /// self, /// _clocks: &mut ClockTree, -/// _old_config: Option, -/// _new_config: ParlIoTxClockConfig, +/// _old_config: Option, +/// _new_config: ParlIoClkConfig, /// ) { /// todo!() /// } @@ -1566,6 +1768,11 @@ macro_rules! for_each_sw_interrupt { /// ``` macro_rules! define_clock_tree_types { () => { + #[derive(Clone, Copy, PartialEq, Eq, Debug)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum AdcInstance { + ApbSaradc = 0, + } #[derive(Clone, Copy, PartialEq, Eq, Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum SdmInstance { @@ -1579,6 +1786,11 @@ macro_rules! define_clock_tree_types { } #[derive(Clone, Copy, PartialEq, Eq, Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum I2sInstance { + I2s0 = 0, + } + #[derive(Clone, Copy, PartialEq, Eq, Debug)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum McpwmInstance { Mcpwm0 = 0, } @@ -1668,7 +1880,7 @@ macro_rules! define_clock_tree_types { ); Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -1694,7 +1906,7 @@ macro_rules! define_clock_tree_types { ); Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -1720,7 +1932,7 @@ macro_rules! define_clock_tree_types { ); Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -1730,6 +1942,7 @@ macro_rules! define_clock_tree_types { pub enum LpFastClkConfig { /// Selects `RC_FAST_CLK`. RcFastClk, + #[cfg(use_xtal32k)] /// Selects `PLL_LP_CLK`. PllLpClk, /// Selects `XTAL_D2_CLK`. @@ -1739,6 +1952,7 @@ macro_rules! define_clock_tree_types { #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum LpSlowClkConfig { + #[cfg(use_xtal32k)] /// Selects `XTAL32K_CLK`. Xtal32k, /// Selects `RC_SLOW_CLK`. @@ -1746,6 +1960,31 @@ macro_rules! define_clock_tree_types { /// Selects `OSC_SLOW_CLK`. OscSlow, } + /// The list of clock signals that the `BLE_LP_CLK` multiplexer can output. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum BleLpClkConfig { + /// Selects `BLE_LP_XTAL_CLK`. + Xtal, + /// Selects `BLE_LP_RC_SLOW_CLK`. + RcSlow, + #[cfg(use_xtal32k)] + /// Selects `XTAL32K_CLK`. + Xtal32k, + } + /// The list of clock signals that the `CRYPTO_CLK` multiplexer can output. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum CryptoClkConfig { + /// Selects `XTAL_CLK`. + Xtal, + /// Selects `RC_FAST_CLK`. + RcFast, + /// Selects `PLL_F64M_CLK`. + PllF64m, + /// Selects `PLL_F96M_CLK`. + PllF96m, + } /// The list of clock signals that the `TIMG_CALIBRATION_CLOCK` multiplexer can output. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] @@ -1754,9 +1993,22 @@ macro_rules! define_clock_tree_types { RcSlowClk, /// Selects `RC_FAST_CLK`. RcFastDivClk, + #[cfg(use_xtal32k)] /// Selects `XTAL32K_CLK`. Xtal32kClk, } + /// The list of clock signals that the `APB_SARADC_FUNCTION_CLOCK` multiplexer can output. + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum AdcFunctionClockConfig { + /// Selects `XTAL_CLK`. + Xtal, + #[default] + /// Selects `PLL_F96M_CLK`. + PllF96m, + /// Selects `RC_FAST_CLK`. + RcFast, + } #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum I2cFunctionClockSclk { @@ -1789,12 +2041,90 @@ macro_rules! define_clock_tree_types { ); Self { sclk, div_num } } - pub(crate) fn sclk(self) -> I2cFunctionClockSclk { + pub fn sclk(self) -> I2cFunctionClockSclk { + self.sclk + } + pub fn div_num(self) -> u32 { + self.div_num as u32 + } + } + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum I2sClkSclk { + /// Selects `XTAL_CLK`. + Xtal, + #[default] + /// Selects `PLL_F96M_CLK`. + PllF96m, + /// Selects `PLL_F64M_CLK`. + PllF64m, + } + /// Configures the `I2S0_TX_CLK` clock node. + /// + /// The output is calculated as `OUTPUT = (sclk * div_a) / (div_num * div_a + div_b)`. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub struct I2sClkConfig { + sclk: I2sClkSclk, + div_num: u32, + div_a: u32, + div_b: u32, + } + impl I2sClkConfig { + /// Creates a new configuration for the TX_CLK clock node. + /// + /// ## Panics + /// + /// Panics if the div_num value is outside the + /// valid range (1 ..= 255). + /// + /// Panics if the div_a value is outside the + /// valid range (1 ..= 511). + /// + /// Panics if the div_b value is outside the + /// valid range (0 ..= 511). + pub const fn new(sclk: I2sClkSclk, div_num: u32, div_a: u32, div_b: u32) -> Self { + ::core::assert!( + div_num >= 1 && div_num <= 255, + "`I2S0_TX_CLK` div_num must be between 1 and 255 (inclusive)." + ); + ::core::assert!( + div_a >= 1 && div_a <= 511, + "`I2S0_TX_CLK` div_a must be between 1 and 511 (inclusive)." + ); + ::core::assert!( + div_b <= 511, + "`I2S0_TX_CLK` div_b must be between 0 and 511 (inclusive)." + ); + Self { + sclk, + div_num, + div_a, + div_b, + } + } + pub fn sclk(self) -> I2sClkSclk { self.sclk } - pub(crate) fn div_num(self) -> u32 { + pub fn div_num(self) -> u32 { self.div_num as u32 } + pub fn div_a(self) -> u32 { + self.div_a as u32 + } + pub fn div_b(self) -> u32 { + self.div_b as u32 + } + } + /// The list of clock signals that the `I2S0_MCLK_OUT` multiplexer can output. + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum I2sMclkOutConfig { + /// Selects `TX_CLK`. + Tx, + #[default] + /// Selects `RX_CLK`. + Rx, } /// The list of clock signals that the `MCPWM0_FUNCTION_CLOCK` multiplexer can output. #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] @@ -1811,19 +2141,7 @@ macro_rules! define_clock_tree_types { /// The list of clock signals that the `PARL_IO_RX_CLOCK` multiplexer can output. #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] - pub enum ParlIoRxClockConfig { - /// Selects `XTAL_CLK`. - XtalClk, - /// Selects `RC_FAST_CLK`. - RcFastClk, - #[default] - /// Selects `PLL_F96M_CLK`. - PllF96m, - } - /// The list of clock signals that the `PARL_IO_TX_CLOCK` multiplexer can output. - #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] - #[cfg_attr(feature = "defmt", derive(defmt::Format))] - pub enum ParlIoTxClockConfig { + pub enum ParlIoClkConfig { /// Selects `XTAL_CLK`. XtalClk, /// Selects `RC_FAST_CLK`. @@ -1846,9 +2164,9 @@ macro_rules! define_clock_tree_types { #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum SpiFunctionClockConfig { - #[default] /// Selects `XTAL_CLK`. Xtal, + #[default] /// Selects `PLL_F48M_CLK`. PllF48m, /// Selects `RC_FAST_CLK`. @@ -1912,10 +2230,10 @@ macro_rules! define_clock_tree_types { ); Self { sclk, div_num } } - pub(crate) fn sclk(self) -> UartFunctionClockSclk { + pub fn sclk(self) -> UartFunctionClockSclk { self.sclk } - pub(crate) fn div_num(self) -> u32 { + pub fn div_num(self) -> u32 { self.div_num as u32 } } @@ -1953,10 +2271,10 @@ macro_rules! define_clock_tree_types { integral, } } - pub(crate) fn fractional(self) -> u32 { + pub fn fractional(self) -> u32 { self.fractional as u32 } - pub(crate) fn integral(self) -> u32 { + pub fn integral(self) -> u32 { self.integral as u32 } } @@ -1970,11 +2288,17 @@ macro_rules! define_clock_tree_types { apb_clk: Option, lp_fast_clk: Option, lp_slow_clk: Option, + ble_lp_clk: Option, + crypto_clk: Option, timg_calibration_clock: Option, + adc_function_clock: [Option; 1], i2c_function_clock: [Option; 2], + i2s_tx_clk: [Option; 1], + i2s_rx_clk: [Option; 1], + i2s_mclk_out: [Option; 1], mcpwm_function_clock: [Option; 1], - parl_io_rx_clock: [Option; 1], - parl_io_tx_clock: [Option; 1], + parl_io_rx_clock: [Option; 1], + parl_io_tx_clock: [Option; 1], rmt_sclk: [Option; 1], spi_function_clock: [Option; 1], timg_function_clock: [Option; 2], @@ -1982,15 +2306,24 @@ macro_rules! define_clock_tree_types { uart_function_clock: [Option; 2], uart_baud_rate_generator: [Option; 2], pll_f96m_clk_refcount: u32, + pll_f64m_clk_refcount: u32, pll_f48m_clk_refcount: u32, rc_fast_clk_refcount: u32, + #[cfg(use_xtal32k)] xtal32k_clk_refcount: u32, + rc_slow_clk_refcount: u32, hp_root_clk_refcount: u32, apb_clk_refcount: u32, lp_fast_clk_refcount: u32, + ble_lp_clk_refcount: u32, + crypto_clk_refcount: u32, timg_calibration_clock_refcount: u32, + adc_function_clock_refcount: [u32; 1], sdm_function_clock_refcount: [u32; 1], i2c_function_clock_refcount: [u32; 2], + i2s_tx_clk_refcount: [u32; 1], + i2s_rx_clk_refcount: [u32; 1], + i2s_mclk_out_refcount: [u32; 1], mcpwm_function_clock_refcount: [u32; 1], parl_io_rx_clock_refcount: [u32; 1], parl_io_tx_clock_refcount: [u32; 1], @@ -2038,10 +2371,22 @@ macro_rules! define_clock_tree_types { pub fn lp_slow_clk(&self) -> Option { self.lp_slow_clk } + /// Returns the current configuration of the BLE_LP_CLK clock tree node + pub fn ble_lp_clk(&self) -> Option { + self.ble_lp_clk + } + /// Returns the current configuration of the CRYPTO_CLK clock tree node + pub fn crypto_clk(&self) -> Option { + self.crypto_clk + } /// Returns the current configuration of the TIMG_CALIBRATION_CLOCK clock tree node pub fn timg_calibration_clock(&self) -> Option { self.timg_calibration_clock } + /// Returns the current configuration of the APB_SARADC_FUNCTION_CLOCK clock tree node + pub fn apb_saradc_function_clock(&self) -> Option { + self.adc_function_clock[AdcInstance::ApbSaradc as usize] + } /// Returns the current configuration of the I2C0_FUNCTION_CLOCK clock tree node pub fn i2c0_function_clock(&self) -> Option { self.i2c_function_clock[I2cInstance::I2c0 as usize] @@ -2050,16 +2395,28 @@ macro_rules! define_clock_tree_types { pub fn i2c1_function_clock(&self) -> Option { self.i2c_function_clock[I2cInstance::I2c1 as usize] } + /// Returns the current configuration of the I2S0_TX_CLK clock tree node + pub fn i2s0_tx_clk(&self) -> Option { + self.i2s_tx_clk[I2sInstance::I2s0 as usize] + } + /// Returns the current configuration of the I2S0_RX_CLK clock tree node + pub fn i2s0_rx_clk(&self) -> Option { + self.i2s_rx_clk[I2sInstance::I2s0 as usize] + } + /// Returns the current configuration of the I2S0_MCLK_OUT clock tree node + pub fn i2s0_mclk_out(&self) -> Option { + self.i2s_mclk_out[I2sInstance::I2s0 as usize] + } /// Returns the current configuration of the MCPWM0_FUNCTION_CLOCK clock tree node pub fn mcpwm0_function_clock(&self) -> Option { self.mcpwm_function_clock[McpwmInstance::Mcpwm0 as usize] } /// Returns the current configuration of the PARL_IO_RX_CLOCK clock tree node - pub fn parl_io_rx_clock(&self) -> Option { + pub fn parl_io_rx_clock(&self) -> Option { self.parl_io_rx_clock[ParlIoInstance::ParlIo as usize] } /// Returns the current configuration of the PARL_IO_TX_CLOCK clock tree node - pub fn parl_io_tx_clock(&self) -> Option { + pub fn parl_io_tx_clock(&self) -> Option { self.parl_io_tx_clock[ParlIoInstance::ParlIo as usize] } /// Returns the current configuration of the RMT_SCLK clock tree node @@ -2113,8 +2470,14 @@ macro_rules! define_clock_tree_types { apb_clk: None, lp_fast_clk: None, lp_slow_clk: None, + ble_lp_clk: None, + crypto_clk: None, timg_calibration_clock: None, + adc_function_clock: [None; 1], i2c_function_clock: [None; 2], + i2s_tx_clk: [None; 1], + i2s_rx_clk: [None; 1], + i2s_mclk_out: [None; 1], mcpwm_function_clock: [None; 1], parl_io_rx_clock: [None; 1], parl_io_tx_clock: [None; 1], @@ -2125,15 +2488,24 @@ macro_rules! define_clock_tree_types { uart_function_clock: [None; 2], uart_baud_rate_generator: [None; 2], pll_f96m_clk_refcount: 0, + pll_f64m_clk_refcount: 0, pll_f48m_clk_refcount: 0, rc_fast_clk_refcount: 0, + #[cfg(use_xtal32k)] xtal32k_clk_refcount: 0, + rc_slow_clk_refcount: 0, hp_root_clk_refcount: 0, apb_clk_refcount: 0, lp_fast_clk_refcount: 0, + ble_lp_clk_refcount: 0, + crypto_clk_refcount: 0, timg_calibration_clock_refcount: 0, + adc_function_clock_refcount: [0; 1], sdm_function_clock_refcount: [0; 1], i2c_function_clock_refcount: [0; 2], + i2s_tx_clk_refcount: [0; 1], + i2s_rx_clk_refcount: [0; 1], + i2s_mclk_out_refcount: [0; 1], mcpwm_function_clock_refcount: [0; 1], parl_io_rx_clock_refcount: [0; 1], parl_io_tx_clock_refcount: [0; 1], @@ -2160,10 +2532,22 @@ macro_rules! define_clock_tree_types { ::core::sync::atomic::AtomicU32::new(0); static LP_SLOW_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); + static BLE_LP_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(0); + static CRYPTO_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(0); static TIMG_CALIBRATION_CLOCK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); + static ADC_FUNCTION_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; static I2C_FUNCTION_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 2] = [const { ::core::sync::atomic::AtomicU32::new(0) }; 2]; + static I2S_TX_CLK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; + static I2S_RX_CLK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; + static I2S_MCLK_OUT_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; static MCPWM_FUNCTION_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; static PARL_IO_RX_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = @@ -2182,56 +2566,208 @@ macro_rules! define_clock_tree_types { [const { ::core::sync::atomic::AtomicU32::new(0) }; 2]; static UART_BAUD_RATE_GENERATOR_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 2] = [const { ::core::sync::atomic::AtomicU32::new(0) }; 2]; - pub fn configure_xtal_clk(clocks: &mut ClockTree, config: XtalClkConfig) { - let old_config = clocks.xtal_clk.replace(config); - refresh_xtal_clk_downstream(clocks); - configure_xtal_clk_impl(clocks, old_config, config); + /// The clock sources of the device. + /// + /// A clock source is a node of the clock tree that other nodes derive their output + /// from. Ask a node which source it runs on with its `..._root_source` function. + #[derive(Debug, enumset::EnumSetType)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum ClockSource { + /// `XTAL_CLK`. + XtalClk, + /// `RC_FAST_CLK`. + RcFastClk, + #[cfg(use_xtal32k)] + /// `XTAL32K_CLK`. + Xtal32kClk, + /// `OSC_SLOW_CLK`. + OscSlowClk, + /// `RC_SLOW_CLK`. + RcSlowClk, } - pub fn xtal_clk_config(clocks: &mut ClockTree) -> Option { - clocks.xtal_clk + /// Returns the clock source that `XTAL_CLK` currently runs on. + pub fn xtal_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::XtalClk) } - fn request_xtal_clk(_clocks: &mut ClockTree) {} - fn release_xtal_clk(_clocks: &mut ClockTree) {} - #[allow(unused_variables)] - pub fn xtal_clk_config_frequency(clocks: &mut ClockTree, config: XtalClkConfig) -> u32 { - config.value() + /// Returns the clock source that `PLL_F96M_CLK` currently runs on. + pub fn pll_f96m_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) } - pub fn xtal_clk_frequency() -> u32 { - XTAL_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) + /// Returns the clock source that `PLL_F64M_CLK` currently runs on. + pub fn pll_f64m_clk_root_source(clocks: &mut ClockTree) -> Option { + pll_f96m_clk_root_source(clocks) } - pub fn request_pll_f96m_clk(clocks: &mut ClockTree) { - trace!("Requesting PLL_F96M_CLK"); - if increment_reference_count(&mut clocks.pll_f96m_clk_refcount) { - trace!("Enabling PLL_F96M_CLK"); - request_xtal_clk(clocks); - enable_pll_f96m_clk_impl(clocks, true); - } + /// Returns the clock source that `PLL_F48M_CLK` currently runs on. + pub fn pll_f48m_clk_root_source(clocks: &mut ClockTree) -> Option { + pll_f96m_clk_root_source(clocks) } - pub fn release_pll_f96m_clk(clocks: &mut ClockTree) { - trace!("Releasing PLL_F96M_CLK"); - if decrement_reference_count(&mut clocks.pll_f96m_clk_refcount) { - trace!("Disabling PLL_F96M_CLK"); - enable_pll_f96m_clk_impl(clocks, false); - release_xtal_clk(clocks); + /// Returns the clock source that `RC_FAST_CLK` currently runs on. + pub fn rc_fast_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::RcFastClk) + } + /// Returns the clock source that `IOMUX_FUNCTION_CLOCK` currently runs on. + pub fn iomux_function_clock_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.iomux_function_clock?; + match config { + IomuxFunctionClockConfig::XtalClk => xtal_clk_root_source(clocks), + IomuxFunctionClockConfig::PllF48m => pll_f48m_clk_root_source(clocks), } } - pub fn pll_f96m_clk_frequency() -> u32 { - 96000000 + #[cfg(use_xtal32k)] + /// Returns the clock source that `XTAL32K_CLK` currently runs on. + pub fn xtal32k_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::Xtal32kClk) } - pub fn pll_f96m_clk_source_frequency() -> u32 { - xtal_clk_frequency() + /// Returns the clock source that `OSC_SLOW_CLK` currently runs on. + pub fn osc_slow_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::OscSlowClk) } - pub fn request_pll_f64m_clk(clocks: &mut ClockTree) { - trace!("Requesting PLL_F64M_CLK"); - trace!("Enabling PLL_F64M_CLK"); - request_pll_f96m_clk(clocks); - enable_pll_f64m_clk_impl(clocks, true); + /// Returns the clock source that `RC_SLOW_CLK` currently runs on. + pub fn rc_slow_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::RcSlowClk) } - pub fn release_pll_f64m_clk(clocks: &mut ClockTree) { - trace!("Releasing PLL_F64M_CLK"); - trace!("Disabling PLL_F64M_CLK"); - enable_pll_f64m_clk_impl(clocks, false); - release_pll_f96m_clk(clocks); + #[cfg(use_xtal32k)] + /// Returns the clock source that `PLL_LP_CLK` currently runs on. + pub fn pll_lp_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal32k_clk_root_source(clocks) + } + /// Returns the clock source that `HP_ROOT_CLK` currently runs on. + pub fn hp_root_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.hp_root_clk?; + match config { + HpRootClkConfig::Pll96 => pll_f96m_clk_root_source(clocks), + HpRootClkConfig::Pll64 => pll_f64m_clk_root_source(clocks), + HpRootClkConfig::Xtal => xtal_clk_root_source(clocks), + HpRootClkConfig::RcFast => rc_fast_clk_root_source(clocks), + } + } + /// Returns the clock source that `CPU_CLK` currently runs on. + pub fn cpu_clk_root_source(clocks: &mut ClockTree) -> Option { + hp_root_clk_root_source(clocks) + } + /// Returns the clock source that `AHB_CLK` currently runs on. + pub fn ahb_clk_root_source(clocks: &mut ClockTree) -> Option { + hp_root_clk_root_source(clocks) + } + /// Returns the clock source that `APB_CLK` currently runs on. + pub fn apb_clk_root_source(clocks: &mut ClockTree) -> Option { + ahb_clk_root_source(clocks) + } + /// Returns the clock source that `XTAL_D2_CLK` currently runs on. + pub fn xtal_d2_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `LP_FAST_CLK` currently runs on. + pub fn lp_fast_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.lp_fast_clk?; + match config { + LpFastClkConfig::RcFastClk => rc_fast_clk_root_source(clocks), + #[cfg(use_xtal32k)] + LpFastClkConfig::PllLpClk => pll_lp_clk_root_source(clocks), + LpFastClkConfig::XtalD2Clk => xtal_d2_clk_root_source(clocks), + } + } + /// Returns the clock source that `LP_SLOW_CLK` currently runs on. + pub fn lp_slow_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.lp_slow_clk?; + match config { + #[cfg(use_xtal32k)] + LpSlowClkConfig::Xtal32k => xtal32k_clk_root_source(clocks), + LpSlowClkConfig::RcSlow => rc_slow_clk_root_source(clocks), + LpSlowClkConfig::OscSlow => osc_slow_clk_root_source(clocks), + } + } + /// Returns the clock source that `BLE_LP_XTAL_CLK` currently runs on. + pub fn ble_lp_xtal_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `BLE_LP_RC_SLOW_CLK` currently runs on. + pub fn ble_lp_rc_slow_clk_root_source(clocks: &mut ClockTree) -> Option { + rc_slow_clk_root_source(clocks) + } + /// Returns the clock source that `BLE_LP_CLK` currently runs on. + pub fn ble_lp_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.ble_lp_clk?; + match config { + BleLpClkConfig::Xtal => ble_lp_xtal_clk_root_source(clocks), + BleLpClkConfig::RcSlow => ble_lp_rc_slow_clk_root_source(clocks), + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => xtal32k_clk_root_source(clocks), + } + } + /// Returns the clock source that `CRYPTO_CLK` currently runs on. + pub fn crypto_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.crypto_clk?; + match config { + CryptoClkConfig::Xtal => xtal_clk_root_source(clocks), + CryptoClkConfig::RcFast => rc_fast_clk_root_source(clocks), + CryptoClkConfig::PllF64m => pll_f64m_clk_root_source(clocks), + CryptoClkConfig::PllF96m => pll_f96m_clk_root_source(clocks), + } + } + /// Returns the clock source that `TIMG_CALIBRATION_CLOCK` currently runs on. + pub fn timg_calibration_clock_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.timg_calibration_clock?; + match config { + TimgCalibrationClockConfig::RcSlowClk => lp_slow_clk_root_source(clocks), + TimgCalibrationClockConfig::RcFastDivClk => rc_fast_clk_root_source(clocks), + #[cfg(use_xtal32k)] + TimgCalibrationClockConfig::Xtal32kClk => xtal32k_clk_root_source(clocks), + } + } + pub fn configure_xtal_clk(clocks: &mut ClockTree, config: XtalClkConfig) { + let old_config = clocks.xtal_clk.replace(config); + refresh_xtal_clk_downstream(clocks); + configure_xtal_clk_impl(clocks, old_config, config); + } + pub fn xtal_clk_config(clocks: &mut ClockTree) -> Option { + clocks.xtal_clk + } + fn request_xtal_clk(_clocks: &mut ClockTree) {} + fn release_xtal_clk(_clocks: &mut ClockTree) {} + pub fn xtal_clk_config_frequency(config: XtalClkConfig) -> u32 { + config.value() + } + pub fn xtal_clk_frequency() -> u32 { + XTAL_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn request_pll_f96m_clk(clocks: &mut ClockTree) { + trace!("Requesting PLL_F96M_CLK"); + if increment_reference_count(&mut clocks.pll_f96m_clk_refcount) { + trace!("Enabling PLL_F96M_CLK"); + request_xtal_clk(clocks); + enable_pll_f96m_clk_impl(clocks, true); + } + } + pub fn release_pll_f96m_clk(clocks: &mut ClockTree) { + trace!("Releasing PLL_F96M_CLK"); + if decrement_reference_count(&mut clocks.pll_f96m_clk_refcount) { + trace!("Disabling PLL_F96M_CLK"); + enable_pll_f96m_clk_impl(clocks, false); + release_xtal_clk(clocks); + } + } + pub fn pll_f96m_clk_frequency() -> u32 { + 96000000 + } + pub fn pll_f96m_clk_source_frequency() -> u32 { + xtal_clk_frequency() + } + pub fn request_pll_f64m_clk(clocks: &mut ClockTree) { + trace!("Requesting PLL_F64M_CLK"); + if increment_reference_count(&mut clocks.pll_f64m_clk_refcount) { + trace!("Enabling PLL_F64M_CLK"); + request_pll_f96m_clk(clocks); + enable_pll_f64m_clk_impl(clocks, true); + } + } + pub fn release_pll_f64m_clk(clocks: &mut ClockTree) { + trace!("Releasing PLL_F64M_CLK"); + if decrement_reference_count(&mut clocks.pll_f64m_clk_refcount) { + trace!("Disabling PLL_F64M_CLK"); + enable_pll_f64m_clk_impl(clocks, false); + release_pll_f96m_clk(clocks); + } } pub fn pll_f64m_clk_frequency() -> u32 { ((pll_f96m_clk_frequency() * 2) / 3) @@ -2275,9 +2811,30 @@ macro_rules! define_clock_tree_types { enable_rc_fast_clk_impl(clocks, false); } } - pub fn rc_fast_clk_frequency() -> u32 { + static RC_FAST_CLK_FREQUENCY: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(rc_fast_clk_nominal_frequency()); + pub const fn rc_fast_clk_nominal_frequency() -> u32 { 8000000 } + pub fn rc_fast_clk_frequency() -> u32 { + RC_FAST_CLK_FREQUENCY.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn set_rc_fast_clk_frequency(clocks: &mut ClockTree, frequency: u32) { + if !(4000000..=12000000).contains(&frequency) { + warn!( + "Ignoring out-of-range RC_FAST_CLK frequency: {} Hz", + frequency + ); + return; + } + debug!( + "Updating RC_FAST_CLK frequency to {} Hz (nominal {} Hz)", + frequency, + rc_fast_clk_nominal_frequency() + ); + RC_FAST_CLK_FREQUENCY.store(frequency, ::core::sync::atomic::Ordering::Release); + refresh_rc_fast_clk_downstream(clocks); + } pub fn configure_iomux_function_clock( clocks: &mut ClockTree, new_selector: IomuxFunctionClockConfig, @@ -2303,11 +2860,7 @@ macro_rules! define_clock_tree_types { } fn request_iomux_function_clock(_clocks: &mut ClockTree) {} fn release_iomux_function_clock(_clocks: &mut ClockTree) {} - #[allow(unused_variables)] - pub fn iomux_function_clock_config_frequency( - clocks: &mut ClockTree, - config: IomuxFunctionClockConfig, - ) -> u32 { + pub fn iomux_function_clock_config_frequency(config: IomuxFunctionClockConfig) -> u32 { match config { IomuxFunctionClockConfig::XtalClk => xtal_clk_frequency(), IomuxFunctionClockConfig::PllF48m => pll_f48m_clk_frequency(), @@ -2317,11 +2870,9 @@ macro_rules! define_clock_tree_types { IOMUX_FUNCTION_CLOCK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn iomux_function_clock_source_frequency(source: IomuxFunctionClockConfig) -> u32 { - match source { - IomuxFunctionClockConfig::XtalClk => xtal_clk_frequency(), - IomuxFunctionClockConfig::PllF48m => pll_f48m_clk_frequency(), - } + iomux_function_clock_config_frequency(source) } + #[cfg(use_xtal32k)] pub fn request_xtal32k_clk(clocks: &mut ClockTree) { trace!("Requesting XTAL32K_CLK"); if increment_reference_count(&mut clocks.xtal32k_clk_refcount) { @@ -2329,6 +2880,7 @@ macro_rules! define_clock_tree_types { enable_xtal32k_clk_impl(clocks, true); } } + #[cfg(use_xtal32k)] pub fn release_xtal32k_clk(clocks: &mut ClockTree) { trace!("Releasing XTAL32K_CLK"); if decrement_reference_count(&mut clocks.xtal32k_clk_refcount) { @@ -2336,16 +2888,15 @@ macro_rules! define_clock_tree_types { enable_xtal32k_clk_impl(clocks, false); } } + #[cfg(use_xtal32k)] pub fn xtal32k_clk_frequency() -> u32 { 32768 } pub fn request_osc_slow_clk(clocks: &mut ClockTree) { - trace!("Requesting OSC_SLOW_CLK"); trace!("Enabling OSC_SLOW_CLK"); enable_osc_slow_clk_impl(clocks, true); } pub fn release_osc_slow_clk(clocks: &mut ClockTree) { - trace!("Releasing OSC_SLOW_CLK"); trace!("Disabling OSC_SLOW_CLK"); enable_osc_slow_clk_impl(clocks, false); } @@ -2354,56 +2905,82 @@ macro_rules! define_clock_tree_types { } pub fn request_rc_slow_clk(clocks: &mut ClockTree) { trace!("Requesting RC_SLOW_CLK"); - trace!("Enabling RC_SLOW_CLK"); - enable_rc_slow_clk_impl(clocks, true); + if increment_reference_count(&mut clocks.rc_slow_clk_refcount) { + trace!("Enabling RC_SLOW_CLK"); + enable_rc_slow_clk_impl(clocks, true); + } } pub fn release_rc_slow_clk(clocks: &mut ClockTree) { trace!("Releasing RC_SLOW_CLK"); - trace!("Disabling RC_SLOW_CLK"); - enable_rc_slow_clk_impl(clocks, false); + if decrement_reference_count(&mut clocks.rc_slow_clk_refcount) { + trace!("Disabling RC_SLOW_CLK"); + enable_rc_slow_clk_impl(clocks, false); + } } - pub fn rc_slow_clk_frequency() -> u32 { + static RC_SLOW_CLK_FREQUENCY: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(rc_slow_clk_nominal_frequency()); + pub const fn rc_slow_clk_nominal_frequency() -> u32 { 130000 } + pub fn rc_slow_clk_frequency() -> u32 { + RC_SLOW_CLK_FREQUENCY.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn set_rc_slow_clk_frequency(clocks: &mut ClockTree, frequency: u32) { + if !(65000..=195000).contains(&frequency) { + warn!( + "Ignoring out-of-range RC_SLOW_CLK frequency: {} Hz", + frequency + ); + return; + } + debug!( + "Updating RC_SLOW_CLK frequency to {} Hz (nominal {} Hz)", + frequency, + rc_slow_clk_nominal_frequency() + ); + RC_SLOW_CLK_FREQUENCY.store(frequency, ::core::sync::atomic::Ordering::Release); + refresh_rc_slow_clk_downstream(clocks); + } + #[cfg(use_xtal32k)] pub fn request_pll_lp_clk(clocks: &mut ClockTree) { - trace!("Requesting PLL_LP_CLK"); trace!("Enabling PLL_LP_CLK"); request_xtal32k_clk(clocks); enable_pll_lp_clk_impl(clocks, true); } + #[cfg(use_xtal32k)] pub fn release_pll_lp_clk(clocks: &mut ClockTree) { - trace!("Releasing PLL_LP_CLK"); trace!("Disabling PLL_LP_CLK"); enable_pll_lp_clk_impl(clocks, false); release_xtal32k_clk(clocks); } + #[cfg(use_xtal32k)] pub fn pll_lp_clk_frequency() -> u32 { 8000000 } + #[cfg(use_xtal32k)] pub fn pll_lp_clk_source_frequency() -> u32 { xtal32k_clk_frequency() } pub fn configure_hp_root_clk(clocks: &mut ClockTree, new_selector: HpRootClkConfig) { let old_selector = clocks.hp_root_clk.replace(new_selector); refresh_hp_root_clk_downstream(clocks); - if clocks.hp_root_clk_refcount > 0 { + let active = clocks.hp_root_clk_refcount > 0; + if active { match new_selector { HpRootClkConfig::Pll96 => request_pll_f96m_clk(clocks), HpRootClkConfig::Pll64 => request_pll_f64m_clk(clocks), HpRootClkConfig::Xtal => request_xtal_clk(clocks), HpRootClkConfig::RcFast => request_rc_fast_clk(clocks), } - configure_hp_root_clk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - HpRootClkConfig::Pll96 => release_pll_f96m_clk(clocks), - HpRootClkConfig::Pll64 => release_pll_f64m_clk(clocks), - HpRootClkConfig::Xtal => release_xtal_clk(clocks), - HpRootClkConfig::RcFast => release_rc_fast_clk(clocks), - } + } + configure_hp_root_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + HpRootClkConfig::Pll96 => release_pll_f96m_clk(clocks), + HpRootClkConfig::Pll64 => release_pll_f64m_clk(clocks), + HpRootClkConfig::Xtal => release_xtal_clk(clocks), + HpRootClkConfig::RcFast => release_rc_fast_clk(clocks), } - } else { - configure_hp_root_clk_impl(clocks, old_selector, new_selector); } } pub fn hp_root_clk_config(clocks: &mut ClockTree) -> Option { @@ -2435,11 +3012,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn hp_root_clk_config_frequency( - clocks: &mut ClockTree, - config: HpRootClkConfig, - ) -> u32 { + pub fn hp_root_clk_config_frequency(config: HpRootClkConfig) -> u32 { match config { HpRootClkConfig::Pll96 => pll_f96m_clk_frequency(), HpRootClkConfig::Pll64 => pll_f64m_clk_frequency(), @@ -2451,12 +3024,7 @@ macro_rules! define_clock_tree_types { HP_ROOT_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn hp_root_clk_source_frequency(source: HpRootClkConfig) -> u32 { - match source { - HpRootClkConfig::Pll96 => pll_f96m_clk_frequency(), - HpRootClkConfig::Pll64 => pll_f64m_clk_frequency(), - HpRootClkConfig::Xtal => xtal_clk_frequency(), - HpRootClkConfig::RcFast => rc_fast_clk_frequency(), - } + hp_root_clk_config_frequency(source) } pub fn configure_cpu_clk(clocks: &mut ClockTree, config: CpuClkConfig) { let old_config = clocks.cpu_clk.replace(config); @@ -2468,8 +3036,7 @@ macro_rules! define_clock_tree_types { } fn request_cpu_clk(_clocks: &mut ClockTree) {} fn release_cpu_clk(_clocks: &mut ClockTree) {} - #[allow(unused_variables)] - pub fn cpu_clk_config_frequency(clocks: &mut ClockTree, config: CpuClkConfig) -> u32 { + pub fn cpu_clk_config_frequency(config: CpuClkConfig) -> u32 { (hp_root_clk_frequency() / (config.divisor() + 1)) } pub fn cpu_clk_frequency() -> u32 { @@ -2488,8 +3055,7 @@ macro_rules! define_clock_tree_types { } fn request_ahb_clk(_clocks: &mut ClockTree) {} fn release_ahb_clk(_clocks: &mut ClockTree) {} - #[allow(unused_variables)] - pub fn ahb_clk_config_frequency(clocks: &mut ClockTree, config: AhbClkConfig) -> u32 { + pub fn ahb_clk_config_frequency(config: AhbClkConfig) -> u32 { (hp_root_clk_frequency() / (config.divisor() + 1)) } pub fn ahb_clk_frequency() -> u32 { @@ -2522,8 +3088,7 @@ macro_rules! define_clock_tree_types { release_ahb_clk(clocks); } } - #[allow(unused_variables)] - pub fn apb_clk_config_frequency(clocks: &mut ClockTree, config: ApbClkConfig) -> u32 { + pub fn apb_clk_config_frequency(config: ApbClkConfig) -> u32 { (ahb_clk_frequency() / (config.divisor() + 1)) } pub fn apb_clk_frequency() -> u32 { @@ -2533,13 +3098,11 @@ macro_rules! define_clock_tree_types { ahb_clk_frequency() } pub fn request_xtal_d2_clk(clocks: &mut ClockTree) { - trace!("Requesting XTAL_D2_CLK"); trace!("Enabling XTAL_D2_CLK"); request_xtal_clk(clocks); enable_xtal_d2_clk_impl(clocks, true); } pub fn release_xtal_d2_clk(clocks: &mut ClockTree) { - trace!("Releasing XTAL_D2_CLK"); trace!("Disabling XTAL_D2_CLK"); enable_xtal_d2_clk_impl(clocks, false); release_xtal_clk(clocks); @@ -2553,22 +3116,23 @@ macro_rules! define_clock_tree_types { pub fn configure_lp_fast_clk(clocks: &mut ClockTree, new_selector: LpFastClkConfig) { let old_selector = clocks.lp_fast_clk.replace(new_selector); refresh_lp_fast_clk_downstream(clocks); - if clocks.lp_fast_clk_refcount > 0 { + let active = clocks.lp_fast_clk_refcount > 0; + if active { match new_selector { LpFastClkConfig::RcFastClk => request_rc_fast_clk(clocks), + #[cfg(use_xtal32k)] LpFastClkConfig::PllLpClk => request_pll_lp_clk(clocks), LpFastClkConfig::XtalD2Clk => request_xtal_d2_clk(clocks), } - configure_lp_fast_clk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - LpFastClkConfig::RcFastClk => release_rc_fast_clk(clocks), - LpFastClkConfig::PllLpClk => release_pll_lp_clk(clocks), - LpFastClkConfig::XtalD2Clk => release_xtal_d2_clk(clocks), - } + } + configure_lp_fast_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + LpFastClkConfig::RcFastClk => release_rc_fast_clk(clocks), + #[cfg(use_xtal32k)] + LpFastClkConfig::PllLpClk => release_pll_lp_clk(clocks), + LpFastClkConfig::XtalD2Clk => release_xtal_d2_clk(clocks), } - } else { - configure_lp_fast_clk_impl(clocks, old_selector, new_selector); } } pub fn lp_fast_clk_config(clocks: &mut ClockTree) -> Option { @@ -2580,6 +3144,7 @@ macro_rules! define_clock_tree_types { trace!("Enabling LP_FAST_CLK"); match unwrap!(clocks.lp_fast_clk) { LpFastClkConfig::RcFastClk => request_rc_fast_clk(clocks), + #[cfg(use_xtal32k)] LpFastClkConfig::PllLpClk => request_pll_lp_clk(clocks), LpFastClkConfig::XtalD2Clk => request_xtal_d2_clk(clocks), } @@ -2593,18 +3158,16 @@ macro_rules! define_clock_tree_types { enable_lp_fast_clk_impl(clocks, false); match unwrap!(clocks.lp_fast_clk) { LpFastClkConfig::RcFastClk => release_rc_fast_clk(clocks), + #[cfg(use_xtal32k)] LpFastClkConfig::PllLpClk => release_pll_lp_clk(clocks), LpFastClkConfig::XtalD2Clk => release_xtal_d2_clk(clocks), } } } - #[allow(unused_variables)] - pub fn lp_fast_clk_config_frequency( - clocks: &mut ClockTree, - config: LpFastClkConfig, - ) -> u32 { + pub fn lp_fast_clk_config_frequency(config: LpFastClkConfig) -> u32 { match config { LpFastClkConfig::RcFastClk => rc_fast_clk_frequency(), + #[cfg(use_xtal32k)] LpFastClkConfig::PllLpClk => pll_lp_clk_frequency(), LpFastClkConfig::XtalD2Clk => xtal_d2_clk_frequency(), } @@ -2613,16 +3176,13 @@ macro_rules! define_clock_tree_types { LP_FAST_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn lp_fast_clk_source_frequency(source: LpFastClkConfig) -> u32 { - match source { - LpFastClkConfig::RcFastClk => rc_fast_clk_frequency(), - LpFastClkConfig::PllLpClk => pll_lp_clk_frequency(), - LpFastClkConfig::XtalD2Clk => xtal_d2_clk_frequency(), - } + lp_fast_clk_config_frequency(source) } pub fn configure_lp_slow_clk(clocks: &mut ClockTree, new_selector: LpSlowClkConfig) { let old_selector = clocks.lp_slow_clk.replace(new_selector); refresh_lp_slow_clk_downstream(clocks); match new_selector { + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => request_xtal32k_clk(clocks), LpSlowClkConfig::RcSlow => request_rc_slow_clk(clocks), LpSlowClkConfig::OscSlow => request_osc_slow_clk(clocks), @@ -2630,6 +3190,7 @@ macro_rules! define_clock_tree_types { configure_lp_slow_clk_impl(clocks, old_selector, new_selector); if let Some(old_selector) = old_selector { match old_selector { + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => release_xtal32k_clk(clocks), LpSlowClkConfig::RcSlow => release_rc_slow_clk(clocks), LpSlowClkConfig::OscSlow => release_osc_slow_clk(clocks), @@ -2640,9 +3201,9 @@ macro_rules! define_clock_tree_types { clocks.lp_slow_clk } pub fn request_lp_slow_clk(clocks: &mut ClockTree) { - trace!("Requesting LP_SLOW_CLK"); trace!("Enabling LP_SLOW_CLK"); match unwrap!(clocks.lp_slow_clk) { + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => request_xtal32k_clk(clocks), LpSlowClkConfig::RcSlow => request_rc_slow_clk(clocks), LpSlowClkConfig::OscSlow => request_osc_slow_clk(clocks), @@ -2650,21 +3211,18 @@ macro_rules! define_clock_tree_types { enable_lp_slow_clk_impl(clocks, true); } pub fn release_lp_slow_clk(clocks: &mut ClockTree) { - trace!("Releasing LP_SLOW_CLK"); trace!("Disabling LP_SLOW_CLK"); enable_lp_slow_clk_impl(clocks, false); match unwrap!(clocks.lp_slow_clk) { + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => release_xtal32k_clk(clocks), LpSlowClkConfig::RcSlow => release_rc_slow_clk(clocks), LpSlowClkConfig::OscSlow => release_osc_slow_clk(clocks), } } - #[allow(unused_variables)] - pub fn lp_slow_clk_config_frequency( - clocks: &mut ClockTree, - config: LpSlowClkConfig, - ) -> u32 { + pub fn lp_slow_clk_config_frequency(config: LpSlowClkConfig) -> u32 { match config { + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => xtal32k_clk_frequency(), LpSlowClkConfig::RcSlow => rc_slow_clk_frequency(), LpSlowClkConfig::OscSlow => osc_slow_clk_frequency(), @@ -2674,34 +3232,193 @@ macro_rules! define_clock_tree_types { LP_SLOW_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn lp_slow_clk_source_frequency(source: LpSlowClkConfig) -> u32 { - match source { - LpSlowClkConfig::Xtal32k => xtal32k_clk_frequency(), - LpSlowClkConfig::RcSlow => rc_slow_clk_frequency(), - LpSlowClkConfig::OscSlow => osc_slow_clk_frequency(), + lp_slow_clk_config_frequency(source) + } + pub fn request_ble_lp_xtal_clk(clocks: &mut ClockTree) { + trace!("Enabling BLE_LP_XTAL_CLK"); + request_xtal_clk(clocks); + enable_ble_lp_xtal_clk_impl(clocks, true); + } + pub fn release_ble_lp_xtal_clk(clocks: &mut ClockTree) { + trace!("Disabling BLE_LP_XTAL_CLK"); + enable_ble_lp_xtal_clk_impl(clocks, false); + release_xtal_clk(clocks); + } + pub fn ble_lp_xtal_clk_frequency() -> u32 { + 100000 + } + pub fn ble_lp_xtal_clk_source_frequency() -> u32 { + xtal_clk_frequency() + } + pub fn request_ble_lp_rc_slow_clk(clocks: &mut ClockTree) { + trace!("Enabling BLE_LP_RC_SLOW_CLK"); + request_rc_slow_clk(clocks); + enable_ble_lp_rc_slow_clk_impl(clocks, true); + } + pub fn release_ble_lp_rc_slow_clk(clocks: &mut ClockTree) { + trace!("Disabling BLE_LP_RC_SLOW_CLK"); + enable_ble_lp_rc_slow_clk_impl(clocks, false); + release_rc_slow_clk(clocks); + } + pub fn ble_lp_rc_slow_clk_frequency() -> u32 { + (rc_slow_clk_frequency() / 5) + } + pub fn ble_lp_rc_slow_clk_source_frequency() -> u32 { + rc_slow_clk_frequency() + } + pub fn configure_ble_lp_clk(clocks: &mut ClockTree, new_selector: BleLpClkConfig) { + let old_selector = clocks.ble_lp_clk.replace(new_selector); + refresh_ble_lp_clk_downstream(clocks); + let active = clocks.ble_lp_clk_refcount > 0; + if active { + match new_selector { + BleLpClkConfig::Xtal => request_ble_lp_xtal_clk(clocks), + BleLpClkConfig::RcSlow => request_ble_lp_rc_slow_clk(clocks), + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => request_xtal32k_clk(clocks), + } + } + configure_ble_lp_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + BleLpClkConfig::Xtal => release_ble_lp_xtal_clk(clocks), + BleLpClkConfig::RcSlow => release_ble_lp_rc_slow_clk(clocks), + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => release_xtal32k_clk(clocks), + } + } + } + pub fn ble_lp_clk_config(clocks: &mut ClockTree) -> Option { + clocks.ble_lp_clk + } + pub fn request_ble_lp_clk(clocks: &mut ClockTree) { + trace!("Requesting BLE_LP_CLK"); + if increment_reference_count(&mut clocks.ble_lp_clk_refcount) { + trace!("Enabling BLE_LP_CLK"); + match unwrap!(clocks.ble_lp_clk) { + BleLpClkConfig::Xtal => request_ble_lp_xtal_clk(clocks), + BleLpClkConfig::RcSlow => request_ble_lp_rc_slow_clk(clocks), + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => request_xtal32k_clk(clocks), + } + enable_ble_lp_clk_impl(clocks, true); + } + } + pub fn release_ble_lp_clk(clocks: &mut ClockTree) { + trace!("Releasing BLE_LP_CLK"); + if decrement_reference_count(&mut clocks.ble_lp_clk_refcount) { + trace!("Disabling BLE_LP_CLK"); + enable_ble_lp_clk_impl(clocks, false); + match unwrap!(clocks.ble_lp_clk) { + BleLpClkConfig::Xtal => release_ble_lp_xtal_clk(clocks), + BleLpClkConfig::RcSlow => release_ble_lp_rc_slow_clk(clocks), + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => release_xtal32k_clk(clocks), + } + } + } + pub fn ble_lp_clk_config_frequency(config: BleLpClkConfig) -> u32 { + match config { + BleLpClkConfig::Xtal => ble_lp_xtal_clk_frequency(), + BleLpClkConfig::RcSlow => ble_lp_rc_slow_clk_frequency(), + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => xtal32k_clk_frequency(), } } + pub fn ble_lp_clk_frequency() -> u32 { + BLE_LP_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn ble_lp_clk_source_frequency(source: BleLpClkConfig) -> u32 { + ble_lp_clk_config_frequency(source) + } + pub fn configure_crypto_clk(clocks: &mut ClockTree, new_selector: CryptoClkConfig) { + let old_selector = clocks.crypto_clk.replace(new_selector); + refresh_crypto_clk_downstream(clocks); + let active = clocks.crypto_clk_refcount > 0; + if active { + match new_selector { + CryptoClkConfig::Xtal => request_xtal_clk(clocks), + CryptoClkConfig::RcFast => request_rc_fast_clk(clocks), + CryptoClkConfig::PllF64m => request_pll_f64m_clk(clocks), + CryptoClkConfig::PllF96m => request_pll_f96m_clk(clocks), + } + } + configure_crypto_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + CryptoClkConfig::Xtal => release_xtal_clk(clocks), + CryptoClkConfig::RcFast => release_rc_fast_clk(clocks), + CryptoClkConfig::PllF64m => release_pll_f64m_clk(clocks), + CryptoClkConfig::PllF96m => release_pll_f96m_clk(clocks), + } + } + } + pub fn crypto_clk_config(clocks: &mut ClockTree) -> Option { + clocks.crypto_clk + } + pub fn request_crypto_clk(clocks: &mut ClockTree) { + trace!("Requesting CRYPTO_CLK"); + if increment_reference_count(&mut clocks.crypto_clk_refcount) { + trace!("Enabling CRYPTO_CLK"); + match unwrap!(clocks.crypto_clk) { + CryptoClkConfig::Xtal => request_xtal_clk(clocks), + CryptoClkConfig::RcFast => request_rc_fast_clk(clocks), + CryptoClkConfig::PllF64m => request_pll_f64m_clk(clocks), + CryptoClkConfig::PllF96m => request_pll_f96m_clk(clocks), + } + enable_crypto_clk_impl(clocks, true); + } + } + pub fn release_crypto_clk(clocks: &mut ClockTree) { + trace!("Releasing CRYPTO_CLK"); + if decrement_reference_count(&mut clocks.crypto_clk_refcount) { + trace!("Disabling CRYPTO_CLK"); + enable_crypto_clk_impl(clocks, false); + match unwrap!(clocks.crypto_clk) { + CryptoClkConfig::Xtal => release_xtal_clk(clocks), + CryptoClkConfig::RcFast => release_rc_fast_clk(clocks), + CryptoClkConfig::PllF64m => release_pll_f64m_clk(clocks), + CryptoClkConfig::PllF96m => release_pll_f96m_clk(clocks), + } + } + } + pub fn crypto_clk_config_frequency(config: CryptoClkConfig) -> u32 { + match config { + CryptoClkConfig::Xtal => xtal_clk_frequency(), + CryptoClkConfig::RcFast => rc_fast_clk_frequency(), + CryptoClkConfig::PllF64m => pll_f64m_clk_frequency(), + CryptoClkConfig::PllF96m => pll_f96m_clk_frequency(), + } + } + pub fn crypto_clk_frequency() -> u32 { + CRYPTO_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn crypto_clk_source_frequency(source: CryptoClkConfig) -> u32 { + crypto_clk_config_frequency(source) + } pub fn configure_timg_calibration_clock( clocks: &mut ClockTree, new_selector: TimgCalibrationClockConfig, ) { let old_selector = clocks.timg_calibration_clock.replace(new_selector); refresh_timg_calibration_clock_downstream(clocks); - if clocks.timg_calibration_clock_refcount > 0 { + let active = clocks.timg_calibration_clock_refcount > 0; + if active { match new_selector { TimgCalibrationClockConfig::RcSlowClk => request_lp_slow_clk(clocks), TimgCalibrationClockConfig::RcFastDivClk => request_rc_fast_clk(clocks), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => request_xtal32k_clk(clocks), } - configure_timg_calibration_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - TimgCalibrationClockConfig::RcSlowClk => release_lp_slow_clk(clocks), - TimgCalibrationClockConfig::RcFastDivClk => release_rc_fast_clk(clocks), - TimgCalibrationClockConfig::Xtal32kClk => release_xtal32k_clk(clocks), - } + } + configure_timg_calibration_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + TimgCalibrationClockConfig::RcSlowClk => release_lp_slow_clk(clocks), + TimgCalibrationClockConfig::RcFastDivClk => release_rc_fast_clk(clocks), + #[cfg(use_xtal32k)] + TimgCalibrationClockConfig::Xtal32kClk => release_xtal32k_clk(clocks), } - } else { - configure_timg_calibration_clock_impl(clocks, old_selector, new_selector); } } pub fn timg_calibration_clock_config( @@ -2717,6 +3434,7 @@ macro_rules! define_clock_tree_types { match unwrap!(clocks.timg_calibration_clock) { TimgCalibrationClockConfig::RcSlowClk => request_lp_slow_clk(clocks), TimgCalibrationClockConfig::RcFastDivClk => request_rc_fast_clk(clocks), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => request_xtal32k_clk(clocks), } enable_timg_calibration_clock_impl(clocks, true); @@ -2731,18 +3449,16 @@ macro_rules! define_clock_tree_types { match unwrap!(clocks.timg_calibration_clock) { TimgCalibrationClockConfig::RcSlowClk => release_lp_slow_clk(clocks), TimgCalibrationClockConfig::RcFastDivClk => release_rc_fast_clk(clocks), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => release_xtal32k_clk(clocks), } } } - #[allow(unused_variables)] - pub fn timg_calibration_clock_config_frequency( - clocks: &mut ClockTree, - config: TimgCalibrationClockConfig, - ) -> u32 { + pub fn timg_calibration_clock_config_frequency(config: TimgCalibrationClockConfig) -> u32 { match config { TimgCalibrationClockConfig::RcSlowClk => lp_slow_clk_frequency(), TimgCalibrationClockConfig::RcFastDivClk => rc_fast_clk_frequency(), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => xtal32k_clk_frequency(), } } @@ -2750,10 +3466,78 @@ macro_rules! define_clock_tree_types { TIMG_CALIBRATION_CLOCK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn timg_calibration_clock_source_frequency(source: TimgCalibrationClockConfig) -> u32 { - match source { - TimgCalibrationClockConfig::RcSlowClk => lp_slow_clk_frequency(), - TimgCalibrationClockConfig::RcFastDivClk => rc_fast_clk_frequency(), - TimgCalibrationClockConfig::Xtal32kClk => xtal32k_clk_frequency(), + timg_calibration_clock_config_frequency(source) + } + impl AdcInstance { + pub fn configure_function_clock( + self, + clocks: &mut ClockTree, + new_selector: AdcFunctionClockConfig, + ) { + let old_selector = clocks.adc_function_clock[self as usize].replace(new_selector); + refresh_adc_function_clock_downstream(clocks, self); + let active = clocks.adc_function_clock_refcount[self as usize] > 0; + if active { + match new_selector { + AdcFunctionClockConfig::Xtal => request_xtal_clk(clocks), + AdcFunctionClockConfig::PllF96m => request_pll_f96m_clk(clocks), + AdcFunctionClockConfig::RcFast => request_rc_fast_clk(clocks), + } + } + self.configure_function_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + AdcFunctionClockConfig::Xtal => release_xtal_clk(clocks), + AdcFunctionClockConfig::PllF96m => release_pll_f96m_clk(clocks), + AdcFunctionClockConfig::RcFast => release_rc_fast_clk(clocks), + } + } + } + pub fn function_clock_config( + self, + clocks: &mut ClockTree, + ) -> Option { + clocks.adc_function_clock[self as usize] + } + pub fn request_function_clock(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::FUNCTION_CLOCK", self); + if increment_reference_count(&mut clocks.adc_function_clock_refcount[self as usize]) + { + trace!("Enabling {:?}::FUNCTION_CLOCK", self); + match unwrap!(clocks.adc_function_clock[self as usize]) { + AdcFunctionClockConfig::Xtal => request_xtal_clk(clocks), + AdcFunctionClockConfig::PllF96m => request_pll_f96m_clk(clocks), + AdcFunctionClockConfig::RcFast => request_rc_fast_clk(clocks), + } + self.enable_function_clock_impl(clocks, true); + } + } + pub fn release_function_clock(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::FUNCTION_CLOCK", self); + if decrement_reference_count(&mut clocks.adc_function_clock_refcount[self as usize]) + { + trace!("Disabling {:?}::FUNCTION_CLOCK", self); + self.enable_function_clock_impl(clocks, false); + match unwrap!(clocks.adc_function_clock[self as usize]) { + AdcFunctionClockConfig::Xtal => release_xtal_clk(clocks), + AdcFunctionClockConfig::PllF96m => release_pll_f96m_clk(clocks), + AdcFunctionClockConfig::RcFast => release_rc_fast_clk(clocks), + } + } + } + pub fn function_clock_config_frequency(config: AdcFunctionClockConfig) -> u32 { + match config { + AdcFunctionClockConfig::Xtal => xtal_clk_frequency(), + AdcFunctionClockConfig::PllF96m => pll_f96m_clk_frequency(), + AdcFunctionClockConfig::RcFast => rc_fast_clk_frequency(), + } + } + pub fn function_clock_frequency(self) -> u32 { + ADC_FUNCTION_CLOCK_FREQ_CACHE[self as usize] + .load(::core::sync::atomic::Ordering::Acquire) + } + pub fn function_clock_source_frequency(source: AdcFunctionClockConfig) -> u32 { + Self::function_clock_config_frequency(source) } } impl SdmInstance { @@ -2790,20 +3574,19 @@ macro_rules! define_clock_tree_types { ) { let old_config = clocks.i2c_function_clock[self as usize].replace(config); refresh_i2c_function_clock_downstream(clocks, self); - if clocks.i2c_function_clock_refcount[self as usize] > 0 { + let active = clocks.i2c_function_clock_refcount[self as usize] > 0; + if active { match config.sclk { I2cFunctionClockSclk::Xtal => request_xtal_clk(clocks), I2cFunctionClockSclk::RcFast => request_rc_fast_clk(clocks), } - self.configure_function_clock_impl(clocks, old_config, config); - if let Some(old_config) = old_config { - match old_config.sclk { - I2cFunctionClockSclk::Xtal => release_xtal_clk(clocks), - I2cFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), - } + } + self.configure_function_clock_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + I2cFunctionClockSclk::Xtal => release_xtal_clk(clocks), + I2cFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_config, config); } } pub fn function_clock_config( @@ -2838,11 +3621,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: I2cFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: I2cFunctionClockConfig) -> u32 { (match config.sclk { I2cFunctionClockSclk::Xtal => xtal_clk_frequency(), I2cFunctionClockSclk::RcFast => rc_fast_clk_frequency(), @@ -2859,6 +3638,202 @@ macro_rules! define_clock_tree_types { } } } + impl I2sInstance { + pub fn configure_tx_clk(self, clocks: &mut ClockTree, config: I2sClkConfig) { + let old_config = clocks.i2s_tx_clk[self as usize].replace(config); + refresh_i2s_tx_clk_downstream(clocks, self); + let active = clocks.i2s_tx_clk_refcount[self as usize] > 0; + if active { + match config.sclk { + I2sClkSclk::Xtal => request_xtal_clk(clocks), + I2sClkSclk::PllF96m => request_pll_f96m_clk(clocks), + I2sClkSclk::PllF64m => request_pll_f64m_clk(clocks), + } + } + self.configure_tx_clk_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + I2sClkSclk::Xtal => release_xtal_clk(clocks), + I2sClkSclk::PllF96m => release_pll_f96m_clk(clocks), + I2sClkSclk::PllF64m => release_pll_f64m_clk(clocks), + } + } + } + pub fn tx_clk_config(self, clocks: &mut ClockTree) -> Option { + clocks.i2s_tx_clk[self as usize] + } + pub fn request_tx_clk(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::TX_CLK", self); + if increment_reference_count(&mut clocks.i2s_tx_clk_refcount[self as usize]) { + trace!("Enabling {:?}::TX_CLK", self); + crate::rtc_cntl::WakeLock::acquire(); + match unwrap!(clocks.i2s_tx_clk[self as usize]).sclk { + I2sClkSclk::Xtal => request_xtal_clk(clocks), + I2sClkSclk::PllF96m => request_pll_f96m_clk(clocks), + I2sClkSclk::PllF64m => request_pll_f64m_clk(clocks), + } + self.enable_tx_clk_impl(clocks, true); + } + } + pub fn release_tx_clk(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::TX_CLK", self); + if decrement_reference_count(&mut clocks.i2s_tx_clk_refcount[self as usize]) { + trace!("Disabling {:?}::TX_CLK", self); + crate::rtc_cntl::WakeLock::release(); + self.enable_tx_clk_impl(clocks, false); + match unwrap!(clocks.i2s_tx_clk[self as usize]).sclk { + I2sClkSclk::Xtal => release_xtal_clk(clocks), + I2sClkSclk::PllF96m => release_pll_f96m_clk(clocks), + I2sClkSclk::PllF64m => release_pll_f64m_clk(clocks), + } + } + } + pub fn tx_clk_config_frequency(config: I2sClkConfig) -> u32 { + (((match config.sclk { + I2sClkSclk::Xtal => xtal_clk_frequency(), + I2sClkSclk::PllF96m => pll_f96m_clk_frequency(), + I2sClkSclk::PllF64m => pll_f64m_clk_frequency(), + } as u64) + * (config.div_a() as u64)) + / (((config.div_num() * config.div_a()) + config.div_b()) as u64)) + as u32 + } + pub fn tx_clk_frequency(self) -> u32 { + I2S_TX_CLK_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) + } + pub fn tx_clk_source_frequency(sclk: I2sClkSclk) -> u32 { + match sclk { + I2sClkSclk::Xtal => xtal_clk_frequency(), + I2sClkSclk::PllF96m => pll_f96m_clk_frequency(), + I2sClkSclk::PllF64m => pll_f64m_clk_frequency(), + } + } + pub fn configure_rx_clk(self, clocks: &mut ClockTree, config: I2sClkConfig) { + let old_config = clocks.i2s_rx_clk[self as usize].replace(config); + refresh_i2s_rx_clk_downstream(clocks, self); + let active = clocks.i2s_rx_clk_refcount[self as usize] > 0; + if active { + match config.sclk { + I2sClkSclk::Xtal => request_xtal_clk(clocks), + I2sClkSclk::PllF96m => request_pll_f96m_clk(clocks), + I2sClkSclk::PllF64m => request_pll_f64m_clk(clocks), + } + } + self.configure_rx_clk_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + I2sClkSclk::Xtal => release_xtal_clk(clocks), + I2sClkSclk::PllF96m => release_pll_f96m_clk(clocks), + I2sClkSclk::PllF64m => release_pll_f64m_clk(clocks), + } + } + } + pub fn rx_clk_config(self, clocks: &mut ClockTree) -> Option { + clocks.i2s_rx_clk[self as usize] + } + pub fn request_rx_clk(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::RX_CLK", self); + if increment_reference_count(&mut clocks.i2s_rx_clk_refcount[self as usize]) { + trace!("Enabling {:?}::RX_CLK", self); + crate::rtc_cntl::WakeLock::acquire(); + match unwrap!(clocks.i2s_rx_clk[self as usize]).sclk { + I2sClkSclk::Xtal => request_xtal_clk(clocks), + I2sClkSclk::PllF96m => request_pll_f96m_clk(clocks), + I2sClkSclk::PllF64m => request_pll_f64m_clk(clocks), + } + self.enable_rx_clk_impl(clocks, true); + } + } + pub fn release_rx_clk(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::RX_CLK", self); + if decrement_reference_count(&mut clocks.i2s_rx_clk_refcount[self as usize]) { + trace!("Disabling {:?}::RX_CLK", self); + crate::rtc_cntl::WakeLock::release(); + self.enable_rx_clk_impl(clocks, false); + match unwrap!(clocks.i2s_rx_clk[self as usize]).sclk { + I2sClkSclk::Xtal => release_xtal_clk(clocks), + I2sClkSclk::PllF96m => release_pll_f96m_clk(clocks), + I2sClkSclk::PllF64m => release_pll_f64m_clk(clocks), + } + } + } + pub fn rx_clk_config_frequency(config: I2sClkConfig) -> u32 { + (((match config.sclk { + I2sClkSclk::Xtal => xtal_clk_frequency(), + I2sClkSclk::PllF96m => pll_f96m_clk_frequency(), + I2sClkSclk::PllF64m => pll_f64m_clk_frequency(), + } as u64) + * (config.div_a() as u64)) + / (((config.div_num() * config.div_a()) + config.div_b()) as u64)) + as u32 + } + pub fn rx_clk_frequency(self) -> u32 { + I2S_RX_CLK_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) + } + pub fn rx_clk_source_frequency(sclk: I2sClkSclk) -> u32 { + match sclk { + I2sClkSclk::Xtal => xtal_clk_frequency(), + I2sClkSclk::PllF96m => pll_f96m_clk_frequency(), + I2sClkSclk::PllF64m => pll_f64m_clk_frequency(), + } + } + pub fn configure_mclk_out( + self, + clocks: &mut ClockTree, + new_selector: I2sMclkOutConfig, + ) { + let old_selector = clocks.i2s_mclk_out[self as usize].replace(new_selector); + refresh_i2s_mclk_out_downstream(clocks, self); + let active = clocks.i2s_mclk_out_refcount[self as usize] > 0; + if active { + match new_selector { + I2sMclkOutConfig::Tx => self.request_tx_clk(clocks), + I2sMclkOutConfig::Rx => self.request_rx_clk(clocks), + } + } + self.configure_mclk_out_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + I2sMclkOutConfig::Tx => self.release_tx_clk(clocks), + I2sMclkOutConfig::Rx => self.release_rx_clk(clocks), + } + } + } + pub fn mclk_out_config(self, clocks: &mut ClockTree) -> Option { + clocks.i2s_mclk_out[self as usize] + } + pub fn request_mclk_out(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::MCLK_OUT", self); + if increment_reference_count(&mut clocks.i2s_mclk_out_refcount[self as usize]) { + trace!("Enabling {:?}::MCLK_OUT", self); + match unwrap!(clocks.i2s_mclk_out[self as usize]) { + I2sMclkOutConfig::Tx => self.request_tx_clk(clocks), + I2sMclkOutConfig::Rx => self.request_rx_clk(clocks), + } + self.enable_mclk_out_impl(clocks, true); + } + } + pub fn release_mclk_out(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::MCLK_OUT", self); + if decrement_reference_count(&mut clocks.i2s_mclk_out_refcount[self as usize]) { + trace!("Disabling {:?}::MCLK_OUT", self); + self.enable_mclk_out_impl(clocks, false); + match unwrap!(clocks.i2s_mclk_out[self as usize]) { + I2sMclkOutConfig::Tx => self.release_tx_clk(clocks), + I2sMclkOutConfig::Rx => self.release_rx_clk(clocks), + } + } + } + pub fn mclk_out_config_frequency(self, config: I2sMclkOutConfig) -> u32 { + match config { + I2sMclkOutConfig::Tx => self.tx_clk_frequency(), + I2sMclkOutConfig::Rx => self.rx_clk_frequency(), + } + } + pub fn mclk_out_frequency(self) -> u32 { + I2S_MCLK_OUT_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) + } + } impl McpwmInstance { pub fn configure_function_clock( self, @@ -2867,22 +3842,21 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.mcpwm_function_clock[self as usize].replace(new_selector); refresh_mcpwm_function_clock_downstream(clocks, self); - if clocks.mcpwm_function_clock_refcount[self as usize] > 0 { + let active = clocks.mcpwm_function_clock_refcount[self as usize] > 0; + if active { match new_selector { McpwmFunctionClockConfig::PllF96m => request_pll_f96m_clk(clocks), McpwmFunctionClockConfig::RcFastClk => request_rc_fast_clk(clocks), McpwmFunctionClockConfig::XtalClk => request_xtal_clk(clocks), } - self.configure_function_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - McpwmFunctionClockConfig::PllF96m => release_pll_f96m_clk(clocks), - McpwmFunctionClockConfig::RcFastClk => release_rc_fast_clk(clocks), - McpwmFunctionClockConfig::XtalClk => release_xtal_clk(clocks), - } + } + self.configure_function_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + McpwmFunctionClockConfig::PllF96m => release_pll_f96m_clk(clocks), + McpwmFunctionClockConfig::RcFastClk => release_rc_fast_clk(clocks), + McpwmFunctionClockConfig::XtalClk => release_xtal_clk(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_selector, new_selector); } } pub fn function_clock_config( @@ -2921,11 +3895,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: McpwmFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: McpwmFunctionClockConfig) -> u32 { match config { McpwmFunctionClockConfig::PllF96m => pll_f96m_clk_frequency(), McpwmFunctionClockConfig::RcFastClk => rc_fast_clk_frequency(), @@ -2937,40 +3907,31 @@ macro_rules! define_clock_tree_types { .load(::core::sync::atomic::Ordering::Acquire) } pub fn function_clock_source_frequency(source: McpwmFunctionClockConfig) -> u32 { - match source { - McpwmFunctionClockConfig::PllF96m => pll_f96m_clk_frequency(), - McpwmFunctionClockConfig::RcFastClk => rc_fast_clk_frequency(), - McpwmFunctionClockConfig::XtalClk => xtal_clk_frequency(), - } + Self::function_clock_config_frequency(source) } } impl ParlIoInstance { - pub fn configure_rx_clock( - self, - clocks: &mut ClockTree, - new_selector: ParlIoRxClockConfig, - ) { + pub fn configure_rx_clock(self, clocks: &mut ClockTree, new_selector: ParlIoClkConfig) { let old_selector = clocks.parl_io_rx_clock[self as usize].replace(new_selector); refresh_parl_io_rx_clock_downstream(clocks, self); - if clocks.parl_io_rx_clock_refcount[self as usize] > 0 { + let active = clocks.parl_io_rx_clock_refcount[self as usize] > 0; + if active { match new_selector { - ParlIoRxClockConfig::XtalClk => request_xtal_clk(clocks), - ParlIoRxClockConfig::RcFastClk => request_rc_fast_clk(clocks), - ParlIoRxClockConfig::PllF96m => request_pll_f96m_clk(clocks), + ParlIoClkConfig::XtalClk => request_xtal_clk(clocks), + ParlIoClkConfig::RcFastClk => request_rc_fast_clk(clocks), + ParlIoClkConfig::PllF96m => request_pll_f96m_clk(clocks), } - self.configure_rx_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - ParlIoRxClockConfig::XtalClk => release_xtal_clk(clocks), - ParlIoRxClockConfig::RcFastClk => release_rc_fast_clk(clocks), - ParlIoRxClockConfig::PllF96m => release_pll_f96m_clk(clocks), - } + } + self.configure_rx_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + ParlIoClkConfig::XtalClk => release_xtal_clk(clocks), + ParlIoClkConfig::RcFastClk => release_rc_fast_clk(clocks), + ParlIoClkConfig::PllF96m => release_pll_f96m_clk(clocks), } - } else { - self.configure_rx_clock_impl(clocks, old_selector, new_selector); } } - pub fn rx_clock_config(self, clocks: &mut ClockTree) -> Option { + pub fn rx_clock_config(self, clocks: &mut ClockTree) -> Option { clocks.parl_io_rx_clock[self as usize] } pub fn request_rx_clock(self, clocks: &mut ClockTree) { @@ -2979,9 +3940,9 @@ macro_rules! define_clock_tree_types { trace!("Enabling {:?}::RX_CLOCK", self); crate::rtc_cntl::WakeLock::acquire(); match unwrap!(clocks.parl_io_rx_clock[self as usize]) { - ParlIoRxClockConfig::XtalClk => request_xtal_clk(clocks), - ParlIoRxClockConfig::RcFastClk => request_rc_fast_clk(clocks), - ParlIoRxClockConfig::PllF96m => request_pll_f96m_clk(clocks), + ParlIoClkConfig::XtalClk => request_xtal_clk(clocks), + ParlIoClkConfig::RcFastClk => request_rc_fast_clk(clocks), + ParlIoClkConfig::PllF96m => request_pll_f96m_clk(clocks), } self.enable_rx_clock_impl(clocks, true); } @@ -2993,60 +3954,47 @@ macro_rules! define_clock_tree_types { crate::rtc_cntl::WakeLock::release(); self.enable_rx_clock_impl(clocks, false); match unwrap!(clocks.parl_io_rx_clock[self as usize]) { - ParlIoRxClockConfig::XtalClk => release_xtal_clk(clocks), - ParlIoRxClockConfig::RcFastClk => release_rc_fast_clk(clocks), - ParlIoRxClockConfig::PllF96m => release_pll_f96m_clk(clocks), + ParlIoClkConfig::XtalClk => release_xtal_clk(clocks), + ParlIoClkConfig::RcFastClk => release_rc_fast_clk(clocks), + ParlIoClkConfig::PllF96m => release_pll_f96m_clk(clocks), } } } - #[allow(unused_variables)] - pub fn rx_clock_config_frequency( - clocks: &mut ClockTree, - config: ParlIoRxClockConfig, - ) -> u32 { + pub fn rx_clock_config_frequency(config: ParlIoClkConfig) -> u32 { match config { - ParlIoRxClockConfig::XtalClk => xtal_clk_frequency(), - ParlIoRxClockConfig::RcFastClk => rc_fast_clk_frequency(), - ParlIoRxClockConfig::PllF96m => pll_f96m_clk_frequency(), + ParlIoClkConfig::XtalClk => xtal_clk_frequency(), + ParlIoClkConfig::RcFastClk => rc_fast_clk_frequency(), + ParlIoClkConfig::PllF96m => pll_f96m_clk_frequency(), } } pub fn rx_clock_frequency(self) -> u32 { PARL_IO_RX_CLOCK_FREQ_CACHE[self as usize] .load(::core::sync::atomic::Ordering::Acquire) } - pub fn rx_clock_source_frequency(source: ParlIoRxClockConfig) -> u32 { - match source { - ParlIoRxClockConfig::XtalClk => xtal_clk_frequency(), - ParlIoRxClockConfig::RcFastClk => rc_fast_clk_frequency(), - ParlIoRxClockConfig::PllF96m => pll_f96m_clk_frequency(), - } + pub fn rx_clock_source_frequency(source: ParlIoClkConfig) -> u32 { + Self::rx_clock_config_frequency(source) } - pub fn configure_tx_clock( - self, - clocks: &mut ClockTree, - new_selector: ParlIoTxClockConfig, - ) { + pub fn configure_tx_clock(self, clocks: &mut ClockTree, new_selector: ParlIoClkConfig) { let old_selector = clocks.parl_io_tx_clock[self as usize].replace(new_selector); refresh_parl_io_tx_clock_downstream(clocks, self); - if clocks.parl_io_tx_clock_refcount[self as usize] > 0 { + let active = clocks.parl_io_tx_clock_refcount[self as usize] > 0; + if active { match new_selector { - ParlIoTxClockConfig::XtalClk => request_xtal_clk(clocks), - ParlIoTxClockConfig::RcFastClk => request_rc_fast_clk(clocks), - ParlIoTxClockConfig::PllF96m => request_pll_f96m_clk(clocks), + ParlIoClkConfig::XtalClk => request_xtal_clk(clocks), + ParlIoClkConfig::RcFastClk => request_rc_fast_clk(clocks), + ParlIoClkConfig::PllF96m => request_pll_f96m_clk(clocks), } - self.configure_tx_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - ParlIoTxClockConfig::XtalClk => release_xtal_clk(clocks), - ParlIoTxClockConfig::RcFastClk => release_rc_fast_clk(clocks), - ParlIoTxClockConfig::PllF96m => release_pll_f96m_clk(clocks), - } + } + self.configure_tx_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + ParlIoClkConfig::XtalClk => release_xtal_clk(clocks), + ParlIoClkConfig::RcFastClk => release_rc_fast_clk(clocks), + ParlIoClkConfig::PllF96m => release_pll_f96m_clk(clocks), } - } else { - self.configure_tx_clock_impl(clocks, old_selector, new_selector); } } - pub fn tx_clock_config(self, clocks: &mut ClockTree) -> Option { + pub fn tx_clock_config(self, clocks: &mut ClockTree) -> Option { clocks.parl_io_tx_clock[self as usize] } pub fn request_tx_clock(self, clocks: &mut ClockTree) { @@ -3055,9 +4003,9 @@ macro_rules! define_clock_tree_types { trace!("Enabling {:?}::TX_CLOCK", self); crate::rtc_cntl::WakeLock::acquire(); match unwrap!(clocks.parl_io_tx_clock[self as usize]) { - ParlIoTxClockConfig::XtalClk => request_xtal_clk(clocks), - ParlIoTxClockConfig::RcFastClk => request_rc_fast_clk(clocks), - ParlIoTxClockConfig::PllF96m => request_pll_f96m_clk(clocks), + ParlIoClkConfig::XtalClk => request_xtal_clk(clocks), + ParlIoClkConfig::RcFastClk => request_rc_fast_clk(clocks), + ParlIoClkConfig::PllF96m => request_pll_f96m_clk(clocks), } self.enable_tx_clock_impl(clocks, true); } @@ -3069,53 +4017,44 @@ macro_rules! define_clock_tree_types { crate::rtc_cntl::WakeLock::release(); self.enable_tx_clock_impl(clocks, false); match unwrap!(clocks.parl_io_tx_clock[self as usize]) { - ParlIoTxClockConfig::XtalClk => release_xtal_clk(clocks), - ParlIoTxClockConfig::RcFastClk => release_rc_fast_clk(clocks), - ParlIoTxClockConfig::PllF96m => release_pll_f96m_clk(clocks), + ParlIoClkConfig::XtalClk => release_xtal_clk(clocks), + ParlIoClkConfig::RcFastClk => release_rc_fast_clk(clocks), + ParlIoClkConfig::PllF96m => release_pll_f96m_clk(clocks), } } } - #[allow(unused_variables)] - pub fn tx_clock_config_frequency( - clocks: &mut ClockTree, - config: ParlIoTxClockConfig, - ) -> u32 { + pub fn tx_clock_config_frequency(config: ParlIoClkConfig) -> u32 { match config { - ParlIoTxClockConfig::XtalClk => xtal_clk_frequency(), - ParlIoTxClockConfig::RcFastClk => rc_fast_clk_frequency(), - ParlIoTxClockConfig::PllF96m => pll_f96m_clk_frequency(), + ParlIoClkConfig::XtalClk => xtal_clk_frequency(), + ParlIoClkConfig::RcFastClk => rc_fast_clk_frequency(), + ParlIoClkConfig::PllF96m => pll_f96m_clk_frequency(), } } pub fn tx_clock_frequency(self) -> u32 { PARL_IO_TX_CLOCK_FREQ_CACHE[self as usize] .load(::core::sync::atomic::Ordering::Acquire) } - pub fn tx_clock_source_frequency(source: ParlIoTxClockConfig) -> u32 { - match source { - ParlIoTxClockConfig::XtalClk => xtal_clk_frequency(), - ParlIoTxClockConfig::RcFastClk => rc_fast_clk_frequency(), - ParlIoTxClockConfig::PllF96m => pll_f96m_clk_frequency(), - } + pub fn tx_clock_source_frequency(source: ParlIoClkConfig) -> u32 { + Self::tx_clock_config_frequency(source) } } impl RmtInstance { pub fn configure_sclk(self, clocks: &mut ClockTree, new_selector: RmtSclkConfig) { let old_selector = clocks.rmt_sclk[self as usize].replace(new_selector); refresh_rmt_sclk_downstream(clocks, self); - if clocks.rmt_sclk_refcount[self as usize] > 0 { + let active = clocks.rmt_sclk_refcount[self as usize] > 0; + if active { match new_selector { RmtSclkConfig::XtalClk => request_xtal_clk(clocks), RmtSclkConfig::RcFastClk => request_rc_fast_clk(clocks), } - self.configure_sclk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - RmtSclkConfig::XtalClk => release_xtal_clk(clocks), - RmtSclkConfig::RcFastClk => release_rc_fast_clk(clocks), - } + } + self.configure_sclk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + RmtSclkConfig::XtalClk => release_xtal_clk(clocks), + RmtSclkConfig::RcFastClk => release_rc_fast_clk(clocks), } - } else { - self.configure_sclk_impl(clocks, old_selector, new_selector); } } pub fn sclk_config(self, clocks: &mut ClockTree) -> Option { @@ -3145,8 +4084,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn sclk_config_frequency(clocks: &mut ClockTree, config: RmtSclkConfig) -> u32 { + pub fn sclk_config_frequency(config: RmtSclkConfig) -> u32 { match config { RmtSclkConfig::XtalClk => xtal_clk_frequency(), RmtSclkConfig::RcFastClk => rc_fast_clk_frequency(), @@ -3156,10 +4094,7 @@ macro_rules! define_clock_tree_types { RMT_SCLK_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) } pub fn sclk_source_frequency(source: RmtSclkConfig) -> u32 { - match source { - RmtSclkConfig::XtalClk => xtal_clk_frequency(), - RmtSclkConfig::RcFastClk => rc_fast_clk_frequency(), - } + Self::sclk_config_frequency(source) } } impl SpiInstance { @@ -3170,22 +4105,21 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.spi_function_clock[self as usize].replace(new_selector); refresh_spi_function_clock_downstream(clocks, self); - if clocks.spi_function_clock_refcount[self as usize] > 0 { + let active = clocks.spi_function_clock_refcount[self as usize] > 0; + if active { match new_selector { SpiFunctionClockConfig::Xtal => request_xtal_clk(clocks), SpiFunctionClockConfig::PllF48m => request_pll_f48m_clk(clocks), SpiFunctionClockConfig::RcFast => request_rc_fast_clk(clocks), } - self.configure_function_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - SpiFunctionClockConfig::Xtal => release_xtal_clk(clocks), - SpiFunctionClockConfig::PllF48m => release_pll_f48m_clk(clocks), - SpiFunctionClockConfig::RcFast => release_rc_fast_clk(clocks), - } + } + self.configure_function_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + SpiFunctionClockConfig::Xtal => release_xtal_clk(clocks), + SpiFunctionClockConfig::PllF48m => release_pll_f48m_clk(clocks), + SpiFunctionClockConfig::RcFast => release_rc_fast_clk(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_selector, new_selector); } } pub fn function_clock_config( @@ -3222,11 +4156,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: SpiFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: SpiFunctionClockConfig) -> u32 { match config { SpiFunctionClockConfig::Xtal => xtal_clk_frequency(), SpiFunctionClockConfig::PllF48m => pll_f48m_clk_frequency(), @@ -3238,11 +4168,7 @@ macro_rules! define_clock_tree_types { .load(::core::sync::atomic::Ordering::Acquire) } pub fn function_clock_source_frequency(source: SpiFunctionClockConfig) -> u32 { - match source { - SpiFunctionClockConfig::Xtal => xtal_clk_frequency(), - SpiFunctionClockConfig::PllF48m => pll_f48m_clk_frequency(), - SpiFunctionClockConfig::RcFast => rc_fast_clk_frequency(), - } + Self::function_clock_config_frequency(source) } } impl TimgInstance { @@ -3253,22 +4179,21 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.timg_function_clock[self as usize].replace(new_selector); refresh_timg_function_clock_downstream(clocks, self); - if clocks.timg_function_clock_refcount[self as usize] > 0 { + let active = clocks.timg_function_clock_refcount[self as usize] > 0; + if active { match new_selector { TimgFunctionClockConfig::XtalClk => request_xtal_clk(clocks), TimgFunctionClockConfig::RcFastClk => request_rc_fast_clk(clocks), TimgFunctionClockConfig::PllF48m => request_pll_f48m_clk(clocks), } - self.configure_function_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - TimgFunctionClockConfig::XtalClk => release_xtal_clk(clocks), - TimgFunctionClockConfig::RcFastClk => release_rc_fast_clk(clocks), - TimgFunctionClockConfig::PllF48m => release_pll_f48m_clk(clocks), - } + } + self.configure_function_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + TimgFunctionClockConfig::XtalClk => release_xtal_clk(clocks), + TimgFunctionClockConfig::RcFastClk => release_rc_fast_clk(clocks), + TimgFunctionClockConfig::PllF48m => release_pll_f48m_clk(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_selector, new_selector); } } pub fn function_clock_config( @@ -3305,11 +4230,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: TimgFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: TimgFunctionClockConfig) -> u32 { match config { TimgFunctionClockConfig::XtalClk => xtal_clk_frequency(), TimgFunctionClockConfig::RcFastClk => rc_fast_clk_frequency(), @@ -3321,11 +4242,7 @@ macro_rules! define_clock_tree_types { .load(::core::sync::atomic::Ordering::Acquire) } pub fn function_clock_source_frequency(source: TimgFunctionClockConfig) -> u32 { - match source { - TimgFunctionClockConfig::XtalClk => xtal_clk_frequency(), - TimgFunctionClockConfig::RcFastClk => rc_fast_clk_frequency(), - TimgFunctionClockConfig::PllF48m => pll_f48m_clk_frequency(), - } + Self::function_clock_config_frequency(source) } pub fn configure_wdt_clock( self, @@ -3334,22 +4251,21 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.timg_wdt_clock[self as usize].replace(new_selector); refresh_timg_wdt_clock_downstream(clocks, self); - if clocks.timg_wdt_clock_refcount[self as usize] > 0 { + let active = clocks.timg_wdt_clock_refcount[self as usize] > 0; + if active { match new_selector { TimgWdtClockConfig::XtalClk => request_xtal_clk(clocks), TimgWdtClockConfig::RcFastClk => request_rc_fast_clk(clocks), TimgWdtClockConfig::PllF48m => request_pll_f48m_clk(clocks), } - self.configure_wdt_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - TimgWdtClockConfig::XtalClk => release_xtal_clk(clocks), - TimgWdtClockConfig::RcFastClk => release_rc_fast_clk(clocks), - TimgWdtClockConfig::PllF48m => release_pll_f48m_clk(clocks), - } + } + self.configure_wdt_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + TimgWdtClockConfig::XtalClk => release_xtal_clk(clocks), + TimgWdtClockConfig::RcFastClk => release_rc_fast_clk(clocks), + TimgWdtClockConfig::PllF48m => release_pll_f48m_clk(clocks), } - } else { - self.configure_wdt_clock_impl(clocks, old_selector, new_selector); } } pub fn wdt_clock_config(self, clocks: &mut ClockTree) -> Option { @@ -3379,11 +4295,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn wdt_clock_config_frequency( - clocks: &mut ClockTree, - config: TimgWdtClockConfig, - ) -> u32 { + pub fn wdt_clock_config_frequency(config: TimgWdtClockConfig) -> u32 { match config { TimgWdtClockConfig::XtalClk => xtal_clk_frequency(), TimgWdtClockConfig::RcFastClk => rc_fast_clk_frequency(), @@ -3395,11 +4307,7 @@ macro_rules! define_clock_tree_types { .load(::core::sync::atomic::Ordering::Acquire) } pub fn wdt_clock_source_frequency(source: TimgWdtClockConfig) -> u32 { - match source { - TimgWdtClockConfig::XtalClk => xtal_clk_frequency(), - TimgWdtClockConfig::RcFastClk => rc_fast_clk_frequency(), - TimgWdtClockConfig::PllF48m => pll_f48m_clk_frequency(), - } + Self::wdt_clock_config_frequency(source) } } impl UartInstance { @@ -3410,22 +4318,21 @@ macro_rules! define_clock_tree_types { ) { let old_config = clocks.uart_function_clock[self as usize].replace(config); refresh_uart_function_clock_downstream(clocks, self); - if clocks.uart_function_clock_refcount[self as usize] > 0 { + let active = clocks.uart_function_clock_refcount[self as usize] > 0; + if active { match config.sclk { UartFunctionClockSclk::PllF48m => request_pll_f48m_clk(clocks), UartFunctionClockSclk::RcFast => request_rc_fast_clk(clocks), UartFunctionClockSclk::Xtal => request_xtal_clk(clocks), } - self.configure_function_clock_impl(clocks, old_config, config); - if let Some(old_config) = old_config { - match old_config.sclk { - UartFunctionClockSclk::PllF48m => release_pll_f48m_clk(clocks), - UartFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), - UartFunctionClockSclk::Xtal => release_xtal_clk(clocks), - } + } + self.configure_function_clock_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + UartFunctionClockSclk::PllF48m => release_pll_f48m_clk(clocks), + UartFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), + UartFunctionClockSclk::Xtal => release_xtal_clk(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_config, config); } } pub fn function_clock_config( @@ -3464,11 +4371,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: UartFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: UartFunctionClockConfig) -> u32 { (match config.sclk { UartFunctionClockSclk::PllF48m => pll_f48m_clk_frequency(), UartFunctionClockSclk::RcFast => rc_fast_clk_frequency(), @@ -3521,10 +4424,8 @@ macro_rules! define_clock_tree_types { self.release_function_clock(clocks); } } - #[allow(unused_variables)] pub fn baud_rate_generator_config_frequency( self, - clocks: &mut ClockTree, config: UartBaudRateGeneratorConfig, ) -> u32 { ((self.function_clock_frequency() * 16) @@ -3562,6 +4463,10 @@ macro_rules! define_clock_tree_types { pub lp_fast_clk: Option, /// `LP_SLOW_CLK` configuration. pub lp_slow_clk: Option, + /// `BLE_LP_CLK` configuration. + pub ble_lp_clk: Option, + /// `CRYPTO_CLK` configuration. + pub crypto_clk: Option, /// `TIMG_CALIBRATION_CLOCK` configuration. pub timg_calibration_clock: Option, } @@ -3591,6 +4496,12 @@ macro_rules! define_clock_tree_types { if let Some(config) = self.lp_slow_clk { configure_lp_slow_clk(clocks, config); } + if let Some(config) = self.ble_lp_clk { + configure_ble_lp_clk(clocks, config); + } + if let Some(config) = self.crypto_clk { + configure_crypto_clk(clocks, config); + } if let Some(config) = self.timg_calibration_clock { configure_timg_calibration_clock(clocks, config); } @@ -3609,13 +4520,54 @@ macro_rules! define_clock_tree_types { fn refresh_xtal_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.xtal_clk { XTAL_CLK_FREQ_CACHE.store( - xtal_clk_config_frequency(clocks, config), + xtal_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } refresh_iomux_function_clock_downstream(clocks); refresh_hp_root_clk_downstream(clocks); refresh_lp_fast_clk_downstream(clocks); + refresh_ble_lp_clk_downstream(clocks); + refresh_crypto_clk_downstream(clocks); + for child_instance in [AdcInstance::ApbSaradc] { + refresh_adc_function_clock_downstream(clocks, child_instance); + } + for child_instance in [I2cInstance::I2c0, I2cInstance::I2c1] { + refresh_i2c_function_clock_downstream(clocks, child_instance); + } + for child_instance in [I2sInstance::I2s0] { + refresh_i2s_tx_clk_downstream(clocks, child_instance); + refresh_i2s_rx_clk_downstream(clocks, child_instance); + } + for child_instance in [McpwmInstance::Mcpwm0] { + refresh_mcpwm_function_clock_downstream(clocks, child_instance); + } + for child_instance in [ParlIoInstance::ParlIo] { + refresh_parl_io_rx_clock_downstream(clocks, child_instance); + refresh_parl_io_tx_clock_downstream(clocks, child_instance); + } + for child_instance in [RmtInstance::Rmt] { + refresh_rmt_sclk_downstream(clocks, child_instance); + } + for child_instance in [SpiInstance::Spi2] { + refresh_spi_function_clock_downstream(clocks, child_instance); + } + for child_instance in [TimgInstance::Timg0, TimgInstance::Timg1] { + refresh_timg_function_clock_downstream(clocks, child_instance); + refresh_timg_wdt_clock_downstream(clocks, child_instance); + } + for child_instance in [UartInstance::Uart0, UartInstance::Uart1] { + refresh_uart_function_clock_downstream(clocks, child_instance); + } + } + fn refresh_rc_fast_clk_downstream(clocks: &mut ClockTree) { + refresh_hp_root_clk_downstream(clocks); + refresh_lp_fast_clk_downstream(clocks); + refresh_crypto_clk_downstream(clocks); + refresh_timg_calibration_clock_downstream(clocks); + for child_instance in [AdcInstance::ApbSaradc] { + refresh_adc_function_clock_downstream(clocks, child_instance); + } for child_instance in [I2cInstance::I2c0, I2cInstance::I2c1] { refresh_i2c_function_clock_downstream(clocks, child_instance); } @@ -3643,15 +4595,19 @@ macro_rules! define_clock_tree_types { fn refresh_iomux_function_clock_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.iomux_function_clock { IOMUX_FUNCTION_CLOCK_FREQ_CACHE.store( - iomux_function_clock_config_frequency(clocks, config), + iomux_function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } } + fn refresh_rc_slow_clk_downstream(clocks: &mut ClockTree) { + refresh_lp_slow_clk_downstream(clocks); + refresh_ble_lp_clk_downstream(clocks); + } fn refresh_hp_root_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.hp_root_clk { HP_ROOT_CLK_FREQ_CACHE.store( - hp_root_clk_config_frequency(clocks, config), + hp_root_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3661,7 +4617,7 @@ macro_rules! define_clock_tree_types { fn refresh_cpu_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.cpu_clk { CPU_CLK_FREQ_CACHE.store( - cpu_clk_config_frequency(clocks, config), + cpu_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3669,7 +4625,7 @@ macro_rules! define_clock_tree_types { fn refresh_ahb_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.ahb_clk { AHB_CLK_FREQ_CACHE.store( - ahb_clk_config_frequency(clocks, config), + ahb_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3678,7 +4634,7 @@ macro_rules! define_clock_tree_types { fn refresh_apb_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.apb_clk { APB_CLK_FREQ_CACHE.store( - apb_clk_config_frequency(clocks, config), + apb_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3686,7 +4642,7 @@ macro_rules! define_clock_tree_types { fn refresh_lp_fast_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.lp_fast_clk { LP_FAST_CLK_FREQ_CACHE.store( - lp_fast_clk_config_frequency(clocks, config), + lp_fast_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3694,16 +4650,40 @@ macro_rules! define_clock_tree_types { fn refresh_lp_slow_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.lp_slow_clk { LP_SLOW_CLK_FREQ_CACHE.store( - lp_slow_clk_config_frequency(clocks, config), + lp_slow_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } refresh_timg_calibration_clock_downstream(clocks); } + fn refresh_ble_lp_clk_downstream(clocks: &mut ClockTree) { + if let Some(config) = clocks.ble_lp_clk { + BLE_LP_CLK_FREQ_CACHE.store( + ble_lp_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + fn refresh_crypto_clk_downstream(clocks: &mut ClockTree) { + if let Some(config) = clocks.crypto_clk { + CRYPTO_CLK_FREQ_CACHE.store( + crypto_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } fn refresh_timg_calibration_clock_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.timg_calibration_clock { TIMG_CALIBRATION_CLOCK_FREQ_CACHE.store( - timg_calibration_clock_config_frequency(clocks, config), + timg_calibration_clock_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + fn refresh_adc_function_clock_downstream(clocks: &mut ClockTree, instance: AdcInstance) { + if let Some(config) = clocks.adc_function_clock[instance as usize] { + ADC_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( + AdcInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3711,7 +4691,33 @@ macro_rules! define_clock_tree_types { fn refresh_i2c_function_clock_downstream(clocks: &mut ClockTree, instance: I2cInstance) { if let Some(config) = clocks.i2c_function_clock[instance as usize] { I2C_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - I2cInstance::function_clock_config_frequency(clocks, config), + I2cInstance::function_clock_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + fn refresh_i2s_tx_clk_downstream(clocks: &mut ClockTree, instance: I2sInstance) { + if let Some(config) = clocks.i2s_tx_clk[instance as usize] { + I2S_TX_CLK_FREQ_CACHE[instance as usize].store( + I2sInstance::tx_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + refresh_i2s_mclk_out_downstream(clocks, instance); + } + fn refresh_i2s_rx_clk_downstream(clocks: &mut ClockTree, instance: I2sInstance) { + if let Some(config) = clocks.i2s_rx_clk[instance as usize] { + I2S_RX_CLK_FREQ_CACHE[instance as usize].store( + I2sInstance::rx_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + refresh_i2s_mclk_out_downstream(clocks, instance); + } + fn refresh_i2s_mclk_out_downstream(clocks: &mut ClockTree, instance: I2sInstance) { + if let Some(config) = clocks.i2s_mclk_out[instance as usize] { + I2S_MCLK_OUT_FREQ_CACHE[instance as usize].store( + instance.mclk_out_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3722,7 +4728,7 @@ macro_rules! define_clock_tree_types { ) { if let Some(config) = clocks.mcpwm_function_clock[instance as usize] { MCPWM_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - McpwmInstance::function_clock_config_frequency(clocks, config), + McpwmInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3730,7 +4736,7 @@ macro_rules! define_clock_tree_types { fn refresh_parl_io_rx_clock_downstream(clocks: &mut ClockTree, instance: ParlIoInstance) { if let Some(config) = clocks.parl_io_rx_clock[instance as usize] { PARL_IO_RX_CLOCK_FREQ_CACHE[instance as usize].store( - ParlIoInstance::rx_clock_config_frequency(clocks, config), + ParlIoInstance::rx_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3738,7 +4744,7 @@ macro_rules! define_clock_tree_types { fn refresh_parl_io_tx_clock_downstream(clocks: &mut ClockTree, instance: ParlIoInstance) { if let Some(config) = clocks.parl_io_tx_clock[instance as usize] { PARL_IO_TX_CLOCK_FREQ_CACHE[instance as usize].store( - ParlIoInstance::tx_clock_config_frequency(clocks, config), + ParlIoInstance::tx_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3746,7 +4752,7 @@ macro_rules! define_clock_tree_types { fn refresh_rmt_sclk_downstream(clocks: &mut ClockTree, instance: RmtInstance) { if let Some(config) = clocks.rmt_sclk[instance as usize] { RMT_SCLK_FREQ_CACHE[instance as usize].store( - RmtInstance::sclk_config_frequency(clocks, config), + RmtInstance::sclk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3754,7 +4760,7 @@ macro_rules! define_clock_tree_types { fn refresh_spi_function_clock_downstream(clocks: &mut ClockTree, instance: SpiInstance) { if let Some(config) = clocks.spi_function_clock[instance as usize] { SPI_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - SpiInstance::function_clock_config_frequency(clocks, config), + SpiInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3762,7 +4768,7 @@ macro_rules! define_clock_tree_types { fn refresh_timg_function_clock_downstream(clocks: &mut ClockTree, instance: TimgInstance) { if let Some(config) = clocks.timg_function_clock[instance as usize] { TIMG_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - TimgInstance::function_clock_config_frequency(clocks, config), + TimgInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3770,7 +4776,7 @@ macro_rules! define_clock_tree_types { fn refresh_timg_wdt_clock_downstream(clocks: &mut ClockTree, instance: TimgInstance) { if let Some(config) = clocks.timg_wdt_clock[instance as usize] { TIMG_WDT_CLOCK_FREQ_CACHE[instance as usize].store( - TimgInstance::wdt_clock_config_frequency(clocks, config), + TimgInstance::wdt_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3778,7 +4784,7 @@ macro_rules! define_clock_tree_types { fn refresh_uart_function_clock_downstream(clocks: &mut ClockTree, instance: UartInstance) { if let Some(config) = clocks.uart_function_clock[instance as usize] { UART_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - UartInstance::function_clock_config_frequency(clocks, config), + UartInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3790,7 +4796,7 @@ macro_rules! define_clock_tree_types { ) { if let Some(config) = clocks.uart_baud_rate_generator[instance as usize] { UART_BAUD_RATE_GENERATOR_FREQ_CACHE[instance as usize].store( - instance.baud_rate_generator_config_frequency(clocks, config), + instance.baud_rate_generator_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4416,6 +5422,57 @@ macro_rules! for_each_spi_slave { Spi2, FSPICLK, FSPID, FSPIQ, FSPICS0))); }; } +/// This macro can be used to generate code for each PCNT unit. +/// +/// For an explanation on the general syntax, as well as usage of individual/repeated +/// matchers, refer to [the crate-level documentation][crate#for_each-macros]. +/// +/// This macro has four options for its "Individual matcher" case: +/// +/// - `names`: `($instance:ident)` +/// - `all`: `($peri:ident, $variant:ident, $sys:ident, $regs:ident, $unit:literal, +/// $interrupt:ident, $sig_ch0:ident, $sig_ch1:ident, $ctrl_ch0:ident, $ctrl_ch1:ident)` +/// - `interrupt`: `($interrupt:ident)` (repeated: one ident per unique IRQ) +/// - `regs`: `($regs:ident)` (repeated: one ident per register block) +/// +/// Macro fragments: +/// +/// - `$peri`: unit singleton name (`PCNT0_UNIT0`, `PCNT1_UNIT0`, …) +/// - `$variant`: `AnyPcntUnit` enum variant (`Pcnt0Unit0`, `Pcnt1Unit0`, …) +/// - `$sys`: `esp_hal::system::Peripheral` variant for clocks +/// - `$regs`: register-block singleton (`PCNT`, `PCNT1`) +/// - `$unit`: hardware unit index within that register block +/// - `$interrupt`: shared peripheral interrupt +/// - `$sig_ch0`, `$sig_ch1`, `$ctrl_ch0`, `$ctrl_ch1`: GPIO matrix input signals +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! for_each_pcnt_unit { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _for_each_inner_pcnt_unit { $(($pattern) => $code;)* ($other : tt) + => {} } _for_each_inner_pcnt_unit!((PCNT0_UNIT0)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT2)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT3)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT0, Pcnt0Unit0, Pcnt, PCNT, 0, PCNT, + PCNT0_SIG_CH0, PCNT0_SIG_CH1, PCNT0_CTRL_CH0, PCNT0_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT1, Pcnt0Unit1, Pcnt, PCNT, 1, PCNT, + PCNT1_SIG_CH0, PCNT1_SIG_CH1, PCNT1_CTRL_CH0, PCNT1_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT2, Pcnt0Unit2, Pcnt, PCNT, 2, PCNT, + PCNT2_SIG_CH0, PCNT2_SIG_CH1, PCNT2_CTRL_CH0, PCNT2_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT3, Pcnt0Unit3, Pcnt, PCNT, 3, PCNT, + PCNT3_SIG_CH0, PCNT3_SIG_CH1, PCNT3_CTRL_CH0, PCNT3_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT)); _for_each_inner_pcnt_unit!((PCNT)); + _for_each_inner_pcnt_unit!((names(PCNT0_UNIT0), (PCNT0_UNIT1), (PCNT0_UNIT2), + (PCNT0_UNIT3))); _for_each_inner_pcnt_unit!((all(PCNT0_UNIT0, Pcnt0Unit0, Pcnt, + PCNT, 0, PCNT, PCNT0_SIG_CH0, PCNT0_SIG_CH1, PCNT0_CTRL_CH0, PCNT0_CTRL_CH1), + (PCNT0_UNIT1, Pcnt0Unit1, Pcnt, PCNT, 1, PCNT, PCNT1_SIG_CH0, PCNT1_SIG_CH1, + PCNT1_CTRL_CH0, PCNT1_CTRL_CH1), (PCNT0_UNIT2, Pcnt0Unit2, Pcnt, PCNT, 2, PCNT, + PCNT2_SIG_CH0, PCNT2_SIG_CH1, PCNT2_CTRL_CH0, PCNT2_CTRL_CH1), (PCNT0_UNIT3, + Pcnt0Unit3, Pcnt, PCNT, 3, PCNT, PCNT3_SIG_CH0, PCNT3_SIG_CH1, PCNT3_CTRL_CH0, + PCNT3_CTRL_CH1))); _for_each_inner_pcnt_unit!((interrupt(PCNT))); + _for_each_inner_pcnt_unit!((regs(PCNT))); + }; +} #[macro_export] #[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] macro_rules! for_each_peripheral { @@ -4535,9 +5592,16 @@ macro_rules! for_each_peripheral { { bind_dma_in_interrupt, enable_dma_in_interrupt, disable_dma_in_interrupt }, DMA_OUT_CH2 : { bind_dma_out_interrupt, enable_dma_out_interrupt, disable_dma_out_interrupt }) (unstable))); _for_each_inner_peripheral!((@ - peri_type #[doc = "SDM_CH0 peripheral singleton"] SDM_CH0 <= virtual() + peri_type #[doc = "PCNT0_UNIT0 peripheral singleton"] PCNT0_UNIT0 <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "SDM_CH1 peripheral singleton"] SDM_CH1 <= virtual() (unstable))); + "PCNT0_UNIT1 peripheral singleton"] PCNT0_UNIT1 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT0_UNIT2 peripheral singleton"] PCNT0_UNIT2 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT0_UNIT3 peripheral singleton"] PCNT0_UNIT3 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "SDM_CH0 peripheral singleton"] + SDM_CH0 <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc + = "SDM_CH1 peripheral singleton"] SDM_CH1 <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "SDM_CH2 peripheral singleton"] SDM_CH2 <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "SDM_CH3 peripheral singleton"] SDM_CH3 <= virtual() (unstable))); @@ -4547,12 +5611,15 @@ macro_rules! for_each_peripheral { "APB_SARADC peripheral singleton"] APB_SARADC <= APB_SARADC() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "ASSIST_DEBUG peripheral singleton"] ASSIST_DEBUG <= ASSIST_DEBUG() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "DMA peripheral singleton"] DMA - <= DMA() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "DS peripheral singleton"] DS <= DS() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "ECC peripheral singleton"] ECC - <= ECC() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "EFUSE peripheral singleton"] EFUSE <= EFUSE() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "CLINT peripheral singleton"] + CLINT <= CLINT() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "DMA peripheral singleton"] DMA <= DMA() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "DS peripheral singleton"] DS <= + DS() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "ECC peripheral singleton"] ECC <= ECC() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "EFUSE peripheral singleton"] + EFUSE <= EFUSE() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "EXTMEM peripheral singleton"] EXTMEM <= EXTMEM() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "GPIO peripheral singleton"] GPIO <= GPIO() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "GPIO_SD peripheral singleton"] GPIO_SD <= GPIO_SD() (unstable))); @@ -4608,44 +5675,46 @@ macro_rules! for_each_peripheral { disable_tx_interrupt }) (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "PAU peripheral singleton"] PAU <= PAU() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "PCNT peripheral singleton"] - PCNT <= PCNT() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "PCR peripheral singleton"] PCR <= PCR() (unstable))); + PCNT <= PCNT(PCNT : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt }) (unstable))); _for_each_inner_peripheral!((@ peri_type + #[doc = "PCR peripheral singleton"] PCR <= PCR() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "PLIC_MX peripheral singleton"] PLIC_MX <= PLIC_MX() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc - = "PMU peripheral singleton"] PMU <= PMU() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "RMT peripheral singleton"] RMT - <= RMT() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "RNG peripheral singleton"] RNG <= virtual() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "RSA peripheral singleton"] RSA - <= RSA(RSA : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt - }) (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "SHA peripheral singleton"] SHA <= SHA(SHA : { bind_peri_interrupt, + = "PLIC_UX peripheral singleton"] PLIC_UX <= PLIC_UX() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "PMU peripheral singleton"] PMU + <= PMU() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "RMT peripheral singleton"] RMT <= RMT() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "RNG peripheral singleton"] RNG + <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "RSA peripheral singleton"] RSA <= RSA(RSA : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "ETM peripheral singleton"] ETM - <= SOC_ETM() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "SPI0 peripheral singleton"] SPI0 <= SPI0() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "SPI1 peripheral singleton"] - SPI1 <= SPI1() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "SPI2 peripheral singleton"] SPI2 <= SPI2(SPI2 : { bind_peri_interrupt, - enable_peri_interrupt, disable_peri_interrupt }))); - _for_each_inner_peripheral!((@ peri_type #[doc = "SYSTEM peripheral singleton"] - SYSTEM <= PCR() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "SYSTIMER peripheral singleton"] SYSTIMER <= SYSTIMER() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "TEE peripheral singleton"] TEE - <= TEE() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "TIMG0 peripheral singleton"] TIMG0 <= TIMG0() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "TIMG1 peripheral singleton"] - TIMG1 <= TIMG1() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "TRACE0 peripheral singleton"] TRACE0 <= TRACE() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "TWAI0 peripheral singleton"] - TWAI0 <= TWAI0() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "UART0 peripheral singleton"] UART0 <= UART0(UART0 : { bind_peri_interrupt, - enable_peri_interrupt, disable_peri_interrupt }))); - _for_each_inner_peripheral!((@ peri_type #[doc = "UART1 peripheral singleton"] - UART1 <= UART1(UART1 : { bind_peri_interrupt, enable_peri_interrupt, + _for_each_inner_peripheral!((@ peri_type #[doc = "SHA peripheral singleton"] SHA + <= SHA(SHA : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt + }) (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "ETM peripheral singleton"] ETM <= SOC_ETM() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "SPI0 peripheral singleton"] + SPI0 <= SPI0() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "SPI1 peripheral singleton"] SPI1 <= SPI1() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "SPI2 peripheral singleton"] + SPI2 <= SPI2(SPI2 : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }))); _for_each_inner_peripheral!((@ peri_type #[doc = - "UHCI0 peripheral singleton"] UHCI0 <= UHCI0() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = + "SYSTEM peripheral singleton"] SYSTEM <= PCR() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "SYSTIMER peripheral singleton"] + SYSTIMER <= SYSTIMER() (unstable))); _for_each_inner_peripheral!((@ peri_type + #[doc = "TEE peripheral singleton"] TEE <= TEE() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "TIMG0 peripheral singleton"] + TIMG0 <= TIMG0() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "TIMG1 peripheral singleton"] TIMG1 <= TIMG1() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "TRACE0 peripheral singleton"] + TRACE0 <= TRACE() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "TWAI0 peripheral singleton"] TWAI0 <= TWAI0() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "UART0 peripheral singleton"] + UART0 <= UART0(UART0 : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt }))); _for_each_inner_peripheral!((@ peri_type #[doc = + "UART1 peripheral singleton"] UART1 <= UART1(UART1 : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }))); + _for_each_inner_peripheral!((@ peri_type #[doc = "UHCI0 peripheral singleton"] + UHCI0 <= UHCI0() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "USB_DEVICE peripheral singleton"] USB_DEVICE <= USB_DEVICE(USB_DEVICE : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = @@ -4680,6 +5749,10 @@ macro_rules! for_each_peripheral { _for_each_inner_peripheral!((DMA_CH0(unstable))); _for_each_inner_peripheral!((DMA_CH1(unstable))); _for_each_inner_peripheral!((DMA_CH2(unstable))); + _for_each_inner_peripheral!((PCNT0_UNIT0(unstable))); + _for_each_inner_peripheral!((PCNT0_UNIT1(unstable))); + _for_each_inner_peripheral!((PCNT0_UNIT2(unstable))); + _for_each_inner_peripheral!((PCNT0_UNIT3(unstable))); _for_each_inner_peripheral!((SDM_CH0(unstable))); _for_each_inner_peripheral!((SDM_CH1(unstable))); _for_each_inner_peripheral!((SDM_CH2(unstable))); @@ -4855,54 +5928,61 @@ macro_rules! for_each_peripheral { bind_dma_in_interrupt, enable_dma_in_interrupt, disable_dma_in_interrupt }, DMA_OUT_CH2 : { bind_dma_out_interrupt, enable_dma_out_interrupt, disable_dma_out_interrupt }) (unstable)), (@ peri_type #[doc = - "SDM_CH0 peripheral singleton"] SDM_CH0 <= virtual() (unstable)), (@ peri_type - #[doc = "SDM_CH1 peripheral singleton"] SDM_CH1 <= virtual() (unstable)), (@ - peri_type #[doc = "SDM_CH2 peripheral singleton"] SDM_CH2 <= virtual() - (unstable)), (@ peri_type #[doc = "SDM_CH3 peripheral singleton"] SDM_CH3 <= - virtual() (unstable)), (@ peri_type #[doc = "AES peripheral singleton"] AES <= - AES(AES : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) - (unstable)), (@ peri_type #[doc = "APB_SARADC peripheral singleton"] APB_SARADC - <= APB_SARADC() (unstable)), (@ peri_type #[doc = - "ASSIST_DEBUG peripheral singleton"] ASSIST_DEBUG <= ASSIST_DEBUG() (unstable)), - (@ peri_type #[doc = "DMA peripheral singleton"] DMA <= DMA() (unstable)), (@ - peri_type #[doc = "DS peripheral singleton"] DS <= DS() (unstable)), (@ peri_type - #[doc = "ECC peripheral singleton"] ECC <= ECC() (unstable)), (@ peri_type #[doc - = "EFUSE peripheral singleton"] EFUSE <= EFUSE() (unstable)), (@ peri_type #[doc - = "GPIO peripheral singleton"] GPIO <= GPIO() (unstable)), (@ peri_type #[doc = - "GPIO_SD peripheral singleton"] GPIO_SD <= GPIO_SD() (unstable)), (@ peri_type - #[doc = "HMAC peripheral singleton"] HMAC <= HMAC() (unstable)), (@ peri_type - #[doc = "HP_APM peripheral singleton"] HP_APM <= HP_APM() (unstable)), (@ - peri_type #[doc = "HP_SYS peripheral singleton"] HP_SYS <= HP_SYS() (unstable)), - (@ peri_type #[doc = "I2C_ANA_MST peripheral singleton"] I2C_ANA_MST <= - I2C_ANA_MST() (unstable)), (@ peri_type #[doc = "I2C0 peripheral singleton"] I2C0 - <= I2C0(I2C_EXT0 : { bind_peri_interrupt, enable_peri_interrupt, - disable_peri_interrupt })), (@ peri_type #[doc = "I2C1 peripheral singleton"] - I2C1 <= I2C1(I2C_EXT1 : { bind_peri_interrupt, enable_peri_interrupt, - disable_peri_interrupt })), (@ peri_type #[doc = "I2S0 peripheral singleton"] - I2S0 <= I2S0(I2S0 : { bind_peri_interrupt, enable_peri_interrupt, - disable_peri_interrupt }) (unstable)), (@ peri_type #[doc = - "IEEE802154 peripheral singleton"] IEEE802154 <= IEEE802154(ZB_MAC : { - bind_mac_interrupt, enable_mac_interrupt, disable_mac_interrupt }) (unstable)), - (@ peri_type #[doc = "INTERRUPT_CORE0 peripheral singleton"] INTERRUPT_CORE0 <= - INTERRUPT_CORE0() (unstable)), (@ peri_type #[doc = - "INTPRI peripheral singleton"] INTPRI <= INTPRI() (unstable)), (@ peri_type #[doc - = "IO_MUX peripheral singleton"] IO_MUX <= IO_MUX() (unstable)), (@ peri_type - #[doc = "LEDC peripheral singleton"] LEDC <= LEDC() (unstable)), (@ peri_type - #[doc = "LPWR peripheral singleton"] LPWR <= LP_CLKRST() (unstable)), (@ - peri_type #[doc = "LP_ANA peripheral singleton"] LP_ANA <= LP_ANA() (unstable)), - (@ peri_type #[doc = "LP_AON peripheral singleton"] LP_AON <= LP_AON() - (unstable)), (@ peri_type #[doc = "LP_APM peripheral singleton"] LP_APM <= - LP_APM() (unstable)), (@ peri_type #[doc = "LP_APM0 peripheral singleton"] - LP_APM0 <= LP_APM0() (unstable)), (@ peri_type #[doc = - "LP_CLKRST peripheral singleton"] LP_CLKRST <= LP_CLKRST() (unstable)), (@ - peri_type #[doc = "LP_PERI peripheral singleton"] LP_PERI <= LP_PERI() - (unstable)), (@ peri_type #[doc = "RTC_TIMER peripheral singleton"] RTC_TIMER <= - LP_TIMER() (unstable)), (@ peri_type #[doc = "LP_WDT peripheral singleton"] - LP_WDT <= LP_WDT() (unstable)), (@ peri_type #[doc = - "MCPWM0 peripheral singleton"] MCPWM0 <= MCPWM0() (unstable)), (@ peri_type #[doc - = "MEM_MONITOR peripheral singleton"] MEM_MONITOR <= MEM_MONITOR() (unstable)), - (@ peri_type #[doc = "MODEM_LPCON peripheral singleton"] MODEM_LPCON <= - MODEM_LPCON() (unstable)), (@ peri_type #[doc = + "PCNT0_UNIT0 peripheral singleton"] PCNT0_UNIT0 <= virtual() (unstable)), (@ + peri_type #[doc = "PCNT0_UNIT1 peripheral singleton"] PCNT0_UNIT1 <= virtual() + (unstable)), (@ peri_type #[doc = "PCNT0_UNIT2 peripheral singleton"] PCNT0_UNIT2 + <= virtual() (unstable)), (@ peri_type #[doc = + "PCNT0_UNIT3 peripheral singleton"] PCNT0_UNIT3 <= virtual() (unstable)), (@ + peri_type #[doc = "SDM_CH0 peripheral singleton"] SDM_CH0 <= virtual() + (unstable)), (@ peri_type #[doc = "SDM_CH1 peripheral singleton"] SDM_CH1 <= + virtual() (unstable)), (@ peri_type #[doc = "SDM_CH2 peripheral singleton"] + SDM_CH2 <= virtual() (unstable)), (@ peri_type #[doc = + "SDM_CH3 peripheral singleton"] SDM_CH3 <= virtual() (unstable)), (@ peri_type + #[doc = "AES peripheral singleton"] AES <= AES(AES : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc + = "APB_SARADC peripheral singleton"] APB_SARADC <= APB_SARADC() (unstable)), (@ + peri_type #[doc = "ASSIST_DEBUG peripheral singleton"] ASSIST_DEBUG <= + ASSIST_DEBUG() (unstable)), (@ peri_type #[doc = "CLINT peripheral singleton"] + CLINT <= CLINT() (unstable)), (@ peri_type #[doc = "DMA peripheral singleton"] + DMA <= DMA() (unstable)), (@ peri_type #[doc = "DS peripheral singleton"] DS <= + DS() (unstable)), (@ peri_type #[doc = "ECC peripheral singleton"] ECC <= ECC() + (unstable)), (@ peri_type #[doc = "EFUSE peripheral singleton"] EFUSE <= EFUSE() + (unstable)), (@ peri_type #[doc = "EXTMEM peripheral singleton"] EXTMEM <= + EXTMEM() (unstable)), (@ peri_type #[doc = "GPIO peripheral singleton"] GPIO <= + GPIO() (unstable)), (@ peri_type #[doc = "GPIO_SD peripheral singleton"] GPIO_SD + <= GPIO_SD() (unstable)), (@ peri_type #[doc = "HMAC peripheral singleton"] HMAC + <= HMAC() (unstable)), (@ peri_type #[doc = "HP_APM peripheral singleton"] HP_APM + <= HP_APM() (unstable)), (@ peri_type #[doc = "HP_SYS peripheral singleton"] + HP_SYS <= HP_SYS() (unstable)), (@ peri_type #[doc = + "I2C_ANA_MST peripheral singleton"] I2C_ANA_MST <= I2C_ANA_MST() (unstable)), (@ + peri_type #[doc = "I2C0 peripheral singleton"] I2C0 <= I2C0(I2C_EXT0 : { + bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt })), (@ + peri_type #[doc = "I2C1 peripheral singleton"] I2C1 <= I2C1(I2C_EXT1 : { + bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt })), (@ + peri_type #[doc = "I2S0 peripheral singleton"] I2S0 <= I2S0(I2S0 : { + bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) + (unstable)), (@ peri_type #[doc = "IEEE802154 peripheral singleton"] IEEE802154 + <= IEEE802154(ZB_MAC : { bind_mac_interrupt, enable_mac_interrupt, + disable_mac_interrupt }) (unstable)), (@ peri_type #[doc = + "INTERRUPT_CORE0 peripheral singleton"] INTERRUPT_CORE0 <= INTERRUPT_CORE0() + (unstable)), (@ peri_type #[doc = "INTPRI peripheral singleton"] INTPRI <= + INTPRI() (unstable)), (@ peri_type #[doc = "IO_MUX peripheral singleton"] IO_MUX + <= IO_MUX() (unstable)), (@ peri_type #[doc = "LEDC peripheral singleton"] LEDC + <= LEDC() (unstable)), (@ peri_type #[doc = "LPWR peripheral singleton"] LPWR <= + LP_CLKRST() (unstable)), (@ peri_type #[doc = "LP_ANA peripheral singleton"] + LP_ANA <= LP_ANA() (unstable)), (@ peri_type #[doc = + "LP_AON peripheral singleton"] LP_AON <= LP_AON() (unstable)), (@ peri_type #[doc + = "LP_APM peripheral singleton"] LP_APM <= LP_APM() (unstable)), (@ peri_type + #[doc = "LP_APM0 peripheral singleton"] LP_APM0 <= LP_APM0() (unstable)), (@ + peri_type #[doc = "LP_CLKRST peripheral singleton"] LP_CLKRST <= LP_CLKRST() + (unstable)), (@ peri_type #[doc = "LP_PERI peripheral singleton"] LP_PERI <= + LP_PERI() (unstable)), (@ peri_type #[doc = "RTC_TIMER peripheral singleton"] + RTC_TIMER <= LP_TIMER() (unstable)), (@ peri_type #[doc = + "LP_WDT peripheral singleton"] LP_WDT <= LP_WDT() (unstable)), (@ peri_type #[doc + = "MCPWM0 peripheral singleton"] MCPWM0 <= MCPWM0() (unstable)), (@ peri_type + #[doc = "MEM_MONITOR peripheral singleton"] MEM_MONITOR <= MEM_MONITOR() + (unstable)), (@ peri_type #[doc = "MODEM_LPCON peripheral singleton"] MODEM_LPCON + <= MODEM_LPCON() (unstable)), (@ peri_type #[doc = "MODEM_SYSCON peripheral singleton"] MODEM_SYSCON <= MODEM_SYSCON() (unstable)), (@ peri_type #[doc = "OTP_DEBUG peripheral singleton"] OTP_DEBUG <= OTP_DEBUG() (unstable)), (@ peri_type #[doc = "PARL_IO peripheral singleton"] PARL_IO <= @@ -4910,43 +5990,45 @@ macro_rules! for_each_peripheral { disable_rx_interrupt }, PARL_IO_TX : { bind_tx_interrupt, enable_tx_interrupt, disable_tx_interrupt }) (unstable)), (@ peri_type #[doc = "PAU peripheral singleton"] PAU <= PAU() (unstable)), (@ peri_type #[doc = - "PCNT peripheral singleton"] PCNT <= PCNT() (unstable)), (@ peri_type #[doc = - "PCR peripheral singleton"] PCR <= PCR() (unstable)), (@ peri_type #[doc = - "PLIC_MX peripheral singleton"] PLIC_MX <= PLIC_MX() (unstable)), (@ peri_type - #[doc = "PMU peripheral singleton"] PMU <= PMU() (unstable)), (@ peri_type #[doc - = "RMT peripheral singleton"] RMT <= RMT() (unstable)), (@ peri_type #[doc = - "RNG peripheral singleton"] RNG <= virtual() (unstable)), (@ peri_type #[doc = - "RSA peripheral singleton"] RSA <= RSA(RSA : { bind_peri_interrupt, + "PCNT peripheral singleton"] PCNT <= PCNT(PCNT : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc - = "SHA peripheral singleton"] SHA <= SHA(SHA : { bind_peri_interrupt, - enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc - = "ETM peripheral singleton"] ETM <= SOC_ETM() (unstable)), (@ peri_type #[doc = - "SPI0 peripheral singleton"] SPI0 <= SPI0() (unstable)), (@ peri_type #[doc = - "SPI1 peripheral singleton"] SPI1 <= SPI1() (unstable)), (@ peri_type #[doc = - "SPI2 peripheral singleton"] SPI2 <= SPI2(SPI2 : { bind_peri_interrupt, - enable_peri_interrupt, disable_peri_interrupt })), (@ peri_type #[doc = - "SYSTEM peripheral singleton"] SYSTEM <= PCR() (unstable)), (@ peri_type #[doc = - "SYSTIMER peripheral singleton"] SYSTIMER <= SYSTIMER() (unstable)), (@ peri_type - #[doc = "TEE peripheral singleton"] TEE <= TEE() (unstable)), (@ peri_type #[doc - = "TIMG0 peripheral singleton"] TIMG0 <= TIMG0() (unstable)), (@ peri_type #[doc - = "TIMG1 peripheral singleton"] TIMG1 <= TIMG1() (unstable)), (@ peri_type #[doc - = "TRACE0 peripheral singleton"] TRACE0 <= TRACE() (unstable)), (@ peri_type - #[doc = "TWAI0 peripheral singleton"] TWAI0 <= TWAI0() (unstable)), (@ peri_type - #[doc = "UART0 peripheral singleton"] UART0 <= UART0(UART0 : { - bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt })), (@ - peri_type #[doc = "UART1 peripheral singleton"] UART1 <= UART1(UART1 : { - bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt })), (@ - peri_type #[doc = "UHCI0 peripheral singleton"] UHCI0 <= UHCI0() (unstable)), (@ - peri_type #[doc = "USB_DEVICE peripheral singleton"] USB_DEVICE <= - USB_DEVICE(USB_DEVICE : { bind_peri_interrupt, enable_peri_interrupt, - disable_peri_interrupt }) (unstable)), (@ peri_type #[doc = - "ADC1 peripheral singleton"] ADC1 <= virtual() (unstable)), (@ peri_type #[doc = - "BT peripheral singleton"] BT <= virtual(LP_BLE_TIMER : { - bind_lp_timer_interrupt, enable_lp_timer_interrupt, disable_lp_timer_interrupt }, - BT_MAC : { bind_mac_interrupt, enable_mac_interrupt, disable_mac_interrupt }) - (unstable)), (@ peri_type #[doc = "FLASH peripheral singleton"] FLASH <= - virtual() (unstable)), (@ peri_type #[doc = - "GPIO_DEDICATED peripheral singleton"] GPIO_DEDICATED <= virtual() (unstable)), + = "PCR peripheral singleton"] PCR <= PCR() (unstable)), (@ peri_type #[doc = + "PLIC_MX peripheral singleton"] PLIC_MX <= PLIC_MX() (unstable)), (@ peri_type + #[doc = "PLIC_UX peripheral singleton"] PLIC_UX <= PLIC_UX() (unstable)), (@ + peri_type #[doc = "PMU peripheral singleton"] PMU <= PMU() (unstable)), (@ + peri_type #[doc = "RMT peripheral singleton"] RMT <= RMT() (unstable)), (@ + peri_type #[doc = "RNG peripheral singleton"] RNG <= virtual() (unstable)), (@ + peri_type #[doc = "RSA peripheral singleton"] RSA <= RSA(RSA : { + bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) + (unstable)), (@ peri_type #[doc = "SHA peripheral singleton"] SHA <= SHA(SHA : { + bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) + (unstable)), (@ peri_type #[doc = "ETM peripheral singleton"] ETM <= SOC_ETM() + (unstable)), (@ peri_type #[doc = "SPI0 peripheral singleton"] SPI0 <= SPI0() + (unstable)), (@ peri_type #[doc = "SPI1 peripheral singleton"] SPI1 <= SPI1() + (unstable)), (@ peri_type #[doc = "SPI2 peripheral singleton"] SPI2 <= SPI2(SPI2 + : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt })), (@ + peri_type #[doc = "SYSTEM peripheral singleton"] SYSTEM <= PCR() (unstable)), (@ + peri_type #[doc = "SYSTIMER peripheral singleton"] SYSTIMER <= SYSTIMER() + (unstable)), (@ peri_type #[doc = "TEE peripheral singleton"] TEE <= TEE() + (unstable)), (@ peri_type #[doc = "TIMG0 peripheral singleton"] TIMG0 <= TIMG0() + (unstable)), (@ peri_type #[doc = "TIMG1 peripheral singleton"] TIMG1 <= TIMG1() + (unstable)), (@ peri_type #[doc = "TRACE0 peripheral singleton"] TRACE0 <= + TRACE() (unstable)), (@ peri_type #[doc = "TWAI0 peripheral singleton"] TWAI0 <= + TWAI0() (unstable)), (@ peri_type #[doc = "UART0 peripheral singleton"] UART0 <= + UART0(UART0 : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt })), (@ peri_type #[doc = "UART1 peripheral singleton"] + UART1 <= UART1(UART1 : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt })), (@ peri_type #[doc = "UHCI0 peripheral singleton"] + UHCI0 <= UHCI0() (unstable)), (@ peri_type #[doc = + "USB_DEVICE peripheral singleton"] USB_DEVICE <= USB_DEVICE(USB_DEVICE : { + bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) + (unstable)), (@ peri_type #[doc = "ADC1 peripheral singleton"] ADC1 <= virtual() + (unstable)), (@ peri_type #[doc = "BT peripheral singleton"] BT <= + virtual(LP_BLE_TIMER : { bind_lp_timer_interrupt, enable_lp_timer_interrupt, + disable_lp_timer_interrupt }, BT_MAC : { bind_mac_interrupt, + enable_mac_interrupt, disable_mac_interrupt }) (unstable)), (@ peri_type #[doc = + "FLASH peripheral singleton"] FLASH <= virtual() (unstable)), (@ peri_type #[doc + = "GPIO_DEDICATED peripheral singleton"] GPIO_DEDICATED <= virtual() (unstable)), (@ peri_type #[doc = "FROM_CPU_INTR0 peripheral singleton"] FROM_CPU_INTR0 <= virtual() (unstable)), (@ peri_type #[doc = "FROM_CPU_INTR1 peripheral singleton"] FROM_CPU_INTR1 <= virtual() (unstable)), @@ -4957,12 +6039,13 @@ macro_rules! for_each_peripheral { (GPIO4), (GPIO5), (GPIO6), (GPIO7), (GPIO8), (GPIO9), (GPIO10), (GPIO11), (GPIO12), (#[cfg(not(use_xtal32k))] GPIO13), (#[cfg(not(use_xtal32k))] GPIO14), (GPIO22), (GPIO23), (GPIO24), (GPIO25), (GPIO26), (GPIO27), (DMA_CH0(unstable)), - (DMA_CH1(unstable)), (DMA_CH2(unstable)), (SDM_CH0(unstable)), - (SDM_CH1(unstable)), (SDM_CH2(unstable)), (SDM_CH3(unstable)), (AES(unstable)), - (APB_SARADC(unstable)), (ASSIST_DEBUG(unstable)), (DMA(unstable)), - (DS(unstable)), (ECC(unstable)), (GPIO(unstable)), (GPIO_SD(unstable)), - (HMAC(unstable)), (HP_APM(unstable)), (HP_SYS(unstable)), - (I2C_ANA_MST(unstable)), (I2C0), (I2C1), (I2S0(unstable)), + (DMA_CH1(unstable)), (DMA_CH2(unstable)), (PCNT0_UNIT0(unstable)), + (PCNT0_UNIT1(unstable)), (PCNT0_UNIT2(unstable)), (PCNT0_UNIT3(unstable)), + (SDM_CH0(unstable)), (SDM_CH1(unstable)), (SDM_CH2(unstable)), + (SDM_CH3(unstable)), (AES(unstable)), (APB_SARADC(unstable)), + (ASSIST_DEBUG(unstable)), (DMA(unstable)), (DS(unstable)), (ECC(unstable)), + (GPIO(unstable)), (GPIO_SD(unstable)), (HMAC(unstable)), (HP_APM(unstable)), + (HP_SYS(unstable)), (I2C_ANA_MST(unstable)), (I2C0), (I2C1), (I2S0(unstable)), (IEEE802154(unstable)), (INTERRUPT_CORE0(unstable)), (INTPRI(unstable)), (IO_MUX(unstable)), (LEDC(unstable)), (LPWR(unstable)), (LP_ANA(unstable)), (LP_AON(unstable)), (LP_APM(unstable)), (LP_APM0(unstable)), diff --git a/esp-metadata-generated/src/_generated_esp32h4.rs b/esp-metadata-generated/src/_generated_esp32h4.rs new file mode 100644 index 00000000000..d4737cb3f2f --- /dev/null +++ b/esp-metadata-generated/src/_generated_esp32h4.rs @@ -0,0 +1,5616 @@ +// Do NOT edit this file directly. Make your changes to esp-metadata, +// then run `cargo update-metadata`. + +/// The name of the chip as `&str` +/// +/// # Example +/// +/// ```rust, no_run +/// use esp_hal::chip; +/// let chip_name = chip!(); +#[doc = concat!("assert_eq!(chip_name, ", chip!(), ")")] +/// ``` +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! chip { + () => { + "esp32h4" + }; +} +/// The pretty name of the chip as `&str` +/// +/// # Example +/// +/// ```rust, no_run +/// use esp_hal::chip; +/// let chip_name = chip_pretty!(); +#[doc = concat!("assert_eq!(chip_name, ", chip_pretty!(), ")")] +/// ``` +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! chip_pretty { + () => { + "ESP32-H4" + }; +} +/// The properties of this chip and its drivers. +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! property { + ("chip") => { + "esp32h4" + }; + ("arch") => { + "riscv" + }; + ("cores") => { + 2 + }; + ("cores", str) => { + stringify!(2) + }; + ("trm") => { + "https://www.espressif.com/sites/default/files/documentation/esp32-h4_technical_reference_manual_en.pdf" + }; + ("gpio.version") => { + 3 + }; + ("gpio.version", str) => { + stringify!(3) + }; + ("gpio.has_input_sync") => { + true + }; + ("gpio.gpio_function") => { + 1 + }; + ("gpio.gpio_function", str) => { + stringify!(1) + }; + ("gpio.constant_0_input") => { + 96 + }; + ("gpio.constant_0_input", str) => { + stringify!(96) + }; + ("gpio.constant_1_input") => { + 64 + }; + ("gpio.constant_1_input", str) => { + stringify!(64) + }; + ("gpio.remap_iomux_pin_registers") => { + false + }; + ("gpio.func_in_sel_offset") => { + 0 + }; + ("gpio.func_in_sel_offset", str) => { + stringify!(0) + }; + ("gpio.need_soft_isolate_during_pd") => { + false + }; + ("gpio.has_bank_1") => { + true + }; + ("gpio.input_signal_max") => { + 189 + }; + ("gpio.input_signal_max", str) => { + stringify!(189) + }; + ("gpio.output_signal_max") => { + 256 + }; + ("gpio.output_signal_max", str) => { + stringify!(256) + }; + ("dedicated_gpio.version") => { + "riscv_v1" + }; + ("dedicated_gpio.needs_initialization") => { + false + }; + ("dedicated_gpio.channel_count") => { + 8 + }; + ("dedicated_gpio.channel_count", str) => { + stringify!(8) + }; + ("lp_io.version") => { + "v4" + }; + ("lp_io.has_gpio_matrix") => { + false + }; + ("uart.ram_size") => { + 128 + }; + ("uart.ram_size", str) => { + stringify!(128) + }; + ("uart.version") => { + 2 + }; + ("uart.version", str) => { + stringify!(2) + }; + ("uart.peripheral_controls_mem_clk") => { + true + }; + ("uart.has_sclk_divider") => { + false + }; + ("uart.has_sclk_enable") => { + true + }; + ("i2c_master.version") => { + 4 + }; + ("i2c_master.version", str) => { + stringify!(4) + }; + ("i2c_master.has_fsm_timeouts") => { + true + }; + ("i2c_master.has_hw_bus_clear") => { + true + }; + ("i2c_master.has_bus_timeout_enable") => { + true + }; + ("i2c_master.separate_filter_config_registers") => { + false + }; + ("i2c_master.can_estimate_nack_reason") => { + true + }; + ("i2c_master.has_conf_update") => { + true + }; + ("i2c_master.has_reliable_fsm_reset") => { + true + }; + ("i2c_master.has_arbitration_en") => { + true + }; + ("i2c_master.has_tx_fifo_watermark") => { + true + }; + ("i2c_master.bus_timeout_is_exponential") => { + true + }; + ("i2c_master.has_pd_en") => { + true + }; + ("i2c_master.max_bus_timeout") => { + 31 + }; + ("i2c_master.max_bus_timeout", str) => { + stringify!(31) + }; + ("i2c_master.ll_intr_mask") => { + 262143 + }; + ("i2c_master.ll_intr_mask", str) => { + stringify!(262143) + }; + ("i2c_master.fifo_size") => { + 32 + }; + ("i2c_master.fifo_size", str) => { + stringify!(32) + }; + ("spi_master.version") => { + 3 + }; + ("spi_master.version", str) => { + stringify!(3) + }; + ("spi_master.fifo_size") => { + 64 + }; + ("spi_master.fifo_size", str) => { + stringify!(64) + }; + ("spi_master.bit_order_is_bool") => { + false + }; + ("spi_master.has_octal") => { + false + }; + ("spi_master.has_app_interrupts") => { + true + }; + ("spi_master.has_dma_segmented_transfer") => { + true + }; + ("spi_master.has_clk_pre_div") => { + false + }; + ("spi_master.dma_can_access_flash") => { + false + }; + ("i2s.version") => { + 3 + }; + ("i2s.version", str) => { + stringify!(3) + }; + ("i2s.mclk_divider_bit_width") => { + 9 + }; + ("i2s.mclk_divider_bit_width", str) => { + stringify!(9) + }; + ("i2s.max_ws_width") => { + 512 + }; + ("i2s.max_ws_width", str) => { + stringify!(512) + }; + ("i2s.clock_configured_by_pcr") => { + true + }; + ("i2s.clock_configured_by_hp_sys_clkrst") => { + false + }; + ("i2s.supports_pdm_rx_hp_filter") => { + false + }; + ("i2s.supports_pdm_tx") => { + true + }; + ("i2s.supports_pdm_rx") => { + true + }; + ("i2s.supports_pcm2pdm") => { + true + }; + ("i2s.supports_pdm2pcm") => { + false + }; + ("bt.controller") => { + "btdm2" + }; + ("phy.combo_module") => { + false + }; + ("timergroup.timg_has_timer1") => { + false + }; + ("timergroup.timg_has_divcnt_rst") => { + true + }; + ("timergroup.wdt_has_conf_update") => { + true + }; + ("timergroup.rc_fast_calibration_divider_min_rev") => { + 0 + }; + ("timergroup.rc_fast_calibration_divider") => { + 32 + }; + ("timergroup.rc_fast_calibration_tick_enable") => { + false + }; + ("timergroup.rc_slow_calibration_multiplier") => { + 4 + }; + ("rng.apb_cycle_wait_num") => { + 16 + }; + ("rng.apb_cycle_wait_num", str) => { + stringify!(16) + }; + ("rng.trng_supported") => { + false + }; + ("rng.is_lp_sys") => { + false + }; + ("sleep.light_sleep") => { + true + }; + ("sleep.deep_sleep") => { + true + }; + ("sleep.rejectable_mask") => { + 17622 + }; + ("sleep.ext1_version") => { + 2 + }; + ("sleep.ext1_version", str) => { + stringify!(2) + }; + ("sleep.pin_wakeup_version") => { + 3 + }; + ("sleep.pin_wakeup_version", str) => { + stringify!(3) + }; + ("sleep.deep_sleep_needs_gpio_isolation") => { + false + }; + ("dma.mem2mem_requires_peripheral") => { + false + }; + ("dma.ext_mem_configurable_block_size") => { + false + }; + ("dma.separate_in_out_interrupts") => { + true + }; + ("dma.gdma_version") => { + 3 + }; + ("dma.gdma_version", str) => { + stringify!(3) + }; + ("interrupts.status_registers") => { + 4 + }; + ("interrupts.status_registers", str) => { + stringify!(4) + }; + ("interrupts.disabled_interrupt") => { + 0 + }; + ("mmu.page_size") => { + 65536 + }; + ("mmu.page_size", str) => { + stringify!(65536) + }; + ("mmu.entry_num") => { + 512 + }; + ("mmu.entry_num", str) => { + stringify!(512) + }; + ("rom.has_crc_le") => { + true + }; + ("rom.has_crc_be") => { + true + }; + ("rom.has_md5_bsd") => { + true + }; + ("rom.has_md5_mbedtls") => { + false + }; + ("soc.cpu_has_branch_predictor") => { + true + }; + ("soc.cpu_has_csr_pc") => { + false + }; + ("soc.cpu_has_zcmp_workaround") => { + true + }; + ("soc.multi_core_enabled") => { + true + }; + ("soc.cpu_csr_prv_mode") => { + 2064 + }; + ("soc.cpu_csr_prv_mode", str) => { + stringify!(2064) + }; + ("soc.internal_memory_cached") => { + false + }; + ("soc.has_swd_watchdog") => { + true + }; + ("soc.cpu_mcause_mask") => { + 63 + }; + ("soc.cpu_mcause_mask", str) => { + stringify!(63) + }; + ("soc.cpu_pmp_granularity") => { + 128 + }; + ("soc.cpu_pmp_granularity", str) => { + stringify!(128) + }; + ("clock_tree.iomux_function_clock") => { + [crate ::soc::clocks::IomuxFunctionClockConfig::XtalClk, crate + ::soc::clocks::IomuxFunctionClockConfig::RcFastClk, crate + ::soc::clocks::IomuxFunctionClockConfig::PllF48m] + }; + ("clock_tree.hp_root_clk") => { + [crate ::soc::clocks::HpRootClkConfig::Xtal, crate + ::soc::clocks::HpRootClkConfig::RcFast, crate + ::soc::clocks::HpRootClkConfig::XtalX2, crate + ::soc::clocks::HpRootClkConfig::Pll] + }; + ("clock_tree.cpu_clk.divisor") => { + [0, 1, 3, 7, 15, 31, 63, 127] + }; + ("clock_tree.ahb_clk.divisor") => { + (0, 255) + }; + ("clock_tree.apb_clk.divisor") => { + [0, 1, 3] + }; + ("clock_tree.lp_fast_clk") => { + [crate ::soc::clocks::LpFastClkConfig::RcFastClk, crate + ::soc::clocks::LpFastClkConfig::XtalD2Clk] + }; + ("clock_tree.lp_slow_clk") => { + [#[cfg(use_xtal32k)] crate ::soc::clocks::LpSlowClkConfig::Xtal32k, crate + ::soc::clocks::LpSlowClkConfig::RcSlow, crate + ::soc::clocks::LpSlowClkConfig::OscSlow] + }; + ("clock_tree.ble_lp_clk") => { + [crate ::soc::clocks::BleLpClkConfig::Xtal, #[cfg(use_xtal32k)] crate + ::soc::clocks::BleLpClkConfig::Xtal32k] + }; + ("clock_tree.timg_calibration_clock") => { + [crate ::soc::clocks::TimgCalibrationClockConfig::RcSlowClk, crate + ::soc::clocks::TimgCalibrationClockConfig::RcFastDivClk, #[cfg(use_xtal32k)] + crate ::soc::clocks::TimgCalibrationClockConfig::Xtal32kClk] + }; + ("clock_tree.uart.function_clock.sclk") => { + [crate ::soc::clocks::UartFunctionClockSclk::PllF48m, crate + ::soc::clocks::UartFunctionClockSclk::RcFast, crate + ::soc::clocks::UartFunctionClockSclk::Xtal] + }; + ("clock_tree.uart.function_clock.div_num") => { + (0, 255) + }; + ("clock_tree.uart.baud_rate_generator.fractional") => { + (0, 15) + }; + ("clock_tree.uart.baud_rate_generator.integral") => { + (0, 4095) + }; + ("clock_tree.spi.function_clock") => { + [crate ::soc::clocks::SpiFunctionClockConfig::Xtal, crate + ::soc::clocks::SpiFunctionClockConfig::PllF48m, crate + ::soc::clocks::SpiFunctionClockConfig::RcFast] + }; + ("clock_tree.i2s.tx_clk.sclk") => { + [crate ::soc::clocks::I2sClkSclk::Xtal, crate ::soc::clocks::I2sClkSclk::PllF96m, + crate ::soc::clocks::I2sClkSclk::XtalX2] + }; + ("clock_tree.i2s.tx_clk.div_num") => { + (1, 255) + }; + ("clock_tree.i2s.tx_clk.div_a") => { + (1, 511) + }; + ("clock_tree.i2s.tx_clk.div_b") => { + (0, 511) + }; + ("clock_tree.i2s.rx_clk.sclk") => { + [crate ::soc::clocks::I2sClkSclk::Xtal, crate ::soc::clocks::I2sClkSclk::PllF96m, + crate ::soc::clocks::I2sClkSclk::XtalX2] + }; + ("clock_tree.i2s.rx_clk.div_num") => { + (1, 255) + }; + ("clock_tree.i2s.rx_clk.div_a") => { + (1, 511) + }; + ("clock_tree.i2s.rx_clk.div_b") => { + (0, 511) + }; + ("clock_tree.i2s.mclk_out") => { + [crate ::soc::clocks::I2sMclkOutConfig::Tx, crate + ::soc::clocks::I2sMclkOutConfig::Rx] + }; + ("clock_tree.i2c.function_clock.sclk") => { + [crate ::soc::clocks::I2cFunctionClockSclk::Xtal, crate + ::soc::clocks::I2cFunctionClockSclk::RcFast] + }; + ("clock_tree.i2c.function_clock.div_num") => { + (0, 255) + }; + ("clock_tree.timg.function_clock") => { + [crate ::soc::clocks::TimgFunctionClockConfig::XtalClk, crate + ::soc::clocks::TimgFunctionClockConfig::RcFastClk, crate + ::soc::clocks::TimgFunctionClockConfig::PllF48m] + }; + ("clock_tree.timg.wdt_clock") => { + [crate ::soc::clocks::TimgWdtClockConfig::XtalClk, crate + ::soc::clocks::TimgWdtClockConfig::RcFastClk, crate + ::soc::clocks::TimgWdtClockConfig::PllF48m] + }; +} +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! for_each_dedicated_gpio { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _for_each_inner_dedicated_gpio { $(($pattern) => $code;)* ($other : + tt) => {} } _for_each_inner_dedicated_gpio!((0)); + _for_each_inner_dedicated_gpio!((1)); _for_each_inner_dedicated_gpio!((2)); + _for_each_inner_dedicated_gpio!((3)); _for_each_inner_dedicated_gpio!((4)); + _for_each_inner_dedicated_gpio!((5)); _for_each_inner_dedicated_gpio!((6)); + _for_each_inner_dedicated_gpio!((7)); _for_each_inner_dedicated_gpio!((0, 0, + CPU_GPIO_0)); _for_each_inner_dedicated_gpio!((0, 1, CPU_GPIO_1)); + _for_each_inner_dedicated_gpio!((0, 2, CPU_GPIO_2)); + _for_each_inner_dedicated_gpio!((0, 3, CPU_GPIO_3)); + _for_each_inner_dedicated_gpio!((0, 4, CPU_GPIO_4)); + _for_each_inner_dedicated_gpio!((0, 5, CPU_GPIO_5)); + _for_each_inner_dedicated_gpio!((0, 6, CPU_GPIO_6)); + _for_each_inner_dedicated_gpio!((0, 7, CPU_GPIO_7)); + _for_each_inner_dedicated_gpio!((1, 0, CPU_GPIO_8)); + _for_each_inner_dedicated_gpio!((1, 1, CPU_GPIO_9)); + _for_each_inner_dedicated_gpio!((1, 2, CPU_GPIO_10)); + _for_each_inner_dedicated_gpio!((1, 3, CPU_GPIO_11)); + _for_each_inner_dedicated_gpio!((1, 4, CPU_GPIO_12)); + _for_each_inner_dedicated_gpio!((1, 5, CPU_GPIO_13)); + _for_each_inner_dedicated_gpio!((1, 6, CPU_GPIO_14)); + _for_each_inner_dedicated_gpio!((1, 7, CPU_GPIO_15)); + _for_each_inner_dedicated_gpio!((channels(0), (1), (2), (3), (4), (5), (6), + (7))); _for_each_inner_dedicated_gpio!((signals(0, 0, CPU_GPIO_0), (0, 1, + CPU_GPIO_1), (0, 2, CPU_GPIO_2), (0, 3, CPU_GPIO_3), (0, 4, CPU_GPIO_4), (0, 5, + CPU_GPIO_5), (0, 6, CPU_GPIO_6), (0, 7, CPU_GPIO_7), (1, 0, CPU_GPIO_8), (1, 1, + CPU_GPIO_9), (1, 2, CPU_GPIO_10), (1, 3, CPU_GPIO_11), (1, 4, CPU_GPIO_12), (1, + 5, CPU_GPIO_13), (1, 6, CPU_GPIO_14), (1, 7, CPU_GPIO_15))); + }; +} +/// Defines the `LpInputSignal` and `LpOutputSignal` enums. +/// +/// This macro is intended to be called in esp-hal only. +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! define_lp_io_signals { + () => {}; +} +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! for_each_wakeup_source { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _for_each_inner_wakeup_source { $(($pattern) => $code;)* ($other : + tt) => {} } _for_each_inner_wakeup_source!((Ext1, 1)); + _for_each_inner_wakeup_source!((Gpio, 2)); _for_each_inner_wakeup_source!((Timer, + 4)); _for_each_inner_wakeup_source!((Uart0, 6)); + _for_each_inner_wakeup_source!((Uart1, 7)); _for_each_inner_wakeup_source!((Bt, + 10)); _for_each_inner_wakeup_source!((Usb, 14)); + _for_each_inner_wakeup_source!((all(Ext1, 1), (Gpio, 2), (Timer, 4), (Uart0, 6), + (Uart1, 7), (Bt, 10), (Usb, 14))); + }; +} +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! for_each_dma_engine { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _for_each_inner_dma_engine { $(($pattern) => $code;)* ($other : tt) + => {} } _for_each_inner_dma_engine!(("AHB_GDMA")); + _for_each_inner_dma_engine!((all("AHB_GDMA"))); + }; +} +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! for_each_dma_channel { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _for_each_inner_dma_channel { $(($pattern) => $code;)* ($other : tt) + => {} } _for_each_inner_dma_channel!(("AHB_GDMA", DMA_CH0)); + _for_each_inner_dma_channel!(("AHB_GDMA", DMA_CH1)); + _for_each_inner_dma_channel!(("AHB_GDMA", DMA_CH2)); + _for_each_inner_dma_channel!(("AHB_GDMA", DMA_CH3)); + _for_each_inner_dma_channel!(("AHB_GDMA", DMA_CH4)); + _for_each_inner_dma_channel!(("AHB_GDMA", any_channel = AhbGdmaChannel)); + _for_each_inner_dma_channel!(("AHB_GDMA", DMA_CH0, 0, interrupt_in = DMA_IN_CH0, + interrupt_out = DMA_OUT_CH0, compatible = [SPI3, SPI2, UHCI0, I2S0, AES, SHA, + PARL_IO])); _for_each_inner_dma_channel!(("AHB_GDMA", DMA_CH1, 1, interrupt_in = + DMA_IN_CH1, interrupt_out = DMA_OUT_CH1, compatible = [SPI3, SPI2, UHCI0, I2S0, + AES, SHA, PARL_IO])); _for_each_inner_dma_channel!(("AHB_GDMA", DMA_CH2, 2, + interrupt_in = DMA_IN_CH2, interrupt_out = DMA_OUT_CH2, compatible = [SPI3, SPI2, + UHCI0, I2S0, AES, SHA, PARL_IO])); _for_each_inner_dma_channel!(("AHB_GDMA", + DMA_CH3, 3, interrupt_in = DMA_IN_CH3, interrupt_out = DMA_OUT_CH3, compatible = + [SPI3, SPI2, UHCI0, I2S0, AES, SHA, PARL_IO])); + _for_each_inner_dma_channel!(("AHB_GDMA", DMA_CH4, 4, interrupt_in = DMA_IN_CH4, + interrupt_out = DMA_OUT_CH4, compatible = [SPI3, SPI2, UHCI0, I2S0, AES, SHA, + PARL_IO])); _for_each_inner_dma_channel!((names("AHB_GDMA", DMA_CH0), + ("AHB_GDMA", DMA_CH1), ("AHB_GDMA", DMA_CH2), ("AHB_GDMA", DMA_CH3), ("AHB_GDMA", + DMA_CH4))); _for_each_inner_dma_channel!((separate_any_type("AHB_GDMA", + any_channel = AhbGdmaChannel))); _for_each_inner_dma_channel!((shared)); + _for_each_inner_dma_channel!((split("AHB_GDMA", DMA_CH0, 0, interrupt_in = + DMA_IN_CH0, interrupt_out = DMA_OUT_CH0, compatible = [SPI3, SPI2, UHCI0, I2S0, + AES, SHA, PARL_IO]), ("AHB_GDMA", DMA_CH1, 1, interrupt_in = DMA_IN_CH1, + interrupt_out = DMA_OUT_CH1, compatible = [SPI3, SPI2, UHCI0, I2S0, AES, SHA, + PARL_IO]), ("AHB_GDMA", DMA_CH2, 2, interrupt_in = DMA_IN_CH2, interrupt_out = + DMA_OUT_CH2, compatible = [SPI3, SPI2, UHCI0, I2S0, AES, SHA, PARL_IO]), + ("AHB_GDMA", DMA_CH3, 3, interrupt_in = DMA_IN_CH3, interrupt_out = DMA_OUT_CH3, + compatible = [SPI3, SPI2, UHCI0, I2S0, AES, SHA, PARL_IO]), ("AHB_GDMA", DMA_CH4, + 4, interrupt_in = DMA_IN_CH4, interrupt_out = DMA_OUT_CH4, compatible = [SPI3, + SPI2, UHCI0, I2S0, AES, SHA, PARL_IO]))); + _for_each_inner_dma_channel!((no_own_interrupt)); + }; +} +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! for_each_dma_channel_peri_pair { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _for_each_inner_dma_channel_peri_pair { $(($pattern) => $code;)* + ($other : tt) => {} } _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", + DMA_CH0, SPI3)); _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH0, + SPI2)); _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH0, UHCI0)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH0, I2S0)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH0, AES)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH0, SHA)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH0, PARL_IO)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH1, SPI3)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH1, SPI2)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH1, UHCI0)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH1, I2S0)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH1, AES)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH1, SHA)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH1, PARL_IO)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH2, SPI3)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH2, SPI2)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH2, UHCI0)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH2, I2S0)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH2, AES)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH2, SHA)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH2, PARL_IO)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH3, SPI3)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH3, SPI2)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH3, UHCI0)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH3, I2S0)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH3, AES)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH3, SHA)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH3, PARL_IO)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH4, SPI3)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH4, SPI2)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH4, UHCI0)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH4, I2S0)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH4, AES)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH4, SHA)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH4, PARL_IO)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", any_channel = AhbGdmaChannel, + SPI3)); _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", any_channel = + AhbGdmaChannel, SPI2)); _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", + any_channel = AhbGdmaChannel, UHCI0)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", any_channel = AhbGdmaChannel, + I2S0)); _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", any_channel = + AhbGdmaChannel, AES)); _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", + any_channel = AhbGdmaChannel, SHA)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", any_channel = AhbGdmaChannel, + PARL_IO)); _for_each_inner_dma_channel_peri_pair!((channels("AHB_GDMA", DMA_CH0, + SPI3), ("AHB_GDMA", DMA_CH0, SPI2), ("AHB_GDMA", DMA_CH0, UHCI0), ("AHB_GDMA", + DMA_CH0, I2S0), ("AHB_GDMA", DMA_CH0, AES), ("AHB_GDMA", DMA_CH0, SHA), + ("AHB_GDMA", DMA_CH0, PARL_IO), ("AHB_GDMA", DMA_CH1, SPI3), ("AHB_GDMA", + DMA_CH1, SPI2), ("AHB_GDMA", DMA_CH1, UHCI0), ("AHB_GDMA", DMA_CH1, I2S0), + ("AHB_GDMA", DMA_CH1, AES), ("AHB_GDMA", DMA_CH1, SHA), ("AHB_GDMA", DMA_CH1, + PARL_IO), ("AHB_GDMA", DMA_CH2, SPI3), ("AHB_GDMA", DMA_CH2, SPI2), ("AHB_GDMA", + DMA_CH2, UHCI0), ("AHB_GDMA", DMA_CH2, I2S0), ("AHB_GDMA", DMA_CH2, AES), + ("AHB_GDMA", DMA_CH2, SHA), ("AHB_GDMA", DMA_CH2, PARL_IO), ("AHB_GDMA", DMA_CH3, + SPI3), ("AHB_GDMA", DMA_CH3, SPI2), ("AHB_GDMA", DMA_CH3, UHCI0), ("AHB_GDMA", + DMA_CH3, I2S0), ("AHB_GDMA", DMA_CH3, AES), ("AHB_GDMA", DMA_CH3, SHA), + ("AHB_GDMA", DMA_CH3, PARL_IO), ("AHB_GDMA", DMA_CH4, SPI3), ("AHB_GDMA", + DMA_CH4, SPI2), ("AHB_GDMA", DMA_CH4, UHCI0), ("AHB_GDMA", DMA_CH4, I2S0), + ("AHB_GDMA", DMA_CH4, AES), ("AHB_GDMA", DMA_CH4, SHA), ("AHB_GDMA", DMA_CH4, + PARL_IO))); _for_each_inner_dma_channel_peri_pair!((any_channels("AHB_GDMA", + any_channel = AhbGdmaChannel, SPI3), ("AHB_GDMA", any_channel = AhbGdmaChannel, + SPI2), ("AHB_GDMA", any_channel = AhbGdmaChannel, UHCI0), ("AHB_GDMA", + any_channel = AhbGdmaChannel, I2S0), ("AHB_GDMA", any_channel = AhbGdmaChannel, + AES), ("AHB_GDMA", any_channel = AhbGdmaChannel, SHA), ("AHB_GDMA", any_channel = + AhbGdmaChannel, PARL_IO))); + }; +} +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! for_each_mem2mem_channel { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _for_each_inner_mem2mem_channel { $(($pattern) => $code;)* ($other : + tt) => {} } _for_each_inner_mem2mem_channel!(("AHB_GDMA", AhbGdma, + AhbGdmaChannel, DMA_CH0, 10)); _for_each_inner_mem2mem_channel!(("AHB_GDMA", + AhbGdma, AhbGdmaChannel, DMA_CH1, 11)); + _for_each_inner_mem2mem_channel!(("AHB_GDMA", AhbGdma, AhbGdmaChannel, DMA_CH2, + 12)); _for_each_inner_mem2mem_channel!(("AHB_GDMA", AhbGdma, AhbGdmaChannel, + DMA_CH3, 13)); _for_each_inner_mem2mem_channel!(("AHB_GDMA", AhbGdma, + AhbGdmaChannel, DMA_CH4, 14)); _for_each_inner_mem2mem_channel!(("AHB_GDMA", + AhbGdma, AhbGdmaChannel, 0, 10, 1, 11, 2, 12, 3, 13, 4, 14)); + _for_each_inner_mem2mem_channel!(("AHB_GDMA", AhbGdma, AhbGdmaChannel)); + _for_each_inner_mem2mem_channel!((channels("AHB_GDMA", AhbGdma, AhbGdmaChannel, + DMA_CH0, 10), ("AHB_GDMA", AhbGdma, AhbGdmaChannel, DMA_CH1, 11), ("AHB_GDMA", + AhbGdma, AhbGdmaChannel, DMA_CH2, 12), ("AHB_GDMA", AhbGdma, AhbGdmaChannel, + DMA_CH3, 13), ("AHB_GDMA", AhbGdma, AhbGdmaChannel, DMA_CH4, 14))); + _for_each_inner_mem2mem_channel!((erased("AHB_GDMA", AhbGdma, AhbGdmaChannel, 0, + 10, 1, 11, 2, 12, 3, 13, 4, 14))); + _for_each_inner_mem2mem_channel!((engines("AHB_GDMA", AhbGdma, AhbGdmaChannel))); + }; +} +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! with_i2s_dma_engine { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _with_inner_i2s_dma_engine { $(($pattern) => $code;)* ($other : tt) + => {} } _with_inner_i2s_dma_engine!(("AHB_GDMA", AhbGdmaChannel)); + }; +} +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! with_spi_master_dma_engine { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _with_inner_spi_master_dma_engine { $(($pattern) => $code;)* ($other + : tt) => {} } _with_inner_spi_master_dma_engine!(("AHB_GDMA", AhbGdmaChannel)); + }; +} +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! for_each_interrupt { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _for_each_inner_interrupt { $(($pattern) => $code;)* ($other : tt) + => {} } _for_each_inner_interrupt!(([disabled 0] 0)); + _for_each_inner_interrupt!(([reserved 0] 1)); + _for_each_inner_interrupt!(([reserved 1] 2)); + _for_each_inner_interrupt!(([reserved 2] 3)); + _for_each_inner_interrupt!(([reserved 3] 4)); + _for_each_inner_interrupt!(([reserved 4] 5)); + _for_each_inner_interrupt!(([reserved 5] 6)); + _for_each_inner_interrupt!(([reserved 6] 7)); + _for_each_inner_interrupt!(([reserved 7] 8)); + _for_each_inner_interrupt!(([reserved 8] 9)); + _for_each_inner_interrupt!(([reserved 9] 10)); + _for_each_inner_interrupt!(([reserved 10] 11)); + _for_each_inner_interrupt!(([reserved 11] 12)); + _for_each_inner_interrupt!(([reserved 12] 13)); + _for_each_inner_interrupt!(([reserved 13] 14)); + _for_each_inner_interrupt!(([reserved 14] 15)); + _for_each_inner_interrupt!(([vector 0] 16)); _for_each_inner_interrupt!(([vector + 1] 17)); _for_each_inner_interrupt!(([vector 2] 18)); + _for_each_inner_interrupt!(([vector 3] 19)); _for_each_inner_interrupt!(([vector + 4] 20)); _for_each_inner_interrupt!(([vector 5] 21)); + _for_each_inner_interrupt!(([vector 6] 22)); _for_each_inner_interrupt!(([vector + 7] 23)); _for_each_inner_interrupt!(([direct_bindable 0] 24)); + _for_each_inner_interrupt!(([direct_bindable 1] 25)); + _for_each_inner_interrupt!(([direct_bindable 2] 26)); + _for_each_inner_interrupt!(([direct_bindable 3] 27)); + _for_each_inner_interrupt!(([direct_bindable 4] 28)); + _for_each_inner_interrupt!(([direct_bindable 5] 29)); + _for_each_inner_interrupt!(([direct_bindable 6] 30)); + _for_each_inner_interrupt!(([direct_bindable 7] 31)); + _for_each_inner_interrupt!(([direct_bindable 8] 32)); + _for_each_inner_interrupt!(([direct_bindable 9] 33)); + _for_each_inner_interrupt!(([direct_bindable 10] 34)); + _for_each_inner_interrupt!(([direct_bindable 11] 35)); + _for_each_inner_interrupt!(([direct_bindable 12] 36)); + _for_each_inner_interrupt!(([direct_bindable 13] 37)); + _for_each_inner_interrupt!(([direct_bindable 14] 38)); + _for_each_inner_interrupt!(([direct_bindable 15] 39)); + _for_each_inner_interrupt!(([direct_bindable 16] 40)); + _for_each_inner_interrupt!(([direct_bindable 17] 41)); + _for_each_inner_interrupt!(([direct_bindable 18] 42)); + _for_each_inner_interrupt!(([direct_bindable 19] 43)); + _for_each_inner_interrupt!(([direct_bindable 20] 44)); + _for_each_inner_interrupt!(([direct_bindable 21] 45)); + _for_each_inner_interrupt!(([direct_bindable 22] 46)); + _for_each_inner_interrupt!(([direct_bindable 23] 47)); + _for_each_inner_interrupt!((all([disabled 0] 0), ([reserved 0] 1), ([reserved 1] + 2), ([reserved 2] 3), ([reserved 3] 4), ([reserved 4] 5), ([reserved 5] 6), + ([reserved 6] 7), ([reserved 7] 8), ([reserved 8] 9), ([reserved 9] 10), + ([reserved 10] 11), ([reserved 11] 12), ([reserved 12] 13), ([reserved 13] 14), + ([reserved 14] 15), ([vector 0] 16), ([vector 1] 17), ([vector 2] 18), ([vector + 3] 19), ([vector 4] 20), ([vector 5] 21), ([vector 6] 22), ([vector 7] 23), + ([direct_bindable 0] 24), ([direct_bindable 1] 25), ([direct_bindable 2] 26), + ([direct_bindable 3] 27), ([direct_bindable 4] 28), ([direct_bindable 5] 29), + ([direct_bindable 6] 30), ([direct_bindable 7] 31), ([direct_bindable 8] 32), + ([direct_bindable 9] 33), ([direct_bindable 10] 34), ([direct_bindable 11] 35), + ([direct_bindable 12] 36), ([direct_bindable 13] 37), ([direct_bindable 14] 38), + ([direct_bindable 15] 39), ([direct_bindable 16] 40), ([direct_bindable 17] 41), + ([direct_bindable 18] 42), ([direct_bindable 19] 43), ([direct_bindable 20] 44), + ([direct_bindable 21] 45), ([direct_bindable 22] 46), ([direct_bindable 23] + 47))); + }; +} +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! for_each_classified_interrupt { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _for_each_inner_classified_interrupt { $(($pattern) => $code;)* + ($other : tt) => {} } _for_each_inner_classified_interrupt!(([direct_bindable 0] + 24)); _for_each_inner_classified_interrupt!(([direct_bindable 1] 25)); + _for_each_inner_classified_interrupt!(([direct_bindable 2] 26)); + _for_each_inner_classified_interrupt!(([direct_bindable 3] 27)); + _for_each_inner_classified_interrupt!(([direct_bindable 4] 28)); + _for_each_inner_classified_interrupt!(([direct_bindable 5] 29)); + _for_each_inner_classified_interrupt!(([direct_bindable 6] 30)); + _for_each_inner_classified_interrupt!(([direct_bindable 7] 31)); + _for_each_inner_classified_interrupt!(([direct_bindable 8] 32)); + _for_each_inner_classified_interrupt!(([direct_bindable 9] 33)); + _for_each_inner_classified_interrupt!(([direct_bindable 10] 34)); + _for_each_inner_classified_interrupt!(([direct_bindable 11] 35)); + _for_each_inner_classified_interrupt!(([direct_bindable 12] 36)); + _for_each_inner_classified_interrupt!(([direct_bindable 13] 37)); + _for_each_inner_classified_interrupt!(([direct_bindable 14] 38)); + _for_each_inner_classified_interrupt!(([direct_bindable 15] 39)); + _for_each_inner_classified_interrupt!(([direct_bindable 16] 40)); + _for_each_inner_classified_interrupt!(([direct_bindable 17] 41)); + _for_each_inner_classified_interrupt!(([direct_bindable 18] 42)); + _for_each_inner_classified_interrupt!(([direct_bindable 19] 43)); + _for_each_inner_classified_interrupt!(([direct_bindable 20] 44)); + _for_each_inner_classified_interrupt!(([direct_bindable 21] 45)); + _for_each_inner_classified_interrupt!(([direct_bindable 22] 46)); + _for_each_inner_classified_interrupt!(([direct_bindable 23] 47)); + _for_each_inner_classified_interrupt!(([vector 0] 16)); + _for_each_inner_classified_interrupt!(([vector 1] 17)); + _for_each_inner_classified_interrupt!(([vector 2] 18)); + _for_each_inner_classified_interrupt!(([vector 3] 19)); + _for_each_inner_classified_interrupt!(([vector 4] 20)); + _for_each_inner_classified_interrupt!(([vector 5] 21)); + _for_each_inner_classified_interrupt!(([vector 6] 22)); + _for_each_inner_classified_interrupt!(([vector 7] 23)); + _for_each_inner_classified_interrupt!(([reserved 0] 1)); + _for_each_inner_classified_interrupt!(([reserved 1] 2)); + _for_each_inner_classified_interrupt!(([reserved 2] 3)); + _for_each_inner_classified_interrupt!(([reserved 3] 4)); + _for_each_inner_classified_interrupt!(([reserved 4] 5)); + _for_each_inner_classified_interrupt!(([reserved 5] 6)); + _for_each_inner_classified_interrupt!(([reserved 6] 7)); + _for_each_inner_classified_interrupt!(([reserved 7] 8)); + _for_each_inner_classified_interrupt!(([reserved 8] 9)); + _for_each_inner_classified_interrupt!(([reserved 9] 10)); + _for_each_inner_classified_interrupt!(([reserved 10] 11)); + _for_each_inner_classified_interrupt!(([reserved 11] 12)); + _for_each_inner_classified_interrupt!(([reserved 12] 13)); + _for_each_inner_classified_interrupt!(([reserved 13] 14)); + _for_each_inner_classified_interrupt!(([reserved 14] 15)); + _for_each_inner_classified_interrupt!((direct_bindable([direct_bindable 0] 24), + ([direct_bindable 1] 25), ([direct_bindable 2] 26), ([direct_bindable 3] 27), + ([direct_bindable 4] 28), ([direct_bindable 5] 29), ([direct_bindable 6] 30), + ([direct_bindable 7] 31), ([direct_bindable 8] 32), ([direct_bindable 9] 33), + ([direct_bindable 10] 34), ([direct_bindable 11] 35), ([direct_bindable 12] 36), + ([direct_bindable 13] 37), ([direct_bindable 14] 38), ([direct_bindable 15] 39), + ([direct_bindable 16] 40), ([direct_bindable 17] 41), ([direct_bindable 18] 42), + ([direct_bindable 19] 43), ([direct_bindable 20] 44), ([direct_bindable 21] 45), + ([direct_bindable 22] 46), ([direct_bindable 23] 47))); + _for_each_inner_classified_interrupt!((vector([vector 0] 16), ([vector 1] 17), + ([vector 2] 18), ([vector 3] 19), ([vector 4] 20), ([vector 5] 21), ([vector 6] + 22), ([vector 7] 23))); _for_each_inner_classified_interrupt!((reserved([reserved + 0] 1), ([reserved 1] 2), ([reserved 2] 3), ([reserved 3] 4), ([reserved 4] 5), + ([reserved 5] 6), ([reserved 6] 7), ([reserved 7] 8), ([reserved 8] 9), + ([reserved 9] 10), ([reserved 10] 11), ([reserved 11] 12), ([reserved 12] 13), + ([reserved 13] 14), ([reserved 14] 15))); + _for_each_inner_classified_interrupt!((context_switch)); + }; +} +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! for_each_interrupt_priority { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _for_each_inner_interrupt_priority { $(($pattern) => $code;)* + ($other : tt) => {} } _for_each_inner_interrupt_priority!((0, 1, Priority1, + Level1)); _for_each_inner_interrupt_priority!((1, 2, Priority2, Level2)); + _for_each_inner_interrupt_priority!((2, 3, Priority3, Level3)); + _for_each_inner_interrupt_priority!((3, 4, Priority4, Level4)); + _for_each_inner_interrupt_priority!((4, 5, Priority5, Level5)); + _for_each_inner_interrupt_priority!((5, 6, Priority6, Level6)); + _for_each_inner_interrupt_priority!((6, 7, Priority7, Level7)); + _for_each_inner_interrupt_priority!((7, 8, Priority8, Level8)); + _for_each_inner_interrupt_priority!((all(0, 1, Priority1, Level1), (1, 2, + Priority2, Level2), (2, 3, Priority3, Level3), (3, 4, Priority4, Level4), (4, 5, + Priority5, Level5), (5, 6, Priority6, Level6), (6, 7, Priority7, Level7), (7, 8, + Priority8, Level8))); + }; +} +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! for_each_sw_interrupt { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _for_each_inner_sw_interrupt { $(($pattern) => $code;)* ($other : + tt) => {} } _for_each_inner_sw_interrupt!((0, FROM_CPU_INTR0, + software_interrupt0)); _for_each_inner_sw_interrupt!((1, FROM_CPU_INTR1, + software_interrupt1)); _for_each_inner_sw_interrupt!((2, FROM_CPU_INTR2, + software_interrupt2)); _for_each_inner_sw_interrupt!((3, FROM_CPU_INTR3, + software_interrupt3)); _for_each_inner_sw_interrupt!((all(0, FROM_CPU_INTR0, + software_interrupt0), (1, FROM_CPU_INTR1, software_interrupt1), (2, + FROM_CPU_INTR2, software_interrupt2), (3, FROM_CPU_INTR3, software_interrupt3))); + }; +} +#[macro_export] +/// ESP-HAL must provide implementation for the following functions: +/// ```rust, no_run +/// // XTAL_CLK +/// +/// // PLL_F96M_CLK +/// +/// fn enable_pll_f96m_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// // PLL_F48M_CLK +/// +/// fn enable_pll_f48m_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// // IOMUX_FUNCTION_CLOCK +/// +/// fn configure_iomux_function_clock_impl( +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: IomuxFunctionClockConfig, +/// ) { +/// todo!() +/// } +/// +/// // XTAL_X2_CLK +/// +/// fn enable_xtal_x2_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// // RC_FAST_CLK +/// +/// fn enable_rc_fast_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// // XTAL32K_CLK +/// +/// #[cfg(use_xtal32k)] +/// fn enable_xtal32k_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// // OSC_SLOW_CLK +/// +/// fn enable_osc_slow_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// // RC_SLOW_CLK +/// +/// fn enable_rc_slow_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// // RC_SLOW_D4_CLK +/// +/// fn enable_rc_slow_d4_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// // HP_ROOT_CLK +/// +/// fn enable_hp_root_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_hp_root_clk_impl( +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: HpRootClkConfig, +/// ) { +/// todo!() +/// } +/// +/// // CPU_CLK +/// +/// fn configure_cpu_clk_impl( +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: CpuClkConfig, +/// ) { +/// todo!() +/// } +/// +/// // AHB_CLK +/// +/// fn configure_ahb_clk_impl( +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: AhbClkConfig, +/// ) { +/// todo!() +/// } +/// +/// // APB_CLK +/// +/// fn enable_apb_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_apb_clk_impl( +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: ApbClkConfig, +/// ) { +/// todo!() +/// } +/// +/// // XTAL_D2_CLK +/// +/// fn enable_xtal_d2_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// // LP_FAST_CLK +/// +/// fn enable_lp_fast_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_lp_fast_clk_impl( +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: LpFastClkConfig, +/// ) { +/// todo!() +/// } +/// +/// // LP_SLOW_CLK +/// +/// fn enable_lp_slow_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_lp_slow_clk_impl( +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: LpSlowClkConfig, +/// ) { +/// todo!() +/// } +/// +/// // BLE_LP_XTAL_CLK +/// +/// fn enable_ble_lp_xtal_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// // BLE_LP_CLK +/// +/// fn enable_ble_lp_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_ble_lp_clk_impl( +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: BleLpClkConfig, +/// ) { +/// todo!() +/// } +/// +/// // TIMG_CALIBRATION_CLOCK +/// +/// fn enable_timg_calibration_clock_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_timg_calibration_clock_impl( +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: TimgCalibrationClockConfig, +/// ) { +/// todo!() +/// } +/// +/// impl I2sInstance { +/// // I2S_TX_CLK +/// +/// fn enable_tx_clk_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_tx_clk_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: I2sClkConfig, +/// ) { +/// todo!() +/// } +/// +/// // I2S_RX_CLK +/// +/// fn enable_rx_clk_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_rx_clk_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: I2sClkConfig, +/// ) { +/// todo!() +/// } +/// +/// // I2S_MCLK_OUT +/// +/// fn enable_mclk_out_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_mclk_out_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: I2sMclkOutConfig, +/// ) { +/// todo!() +/// } +/// } +/// impl I2cInstance { +/// // I2C_FUNCTION_CLOCK +/// +/// fn enable_function_clock_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_function_clock_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: I2cFunctionClockConfig, +/// ) { +/// todo!() +/// } +/// } +/// impl SpiInstance { +/// // SPI_FUNCTION_CLOCK +/// +/// fn enable_function_clock_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_function_clock_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: SpiFunctionClockConfig, +/// ) { +/// todo!() +/// } +/// } +/// impl TimgInstance { +/// // TIMG_FUNCTION_CLOCK +/// +/// fn enable_function_clock_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_function_clock_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: TimgFunctionClockConfig, +/// ) { +/// todo!() +/// } +/// +/// // TIMG_WDT_CLOCK +/// +/// fn enable_wdt_clock_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_wdt_clock_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: TimgWdtClockConfig, +/// ) { +/// todo!() +/// } +/// } +/// impl UartInstance { +/// // UART_FUNCTION_CLOCK +/// +/// fn enable_function_clock_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_function_clock_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: UartFunctionClockConfig, +/// ) { +/// todo!() +/// } +/// +/// // UART_BAUD_RATE_GENERATOR +/// +/// fn enable_baud_rate_generator_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_baud_rate_generator_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: UartBaudRateGeneratorConfig, +/// ) { +/// todo!() +/// } +/// } +/// ``` +macro_rules! define_clock_tree_types { + () => { + #[derive(Clone, Copy, PartialEq, Eq, Debug)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum I2sInstance { + I2s0 = 0, + } + #[derive(Clone, Copy, PartialEq, Eq, Debug)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum I2cInstance { + I2c0 = 0, + I2c1 = 1, + } + #[derive(Clone, Copy, PartialEq, Eq, Debug)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum SpiInstance { + Spi2 = 0, + Spi3 = 1, + } + #[derive(Clone, Copy, PartialEq, Eq, Debug)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum TimgInstance { + Timg0 = 0, + Timg1 = 1, + } + #[derive(Clone, Copy, PartialEq, Eq, Debug)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum UartInstance { + Uart0 = 0, + Uart1 = 1, + } + /// The list of clock signals that the `IOMUX_FUNCTION_CLOCK` multiplexer can output. + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum IomuxFunctionClockConfig { + /// Selects `XTAL_CLK`. + XtalClk, + /// Selects `RC_FAST_CLK`. + RcFastClk, + #[default] + /// Selects `PLL_F48M_CLK`. + PllF48m, + } + /// The list of clock signals that the `HP_ROOT_CLK` multiplexer can output. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum HpRootClkConfig { + /// Selects `XTAL_CLK`. + Xtal, + /// Selects `RC_FAST_CLK`. + RcFast, + /// Selects `XTAL_X2_CLK`. + XtalX2, + /// Selects `PLL_F96M_CLK`. + Pll, + } + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum CpuClkDivisor { + /// Selects `divisor = 0`. + _0 = 0, + /// Selects `divisor = 1`. + _1 = 1, + /// Selects `divisor = 3`. + _3 = 3, + /// Selects `divisor = 7`. + _7 = 7, + /// Selects `divisor = 15`. + _15 = 15, + /// Selects `divisor = 31`. + _31 = 31, + /// Selects `divisor = 63`. + _63 = 63, + /// Selects `divisor = 127`. + _127 = 127, + } + impl CpuClkDivisor { + /// Creates a new parameter value from a raw number. + pub const fn new(raw: u32) -> Self { + match raw { + 0 => Self::_0, + 1 => Self::_1, + 3 => Self::_3, + 7 => Self::_7, + 15 => Self::_15, + 31 => Self::_31, + 63 => Self::_63, + 127 => Self::_127, + _ => ::core::panic!("Invalid CPU_CLK divisor value"), + } + } + } + /// Configures the `CPU_CLK` clock node. + /// + /// The output is calculated as `OUTPUT = HP_ROOT_CLK / (divisor + 1)`. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub struct CpuClkConfig { + divisor: CpuClkDivisor, + } + impl CpuClkConfig { + /// Creates a new configuration for the CPU_CLK clock node. + pub const fn new(divisor: CpuClkDivisor) -> Self { + Self { divisor } + } + pub fn divisor(self) -> u32 { + self.divisor as u32 + } + } + /// Configures the `AHB_CLK` clock node. + /// + /// The output is calculated as `OUTPUT = CPU_CLK / (divisor + 1)`. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub struct AhbClkConfig { + divisor: u32, + } + impl AhbClkConfig { + /// Creates a new configuration for the AHB_CLK clock node. + /// + /// ## Panics + /// + /// Panics if the divisor value is outside the + /// valid range (0 ..= 255). + pub const fn new(divisor: u32) -> Self { + ::core::assert!( + divisor <= 255, + "`AHB_CLK` divisor must be between 0 and 255 (inclusive)." + ); + Self { divisor } + } + pub fn divisor(self) -> u32 { + self.divisor as u32 + } + } + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum ApbClkDivisor { + /// Selects `divisor = 0`. + _0 = 0, + /// Selects `divisor = 1`. + _1 = 1, + /// Selects `divisor = 3`. + _3 = 3, + } + impl ApbClkDivisor { + /// Creates a new parameter value from a raw number. + pub const fn new(raw: u32) -> Self { + match raw { + 0 => Self::_0, + 1 => Self::_1, + 3 => Self::_3, + _ => ::core::panic!("Invalid APB_CLK divisor value"), + } + } + } + /// Configures the `APB_CLK` clock node. + /// + /// The output is calculated as `OUTPUT = AHB_CLK / (divisor + 1)`. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub struct ApbClkConfig { + divisor: ApbClkDivisor, + } + impl ApbClkConfig { + /// Creates a new configuration for the APB_CLK clock node. + pub const fn new(divisor: ApbClkDivisor) -> Self { + Self { divisor } + } + pub fn divisor(self) -> u32 { + self.divisor as u32 + } + } + /// The list of clock signals that the `LP_FAST_CLK` multiplexer can output. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum LpFastClkConfig { + /// Selects `RC_FAST_CLK`. + RcFastClk, + /// Selects `XTAL_D2_CLK`. + XtalD2Clk, + } + /// The list of clock signals that the `LP_SLOW_CLK` multiplexer can output. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum LpSlowClkConfig { + #[cfg(use_xtal32k)] + /// Selects `XTAL32K_CLK`. + Xtal32k, + /// Selects `RC_SLOW_D4_CLK`. + RcSlow, + /// Selects `OSC_SLOW_CLK`. + OscSlow, + } + /// The list of clock signals that the `BLE_LP_CLK` multiplexer can output. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum BleLpClkConfig { + /// Selects `BLE_LP_XTAL_CLK`. + Xtal, + #[cfg(use_xtal32k)] + /// Selects `XTAL32K_CLK`. + Xtal32k, + } + /// The list of clock signals that the `TIMG_CALIBRATION_CLOCK` multiplexer can output. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum TimgCalibrationClockConfig { + /// Selects `RC_SLOW_D4_CLK`. + RcSlowClk, + /// Selects `RC_FAST_CLK`. + RcFastDivClk, + #[cfg(use_xtal32k)] + /// Selects `XTAL32K_CLK`. + Xtal32kClk, + } + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum I2sClkSclk { + /// Selects `XTAL_CLK`. + Xtal, + #[default] + /// Selects `PLL_F96M_CLK`. + PllF96m, + /// Selects `XTAL_X2_CLK`. + XtalX2, + } + /// Configures the `I2S0_TX_CLK` clock node. + /// + /// The output is calculated as `OUTPUT = (sclk * div_a) / (div_num * div_a + div_b)`. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub struct I2sClkConfig { + sclk: I2sClkSclk, + div_num: u32, + div_a: u32, + div_b: u32, + } + impl I2sClkConfig { + /// Creates a new configuration for the TX_CLK clock node. + /// + /// ## Panics + /// + /// Panics if the div_num value is outside the + /// valid range (1 ..= 255). + /// + /// Panics if the div_a value is outside the + /// valid range (1 ..= 511). + /// + /// Panics if the div_b value is outside the + /// valid range (0 ..= 511). + pub const fn new(sclk: I2sClkSclk, div_num: u32, div_a: u32, div_b: u32) -> Self { + ::core::assert!( + div_num >= 1 && div_num <= 255, + "`I2S0_TX_CLK` div_num must be between 1 and 255 (inclusive)." + ); + ::core::assert!( + div_a >= 1 && div_a <= 511, + "`I2S0_TX_CLK` div_a must be between 1 and 511 (inclusive)." + ); + ::core::assert!( + div_b <= 511, + "`I2S0_TX_CLK` div_b must be between 0 and 511 (inclusive)." + ); + Self { + sclk, + div_num, + div_a, + div_b, + } + } + pub fn sclk(self) -> I2sClkSclk { + self.sclk + } + pub fn div_num(self) -> u32 { + self.div_num as u32 + } + pub fn div_a(self) -> u32 { + self.div_a as u32 + } + pub fn div_b(self) -> u32 { + self.div_b as u32 + } + } + /// The list of clock signals that the `I2S0_MCLK_OUT` multiplexer can output. + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum I2sMclkOutConfig { + /// Selects `TX_CLK`. + Tx, + #[default] + /// Selects `RX_CLK`. + Rx, + } + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum I2cFunctionClockSclk { + #[default] + /// Selects `XTAL_CLK`. + Xtal, + /// Selects `RC_FAST_CLK`. + RcFast, + } + /// Configures the `I2C0_FUNCTION_CLOCK` clock node. + /// + /// The output is calculated as `OUTPUT = sclk / (div_num + 1)`. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub struct I2cFunctionClockConfig { + sclk: I2cFunctionClockSclk, + div_num: u32, + } + impl I2cFunctionClockConfig { + /// Creates a new configuration for the FUNCTION_CLOCK clock node. + /// + /// ## Panics + /// + /// Panics if the div_num value is outside the + /// valid range (0 ..= 255). + pub const fn new(sclk: I2cFunctionClockSclk, div_num: u32) -> Self { + ::core::assert!( + div_num <= 255, + "`I2C0_FUNCTION_CLOCK` div_num must be between 0 and 255 (inclusive)." + ); + Self { sclk, div_num } + } + pub fn sclk(self) -> I2cFunctionClockSclk { + self.sclk + } + pub fn div_num(self) -> u32 { + self.div_num as u32 + } + } + /// The list of clock signals that the `SPI2_FUNCTION_CLOCK` multiplexer can output. + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum SpiFunctionClockConfig { + /// Selects `XTAL_CLK`. + Xtal, + #[default] + /// Selects `PLL_F48M_CLK`. + PllF48m, + /// Selects `RC_FAST_CLK`. + RcFast, + } + /// The list of clock signals that the `TIMG0_FUNCTION_CLOCK` multiplexer can output. + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum TimgFunctionClockConfig { + #[default] + /// Selects `XTAL_CLK`. + XtalClk, + /// Selects `RC_FAST_CLK`. + RcFastClk, + /// Selects `PLL_F48M_CLK`. + PllF48m, + } + /// The list of clock signals that the `TIMG0_WDT_CLOCK` multiplexer can output. + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum TimgWdtClockConfig { + #[default] + /// Selects `XTAL_CLK`. + XtalClk, + /// Selects `RC_FAST_CLK`. + RcFastClk, + /// Selects `PLL_F48M_CLK`. + PllF48m, + } + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum UartFunctionClockSclk { + #[default] + /// Selects `PLL_F48M_CLK`. + PllF48m, + /// Selects `RC_FAST_CLK`. + RcFast, + /// Selects `XTAL_CLK`. + Xtal, + } + /// Configures the `UART0_FUNCTION_CLOCK` clock node. + /// + /// The output is calculated as `OUTPUT = sclk / (div_num + 1)`. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub struct UartFunctionClockConfig { + sclk: UartFunctionClockSclk, + div_num: u32, + } + impl UartFunctionClockConfig { + /// Creates a new configuration for the FUNCTION_CLOCK clock node. + /// + /// ## Panics + /// + /// Panics if the div_num value is outside the + /// valid range (0 ..= 255). + pub const fn new(sclk: UartFunctionClockSclk, div_num: u32) -> Self { + ::core::assert!( + div_num <= 255, + "`UART0_FUNCTION_CLOCK` div_num must be between 0 and 255 (inclusive)." + ); + Self { sclk, div_num } + } + pub fn sclk(self) -> UartFunctionClockSclk { + self.sclk + } + pub fn div_num(self) -> u32 { + self.div_num as u32 + } + } + /// Configures the `UART0_BAUD_RATE_GENERATOR` clock node. + /// + /// The output is calculated as `OUTPUT = (FUNCTION_CLOCK * 16) / (integral * 16 + + /// fractional)`. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub struct UartBaudRateGeneratorConfig { + fractional: u32, + integral: u32, + } + impl UartBaudRateGeneratorConfig { + /// Creates a new configuration for the BAUD_RATE_GENERATOR clock node. + /// + /// ## Panics + /// + /// Panics if the fractional value is outside the + /// valid range (0 ..= 15). + /// + /// Panics if the integral value is outside the + /// valid range (0 ..= 4095). + pub const fn new(fractional: u32, integral: u32) -> Self { + ::core::assert!( + fractional <= 15, + "`UART0_BAUD_RATE_GENERATOR` fractional must be between 0 and 15 (inclusive)." + ); + ::core::assert!( + integral <= 4095, + "`UART0_BAUD_RATE_GENERATOR` integral must be between 0 and 4095 (inclusive)." + ); + Self { + fractional, + integral, + } + } + pub fn fractional(self) -> u32 { + self.fractional as u32 + } + pub fn integral(self) -> u32 { + self.integral as u32 + } + } + /// Represents the device's clock tree. + pub struct ClockTree { + iomux_function_clock: Option, + hp_root_clk: Option, + cpu_clk: Option, + ahb_clk: Option, + apb_clk: Option, + lp_fast_clk: Option, + lp_slow_clk: Option, + ble_lp_clk: Option, + timg_calibration_clock: Option, + i2s_tx_clk: [Option; 1], + i2s_rx_clk: [Option; 1], + i2s_mclk_out: [Option; 1], + i2c_function_clock: [Option; 2], + spi_function_clock: [Option; 2], + timg_function_clock: [Option; 2], + timg_wdt_clock: [Option; 2], + uart_function_clock: [Option; 2], + uart_baud_rate_generator: [Option; 2], + pll_f96m_clk_refcount: u32, + pll_f48m_clk_refcount: u32, + xtal_x2_clk_refcount: u32, + rc_fast_clk_refcount: u32, + #[cfg(use_xtal32k)] + xtal32k_clk_refcount: u32, + rc_slow_d4_clk_refcount: u32, + apb_clk_refcount: u32, + lp_fast_clk_refcount: u32, + lp_slow_clk_refcount: u32, + ble_lp_clk_refcount: u32, + timg_calibration_clock_refcount: u32, + i2s_tx_clk_refcount: [u32; 1], + i2s_rx_clk_refcount: [u32; 1], + i2s_mclk_out_refcount: [u32; 1], + i2c_function_clock_refcount: [u32; 2], + spi_function_clock_refcount: [u32; 2], + timg_function_clock_refcount: [u32; 2], + timg_wdt_clock_refcount: [u32; 2], + uart_function_clock_refcount: [u32; 2], + uart_baud_rate_generator_refcount: [u32; 2], + } + impl ClockTree { + /// Locks the clock tree for exclusive access. + pub fn with(f: impl FnOnce(&mut ClockTree) -> R) -> R { + CLOCK_TREE.with(f) + } + /// Returns the current configuration of the IOMUX_FUNCTION_CLOCK clock tree node + pub fn iomux_function_clock(&self) -> Option { + self.iomux_function_clock + } + /// Returns the current configuration of the HP_ROOT_CLK clock tree node + pub fn hp_root_clk(&self) -> Option { + self.hp_root_clk + } + /// Returns the current configuration of the CPU_CLK clock tree node + pub fn cpu_clk(&self) -> Option { + self.cpu_clk + } + /// Returns the current configuration of the AHB_CLK clock tree node + pub fn ahb_clk(&self) -> Option { + self.ahb_clk + } + /// Returns the current configuration of the APB_CLK clock tree node + pub fn apb_clk(&self) -> Option { + self.apb_clk + } + /// Returns the current configuration of the LP_FAST_CLK clock tree node + pub fn lp_fast_clk(&self) -> Option { + self.lp_fast_clk + } + /// Returns the current configuration of the LP_SLOW_CLK clock tree node + pub fn lp_slow_clk(&self) -> Option { + self.lp_slow_clk + } + /// Returns the current configuration of the BLE_LP_CLK clock tree node + pub fn ble_lp_clk(&self) -> Option { + self.ble_lp_clk + } + /// Returns the current configuration of the TIMG_CALIBRATION_CLOCK clock tree node + pub fn timg_calibration_clock(&self) -> Option { + self.timg_calibration_clock + } + /// Returns the current configuration of the I2S0_TX_CLK clock tree node + pub fn i2s0_tx_clk(&self) -> Option { + self.i2s_tx_clk[I2sInstance::I2s0 as usize] + } + /// Returns the current configuration of the I2S0_RX_CLK clock tree node + pub fn i2s0_rx_clk(&self) -> Option { + self.i2s_rx_clk[I2sInstance::I2s0 as usize] + } + /// Returns the current configuration of the I2S0_MCLK_OUT clock tree node + pub fn i2s0_mclk_out(&self) -> Option { + self.i2s_mclk_out[I2sInstance::I2s0 as usize] + } + /// Returns the current configuration of the I2C0_FUNCTION_CLOCK clock tree node + pub fn i2c0_function_clock(&self) -> Option { + self.i2c_function_clock[I2cInstance::I2c0 as usize] + } + /// Returns the current configuration of the I2C1_FUNCTION_CLOCK clock tree node + pub fn i2c1_function_clock(&self) -> Option { + self.i2c_function_clock[I2cInstance::I2c1 as usize] + } + /// Returns the current configuration of the SPI2_FUNCTION_CLOCK clock tree node + pub fn spi2_function_clock(&self) -> Option { + self.spi_function_clock[SpiInstance::Spi2 as usize] + } + /// Returns the current configuration of the SPI3_FUNCTION_CLOCK clock tree node + pub fn spi3_function_clock(&self) -> Option { + self.spi_function_clock[SpiInstance::Spi3 as usize] + } + /// Returns the current configuration of the TIMG0_FUNCTION_CLOCK clock tree node + pub fn timg0_function_clock(&self) -> Option { + self.timg_function_clock[TimgInstance::Timg0 as usize] + } + /// Returns the current configuration of the TIMG0_WDT_CLOCK clock tree node + pub fn timg0_wdt_clock(&self) -> Option { + self.timg_wdt_clock[TimgInstance::Timg0 as usize] + } + /// Returns the current configuration of the TIMG1_FUNCTION_CLOCK clock tree node + pub fn timg1_function_clock(&self) -> Option { + self.timg_function_clock[TimgInstance::Timg1 as usize] + } + /// Returns the current configuration of the TIMG1_WDT_CLOCK clock tree node + pub fn timg1_wdt_clock(&self) -> Option { + self.timg_wdt_clock[TimgInstance::Timg1 as usize] + } + /// Returns the current configuration of the UART0_FUNCTION_CLOCK clock tree node + pub fn uart0_function_clock(&self) -> Option { + self.uart_function_clock[UartInstance::Uart0 as usize] + } + /// Returns the current configuration of the UART0_BAUD_RATE_GENERATOR clock tree node + pub fn uart0_baud_rate_generator(&self) -> Option { + self.uart_baud_rate_generator[UartInstance::Uart0 as usize] + } + /// Returns the current configuration of the UART1_FUNCTION_CLOCK clock tree node + pub fn uart1_function_clock(&self) -> Option { + self.uart_function_clock[UartInstance::Uart1 as usize] + } + /// Returns the current configuration of the UART1_BAUD_RATE_GENERATOR clock tree node + pub fn uart1_baud_rate_generator(&self) -> Option { + self.uart_baud_rate_generator[UartInstance::Uart1 as usize] + } + } + static CLOCK_TREE: ::esp_sync::NonReentrantMutex = + ::esp_sync::NonReentrantMutex::new(ClockTree { + iomux_function_clock: None, + hp_root_clk: None, + cpu_clk: None, + ahb_clk: None, + apb_clk: None, + lp_fast_clk: None, + lp_slow_clk: None, + ble_lp_clk: None, + timg_calibration_clock: None, + i2s_tx_clk: [None; 1], + i2s_rx_clk: [None; 1], + i2s_mclk_out: [None; 1], + i2c_function_clock: [None; 2], + spi_function_clock: [None; 2], + timg_function_clock: [None; 2], + timg_wdt_clock: [None; 2], + uart_function_clock: [None; 2], + uart_baud_rate_generator: [None; 2], + pll_f96m_clk_refcount: 0, + pll_f48m_clk_refcount: 0, + xtal_x2_clk_refcount: 0, + rc_fast_clk_refcount: 0, + #[cfg(use_xtal32k)] + xtal32k_clk_refcount: 0, + rc_slow_d4_clk_refcount: 0, + apb_clk_refcount: 0, + lp_fast_clk_refcount: 0, + lp_slow_clk_refcount: 0, + ble_lp_clk_refcount: 0, + timg_calibration_clock_refcount: 0, + i2s_tx_clk_refcount: [0; 1], + i2s_rx_clk_refcount: [0; 1], + i2s_mclk_out_refcount: [0; 1], + i2c_function_clock_refcount: [0; 2], + spi_function_clock_refcount: [0; 2], + timg_function_clock_refcount: [0; 2], + timg_wdt_clock_refcount: [0; 2], + uart_function_clock_refcount: [0; 2], + uart_baud_rate_generator_refcount: [0; 2], + }); + static HP_ROOT_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(0); + static CPU_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(0); + static AHB_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(0); + static APB_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(0); + static LP_FAST_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(0); + static LP_SLOW_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(0); + static BLE_LP_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(0); + static TIMG_CALIBRATION_CLOCK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(0); + static I2S_TX_CLK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; + static I2S_RX_CLK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; + static I2S_MCLK_OUT_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; + static I2C_FUNCTION_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 2] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 2]; + static SPI_FUNCTION_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 2] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 2]; + static TIMG_FUNCTION_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 2] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 2]; + static TIMG_WDT_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 2] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 2]; + static UART_FUNCTION_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 2] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 2]; + static UART_BAUD_RATE_GENERATOR_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 2] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 2]; + static IOMUX_FUNCTION_CLOCK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(0); + /// The clock sources of the device. + /// + /// A clock source is a node of the clock tree that other nodes derive their output + /// from. Ask a node which source it runs on with its `..._root_source` function. + #[derive(Debug, enumset::EnumSetType)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum ClockSource { + /// `XTAL_CLK`. + XtalClk, + /// `RC_FAST_CLK`. + RcFastClk, + #[cfg(use_xtal32k)] + /// `XTAL32K_CLK`. + Xtal32kClk, + /// `OSC_SLOW_CLK`. + OscSlowClk, + /// `RC_SLOW_CLK`. + RcSlowClk, + } + /// Returns the clock source that `XTAL_CLK` currently runs on. + pub fn xtal_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::XtalClk) + } + /// Returns the clock source that `PLL_F96M_CLK` currently runs on. + pub fn pll_f96m_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `PLL_F48M_CLK` currently runs on. + pub fn pll_f48m_clk_root_source(clocks: &mut ClockTree) -> Option { + pll_f96m_clk_root_source(clocks) + } + /// Returns the clock source that `XTAL_X2_CLK` currently runs on. + pub fn xtal_x2_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `RC_FAST_CLK` currently runs on. + pub fn rc_fast_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::RcFastClk) + } + #[cfg(use_xtal32k)] + /// Returns the clock source that `XTAL32K_CLK` currently runs on. + pub fn xtal32k_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::Xtal32kClk) + } + /// Returns the clock source that `OSC_SLOW_CLK` currently runs on. + pub fn osc_slow_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::OscSlowClk) + } + /// Returns the clock source that `RC_SLOW_CLK` currently runs on. + pub fn rc_slow_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::RcSlowClk) + } + /// Returns the clock source that `RC_SLOW_D4_CLK` currently runs on. + pub fn rc_slow_d4_clk_root_source(clocks: &mut ClockTree) -> Option { + rc_slow_clk_root_source(clocks) + } + /// Returns the clock source that `HP_ROOT_CLK` currently runs on. + pub fn hp_root_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.hp_root_clk?; + match config { + HpRootClkConfig::Xtal => xtal_clk_root_source(clocks), + HpRootClkConfig::RcFast => rc_fast_clk_root_source(clocks), + HpRootClkConfig::XtalX2 => xtal_x2_clk_root_source(clocks), + HpRootClkConfig::Pll => pll_f96m_clk_root_source(clocks), + } + } + /// Returns the clock source that `CPU_CLK` currently runs on. + pub fn cpu_clk_root_source(clocks: &mut ClockTree) -> Option { + hp_root_clk_root_source(clocks) + } + /// Returns the clock source that `AHB_CLK` currently runs on. + pub fn ahb_clk_root_source(clocks: &mut ClockTree) -> Option { + cpu_clk_root_source(clocks) + } + /// Returns the clock source that `APB_CLK` currently runs on. + pub fn apb_clk_root_source(clocks: &mut ClockTree) -> Option { + ahb_clk_root_source(clocks) + } + /// Returns the clock source that `XTAL_D2_CLK` currently runs on. + pub fn xtal_d2_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `LP_FAST_CLK` currently runs on. + pub fn lp_fast_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.lp_fast_clk?; + match config { + LpFastClkConfig::RcFastClk => rc_fast_clk_root_source(clocks), + LpFastClkConfig::XtalD2Clk => xtal_d2_clk_root_source(clocks), + } + } + /// Returns the clock source that `LP_SLOW_CLK` currently runs on. + pub fn lp_slow_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.lp_slow_clk?; + match config { + #[cfg(use_xtal32k)] + LpSlowClkConfig::Xtal32k => xtal32k_clk_root_source(clocks), + LpSlowClkConfig::RcSlow => rc_slow_d4_clk_root_source(clocks), + LpSlowClkConfig::OscSlow => osc_slow_clk_root_source(clocks), + } + } + /// Returns the clock source that `BLE_LP_XTAL_CLK` currently runs on. + pub fn ble_lp_xtal_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `BLE_LP_CLK` currently runs on. + pub fn ble_lp_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.ble_lp_clk?; + match config { + BleLpClkConfig::Xtal => ble_lp_xtal_clk_root_source(clocks), + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => xtal32k_clk_root_source(clocks), + } + } + /// Returns the clock source that `TIMG_CALIBRATION_CLOCK` currently runs on. + pub fn timg_calibration_clock_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.timg_calibration_clock?; + match config { + TimgCalibrationClockConfig::RcSlowClk => rc_slow_d4_clk_root_source(clocks), + TimgCalibrationClockConfig::RcFastDivClk => rc_fast_clk_root_source(clocks), + #[cfg(use_xtal32k)] + TimgCalibrationClockConfig::Xtal32kClk => xtal32k_clk_root_source(clocks), + } + } + /// Returns the clock source that `IOMUX_FUNCTION_CLOCK` currently runs on. + pub fn iomux_function_clock_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.iomux_function_clock?; + match config { + IomuxFunctionClockConfig::XtalClk => xtal_clk_root_source(clocks), + IomuxFunctionClockConfig::RcFastClk => rc_fast_clk_root_source(clocks), + IomuxFunctionClockConfig::PllF48m => pll_f48m_clk_root_source(clocks), + } + } + fn request_xtal_clk(_clocks: &mut ClockTree) {} + fn release_xtal_clk(_clocks: &mut ClockTree) {} + pub fn xtal_clk_frequency() -> u32 { + (32 * 1000000) + } + pub fn request_pll_f96m_clk(clocks: &mut ClockTree) { + trace!("Requesting PLL_F96M_CLK"); + if increment_reference_count(&mut clocks.pll_f96m_clk_refcount) { + trace!("Enabling PLL_F96M_CLK"); + request_xtal_clk(clocks); + enable_pll_f96m_clk_impl(clocks, true); + } + } + pub fn release_pll_f96m_clk(clocks: &mut ClockTree) { + trace!("Releasing PLL_F96M_CLK"); + if decrement_reference_count(&mut clocks.pll_f96m_clk_refcount) { + trace!("Disabling PLL_F96M_CLK"); + enable_pll_f96m_clk_impl(clocks, false); + release_xtal_clk(clocks); + } + } + pub fn pll_f96m_clk_frequency() -> u32 { + 96000000 + } + pub fn pll_f96m_clk_source_frequency() -> u32 { + xtal_clk_frequency() + } + pub fn request_pll_f48m_clk(clocks: &mut ClockTree) { + trace!("Requesting PLL_F48M_CLK"); + if increment_reference_count(&mut clocks.pll_f48m_clk_refcount) { + trace!("Enabling PLL_F48M_CLK"); + request_pll_f96m_clk(clocks); + enable_pll_f48m_clk_impl(clocks, true); + } + } + pub fn release_pll_f48m_clk(clocks: &mut ClockTree) { + trace!("Releasing PLL_F48M_CLK"); + if decrement_reference_count(&mut clocks.pll_f48m_clk_refcount) { + trace!("Disabling PLL_F48M_CLK"); + enable_pll_f48m_clk_impl(clocks, false); + release_pll_f96m_clk(clocks); + } + } + pub fn pll_f48m_clk_frequency() -> u32 { + (pll_f96m_clk_frequency() / 2) + } + pub fn pll_f48m_clk_source_frequency() -> u32 { + pll_f96m_clk_frequency() + } + pub fn configure_iomux_function_clock( + clocks: &mut ClockTree, + new_selector: IomuxFunctionClockConfig, + ) { + let old_selector = clocks.iomux_function_clock.replace(new_selector); + refresh_iomux_function_clock_downstream(clocks); + match new_selector { + IomuxFunctionClockConfig::XtalClk => request_xtal_clk(clocks), + IomuxFunctionClockConfig::RcFastClk => request_rc_fast_clk(clocks), + IomuxFunctionClockConfig::PllF48m => request_pll_f48m_clk(clocks), + } + configure_iomux_function_clock_impl(clocks, old_selector, new_selector); + if let Some(old_selector) = old_selector { + match old_selector { + IomuxFunctionClockConfig::XtalClk => release_xtal_clk(clocks), + IomuxFunctionClockConfig::RcFastClk => release_rc_fast_clk(clocks), + IomuxFunctionClockConfig::PllF48m => release_pll_f48m_clk(clocks), + } + } + } + pub fn iomux_function_clock_config( + clocks: &mut ClockTree, + ) -> Option { + clocks.iomux_function_clock + } + fn request_iomux_function_clock(_clocks: &mut ClockTree) {} + fn release_iomux_function_clock(_clocks: &mut ClockTree) {} + pub fn iomux_function_clock_config_frequency(config: IomuxFunctionClockConfig) -> u32 { + match config { + IomuxFunctionClockConfig::XtalClk => xtal_clk_frequency(), + IomuxFunctionClockConfig::RcFastClk => rc_fast_clk_frequency(), + IomuxFunctionClockConfig::PllF48m => pll_f48m_clk_frequency(), + } + } + pub fn iomux_function_clock_frequency() -> u32 { + IOMUX_FUNCTION_CLOCK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn iomux_function_clock_source_frequency(source: IomuxFunctionClockConfig) -> u32 { + iomux_function_clock_config_frequency(source) + } + pub fn request_xtal_x2_clk(clocks: &mut ClockTree) { + trace!("Requesting XTAL_X2_CLK"); + if increment_reference_count(&mut clocks.xtal_x2_clk_refcount) { + trace!("Enabling XTAL_X2_CLK"); + request_xtal_clk(clocks); + enable_xtal_x2_clk_impl(clocks, true); + } + } + pub fn release_xtal_x2_clk(clocks: &mut ClockTree) { + trace!("Releasing XTAL_X2_CLK"); + if decrement_reference_count(&mut clocks.xtal_x2_clk_refcount) { + trace!("Disabling XTAL_X2_CLK"); + enable_xtal_x2_clk_impl(clocks, false); + release_xtal_clk(clocks); + } + } + pub fn xtal_x2_clk_frequency() -> u32 { + 64000000 + } + pub fn xtal_x2_clk_source_frequency() -> u32 { + xtal_clk_frequency() + } + pub fn request_rc_fast_clk(clocks: &mut ClockTree) { + trace!("Requesting RC_FAST_CLK"); + if increment_reference_count(&mut clocks.rc_fast_clk_refcount) { + trace!("Enabling RC_FAST_CLK"); + enable_rc_fast_clk_impl(clocks, true); + } + } + pub fn release_rc_fast_clk(clocks: &mut ClockTree) { + trace!("Releasing RC_FAST_CLK"); + if decrement_reference_count(&mut clocks.rc_fast_clk_refcount) { + trace!("Disabling RC_FAST_CLK"); + enable_rc_fast_clk_impl(clocks, false); + } + } + static RC_FAST_CLK_FREQUENCY: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(rc_fast_clk_nominal_frequency()); + pub const fn rc_fast_clk_nominal_frequency() -> u32 { + 20000000 + } + pub fn rc_fast_clk_frequency() -> u32 { + RC_FAST_CLK_FREQUENCY.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn set_rc_fast_clk_frequency(clocks: &mut ClockTree, frequency: u32) { + if !(10000000..=30000000).contains(&frequency) { + warn!( + "Ignoring out-of-range RC_FAST_CLK frequency: {} Hz", + frequency + ); + return; + } + debug!( + "Updating RC_FAST_CLK frequency to {} Hz (nominal {} Hz)", + frequency, + rc_fast_clk_nominal_frequency() + ); + RC_FAST_CLK_FREQUENCY.store(frequency, ::core::sync::atomic::Ordering::Release); + refresh_rc_fast_clk_downstream(clocks); + } + #[cfg(use_xtal32k)] + pub fn request_xtal32k_clk(clocks: &mut ClockTree) { + trace!("Requesting XTAL32K_CLK"); + if increment_reference_count(&mut clocks.xtal32k_clk_refcount) { + trace!("Enabling XTAL32K_CLK"); + enable_xtal32k_clk_impl(clocks, true); + } + } + #[cfg(use_xtal32k)] + pub fn release_xtal32k_clk(clocks: &mut ClockTree) { + trace!("Releasing XTAL32K_CLK"); + if decrement_reference_count(&mut clocks.xtal32k_clk_refcount) { + trace!("Disabling XTAL32K_CLK"); + enable_xtal32k_clk_impl(clocks, false); + } + } + #[cfg(use_xtal32k)] + pub fn xtal32k_clk_frequency() -> u32 { + 32768 + } + pub fn request_osc_slow_clk(clocks: &mut ClockTree) { + trace!("Enabling OSC_SLOW_CLK"); + enable_osc_slow_clk_impl(clocks, true); + } + pub fn release_osc_slow_clk(clocks: &mut ClockTree) { + trace!("Disabling OSC_SLOW_CLK"); + enable_osc_slow_clk_impl(clocks, false); + } + pub fn osc_slow_clk_frequency() -> u32 { + 32768 + } + pub fn request_rc_slow_clk(clocks: &mut ClockTree) { + trace!("Enabling RC_SLOW_CLK"); + enable_rc_slow_clk_impl(clocks, true); + } + pub fn release_rc_slow_clk(clocks: &mut ClockTree) { + trace!("Disabling RC_SLOW_CLK"); + enable_rc_slow_clk_impl(clocks, false); + } + static RC_SLOW_CLK_FREQUENCY: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(rc_slow_clk_nominal_frequency()); + pub const fn rc_slow_clk_nominal_frequency() -> u32 { + 600000 + } + pub fn rc_slow_clk_frequency() -> u32 { + RC_SLOW_CLK_FREQUENCY.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn set_rc_slow_clk_frequency(clocks: &mut ClockTree, frequency: u32) { + if !(300000..=900000).contains(&frequency) { + warn!( + "Ignoring out-of-range RC_SLOW_CLK frequency: {} Hz", + frequency + ); + return; + } + debug!( + "Updating RC_SLOW_CLK frequency to {} Hz (nominal {} Hz)", + frequency, + rc_slow_clk_nominal_frequency() + ); + RC_SLOW_CLK_FREQUENCY.store(frequency, ::core::sync::atomic::Ordering::Release); + refresh_rc_slow_clk_downstream(clocks); + } + pub fn request_rc_slow_d4_clk(clocks: &mut ClockTree) { + trace!("Requesting RC_SLOW_D4_CLK"); + if increment_reference_count(&mut clocks.rc_slow_d4_clk_refcount) { + trace!("Enabling RC_SLOW_D4_CLK"); + request_rc_slow_clk(clocks); + enable_rc_slow_d4_clk_impl(clocks, true); + } + } + pub fn release_rc_slow_d4_clk(clocks: &mut ClockTree) { + trace!("Releasing RC_SLOW_D4_CLK"); + if decrement_reference_count(&mut clocks.rc_slow_d4_clk_refcount) { + trace!("Disabling RC_SLOW_D4_CLK"); + enable_rc_slow_d4_clk_impl(clocks, false); + release_rc_slow_clk(clocks); + } + } + pub fn rc_slow_d4_clk_frequency() -> u32 { + (rc_slow_clk_frequency() / 4) + } + pub fn rc_slow_d4_clk_source_frequency() -> u32 { + rc_slow_clk_frequency() + } + pub fn configure_hp_root_clk(clocks: &mut ClockTree, new_selector: HpRootClkConfig) { + let old_selector = clocks.hp_root_clk.replace(new_selector); + refresh_hp_root_clk_downstream(clocks); + match new_selector { + HpRootClkConfig::Xtal => request_xtal_clk(clocks), + HpRootClkConfig::RcFast => request_rc_fast_clk(clocks), + HpRootClkConfig::XtalX2 => request_xtal_x2_clk(clocks), + HpRootClkConfig::Pll => request_pll_f96m_clk(clocks), + } + configure_hp_root_clk_impl(clocks, old_selector, new_selector); + if let Some(old_selector) = old_selector { + match old_selector { + HpRootClkConfig::Xtal => release_xtal_clk(clocks), + HpRootClkConfig::RcFast => release_rc_fast_clk(clocks), + HpRootClkConfig::XtalX2 => release_xtal_x2_clk(clocks), + HpRootClkConfig::Pll => release_pll_f96m_clk(clocks), + } + } + } + pub fn hp_root_clk_config(clocks: &mut ClockTree) -> Option { + clocks.hp_root_clk + } + pub fn request_hp_root_clk(clocks: &mut ClockTree) { + trace!("Enabling HP_ROOT_CLK"); + match unwrap!(clocks.hp_root_clk) { + HpRootClkConfig::Xtal => request_xtal_clk(clocks), + HpRootClkConfig::RcFast => request_rc_fast_clk(clocks), + HpRootClkConfig::XtalX2 => request_xtal_x2_clk(clocks), + HpRootClkConfig::Pll => request_pll_f96m_clk(clocks), + } + enable_hp_root_clk_impl(clocks, true); + } + pub fn release_hp_root_clk(clocks: &mut ClockTree) { + trace!("Disabling HP_ROOT_CLK"); + enable_hp_root_clk_impl(clocks, false); + match unwrap!(clocks.hp_root_clk) { + HpRootClkConfig::Xtal => release_xtal_clk(clocks), + HpRootClkConfig::RcFast => release_rc_fast_clk(clocks), + HpRootClkConfig::XtalX2 => release_xtal_x2_clk(clocks), + HpRootClkConfig::Pll => release_pll_f96m_clk(clocks), + } + } + pub fn hp_root_clk_config_frequency(config: HpRootClkConfig) -> u32 { + match config { + HpRootClkConfig::Xtal => xtal_clk_frequency(), + HpRootClkConfig::RcFast => rc_fast_clk_frequency(), + HpRootClkConfig::XtalX2 => xtal_x2_clk_frequency(), + HpRootClkConfig::Pll => pll_f96m_clk_frequency(), + } + } + pub fn hp_root_clk_frequency() -> u32 { + HP_ROOT_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn hp_root_clk_source_frequency(source: HpRootClkConfig) -> u32 { + hp_root_clk_config_frequency(source) + } + pub fn configure_cpu_clk(clocks: &mut ClockTree, config: CpuClkConfig) { + let old_config = clocks.cpu_clk.replace(config); + refresh_cpu_clk_downstream(clocks); + configure_cpu_clk_impl(clocks, old_config, config); + } + pub fn cpu_clk_config(clocks: &mut ClockTree) -> Option { + clocks.cpu_clk + } + fn request_cpu_clk(_clocks: &mut ClockTree) {} + fn release_cpu_clk(_clocks: &mut ClockTree) {} + pub fn cpu_clk_config_frequency(config: CpuClkConfig) -> u32 { + (hp_root_clk_frequency() / (config.divisor() + 1)) + } + pub fn cpu_clk_frequency() -> u32 { + CPU_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn cpu_clk_source_frequency() -> u32 { + hp_root_clk_frequency() + } + pub fn configure_ahb_clk(clocks: &mut ClockTree, config: AhbClkConfig) { + let old_config = clocks.ahb_clk.replace(config); + refresh_ahb_clk_downstream(clocks); + configure_ahb_clk_impl(clocks, old_config, config); + } + pub fn ahb_clk_config(clocks: &mut ClockTree) -> Option { + clocks.ahb_clk + } + fn request_ahb_clk(_clocks: &mut ClockTree) {} + fn release_ahb_clk(_clocks: &mut ClockTree) {} + pub fn ahb_clk_config_frequency(config: AhbClkConfig) -> u32 { + (cpu_clk_frequency() / (config.divisor() + 1)) + } + pub fn ahb_clk_frequency() -> u32 { + AHB_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn ahb_clk_source_frequency() -> u32 { + cpu_clk_frequency() + } + pub fn configure_apb_clk(clocks: &mut ClockTree, config: ApbClkConfig) { + let old_config = clocks.apb_clk.replace(config); + refresh_apb_clk_downstream(clocks); + configure_apb_clk_impl(clocks, old_config, config); + } + pub fn apb_clk_config(clocks: &mut ClockTree) -> Option { + clocks.apb_clk + } + pub fn request_apb_clk(clocks: &mut ClockTree) { + trace!("Requesting APB_CLK"); + if increment_reference_count(&mut clocks.apb_clk_refcount) { + trace!("Enabling APB_CLK"); + request_ahb_clk(clocks); + enable_apb_clk_impl(clocks, true); + } + } + pub fn release_apb_clk(clocks: &mut ClockTree) { + trace!("Releasing APB_CLK"); + if decrement_reference_count(&mut clocks.apb_clk_refcount) { + trace!("Disabling APB_CLK"); + enable_apb_clk_impl(clocks, false); + release_ahb_clk(clocks); + } + } + pub fn apb_clk_config_frequency(config: ApbClkConfig) -> u32 { + (ahb_clk_frequency() / (config.divisor() + 1)) + } + pub fn apb_clk_frequency() -> u32 { + APB_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn apb_clk_source_frequency() -> u32 { + ahb_clk_frequency() + } + pub fn request_xtal_d2_clk(clocks: &mut ClockTree) { + trace!("Enabling XTAL_D2_CLK"); + request_xtal_clk(clocks); + enable_xtal_d2_clk_impl(clocks, true); + } + pub fn release_xtal_d2_clk(clocks: &mut ClockTree) { + trace!("Disabling XTAL_D2_CLK"); + enable_xtal_d2_clk_impl(clocks, false); + release_xtal_clk(clocks); + } + pub fn xtal_d2_clk_frequency() -> u32 { + (xtal_clk_frequency() / 2) + } + pub fn xtal_d2_clk_source_frequency() -> u32 { + xtal_clk_frequency() + } + pub fn configure_lp_fast_clk(clocks: &mut ClockTree, new_selector: LpFastClkConfig) { + let old_selector = clocks.lp_fast_clk.replace(new_selector); + refresh_lp_fast_clk_downstream(clocks); + let active = clocks.lp_fast_clk_refcount > 0; + if active { + match new_selector { + LpFastClkConfig::RcFastClk => request_rc_fast_clk(clocks), + LpFastClkConfig::XtalD2Clk => request_xtal_d2_clk(clocks), + } + } + configure_lp_fast_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + LpFastClkConfig::RcFastClk => release_rc_fast_clk(clocks), + LpFastClkConfig::XtalD2Clk => release_xtal_d2_clk(clocks), + } + } + } + pub fn lp_fast_clk_config(clocks: &mut ClockTree) -> Option { + clocks.lp_fast_clk + } + pub fn request_lp_fast_clk(clocks: &mut ClockTree) { + trace!("Requesting LP_FAST_CLK"); + if increment_reference_count(&mut clocks.lp_fast_clk_refcount) { + trace!("Enabling LP_FAST_CLK"); + match unwrap!(clocks.lp_fast_clk) { + LpFastClkConfig::RcFastClk => request_rc_fast_clk(clocks), + LpFastClkConfig::XtalD2Clk => request_xtal_d2_clk(clocks), + } + enable_lp_fast_clk_impl(clocks, true); + } + } + pub fn release_lp_fast_clk(clocks: &mut ClockTree) { + trace!("Releasing LP_FAST_CLK"); + if decrement_reference_count(&mut clocks.lp_fast_clk_refcount) { + trace!("Disabling LP_FAST_CLK"); + enable_lp_fast_clk_impl(clocks, false); + match unwrap!(clocks.lp_fast_clk) { + LpFastClkConfig::RcFastClk => release_rc_fast_clk(clocks), + LpFastClkConfig::XtalD2Clk => release_xtal_d2_clk(clocks), + } + } + } + pub fn lp_fast_clk_config_frequency(config: LpFastClkConfig) -> u32 { + match config { + LpFastClkConfig::RcFastClk => rc_fast_clk_frequency(), + LpFastClkConfig::XtalD2Clk => xtal_d2_clk_frequency(), + } + } + pub fn lp_fast_clk_frequency() -> u32 { + LP_FAST_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn lp_fast_clk_source_frequency(source: LpFastClkConfig) -> u32 { + lp_fast_clk_config_frequency(source) + } + pub fn configure_lp_slow_clk(clocks: &mut ClockTree, new_selector: LpSlowClkConfig) { + let old_selector = clocks.lp_slow_clk.replace(new_selector); + refresh_lp_slow_clk_downstream(clocks); + let active = clocks.lp_slow_clk_refcount > 0; + if active { + match new_selector { + #[cfg(use_xtal32k)] + LpSlowClkConfig::Xtal32k => request_xtal32k_clk(clocks), + LpSlowClkConfig::RcSlow => request_rc_slow_d4_clk(clocks), + LpSlowClkConfig::OscSlow => request_osc_slow_clk(clocks), + } + } + configure_lp_slow_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + #[cfg(use_xtal32k)] + LpSlowClkConfig::Xtal32k => release_xtal32k_clk(clocks), + LpSlowClkConfig::RcSlow => release_rc_slow_d4_clk(clocks), + LpSlowClkConfig::OscSlow => release_osc_slow_clk(clocks), + } + } + } + pub fn lp_slow_clk_config(clocks: &mut ClockTree) -> Option { + clocks.lp_slow_clk + } + pub fn request_lp_slow_clk(clocks: &mut ClockTree) { + trace!("Requesting LP_SLOW_CLK"); + if increment_reference_count(&mut clocks.lp_slow_clk_refcount) { + trace!("Enabling LP_SLOW_CLK"); + match unwrap!(clocks.lp_slow_clk) { + #[cfg(use_xtal32k)] + LpSlowClkConfig::Xtal32k => request_xtal32k_clk(clocks), + LpSlowClkConfig::RcSlow => request_rc_slow_d4_clk(clocks), + LpSlowClkConfig::OscSlow => request_osc_slow_clk(clocks), + } + enable_lp_slow_clk_impl(clocks, true); + } + } + pub fn release_lp_slow_clk(clocks: &mut ClockTree) { + trace!("Releasing LP_SLOW_CLK"); + if decrement_reference_count(&mut clocks.lp_slow_clk_refcount) { + trace!("Disabling LP_SLOW_CLK"); + enable_lp_slow_clk_impl(clocks, false); + match unwrap!(clocks.lp_slow_clk) { + #[cfg(use_xtal32k)] + LpSlowClkConfig::Xtal32k => release_xtal32k_clk(clocks), + LpSlowClkConfig::RcSlow => release_rc_slow_d4_clk(clocks), + LpSlowClkConfig::OscSlow => release_osc_slow_clk(clocks), + } + } + } + pub fn lp_slow_clk_config_frequency(config: LpSlowClkConfig) -> u32 { + match config { + #[cfg(use_xtal32k)] + LpSlowClkConfig::Xtal32k => xtal32k_clk_frequency(), + LpSlowClkConfig::RcSlow => rc_slow_d4_clk_frequency(), + LpSlowClkConfig::OscSlow => osc_slow_clk_frequency(), + } + } + pub fn lp_slow_clk_frequency() -> u32 { + LP_SLOW_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn lp_slow_clk_source_frequency(source: LpSlowClkConfig) -> u32 { + lp_slow_clk_config_frequency(source) + } + pub fn request_ble_lp_xtal_clk(clocks: &mut ClockTree) { + trace!("Enabling BLE_LP_XTAL_CLK"); + request_xtal_clk(clocks); + enable_ble_lp_xtal_clk_impl(clocks, true); + } + pub fn release_ble_lp_xtal_clk(clocks: &mut ClockTree) { + trace!("Disabling BLE_LP_XTAL_CLK"); + enable_ble_lp_xtal_clk_impl(clocks, false); + release_xtal_clk(clocks); + } + pub fn ble_lp_xtal_clk_frequency() -> u32 { + 100000 + } + pub fn ble_lp_xtal_clk_source_frequency() -> u32 { + xtal_clk_frequency() + } + pub fn configure_ble_lp_clk(clocks: &mut ClockTree, new_selector: BleLpClkConfig) { + let old_selector = clocks.ble_lp_clk.replace(new_selector); + refresh_ble_lp_clk_downstream(clocks); + let active = clocks.ble_lp_clk_refcount > 0; + if active { + match new_selector { + BleLpClkConfig::Xtal => request_ble_lp_xtal_clk(clocks), + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => request_xtal32k_clk(clocks), + } + } + configure_ble_lp_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + BleLpClkConfig::Xtal => release_ble_lp_xtal_clk(clocks), + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => release_xtal32k_clk(clocks), + } + } + } + pub fn ble_lp_clk_config(clocks: &mut ClockTree) -> Option { + clocks.ble_lp_clk + } + pub fn request_ble_lp_clk(clocks: &mut ClockTree) { + trace!("Requesting BLE_LP_CLK"); + if increment_reference_count(&mut clocks.ble_lp_clk_refcount) { + trace!("Enabling BLE_LP_CLK"); + match unwrap!(clocks.ble_lp_clk) { + BleLpClkConfig::Xtal => request_ble_lp_xtal_clk(clocks), + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => request_xtal32k_clk(clocks), + } + enable_ble_lp_clk_impl(clocks, true); + } + } + pub fn release_ble_lp_clk(clocks: &mut ClockTree) { + trace!("Releasing BLE_LP_CLK"); + if decrement_reference_count(&mut clocks.ble_lp_clk_refcount) { + trace!("Disabling BLE_LP_CLK"); + enable_ble_lp_clk_impl(clocks, false); + match unwrap!(clocks.ble_lp_clk) { + BleLpClkConfig::Xtal => release_ble_lp_xtal_clk(clocks), + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => release_xtal32k_clk(clocks), + } + } + } + pub fn ble_lp_clk_config_frequency(config: BleLpClkConfig) -> u32 { + match config { + BleLpClkConfig::Xtal => ble_lp_xtal_clk_frequency(), + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => xtal32k_clk_frequency(), + } + } + pub fn ble_lp_clk_frequency() -> u32 { + BLE_LP_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn ble_lp_clk_source_frequency(source: BleLpClkConfig) -> u32 { + ble_lp_clk_config_frequency(source) + } + pub fn configure_timg_calibration_clock( + clocks: &mut ClockTree, + new_selector: TimgCalibrationClockConfig, + ) { + let old_selector = clocks.timg_calibration_clock.replace(new_selector); + refresh_timg_calibration_clock_downstream(clocks); + let active = clocks.timg_calibration_clock_refcount > 0; + if active { + match new_selector { + TimgCalibrationClockConfig::RcSlowClk => request_rc_slow_d4_clk(clocks), + TimgCalibrationClockConfig::RcFastDivClk => request_rc_fast_clk(clocks), + #[cfg(use_xtal32k)] + TimgCalibrationClockConfig::Xtal32kClk => request_xtal32k_clk(clocks), + } + } + configure_timg_calibration_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + TimgCalibrationClockConfig::RcSlowClk => release_rc_slow_d4_clk(clocks), + TimgCalibrationClockConfig::RcFastDivClk => release_rc_fast_clk(clocks), + #[cfg(use_xtal32k)] + TimgCalibrationClockConfig::Xtal32kClk => release_xtal32k_clk(clocks), + } + } + } + pub fn timg_calibration_clock_config( + clocks: &mut ClockTree, + ) -> Option { + clocks.timg_calibration_clock + } + pub fn request_timg_calibration_clock(clocks: &mut ClockTree) { + trace!("Requesting TIMG_CALIBRATION_CLOCK"); + if increment_reference_count(&mut clocks.timg_calibration_clock_refcount) { + trace!("Enabling TIMG_CALIBRATION_CLOCK"); + crate::rtc_cntl::WakeLock::acquire(); + match unwrap!(clocks.timg_calibration_clock) { + TimgCalibrationClockConfig::RcSlowClk => request_rc_slow_d4_clk(clocks), + TimgCalibrationClockConfig::RcFastDivClk => request_rc_fast_clk(clocks), + #[cfg(use_xtal32k)] + TimgCalibrationClockConfig::Xtal32kClk => request_xtal32k_clk(clocks), + } + enable_timg_calibration_clock_impl(clocks, true); + } + } + pub fn release_timg_calibration_clock(clocks: &mut ClockTree) { + trace!("Releasing TIMG_CALIBRATION_CLOCK"); + if decrement_reference_count(&mut clocks.timg_calibration_clock_refcount) { + trace!("Disabling TIMG_CALIBRATION_CLOCK"); + crate::rtc_cntl::WakeLock::release(); + enable_timg_calibration_clock_impl(clocks, false); + match unwrap!(clocks.timg_calibration_clock) { + TimgCalibrationClockConfig::RcSlowClk => release_rc_slow_d4_clk(clocks), + TimgCalibrationClockConfig::RcFastDivClk => release_rc_fast_clk(clocks), + #[cfg(use_xtal32k)] + TimgCalibrationClockConfig::Xtal32kClk => release_xtal32k_clk(clocks), + } + } + } + pub fn timg_calibration_clock_config_frequency(config: TimgCalibrationClockConfig) -> u32 { + match config { + TimgCalibrationClockConfig::RcSlowClk => rc_slow_d4_clk_frequency(), + TimgCalibrationClockConfig::RcFastDivClk => rc_fast_clk_frequency(), + #[cfg(use_xtal32k)] + TimgCalibrationClockConfig::Xtal32kClk => xtal32k_clk_frequency(), + } + } + pub fn timg_calibration_clock_frequency() -> u32 { + TIMG_CALIBRATION_CLOCK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn timg_calibration_clock_source_frequency(source: TimgCalibrationClockConfig) -> u32 { + timg_calibration_clock_config_frequency(source) + } + impl I2sInstance { + pub fn configure_tx_clk(self, clocks: &mut ClockTree, config: I2sClkConfig) { + let old_config = clocks.i2s_tx_clk[self as usize].replace(config); + refresh_i2s_tx_clk_downstream(clocks, self); + let active = clocks.i2s_tx_clk_refcount[self as usize] > 0; + if active { + match config.sclk { + I2sClkSclk::Xtal => request_xtal_clk(clocks), + I2sClkSclk::PllF96m => request_pll_f96m_clk(clocks), + I2sClkSclk::XtalX2 => request_xtal_x2_clk(clocks), + } + } + self.configure_tx_clk_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + I2sClkSclk::Xtal => release_xtal_clk(clocks), + I2sClkSclk::PllF96m => release_pll_f96m_clk(clocks), + I2sClkSclk::XtalX2 => release_xtal_x2_clk(clocks), + } + } + } + pub fn tx_clk_config(self, clocks: &mut ClockTree) -> Option { + clocks.i2s_tx_clk[self as usize] + } + pub fn request_tx_clk(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::TX_CLK", self); + if increment_reference_count(&mut clocks.i2s_tx_clk_refcount[self as usize]) { + trace!("Enabling {:?}::TX_CLK", self); + crate::rtc_cntl::WakeLock::acquire(); + match unwrap!(clocks.i2s_tx_clk[self as usize]).sclk { + I2sClkSclk::Xtal => request_xtal_clk(clocks), + I2sClkSclk::PllF96m => request_pll_f96m_clk(clocks), + I2sClkSclk::XtalX2 => request_xtal_x2_clk(clocks), + } + self.enable_tx_clk_impl(clocks, true); + } + } + pub fn release_tx_clk(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::TX_CLK", self); + if decrement_reference_count(&mut clocks.i2s_tx_clk_refcount[self as usize]) { + trace!("Disabling {:?}::TX_CLK", self); + crate::rtc_cntl::WakeLock::release(); + self.enable_tx_clk_impl(clocks, false); + match unwrap!(clocks.i2s_tx_clk[self as usize]).sclk { + I2sClkSclk::Xtal => release_xtal_clk(clocks), + I2sClkSclk::PllF96m => release_pll_f96m_clk(clocks), + I2sClkSclk::XtalX2 => release_xtal_x2_clk(clocks), + } + } + } + pub fn tx_clk_config_frequency(config: I2sClkConfig) -> u32 { + (((match config.sclk { + I2sClkSclk::Xtal => xtal_clk_frequency(), + I2sClkSclk::PllF96m => pll_f96m_clk_frequency(), + I2sClkSclk::XtalX2 => xtal_x2_clk_frequency(), + } as u64) + * (config.div_a() as u64)) + / (((config.div_num() * config.div_a()) + config.div_b()) as u64)) + as u32 + } + pub fn tx_clk_frequency(self) -> u32 { + I2S_TX_CLK_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) + } + pub fn tx_clk_source_frequency(sclk: I2sClkSclk) -> u32 { + match sclk { + I2sClkSclk::Xtal => xtal_clk_frequency(), + I2sClkSclk::PllF96m => pll_f96m_clk_frequency(), + I2sClkSclk::XtalX2 => xtal_x2_clk_frequency(), + } + } + pub fn configure_rx_clk(self, clocks: &mut ClockTree, config: I2sClkConfig) { + let old_config = clocks.i2s_rx_clk[self as usize].replace(config); + refresh_i2s_rx_clk_downstream(clocks, self); + let active = clocks.i2s_rx_clk_refcount[self as usize] > 0; + if active { + match config.sclk { + I2sClkSclk::Xtal => request_xtal_clk(clocks), + I2sClkSclk::PllF96m => request_pll_f96m_clk(clocks), + I2sClkSclk::XtalX2 => request_xtal_x2_clk(clocks), + } + } + self.configure_rx_clk_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + I2sClkSclk::Xtal => release_xtal_clk(clocks), + I2sClkSclk::PllF96m => release_pll_f96m_clk(clocks), + I2sClkSclk::XtalX2 => release_xtal_x2_clk(clocks), + } + } + } + pub fn rx_clk_config(self, clocks: &mut ClockTree) -> Option { + clocks.i2s_rx_clk[self as usize] + } + pub fn request_rx_clk(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::RX_CLK", self); + if increment_reference_count(&mut clocks.i2s_rx_clk_refcount[self as usize]) { + trace!("Enabling {:?}::RX_CLK", self); + crate::rtc_cntl::WakeLock::acquire(); + match unwrap!(clocks.i2s_rx_clk[self as usize]).sclk { + I2sClkSclk::Xtal => request_xtal_clk(clocks), + I2sClkSclk::PllF96m => request_pll_f96m_clk(clocks), + I2sClkSclk::XtalX2 => request_xtal_x2_clk(clocks), + } + self.enable_rx_clk_impl(clocks, true); + } + } + pub fn release_rx_clk(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::RX_CLK", self); + if decrement_reference_count(&mut clocks.i2s_rx_clk_refcount[self as usize]) { + trace!("Disabling {:?}::RX_CLK", self); + crate::rtc_cntl::WakeLock::release(); + self.enable_rx_clk_impl(clocks, false); + match unwrap!(clocks.i2s_rx_clk[self as usize]).sclk { + I2sClkSclk::Xtal => release_xtal_clk(clocks), + I2sClkSclk::PllF96m => release_pll_f96m_clk(clocks), + I2sClkSclk::XtalX2 => release_xtal_x2_clk(clocks), + } + } + } + pub fn rx_clk_config_frequency(config: I2sClkConfig) -> u32 { + (((match config.sclk { + I2sClkSclk::Xtal => xtal_clk_frequency(), + I2sClkSclk::PllF96m => pll_f96m_clk_frequency(), + I2sClkSclk::XtalX2 => xtal_x2_clk_frequency(), + } as u64) + * (config.div_a() as u64)) + / (((config.div_num() * config.div_a()) + config.div_b()) as u64)) + as u32 + } + pub fn rx_clk_frequency(self) -> u32 { + I2S_RX_CLK_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) + } + pub fn rx_clk_source_frequency(sclk: I2sClkSclk) -> u32 { + match sclk { + I2sClkSclk::Xtal => xtal_clk_frequency(), + I2sClkSclk::PllF96m => pll_f96m_clk_frequency(), + I2sClkSclk::XtalX2 => xtal_x2_clk_frequency(), + } + } + pub fn configure_mclk_out( + self, + clocks: &mut ClockTree, + new_selector: I2sMclkOutConfig, + ) { + let old_selector = clocks.i2s_mclk_out[self as usize].replace(new_selector); + refresh_i2s_mclk_out_downstream(clocks, self); + let active = clocks.i2s_mclk_out_refcount[self as usize] > 0; + if active { + match new_selector { + I2sMclkOutConfig::Tx => self.request_tx_clk(clocks), + I2sMclkOutConfig::Rx => self.request_rx_clk(clocks), + } + } + self.configure_mclk_out_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + I2sMclkOutConfig::Tx => self.release_tx_clk(clocks), + I2sMclkOutConfig::Rx => self.release_rx_clk(clocks), + } + } + } + pub fn mclk_out_config(self, clocks: &mut ClockTree) -> Option { + clocks.i2s_mclk_out[self as usize] + } + pub fn request_mclk_out(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::MCLK_OUT", self); + if increment_reference_count(&mut clocks.i2s_mclk_out_refcount[self as usize]) { + trace!("Enabling {:?}::MCLK_OUT", self); + match unwrap!(clocks.i2s_mclk_out[self as usize]) { + I2sMclkOutConfig::Tx => self.request_tx_clk(clocks), + I2sMclkOutConfig::Rx => self.request_rx_clk(clocks), + } + self.enable_mclk_out_impl(clocks, true); + } + } + pub fn release_mclk_out(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::MCLK_OUT", self); + if decrement_reference_count(&mut clocks.i2s_mclk_out_refcount[self as usize]) { + trace!("Disabling {:?}::MCLK_OUT", self); + self.enable_mclk_out_impl(clocks, false); + match unwrap!(clocks.i2s_mclk_out[self as usize]) { + I2sMclkOutConfig::Tx => self.release_tx_clk(clocks), + I2sMclkOutConfig::Rx => self.release_rx_clk(clocks), + } + } + } + pub fn mclk_out_config_frequency(self, config: I2sMclkOutConfig) -> u32 { + match config { + I2sMclkOutConfig::Tx => self.tx_clk_frequency(), + I2sMclkOutConfig::Rx => self.rx_clk_frequency(), + } + } + pub fn mclk_out_frequency(self) -> u32 { + I2S_MCLK_OUT_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) + } + } + impl I2cInstance { + pub fn configure_function_clock( + self, + clocks: &mut ClockTree, + config: I2cFunctionClockConfig, + ) { + let old_config = clocks.i2c_function_clock[self as usize].replace(config); + refresh_i2c_function_clock_downstream(clocks, self); + let active = clocks.i2c_function_clock_refcount[self as usize] > 0; + if active { + match config.sclk { + I2cFunctionClockSclk::Xtal => request_xtal_clk(clocks), + I2cFunctionClockSclk::RcFast => request_rc_fast_clk(clocks), + } + } + self.configure_function_clock_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + I2cFunctionClockSclk::Xtal => release_xtal_clk(clocks), + I2cFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), + } + } + } + pub fn function_clock_config( + self, + clocks: &mut ClockTree, + ) -> Option { + clocks.i2c_function_clock[self as usize] + } + pub fn request_function_clock(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::FUNCTION_CLOCK", self); + if increment_reference_count(&mut clocks.i2c_function_clock_refcount[self as usize]) + { + trace!("Enabling {:?}::FUNCTION_CLOCK", self); + crate::rtc_cntl::WakeLock::acquire(); + match unwrap!(clocks.i2c_function_clock[self as usize]).sclk { + I2cFunctionClockSclk::Xtal => request_xtal_clk(clocks), + I2cFunctionClockSclk::RcFast => request_rc_fast_clk(clocks), + } + self.enable_function_clock_impl(clocks, true); + } + } + pub fn release_function_clock(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::FUNCTION_CLOCK", self); + if decrement_reference_count(&mut clocks.i2c_function_clock_refcount[self as usize]) + { + trace!("Disabling {:?}::FUNCTION_CLOCK", self); + crate::rtc_cntl::WakeLock::release(); + self.enable_function_clock_impl(clocks, false); + match unwrap!(clocks.i2c_function_clock[self as usize]).sclk { + I2cFunctionClockSclk::Xtal => release_xtal_clk(clocks), + I2cFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), + } + } + } + pub fn function_clock_config_frequency(config: I2cFunctionClockConfig) -> u32 { + (match config.sclk { + I2cFunctionClockSclk::Xtal => xtal_clk_frequency(), + I2cFunctionClockSclk::RcFast => rc_fast_clk_frequency(), + } / (config.div_num() + 1)) + } + pub fn function_clock_frequency(self) -> u32 { + I2C_FUNCTION_CLOCK_FREQ_CACHE[self as usize] + .load(::core::sync::atomic::Ordering::Acquire) + } + pub fn function_clock_source_frequency(sclk: I2cFunctionClockSclk) -> u32 { + match sclk { + I2cFunctionClockSclk::Xtal => xtal_clk_frequency(), + I2cFunctionClockSclk::RcFast => rc_fast_clk_frequency(), + } + } + } + impl SpiInstance { + pub fn configure_function_clock( + self, + clocks: &mut ClockTree, + new_selector: SpiFunctionClockConfig, + ) { + let old_selector = clocks.spi_function_clock[self as usize].replace(new_selector); + refresh_spi_function_clock_downstream(clocks, self); + let active = clocks.spi_function_clock_refcount[self as usize] > 0; + if active { + match new_selector { + SpiFunctionClockConfig::Xtal => request_xtal_clk(clocks), + SpiFunctionClockConfig::PllF48m => request_pll_f48m_clk(clocks), + SpiFunctionClockConfig::RcFast => request_rc_fast_clk(clocks), + } + } + self.configure_function_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + SpiFunctionClockConfig::Xtal => release_xtal_clk(clocks), + SpiFunctionClockConfig::PllF48m => release_pll_f48m_clk(clocks), + SpiFunctionClockConfig::RcFast => release_rc_fast_clk(clocks), + } + } + } + pub fn function_clock_config( + self, + clocks: &mut ClockTree, + ) -> Option { + clocks.spi_function_clock[self as usize] + } + pub fn request_function_clock(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::FUNCTION_CLOCK", self); + if increment_reference_count(&mut clocks.spi_function_clock_refcount[self as usize]) + { + trace!("Enabling {:?}::FUNCTION_CLOCK", self); + crate::rtc_cntl::WakeLock::acquire(); + match unwrap!(clocks.spi_function_clock[self as usize]) { + SpiFunctionClockConfig::Xtal => request_xtal_clk(clocks), + SpiFunctionClockConfig::PllF48m => request_pll_f48m_clk(clocks), + SpiFunctionClockConfig::RcFast => request_rc_fast_clk(clocks), + } + self.enable_function_clock_impl(clocks, true); + } + } + pub fn release_function_clock(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::FUNCTION_CLOCK", self); + if decrement_reference_count(&mut clocks.spi_function_clock_refcount[self as usize]) + { + trace!("Disabling {:?}::FUNCTION_CLOCK", self); + crate::rtc_cntl::WakeLock::release(); + self.enable_function_clock_impl(clocks, false); + match unwrap!(clocks.spi_function_clock[self as usize]) { + SpiFunctionClockConfig::Xtal => release_xtal_clk(clocks), + SpiFunctionClockConfig::PllF48m => release_pll_f48m_clk(clocks), + SpiFunctionClockConfig::RcFast => release_rc_fast_clk(clocks), + } + } + } + pub fn function_clock_config_frequency(config: SpiFunctionClockConfig) -> u32 { + match config { + SpiFunctionClockConfig::Xtal => xtal_clk_frequency(), + SpiFunctionClockConfig::PllF48m => pll_f48m_clk_frequency(), + SpiFunctionClockConfig::RcFast => rc_fast_clk_frequency(), + } + } + pub fn function_clock_frequency(self) -> u32 { + SPI_FUNCTION_CLOCK_FREQ_CACHE[self as usize] + .load(::core::sync::atomic::Ordering::Acquire) + } + pub fn function_clock_source_frequency(source: SpiFunctionClockConfig) -> u32 { + Self::function_clock_config_frequency(source) + } + } + impl TimgInstance { + pub fn configure_function_clock( + self, + clocks: &mut ClockTree, + new_selector: TimgFunctionClockConfig, + ) { + let old_selector = clocks.timg_function_clock[self as usize].replace(new_selector); + refresh_timg_function_clock_downstream(clocks, self); + let active = clocks.timg_function_clock_refcount[self as usize] > 0; + if active { + match new_selector { + TimgFunctionClockConfig::XtalClk => request_xtal_clk(clocks), + TimgFunctionClockConfig::RcFastClk => request_rc_fast_clk(clocks), + TimgFunctionClockConfig::PllF48m => request_pll_f48m_clk(clocks), + } + } + self.configure_function_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + TimgFunctionClockConfig::XtalClk => release_xtal_clk(clocks), + TimgFunctionClockConfig::RcFastClk => release_rc_fast_clk(clocks), + TimgFunctionClockConfig::PllF48m => release_pll_f48m_clk(clocks), + } + } + } + pub fn function_clock_config( + self, + clocks: &mut ClockTree, + ) -> Option { + clocks.timg_function_clock[self as usize] + } + pub fn request_function_clock(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::FUNCTION_CLOCK", self); + if increment_reference_count( + &mut clocks.timg_function_clock_refcount[self as usize], + ) { + trace!("Enabling {:?}::FUNCTION_CLOCK", self); + match unwrap!(clocks.timg_function_clock[self as usize]) { + TimgFunctionClockConfig::XtalClk => request_xtal_clk(clocks), + TimgFunctionClockConfig::RcFastClk => request_rc_fast_clk(clocks), + TimgFunctionClockConfig::PllF48m => request_pll_f48m_clk(clocks), + } + self.enable_function_clock_impl(clocks, true); + } + } + pub fn release_function_clock(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::FUNCTION_CLOCK", self); + if decrement_reference_count( + &mut clocks.timg_function_clock_refcount[self as usize], + ) { + trace!("Disabling {:?}::FUNCTION_CLOCK", self); + self.enable_function_clock_impl(clocks, false); + match unwrap!(clocks.timg_function_clock[self as usize]) { + TimgFunctionClockConfig::XtalClk => release_xtal_clk(clocks), + TimgFunctionClockConfig::RcFastClk => release_rc_fast_clk(clocks), + TimgFunctionClockConfig::PllF48m => release_pll_f48m_clk(clocks), + } + } + } + pub fn function_clock_config_frequency(config: TimgFunctionClockConfig) -> u32 { + match config { + TimgFunctionClockConfig::XtalClk => xtal_clk_frequency(), + TimgFunctionClockConfig::RcFastClk => rc_fast_clk_frequency(), + TimgFunctionClockConfig::PllF48m => pll_f48m_clk_frequency(), + } + } + pub fn function_clock_frequency(self) -> u32 { + TIMG_FUNCTION_CLOCK_FREQ_CACHE[self as usize] + .load(::core::sync::atomic::Ordering::Acquire) + } + pub fn function_clock_source_frequency(source: TimgFunctionClockConfig) -> u32 { + Self::function_clock_config_frequency(source) + } + pub fn configure_wdt_clock( + self, + clocks: &mut ClockTree, + new_selector: TimgWdtClockConfig, + ) { + let old_selector = clocks.timg_wdt_clock[self as usize].replace(new_selector); + refresh_timg_wdt_clock_downstream(clocks, self); + let active = clocks.timg_wdt_clock_refcount[self as usize] > 0; + if active { + match new_selector { + TimgWdtClockConfig::XtalClk => request_xtal_clk(clocks), + TimgWdtClockConfig::RcFastClk => request_rc_fast_clk(clocks), + TimgWdtClockConfig::PllF48m => request_pll_f48m_clk(clocks), + } + } + self.configure_wdt_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + TimgWdtClockConfig::XtalClk => release_xtal_clk(clocks), + TimgWdtClockConfig::RcFastClk => release_rc_fast_clk(clocks), + TimgWdtClockConfig::PllF48m => release_pll_f48m_clk(clocks), + } + } + } + pub fn wdt_clock_config(self, clocks: &mut ClockTree) -> Option { + clocks.timg_wdt_clock[self as usize] + } + pub fn request_wdt_clock(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::WDT_CLOCK", self); + if increment_reference_count(&mut clocks.timg_wdt_clock_refcount[self as usize]) { + trace!("Enabling {:?}::WDT_CLOCK", self); + match unwrap!(clocks.timg_wdt_clock[self as usize]) { + TimgWdtClockConfig::XtalClk => request_xtal_clk(clocks), + TimgWdtClockConfig::RcFastClk => request_rc_fast_clk(clocks), + TimgWdtClockConfig::PllF48m => request_pll_f48m_clk(clocks), + } + self.enable_wdt_clock_impl(clocks, true); + } + } + pub fn release_wdt_clock(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::WDT_CLOCK", self); + if decrement_reference_count(&mut clocks.timg_wdt_clock_refcount[self as usize]) { + trace!("Disabling {:?}::WDT_CLOCK", self); + self.enable_wdt_clock_impl(clocks, false); + match unwrap!(clocks.timg_wdt_clock[self as usize]) { + TimgWdtClockConfig::XtalClk => release_xtal_clk(clocks), + TimgWdtClockConfig::RcFastClk => release_rc_fast_clk(clocks), + TimgWdtClockConfig::PllF48m => release_pll_f48m_clk(clocks), + } + } + } + pub fn wdt_clock_config_frequency(config: TimgWdtClockConfig) -> u32 { + match config { + TimgWdtClockConfig::XtalClk => xtal_clk_frequency(), + TimgWdtClockConfig::RcFastClk => rc_fast_clk_frequency(), + TimgWdtClockConfig::PllF48m => pll_f48m_clk_frequency(), + } + } + pub fn wdt_clock_frequency(self) -> u32 { + TIMG_WDT_CLOCK_FREQ_CACHE[self as usize] + .load(::core::sync::atomic::Ordering::Acquire) + } + pub fn wdt_clock_source_frequency(source: TimgWdtClockConfig) -> u32 { + Self::wdt_clock_config_frequency(source) + } + } + impl UartInstance { + pub fn configure_function_clock( + self, + clocks: &mut ClockTree, + config: UartFunctionClockConfig, + ) { + let old_config = clocks.uart_function_clock[self as usize].replace(config); + refresh_uart_function_clock_downstream(clocks, self); + let active = clocks.uart_function_clock_refcount[self as usize] > 0; + if active { + match config.sclk { + UartFunctionClockSclk::PllF48m => request_pll_f48m_clk(clocks), + UartFunctionClockSclk::RcFast => request_rc_fast_clk(clocks), + UartFunctionClockSclk::Xtal => request_xtal_clk(clocks), + } + } + self.configure_function_clock_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + UartFunctionClockSclk::PllF48m => release_pll_f48m_clk(clocks), + UartFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), + UartFunctionClockSclk::Xtal => release_xtal_clk(clocks), + } + } + } + pub fn function_clock_config( + self, + clocks: &mut ClockTree, + ) -> Option { + clocks.uart_function_clock[self as usize] + } + pub fn request_function_clock(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::FUNCTION_CLOCK", self); + if increment_reference_count( + &mut clocks.uart_function_clock_refcount[self as usize], + ) { + trace!("Enabling {:?}::FUNCTION_CLOCK", self); + crate::rtc_cntl::WakeLock::acquire(); + match unwrap!(clocks.uart_function_clock[self as usize]).sclk { + UartFunctionClockSclk::PllF48m => request_pll_f48m_clk(clocks), + UartFunctionClockSclk::RcFast => request_rc_fast_clk(clocks), + UartFunctionClockSclk::Xtal => request_xtal_clk(clocks), + } + self.enable_function_clock_impl(clocks, true); + } + } + pub fn release_function_clock(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::FUNCTION_CLOCK", self); + if decrement_reference_count( + &mut clocks.uart_function_clock_refcount[self as usize], + ) { + trace!("Disabling {:?}::FUNCTION_CLOCK", self); + crate::rtc_cntl::WakeLock::release(); + self.enable_function_clock_impl(clocks, false); + match unwrap!(clocks.uart_function_clock[self as usize]).sclk { + UartFunctionClockSclk::PllF48m => release_pll_f48m_clk(clocks), + UartFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), + UartFunctionClockSclk::Xtal => release_xtal_clk(clocks), + } + } + } + pub fn function_clock_config_frequency(config: UartFunctionClockConfig) -> u32 { + (match config.sclk { + UartFunctionClockSclk::PllF48m => pll_f48m_clk_frequency(), + UartFunctionClockSclk::RcFast => rc_fast_clk_frequency(), + UartFunctionClockSclk::Xtal => xtal_clk_frequency(), + } / (config.div_num() + 1)) + } + pub fn function_clock_frequency(self) -> u32 { + UART_FUNCTION_CLOCK_FREQ_CACHE[self as usize] + .load(::core::sync::atomic::Ordering::Acquire) + } + pub fn function_clock_source_frequency(sclk: UartFunctionClockSclk) -> u32 { + match sclk { + UartFunctionClockSclk::PllF48m => pll_f48m_clk_frequency(), + UartFunctionClockSclk::RcFast => rc_fast_clk_frequency(), + UartFunctionClockSclk::Xtal => xtal_clk_frequency(), + } + } + pub fn configure_baud_rate_generator( + self, + clocks: &mut ClockTree, + config: UartBaudRateGeneratorConfig, + ) { + let old_config = clocks.uart_baud_rate_generator[self as usize].replace(config); + refresh_uart_baud_rate_generator_downstream(clocks, self); + self.configure_baud_rate_generator_impl(clocks, old_config, config); + } + pub fn baud_rate_generator_config( + self, + clocks: &mut ClockTree, + ) -> Option { + clocks.uart_baud_rate_generator[self as usize] + } + pub fn request_baud_rate_generator(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::BAUD_RATE_GENERATOR", self); + if increment_reference_count( + &mut clocks.uart_baud_rate_generator_refcount[self as usize], + ) { + trace!("Enabling {:?}::BAUD_RATE_GENERATOR", self); + self.request_function_clock(clocks); + self.enable_baud_rate_generator_impl(clocks, true); + } + } + pub fn release_baud_rate_generator(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::BAUD_RATE_GENERATOR", self); + if decrement_reference_count( + &mut clocks.uart_baud_rate_generator_refcount[self as usize], + ) { + trace!("Disabling {:?}::BAUD_RATE_GENERATOR", self); + self.enable_baud_rate_generator_impl(clocks, false); + self.release_function_clock(clocks); + } + } + pub fn baud_rate_generator_config_frequency( + self, + config: UartBaudRateGeneratorConfig, + ) -> u32 { + ((self.function_clock_frequency() * 16) + / ((config.integral() * 16) + config.fractional())) + } + pub fn baud_rate_generator_frequency(self) -> u32 { + UART_BAUD_RATE_GENERATOR_FREQ_CACHE[self as usize] + .load(::core::sync::atomic::Ordering::Acquire) + } + } + /// Clock tree configuration. + /// + /// The fields of this struct are optional, with the following caveats: + /// - If `XTAL_CLK` is not specified, the crystal frequency will be automatically detected + /// if possible. + /// - The CPU and its upstream clock nodes will be set to a default configuration. + /// - Other unspecified clock sources will not be useable by peripherals. + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + #[instability::unstable] + pub struct ClockConfig { + /// `IOMUX_FUNCTION_CLOCK` configuration. + pub iomux_function_clock: Option, + /// `HP_ROOT_CLK` configuration. + pub hp_root_clk: Option, + /// `CPU_CLK` configuration. + pub cpu_clk: Option, + /// `AHB_CLK` configuration. + pub ahb_clk: Option, + /// `APB_CLK` configuration. + pub apb_clk: Option, + /// `LP_FAST_CLK` configuration. + pub lp_fast_clk: Option, + /// `LP_SLOW_CLK` configuration. + pub lp_slow_clk: Option, + /// `BLE_LP_CLK` configuration. + pub ble_lp_clk: Option, + /// `TIMG_CALIBRATION_CLOCK` configuration. + pub timg_calibration_clock: Option, + } + impl ClockConfig { + fn apply(&self, clocks: &mut ClockTree) { + if let Some(config) = self.hp_root_clk { + configure_hp_root_clk(clocks, config); + } + if let Some(config) = self.cpu_clk { + configure_cpu_clk(clocks, config); + } + if let Some(config) = self.ahb_clk { + configure_ahb_clk(clocks, config); + } + if let Some(config) = self.apb_clk { + configure_apb_clk(clocks, config); + } + if let Some(config) = self.lp_fast_clk { + configure_lp_fast_clk(clocks, config); + } + if let Some(config) = self.lp_slow_clk { + configure_lp_slow_clk(clocks, config); + } + if let Some(config) = self.ble_lp_clk { + configure_ble_lp_clk(clocks, config); + } + if let Some(config) = self.timg_calibration_clock { + configure_timg_calibration_clock(clocks, config); + } + if let Some(config) = self.iomux_function_clock { + configure_iomux_function_clock(clocks, config); + } + } + } + fn increment_reference_count(refcount: &mut u32) -> bool { + let first = *refcount == 0; + *refcount = unwrap!(refcount.checked_add(1), "Reference count overflow"); + first + } + fn decrement_reference_count(refcount: &mut u32) -> bool { + *refcount = refcount.saturating_sub(1); + let last = *refcount == 0; + last + } + fn refresh_rc_fast_clk_downstream(clocks: &mut ClockTree) { + refresh_hp_root_clk_downstream(clocks); + refresh_lp_fast_clk_downstream(clocks); + refresh_timg_calibration_clock_downstream(clocks); + refresh_iomux_function_clock_downstream(clocks); + for child_instance in [I2cInstance::I2c0, I2cInstance::I2c1] { + refresh_i2c_function_clock_downstream(clocks, child_instance); + } + for child_instance in [SpiInstance::Spi2, SpiInstance::Spi3] { + refresh_spi_function_clock_downstream(clocks, child_instance); + } + for child_instance in [TimgInstance::Timg0, TimgInstance::Timg1] { + refresh_timg_function_clock_downstream(clocks, child_instance); + refresh_timg_wdt_clock_downstream(clocks, child_instance); + } + for child_instance in [UartInstance::Uart0, UartInstance::Uart1] { + refresh_uart_function_clock_downstream(clocks, child_instance); + } + } + fn refresh_rc_slow_clk_downstream(clocks: &mut ClockTree) { + refresh_lp_slow_clk_downstream(clocks); + refresh_timg_calibration_clock_downstream(clocks); + } + fn refresh_hp_root_clk_downstream(clocks: &mut ClockTree) { + if let Some(config) = clocks.hp_root_clk { + HP_ROOT_CLK_FREQ_CACHE.store( + hp_root_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + refresh_cpu_clk_downstream(clocks); + } + fn refresh_cpu_clk_downstream(clocks: &mut ClockTree) { + if let Some(config) = clocks.cpu_clk { + CPU_CLK_FREQ_CACHE.store( + cpu_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + refresh_ahb_clk_downstream(clocks); + } + fn refresh_ahb_clk_downstream(clocks: &mut ClockTree) { + if let Some(config) = clocks.ahb_clk { + AHB_CLK_FREQ_CACHE.store( + ahb_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + refresh_apb_clk_downstream(clocks); + } + fn refresh_apb_clk_downstream(clocks: &mut ClockTree) { + if let Some(config) = clocks.apb_clk { + APB_CLK_FREQ_CACHE.store( + apb_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + fn refresh_lp_fast_clk_downstream(clocks: &mut ClockTree) { + if let Some(config) = clocks.lp_fast_clk { + LP_FAST_CLK_FREQ_CACHE.store( + lp_fast_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + fn refresh_lp_slow_clk_downstream(clocks: &mut ClockTree) { + if let Some(config) = clocks.lp_slow_clk { + LP_SLOW_CLK_FREQ_CACHE.store( + lp_slow_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + fn refresh_ble_lp_clk_downstream(clocks: &mut ClockTree) { + if let Some(config) = clocks.ble_lp_clk { + BLE_LP_CLK_FREQ_CACHE.store( + ble_lp_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + fn refresh_timg_calibration_clock_downstream(clocks: &mut ClockTree) { + if let Some(config) = clocks.timg_calibration_clock { + TIMG_CALIBRATION_CLOCK_FREQ_CACHE.store( + timg_calibration_clock_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + fn refresh_i2s_tx_clk_downstream(clocks: &mut ClockTree, instance: I2sInstance) { + if let Some(config) = clocks.i2s_tx_clk[instance as usize] { + I2S_TX_CLK_FREQ_CACHE[instance as usize].store( + I2sInstance::tx_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + refresh_i2s_mclk_out_downstream(clocks, instance); + } + fn refresh_i2s_rx_clk_downstream(clocks: &mut ClockTree, instance: I2sInstance) { + if let Some(config) = clocks.i2s_rx_clk[instance as usize] { + I2S_RX_CLK_FREQ_CACHE[instance as usize].store( + I2sInstance::rx_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + refresh_i2s_mclk_out_downstream(clocks, instance); + } + fn refresh_i2s_mclk_out_downstream(clocks: &mut ClockTree, instance: I2sInstance) { + if let Some(config) = clocks.i2s_mclk_out[instance as usize] { + I2S_MCLK_OUT_FREQ_CACHE[instance as usize].store( + instance.mclk_out_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + fn refresh_i2c_function_clock_downstream(clocks: &mut ClockTree, instance: I2cInstance) { + if let Some(config) = clocks.i2c_function_clock[instance as usize] { + I2C_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( + I2cInstance::function_clock_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + fn refresh_spi_function_clock_downstream(clocks: &mut ClockTree, instance: SpiInstance) { + if let Some(config) = clocks.spi_function_clock[instance as usize] { + SPI_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( + SpiInstance::function_clock_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + fn refresh_timg_function_clock_downstream(clocks: &mut ClockTree, instance: TimgInstance) { + if let Some(config) = clocks.timg_function_clock[instance as usize] { + TIMG_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( + TimgInstance::function_clock_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + fn refresh_timg_wdt_clock_downstream(clocks: &mut ClockTree, instance: TimgInstance) { + if let Some(config) = clocks.timg_wdt_clock[instance as usize] { + TIMG_WDT_CLOCK_FREQ_CACHE[instance as usize].store( + TimgInstance::wdt_clock_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + fn refresh_uart_function_clock_downstream(clocks: &mut ClockTree, instance: UartInstance) { + if let Some(config) = clocks.uart_function_clock[instance as usize] { + UART_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( + UartInstance::function_clock_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + refresh_uart_baud_rate_generator_downstream(clocks, instance); + } + fn refresh_uart_baud_rate_generator_downstream( + clocks: &mut ClockTree, + instance: UartInstance, + ) { + if let Some(config) = clocks.uart_baud_rate_generator[instance as usize] { + UART_BAUD_RATE_GENERATOR_FREQ_CACHE[instance as usize].store( + instance.baud_rate_generator_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + fn refresh_iomux_function_clock_downstream(clocks: &mut ClockTree) { + if let Some(config) = clocks.iomux_function_clock { + IOMUX_FUNCTION_CLOCK_FREQ_CACHE.store( + iomux_function_clock_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + }; +} +/// Implement the `Peripheral` enum and enable/disable/reset functions. +/// +/// This macro is intended to be placed in `esp_hal::system`. +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! implement_peripheral_clocks { + () => { + #[doc(hidden)] + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + #[repr(u8)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum Peripheral { + /// AES peripheral clock signal + Aes, + /// AHB_GDMA peripheral clock signal + AhbGdma, + /// ECC peripheral clock signal + Ecc, + /// GPIO_SD peripheral clock signal + GpioSd, + /// I2C_EXT0 peripheral clock signal + I2cExt0, + /// I2C_EXT1 peripheral clock signal + I2cExt1, + /// I2S0 peripheral clock signal + I2s0, + /// LEDC peripheral clock signal + Ledc, + /// PARL_IO peripheral clock signal + ParlIo, + /// PCNT peripheral clock signal + Pcnt, + /// RMT peripheral clock signal + Rmt, + /// SHA peripheral clock signal + Sha, + /// SPI2 peripheral clock signal + Spi2, + /// SPI3 peripheral clock signal + Spi3, + /// SYSTIMER peripheral clock signal + Systimer, + /// TIMG0 peripheral clock signal + Timg0, + /// TIMG1 peripheral clock signal + Timg1, + /// UART0 peripheral clock signal + Uart0, + /// UART1 peripheral clock signal + Uart1, + /// UHCI0 peripheral clock signal + Uhci0, + /// USB_DEVICE peripheral clock signal + UsbDevice, + } + impl Peripheral { + const KEEP_ENABLED: &[Peripheral] = + &[Self::Systimer, Self::Timg0, Self::Uart0, Self::UsbDevice]; + const COUNT: usize = Self::ALL.len(); + const ALL: &[Self] = &[ + Self::Aes, + Self::AhbGdma, + Self::Ecc, + Self::GpioSd, + Self::I2cExt0, + Self::I2cExt1, + Self::I2s0, + Self::Ledc, + Self::ParlIo, + Self::Pcnt, + Self::Rmt, + Self::Sha, + Self::Spi2, + Self::Spi3, + Self::Systimer, + Self::Timg0, + Self::Timg1, + Self::Uart0, + Self::Uart1, + Self::Uhci0, + Self::UsbDevice, + ]; + } + unsafe fn enable_internal_racey(peripheral: Peripheral, enable: bool) { + match peripheral { + Peripheral::Aes => { + crate::peripherals::SYSTEM::regs() + .aes_conf() + .modify(|_, w| w.aes_clk_en().bit(enable)); + } + Peripheral::AhbGdma => { + crate::peripherals::SYSTEM::regs() + .gdma_conf() + .modify(|_, w| w.gdma_clk_en().bit(enable)); + } + Peripheral::Ecc => { + crate::peripherals::SYSTEM::regs() + .ecc_conf() + .modify(|_, w| w.ecc_clk_en().bit(enable)); + } + Peripheral::GpioSd => { + crate::peripherals::GPIO_SD::regs() + .clock_gate() + .modify(|_, w| w.clk_en().bit(enable)); + } + Peripheral::I2cExt0 => { + crate::peripherals::SYSTEM::regs() + .i2c0_conf() + .modify(|_, w| w.i2c0_clk_en().bit(enable)); + } + Peripheral::I2cExt1 => { + crate::peripherals::SYSTEM::regs() + .i2c1_conf() + .modify(|_, w| w.i2c1_clk_en().bit(enable)); + } + Peripheral::I2s0 => { + crate::peripherals::SYSTEM::regs() + .i2s_conf() + .modify(|_, w| w.i2s_clk_en().bit(enable)); + } + Peripheral::Ledc => { + crate::peripherals::SYSTEM::regs() + .ledc_conf() + .modify(|_, w| w.ledc_clk_en().bit(enable)); + } + Peripheral::ParlIo => { + crate::peripherals::SYSTEM::regs() + .parl_io_conf() + .modify(|_, w| w.parl_clk_en().bit(enable)); + } + Peripheral::Pcnt => { + crate::peripherals::SYSTEM::regs() + .pcnt_conf() + .modify(|_, w| w.pcnt_clk_en().bit(enable)); + crate::peripherals::SYSTEM::regs() + .pcnt_conf() + .modify(|_, w| w.pcnt_reg_clk_en().bit(enable)); + } + Peripheral::Rmt => { + crate::peripherals::SYSTEM::regs() + .rmt_conf() + .modify(|_, w| w.rmt_clk_en().bit(enable)); + crate::peripherals::SYSTEM::regs() + .rmt_mem_lp_ctrl() + .modify(|_, w| w.rmt_mem_lp_en().bit(!enable)); + } + Peripheral::Sha => { + crate::peripherals::SYSTEM::regs() + .sha_conf() + .modify(|_, w| w.sha_clk_en().bit(enable)); + } + Peripheral::Spi2 => { + crate::peripherals::SYSTEM::regs() + .spi2_conf() + .modify(|_, w| w.spi2_clk_en().bit(enable)); + } + Peripheral::Spi3 => { + crate::peripherals::SYSTEM::regs() + .spi3_conf() + .modify(|_, w| w.spi3_clk_en().bit(enable)); + } + Peripheral::Systimer => { + crate::peripherals::SYSTEM::regs() + .systimer_conf() + .modify(|_, w| w.systimer_clk_en().bit(enable)); + } + Peripheral::Timg0 => { + crate::peripherals::SYSTEM::regs() + .timergroup0_conf() + .modify(|_, w| w.tg0_clk_en().bit(enable)); + } + Peripheral::Timg1 => { + crate::peripherals::SYSTEM::regs() + .timergroup1_conf() + .modify(|_, w| w.tg1_clk_en().bit(enable)); + } + Peripheral::Uart0 => { + crate::peripherals::SYSTEM::regs() + .uart(0) + .conf() + .modify(|_, w| w.clk_en().bit(enable)); + } + Peripheral::Uart1 => { + crate::peripherals::SYSTEM::regs() + .uart(1) + .conf() + .modify(|_, w| w.clk_en().bit(enable)); + } + Peripheral::Uhci0 => { + crate::peripherals::SYSTEM::regs() + .uhci_conf() + .modify(|_, w| w.uhci_clk_en().bit(enable)); + } + Peripheral::UsbDevice => { + crate::peripherals::SYSTEM::regs() + .usb_device_conf() + .modify(|_, w| w.usb_device_clk_en().bit(enable)); + } + } + } + unsafe fn assert_peri_reset_racey(peripheral: Peripheral, reset: bool) { + match peripheral { + Peripheral::Aes => { + crate::peripherals::SYSTEM::regs() + .aes_conf() + .modify(|_, w| w.aes_rst_en().bit(reset)); + } + Peripheral::AhbGdma => { + crate::peripherals::SYSTEM::regs() + .gdma_conf() + .modify(|_, w| w.gdma_rst_en().bit(reset)); + } + Peripheral::Ecc => { + crate::peripherals::SYSTEM::regs() + .ecc_conf() + .modify(|_, w| w.ecc_rst_en().bit(reset)); + } + Peripheral::GpioSd => { + let _ = reset; + } + Peripheral::I2cExt0 => { + crate::peripherals::SYSTEM::regs() + .i2c0_conf() + .modify(|_, w| w.i2c0_rst_en().bit(reset)); + } + Peripheral::I2cExt1 => { + crate::peripherals::SYSTEM::regs() + .i2c1_conf() + .modify(|_, w| w.i2c1_rst_en().bit(reset)); + } + Peripheral::I2s0 => { + crate::peripherals::SYSTEM::regs() + .i2s_conf() + .modify(|_, w| w.i2s_rst_en().bit(reset)); + } + Peripheral::Ledc => { + crate::peripherals::SYSTEM::regs() + .ledc_conf() + .modify(|_, w| w.ledc_rst_en().bit(reset)); + } + Peripheral::ParlIo => { + crate::peripherals::SYSTEM::regs() + .parl_io_conf() + .modify(|_, w| w.parl_rst_en().bit(reset)); + } + Peripheral::Pcnt => { + crate::peripherals::SYSTEM::regs() + .pcnt_conf() + .modify(|_, w| { + w.pcnt_rst_en().bit(reset); + w.pcnt_reg_rst_en().bit(reset) + }); + } + Peripheral::Rmt => { + crate::peripherals::SYSTEM::regs() + .rmt_conf() + .modify(|_, w| w.rmt_rst_en().bit(reset)); + } + Peripheral::Sha => { + crate::peripherals::SYSTEM::regs() + .sha_conf() + .modify(|_, w| w.sha_rst_en().bit(reset)); + } + Peripheral::Spi2 => { + crate::peripherals::SYSTEM::regs() + .spi2_conf() + .modify(|_, w| w.spi2_rst_en().bit(reset)); + } + Peripheral::Spi3 => { + crate::peripherals::SYSTEM::regs() + .spi3_conf() + .modify(|_, w| w.spi3_rst_en().bit(reset)); + } + Peripheral::Systimer => { + crate::peripherals::SYSTEM::regs() + .systimer_conf() + .modify(|_, w| w.systimer_rst_en().bit(reset)); + } + Peripheral::Timg0 => { + crate::peripherals::SYSTEM::regs() + .timergroup0_conf() + .modify(|_, w| w.tg0_rst_en().bit(reset)); + } + Peripheral::Timg1 => { + crate::peripherals::SYSTEM::regs() + .timergroup1_conf() + .modify(|_, w| w.tg1_rst_en().bit(reset)); + } + Peripheral::Uart0 => { + crate::peripherals::SYSTEM::regs() + .uart(0) + .conf() + .modify(|_, w| w.rst_en().bit(reset)); + } + Peripheral::Uart1 => { + crate::peripherals::SYSTEM::regs() + .uart(1) + .conf() + .modify(|_, w| w.rst_en().bit(reset)); + } + Peripheral::Uhci0 => { + crate::peripherals::SYSTEM::regs() + .uhci_conf() + .modify(|_, w| w.uhci_rst_en().bit(reset)); + } + Peripheral::UsbDevice => { + crate::peripherals::SYSTEM::regs() + .usb_device_conf() + .modify(|_, w| w.usb_device_rst_en().bit(reset)); + } + } + } + }; +} +/// Macro to get the address range of the given memory region. +/// +/// This macro provides two syntax options for each memory region: +/// +/// - `memory_range!("region_name")` returns the address range as a range expression (`start..end`). +/// - `memory_range!(size as str, "region_name")` returns the size of the region as a string +/// literal. +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! memory_range { + ("DRAM") => { + 0x40810000..0x4084F350 + }; + (size as str, "DRAM") => { + "258896" + }; + ("DRAM2_UNINIT") => { + 0x4084F350..0x4085D350 + }; + (size as str, "DRAM2_UNINIT") => { + "57344" + }; + ("IROM") => { + 0x42000000..0x44000000 + }; + (size as str, "IROM") => { + "33554432" + }; + ("DROM") => { + 0x42000000..0x44000000 + }; + (size as str, "DROM") => { + "33554432" + }; +} +/// This macro can be used to generate code for each peripheral instance of the I2C master driver. +/// +/// For an explanation on the general syntax, as well as usage of individual/repeated +/// matchers, refer to [the crate-level documentation][crate#for_each-macros]. +/// +/// This macro has one option for its "Individual matcher" case: +/// +/// Syntax: `($id:literal, $instance:ident, $sys:ident, $scl:ident, $sda:ident)` +/// +/// Macro fragments: +/// - `$id`: the index of the I2C instance +/// - `$instance`: the name of the I2C instance +/// - `$sys`: the name of the instance as it is in the `esp_hal::system::Peripheral` enum. +/// - `$scl`, `$sda`: peripheral signal names. +/// +/// Example data: `(0, I2C0, I2cExt0, I2CEXT0_SCL, I2CEXT0_SDA)` +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! for_each_i2c_master { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _for_each_inner_i2c_master { $(($pattern) => $code;)* ($other : tt) + => {} } _for_each_inner_i2c_master!((0, I2C0, I2cExt0, I2CEXT0_SCL, + I2CEXT0_SDA)); _for_each_inner_i2c_master!((1, I2C1, I2cExt1, I2CEXT1_SCL, + I2CEXT1_SDA)); _for_each_inner_i2c_master!((all(0, I2C0, I2cExt0, I2CEXT0_SCL, + I2CEXT0_SDA), (1, I2C1, I2cExt1, I2CEXT1_SCL, I2CEXT1_SDA))); + }; +} +/// This macro can be used to generate code for each peripheral instance of the I2S driver. +/// +/// For an explanation on the general syntax, as well as usage of individual/repeated +/// matchers, refer to [the crate-level documentation][crate#for_each-macros]. +/// +/// This macro has one option for its "Individual matcher" case: +/// +/// Syntax: `($instance:ident, $sys:ident, $mclk:ident, $bclk:ident, $ws:ident, $bclk_rx:ident, +/// $ws_rx:ident, [$($dout:ident),*], [$($din:ident),*], $pdm_tx:literal, $pdm_rx:literal, +/// $pcm2pdm:literal, $pdm2pcm:literal)` +/// +/// Macro fragments: +/// +/// - `$instance`: the name of the I2S instance +/// - `$sys`: the name of the instance as it is in the `esp_hal::system::Peripheral` enum. +/// - `$mclk`: the MCLK output signal (a placeholder on chips without a GPIO-matrix MCLK). +/// - `$bclk`, `$ws`: TX bit clock and word select output signals. +/// - `$bclk_rx`, `$ws_rx`: RX bit clock and word select output signals. +/// - `$dout`, `$din`: data-out and data-in signal names. +/// - `$pdm_tx`, `$pdm_rx`: whether the instance supports PDM TX/RX. +/// - `$pcm2pdm`, `$pdm2pcm`: whether the instance supports the hardware PCM<->PDM format conversion +/// filter on TX/RX. +/// +/// Example data: +/// - `(I2S0, I2s0, I2S_MCLK, I2SO_BCK, I2SO_WS, I2SI_BCK, I2SI_WS, [I2SO_SD], [I2SI_SD], true, +/// true, true, true)` +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! for_each_i2s { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _for_each_inner_i2s { $(($pattern) => $code;)* ($other : tt) => {} } + _for_each_inner_i2s!((I2S0)); _for_each_inner_i2s!((I2S0, I2s0, I2S_MCLK, + I2SO_BCK, I2SO_WS, I2SI_BCK, I2SI_WS, [I2SO_SD, I2SO_SD1], [I2SI_SD], true, true, + true, false)); _for_each_inner_i2s!((names(I2S0))); + _for_each_inner_i2s!((all(I2S0, I2s0, I2S_MCLK, I2SO_BCK, I2SO_WS, I2SI_BCK, + I2SI_WS, [I2SO_SD, I2SO_SD1], [I2SI_SD], true, true, true, false))); + }; +} +/// This macro can be used to generate code for each peripheral instance of the UART driver. +/// +/// For an explanation on the general syntax, as well as usage of individual/repeated +/// matchers, refer to [the crate-level documentation][crate#for_each-macros]. +/// +/// This macro has one option for its "Individual matcher" case: +/// +/// Syntax: `($id:literal, $instance:ident, $sys:ident, $rx:ident, $tx:ident, $cts:ident, +/// $rts:ident)` +/// +/// Macro fragments: +/// +/// - `$id`: the index of the UART instance +/// - `$instance`: the name of the UART instance +/// - `$sys`: the name of the instance as it is in the `esp_hal::system::Peripheral` enum. +/// - `$rx`, `$tx`, `$cts`, `$rts`: signal names. +/// +/// Example data: `(0, UART0, Uart0, U0RXD, U0TXD, U0CTS, U0RTS)` +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! for_each_uart { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _for_each_inner_uart { $(($pattern) => $code;)* ($other : tt) => {} + } _for_each_inner_uart!((0, UART0, Uart0, U0RXD, U0TXD, U0CTS, U0RTS, + wakeup_source = true)); _for_each_inner_uart!((1, UART1, Uart1, U1RXD, U1TXD, + U1CTS, U1RTS, wakeup_source = true)); _for_each_inner_uart!((all(0, UART0, Uart0, + U0RXD, U0TXD, U0CTS, U0RTS, wakeup_source = true), (1, UART1, Uart1, U1RXD, + U1TXD, U1CTS, U1RTS, wakeup_source = true))); + }; +} +/// This macro can be used to generate code for each peripheral instance of the SPI master driver. +/// +/// For an explanation on the general syntax, as well as usage of individual/repeated +/// matchers, refer to [the crate-level documentation][crate#for_each-macros]. +/// +/// This macro has one option for its "Individual matcher" case: +/// +/// Syntax: `($instance:ident, $sys:ident, $sclk:ident [$($cs:ident),*] [$($sio:ident),*] +/// $($is_qspi:literal)?)` +/// +/// Macro fragments: +/// +/// - `$instance`: the name of the SPI instance +/// - `$sys`: the name of the instance as it is in the `esp_hal::system::Peripheral` enum. +/// - `$cs`, `$sio`: chip select and SIO signal names. +/// - `$is_qspi`: a `true` literal present if the SPI instance supports QSPI. +/// +/// Example data: +/// - `(SPI2, Spi2, FSPICLK [FSPICS0, FSPICS1, FSPICS2, FSPICS3, FSPICS4, FSPICS5] [FSPID, FSPIQ, +/// FSPIWP, FSPIHD, FSPIIO4, FSPIIO5, FSPIIO6, FSPIIO7], true)` +/// - `(SPI3, Spi3, SPI3_CLK [SPI3_CS0, SPI3_CS1, SPI3_CS2] [SPI3_D, SPI3_Q])` +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! for_each_spi_master { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _for_each_inner_spi_master { $(($pattern) => $code;)* ($other : tt) + => {} } _for_each_inner_spi_master!((SPI2)); _for_each_inner_spi_master!((SPI3)); + _for_each_inner_spi_master!((SPI2, Spi2, FSPICLK[FSPICS0, FSPICS1, FSPICS2, + FSPICS3, FSPICS4, FSPICS5] [FSPID, FSPIQ, FSPIWP, FSPIHD], true)); + _for_each_inner_spi_master!((SPI3, Spi3, FSPI3CLK[FSPI3CS0, FSPI3CS1, FSPI3CS2] + [FSPI3D, FSPI3Q, FSPI3WP, FSPI3HD], true)); + _for_each_inner_spi_master!((names(SPI2), (SPI3))); + _for_each_inner_spi_master!((all(SPI2, Spi2, FSPICLK[FSPICS0, FSPICS1, FSPICS2, + FSPICS3, FSPICS4, FSPICS5] [FSPID, FSPIQ, FSPIWP, FSPIHD], true), (SPI3, Spi3, + FSPI3CLK[FSPI3CS0, FSPI3CS1, FSPI3CS2] [FSPI3D, FSPI3Q, FSPI3WP, FSPI3HD], + true))); + }; +} +/// This macro can be used to generate code for each peripheral instance of the SPI slave driver. +/// +/// For an explanation on the general syntax, as well as usage of individual/repeated +/// matchers, refer to [the crate-level documentation][crate#for_each-macros]. +/// +/// This macro has one option for its "Individual matcher" case: +/// +/// Syntax: `($instance:ident, $sys:ident, $sclk:ident, $mosi:ident, $miso:ident, $cs:ident)` +/// +/// Macro fragments: +/// +/// - `$instance`: the name of the SPI instance +/// - `$sys`: the name of the instance as it is in the `esp_hal::system::Peripheral` enum. +/// - `$sclk`, `$mosi`, `$miso`, `$cs`: signal names. +/// +/// Example data: `(SPI2, Spi2, FSPICLK, FSPID, FSPIQ, FSPICS0)` +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! for_each_spi_slave { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _for_each_inner_spi_slave { $(($pattern) => $code;)* ($other : tt) + => {} } _for_each_inner_spi_slave!((SPI2)); _for_each_inner_spi_slave!((SPI3)); + _for_each_inner_spi_slave!((SPI2, Spi2, FSPICLK, FSPID, FSPIQ, FSPICS0)); + _for_each_inner_spi_slave!((SPI3, Spi3, FSPI3CLK, FSPI3D, FSPI3Q, FSPI3CS0)); + _for_each_inner_spi_slave!((names(SPI2), (SPI3))); + _for_each_inner_spi_slave!((all(SPI2, Spi2, FSPICLK, FSPID, FSPIQ, FSPICS0), + (SPI3, Spi3, FSPI3CLK, FSPI3D, FSPI3Q, FSPI3CS0))); + }; +} +/// This macro can be used to generate code for each PCNT unit. +/// +/// For an explanation on the general syntax, as well as usage of individual/repeated +/// matchers, refer to [the crate-level documentation][crate#for_each-macros]. +/// +/// This macro has four options for its "Individual matcher" case: +/// +/// - `names`: `($instance:ident)` +/// - `all`: `($peri:ident, $variant:ident, $sys:ident, $regs:ident, $unit:literal, +/// $interrupt:ident, $sig_ch0:ident, $sig_ch1:ident, $ctrl_ch0:ident, $ctrl_ch1:ident)` +/// - `interrupt`: `($interrupt:ident)` (repeated: one ident per unique IRQ) +/// - `regs`: `($regs:ident)` (repeated: one ident per register block) +/// +/// Macro fragments: +/// +/// - `$peri`: unit singleton name (`PCNT0_UNIT0`, `PCNT1_UNIT0`, …) +/// - `$variant`: `AnyPcntUnit` enum variant (`Pcnt0Unit0`, `Pcnt1Unit0`, …) +/// - `$sys`: `esp_hal::system::Peripheral` variant for clocks +/// - `$regs`: register-block singleton (`PCNT`, `PCNT1`) +/// - `$unit`: hardware unit index within that register block +/// - `$interrupt`: shared peripheral interrupt +/// - `$sig_ch0`, `$sig_ch1`, `$ctrl_ch0`, `$ctrl_ch1`: GPIO matrix input signals +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! for_each_pcnt_unit { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _for_each_inner_pcnt_unit { $(($pattern) => $code;)* ($other : tt) + => {} } _for_each_inner_pcnt_unit!((PCNT0_UNIT0)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT2)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT3)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT0, Pcnt0Unit0, Pcnt, PCNT, 0, PCNT, + PCNT0_SIG_CH0, PCNT0_SIG_CH1, PCNT0_CTRL_CH0, PCNT0_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT1, Pcnt0Unit1, Pcnt, PCNT, 1, PCNT, + PCNT1_SIG_CH0, PCNT1_SIG_CH1, PCNT1_CTRL_CH0, PCNT1_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT2, Pcnt0Unit2, Pcnt, PCNT, 2, PCNT, + PCNT2_SIG_CH0, PCNT2_SIG_CH1, PCNT2_CTRL_CH0, PCNT2_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT3, Pcnt0Unit3, Pcnt, PCNT, 3, PCNT, + PCNT3_SIG_CH0, PCNT3_SIG_CH1, PCNT3_CTRL_CH0, PCNT3_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT)); _for_each_inner_pcnt_unit!((PCNT)); + _for_each_inner_pcnt_unit!((names(PCNT0_UNIT0), (PCNT0_UNIT1), (PCNT0_UNIT2), + (PCNT0_UNIT3))); _for_each_inner_pcnt_unit!((all(PCNT0_UNIT0, Pcnt0Unit0, Pcnt, + PCNT, 0, PCNT, PCNT0_SIG_CH0, PCNT0_SIG_CH1, PCNT0_CTRL_CH0, PCNT0_CTRL_CH1), + (PCNT0_UNIT1, Pcnt0Unit1, Pcnt, PCNT, 1, PCNT, PCNT1_SIG_CH0, PCNT1_SIG_CH1, + PCNT1_CTRL_CH0, PCNT1_CTRL_CH1), (PCNT0_UNIT2, Pcnt0Unit2, Pcnt, PCNT, 2, PCNT, + PCNT2_SIG_CH0, PCNT2_SIG_CH1, PCNT2_CTRL_CH0, PCNT2_CTRL_CH1), (PCNT0_UNIT3, + Pcnt0Unit3, Pcnt, PCNT, 3, PCNT, PCNT3_SIG_CH0, PCNT3_SIG_CH1, PCNT3_CTRL_CH0, + PCNT3_CTRL_CH1))); _for_each_inner_pcnt_unit!((interrupt(PCNT))); + _for_each_inner_pcnt_unit!((regs(PCNT))); + }; +} +/// This macro can be used to generate code for each peripheral instance of the CAN FD driver. +/// +/// For an explanation on the general syntax, as well as usage of individual/repeated +/// matchers, refer to [the crate-level documentation][crate#for_each-macros]. +/// +/// This macro has one option for its "Individual matcher" case: +/// +/// Syntax: `($instance:ident, $sys:ident, $rx:ident, $tx:ident)` +/// +/// Macro fragments: +/// +/// - `$instance`: the name of the CAN FD instance +/// - `$sys`: the name of the instance as it is in the `esp_hal::system::Peripheral` enum. +/// - `$rx`, `$tx`: signal names. +/// +/// Example data: `(TWAI0, Twai0, TWAI0_RX, TWAI0_TX)` +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! for_each_canfd { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _for_each_inner_canfd { $(($pattern) => $code;)* ($other : tt) => {} + } _for_each_inner_canfd!((all)); + }; +} +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! for_each_peripheral { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _for_each_inner_peripheral { $(($pattern) => $code;)* ($other : tt) + => {} } _for_each_inner_peripheral!((@ peri_type #[doc = + "GPIO0 peripheral singleton"] GPIO0 <= virtual())); + _for_each_inner_peripheral!((@ peri_type #[doc = "GPIO1 peripheral singleton"] + GPIO1 <= virtual())); _for_each_inner_peripheral!((@ peri_type #[doc = + "GPIO2 peripheral singleton"] GPIO2 <= virtual())); + _for_each_inner_peripheral!((@ peri_type #[doc = "GPIO3 peripheral singleton"] + GPIO3 <= virtual())); _for_each_inner_peripheral!((@ peri_type #[doc = + "GPIO4 peripheral singleton"] GPIO4 <= virtual())); + _for_each_inner_peripheral!((@ peri_type #[doc = "GPIO5 peripheral singleton"] + GPIO5 <= virtual())); _for_each_inner_peripheral!((@ peri_type #[doc = + "GPIO6 peripheral singleton (Limitations exist)"] #[doc = ""] #[doc = + "
"] #[doc = + "This pin may be available with certain limitations. Check your hardware to make sure whether you can use it."] + #[doc = "
    "] #[doc = + "
  • This pin may be reserved for interfacing with SPI flash.
  • "] #[doc = + "
"] #[doc = "
"] GPIO6 <= virtual())); + _for_each_inner_peripheral!((@ peri_type #[doc = + "GPIO7 peripheral singleton (Limitations exist)"] #[doc = ""] #[doc = + "
"] #[doc = + "This pin may be available with certain limitations. Check your hardware to make sure whether you can use it."] + #[doc = "
    "] #[doc = + "
  • This pin may be reserved for interfacing with SPI flash.
  • "] #[doc = + "
"] #[doc = "
"] GPIO7 <= virtual())); + _for_each_inner_peripheral!((@ peri_type #[doc = + "GPIO8 peripheral singleton (Limitations exist)"] #[doc = ""] #[doc = + "
"] #[doc = + "This pin may be available with certain limitations. Check your hardware to make sure whether you can use it."] + #[doc = "
    "] #[doc = + "
  • This pin may be reserved for interfacing with SPI flash.
  • "] #[doc = + "
"] #[doc = "
"] GPIO8 <= virtual())); + _for_each_inner_peripheral!((@ peri_type #[doc = + "GPIO9 peripheral singleton (Limitations exist)"] #[doc = ""] #[doc = + "
"] #[doc = + "This pin may be available with certain limitations. Check your hardware to make sure whether you can use it."] + #[doc = "
    "] #[doc = + "
  • This pin may be reserved for interfacing with SPI flash.
  • "] #[doc = + "
"] #[doc = "
"] GPIO9 <= virtual())); + _for_each_inner_peripheral!((@ peri_type #[doc = + "GPIO10 peripheral singleton (Limitations exist)"] #[doc = ""] #[doc = + "
"] #[doc = + "This pin may be available with certain limitations. Check your hardware to make sure whether you can use it."] + #[doc = "
    "] #[doc = + "
  • This pin may be reserved for interfacing with SPI flash.
  • "] #[doc = + "
"] #[doc = "
"] GPIO10 <= virtual())); + _for_each_inner_peripheral!((@ peri_type #[doc = + "GPIO11 peripheral singleton (Limitations exist)"] #[doc = ""] #[doc = + "
"] #[doc = + "This pin may be available with certain limitations. Check your hardware to make sure whether you can use it."] + #[doc = "
    "] #[doc = + "
  • This pin may be reserved for interfacing with SPI flash.
  • "] #[doc = + "
"] #[doc = "
"] GPIO11 <= virtual())); + _for_each_inner_peripheral!((@ peri_type #[doc = + "GPIO12 peripheral singleton (Limitations exist)"] #[doc = ""] #[doc = + "
"] #[doc = + "This pin may be available with certain limitations. Check your hardware to make sure whether you can use it."] + #[doc = "
    "] #[doc = + "
  • This pin may be reserved for interfacing with SPI flash.
  • "] #[doc = + "
"] #[doc = "
"] GPIO12 <= virtual())); + _for_each_inner_peripheral!((@ peri_type #[doc = + "GPIO13 peripheral singleton (Limitations exist)"] #[doc = ""] #[doc = + "
"] #[doc = + "This pin may be available with certain limitations. Check your hardware to make sure whether you can use it."] + #[doc = "
    "] #[doc = + "
  • These pins may be used to debug the chip using USB.
  • "] #[doc = "
"] + #[doc = "
"] GPIO13 <= virtual())); _for_each_inner_peripheral!((@ + peri_type #[doc = "GPIO14 peripheral singleton (Limitations exist)"] #[doc = ""] + #[doc = "
"] #[doc = + "This pin may be available with certain limitations. Check your hardware to make sure whether you can use it."] + #[doc = "
    "] #[doc = + "
  • These pins may be used to debug the chip using USB.
  • "] #[doc = "
"] + #[doc = "
"] GPIO14 <= virtual())); _for_each_inner_peripheral!((@ + peri_type #[doc = "GPIO15 peripheral singleton"] GPIO15 <= virtual())); + _for_each_inner_peripheral!((@ peri_type #[doc = "GPIO16 peripheral singleton"] + GPIO16 <= virtual())); _for_each_inner_peripheral!((@ peri_type #[doc = + "GPIO17 peripheral singleton"] GPIO17 <= virtual())); + _for_each_inner_peripheral!((@ peri_type #[doc = "GPIO18 peripheral singleton"] + GPIO18 <= virtual())); _for_each_inner_peripheral!((@ peri_type #[doc = + "GPIO19 peripheral singleton"] GPIO19 <= virtual())); + _for_each_inner_peripheral!((@ peri_type #[doc = "GPIO20 peripheral singleton"] + GPIO20 <= virtual())); _for_each_inner_peripheral!((@ peri_type #[doc = + "GPIO21 peripheral singleton"] GPIO21 <= virtual())); + _for_each_inner_peripheral!((@ peri_type #[doc = "GPIO22 peripheral singleton"] + GPIO22 <= virtual())); _for_each_inner_peripheral!((@ peri_type #[doc = + "GPIO23 peripheral singleton (Limitations exist)"] #[doc = ""] #[doc = + "
"] #[doc = + "This pin may be available with certain limitations. Check your hardware to make sure whether you can use it."] + #[doc = "
    "] #[doc = + "
  • By default, this pin is used by the UART programming interface.
  • "] #[doc + = "
"] #[doc = "
"] GPIO23 <= virtual())); + _for_each_inner_peripheral!((@ peri_type #[doc = + "GPIO24 peripheral singleton (Limitations exist)"] #[doc = ""] #[doc = + "
"] #[doc = + "This pin may be available with certain limitations. Check your hardware to make sure whether you can use it."] + #[doc = "
    "] #[doc = + "
  • By default, this pin is used by the UART programming interface.
  • "] #[doc + = "
"] #[doc = "
"] GPIO24 <= virtual())); + _for_each_inner_peripheral!((@ peri_type #[doc = + "GPIO25 peripheral singleton (Limitations exist)"] #[doc = ""] #[doc = + "
"] #[doc = + "This pin may be available with certain limitations. Check your hardware to make sure whether you can use it."] + #[doc = "
    "] #[doc = + "
  • This pin is a strapping pin, it determines how the chip boots.
  • "] #[doc + = "
"] #[doc = "
"] GPIO25 <= virtual())); + _for_each_inner_peripheral!((@ peri_type #[doc = "GPIO26 peripheral singleton"] + GPIO26 <= virtual())); _for_each_inner_peripheral!((@ peri_type #[doc = + "GPIO27 peripheral singleton"] GPIO27 <= virtual())); + _for_each_inner_peripheral!((@ peri_type #[doc = + "GPIO28 peripheral singleton (Limitations exist)"] #[doc = ""] #[doc = + "
"] #[doc = + "This pin may be available with certain limitations. Check your hardware to make sure whether you can use it."] + #[doc = "
    "] #[doc = + "
  • These pins may be used to debug the chip using an external JTAG debugger.
  • "] + #[doc = "
"] #[doc = "
"] GPIO28 <= virtual())); + _for_each_inner_peripheral!((@ peri_type #[doc = + "GPIO29 peripheral singleton (Limitations exist)"] #[doc = ""] #[doc = + "
"] #[doc = + "This pin may be available with certain limitations. Check your hardware to make sure whether you can use it."] + #[doc = "
    "] #[doc = + "
  • These pins may be used to debug the chip using an external JTAG debugger.
  • "] + #[doc = "
"] #[doc = "
"] GPIO29 <= virtual())); + _for_each_inner_peripheral!((@ peri_type #[doc = + "GPIO30 peripheral singleton (Limitations exist)"] #[doc = ""] #[doc = + "
"] #[doc = + "This pin may be available with certain limitations. Check your hardware to make sure whether you can use it."] + #[doc = "
    "] #[doc = + "
  • These pins may be used to debug the chip using an external JTAG debugger.
  • "] + #[doc = "
"] #[doc = "
"] GPIO30 <= virtual())); + _for_each_inner_peripheral!((@ peri_type #[doc = + "GPIO31 peripheral singleton (Limitations exist)"] #[doc = ""] #[doc = + "
"] #[doc = + "This pin may be available with certain limitations. Check your hardware to make sure whether you can use it."] + #[doc = "
    "] #[doc = + "
  • These pins may be used to debug the chip using an external JTAG debugger.
  • "] + #[doc = "
"] #[doc = "
"] GPIO31 <= virtual())); + _for_each_inner_peripheral!((@ peri_type #[doc = "GPIO32 peripheral singleton"] + GPIO32 <= virtual())); _for_each_inner_peripheral!((@ peri_type #[doc = + "GPIO33 peripheral singleton"] GPIO33 <= virtual())); + _for_each_inner_peripheral!((@ peri_type #[doc = "GPIO34 peripheral singleton"] + GPIO34 <= virtual())); _for_each_inner_peripheral!((@ peri_type #[doc = + "GPIO35 peripheral singleton"] GPIO35 <= virtual())); + _for_each_inner_peripheral!((@ peri_type #[doc = + "GPIO36 peripheral singleton (Limitations exist)"] #[doc = ""] #[doc = + "
"] #[doc = + "This pin may be available with certain limitations. Check your hardware to make sure whether you can use it."] + #[doc = "
    "] #[doc = + "
  • This pin is a strapping pin, it determines how the chip boots.
  • "] #[doc + = "
"] #[doc = "
"] GPIO36 <= virtual())); + _for_each_inner_peripheral!((@ peri_type #[doc = "GPIO37 peripheral singleton"] + GPIO37 <= virtual())); _for_each_inner_peripheral!((@ peri_type #[doc = + "GPIO38 peripheral singleton"] GPIO38 <= virtual())); + _for_each_inner_peripheral!((@ peri_type #[doc = "GPIO39 peripheral singleton"] + GPIO39 <= virtual())); _for_each_inner_peripheral!((@ peri_type #[doc = + "DMA_CH0 peripheral singleton"] DMA_CH0 <= virtual(DMA_IN_CH0 : { + bind_dma_in_interrupt, enable_dma_in_interrupt, disable_dma_in_interrupt }, + DMA_OUT_CH0 : { bind_dma_out_interrupt, enable_dma_out_interrupt, + disable_dma_out_interrupt }) (unstable))); _for_each_inner_peripheral!((@ + peri_type #[doc = "DMA_CH1 peripheral singleton"] DMA_CH1 <= virtual(DMA_IN_CH1 : + { bind_dma_in_interrupt, enable_dma_in_interrupt, disable_dma_in_interrupt }, + DMA_OUT_CH1 : { bind_dma_out_interrupt, enable_dma_out_interrupt, + disable_dma_out_interrupt }) (unstable))); _for_each_inner_peripheral!((@ + peri_type #[doc = "DMA_CH2 peripheral singleton"] DMA_CH2 <= virtual(DMA_IN_CH2 : + { bind_dma_in_interrupt, enable_dma_in_interrupt, disable_dma_in_interrupt }, + DMA_OUT_CH2 : { bind_dma_out_interrupt, enable_dma_out_interrupt, + disable_dma_out_interrupt }) (unstable))); _for_each_inner_peripheral!((@ + peri_type #[doc = "DMA_CH3 peripheral singleton"] DMA_CH3 <= virtual(DMA_IN_CH3 : + { bind_dma_in_interrupt, enable_dma_in_interrupt, disable_dma_in_interrupt }, + DMA_OUT_CH3 : { bind_dma_out_interrupt, enable_dma_out_interrupt, + disable_dma_out_interrupt }) (unstable))); _for_each_inner_peripheral!((@ + peri_type #[doc = "DMA_CH4 peripheral singleton"] DMA_CH4 <= virtual(DMA_IN_CH4 : + { bind_dma_in_interrupt, enable_dma_in_interrupt, disable_dma_in_interrupt }, + DMA_OUT_CH4 : { bind_dma_out_interrupt, enable_dma_out_interrupt, + disable_dma_out_interrupt }) (unstable))); _for_each_inner_peripheral!((@ + peri_type #[doc = "AES peripheral singleton"] AES <= AES(AES : { + bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) + (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "APB_SARADC peripheral singleton"] APB_SARADC <= APB_SARADC(APB_ADC : { + bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) + (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "ASRC peripheral singleton"] ASRC <= ASRC(ASRC_CHNL0 : { bind_chnl0_interrupt, + enable_chnl0_interrupt, disable_chnl0_interrupt }, ASRC_CHNL1 : { + bind_chnl1_interrupt, enable_chnl1_interrupt, disable_chnl1_interrupt }) + (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "BUS_MONITOR peripheral singleton"] BUS_MONITOR <= BUS_MONITOR(BUS_MONITOR : { + bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) + (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "CACHE peripheral singleton"] CACHE <= CACHE(CACHE : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }) (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "CLIC peripheral singleton"] + CLIC <= CLIC() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "CLINT peripheral singleton"] CLINT <= CLINT() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "CLINT_OTHER_CORE peripheral singleton"] CLINT_OTHER_CORE <= CLINT_OTHER_CORE() + (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "CPU_APM peripheral singleton"] CPU_APM <= CPU_APM() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "DMA peripheral singleton"] DMA + <= DMA() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "ECC peripheral singleton"] ECC <= ECC(ECC : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }) (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "ECDSA peripheral singleton"] + ECDSA <= ECDSA(ECDSA : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt }) (unstable))); _for_each_inner_peripheral!((@ peri_type + #[doc = "EFUSE peripheral singleton"] EFUSE <= EFUSE() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "ETM peripheral singleton"] ETM + <= SOC_ETM() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "GPIO peripheral singleton"] GPIO <= GPIO() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "GPIO_DEDICATED peripheral singleton"] GPIO_DEDICATED <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "GPIO_SD peripheral singleton"] + GPIO_SD <= GPIO_SD() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc + = "HMAC peripheral singleton"] HMAC <= HMAC() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "HP_APM peripheral singleton"] + HP_APM <= HP_APM() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "HP_SYS peripheral singleton"] HP_SYS <= HP_SYS() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "HUK peripheral singleton"] HUK + <= HUK(HUK : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt + }) (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "I2C_ANA_MST peripheral singleton"] I2C_ANA_MST <= I2C_ANA_MST() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "I2S0 peripheral singleton"] + I2S0 <= I2S0(I2S : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt }) (unstable))); _for_each_inner_peripheral!((@ peri_type + #[doc = "I2C0 peripheral singleton"] I2C0 <= I2C0(I2C_EXT0 : { + bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }))); + _for_each_inner_peripheral!((@ peri_type #[doc = "I2C1 peripheral singleton"] + I2C1 <= I2C1(I2C_EXT1 : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt }))); _for_each_inner_peripheral!((@ peri_type #[doc = + "IEEE802154 peripheral singleton"] IEEE802154 <= IEEE802154(ZB_MAC : { + bind_mac_interrupt, enable_mac_interrupt, disable_mac_interrupt }) (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "INTERRUPT_CORE0 peripheral singleton"] INTERRUPT_CORE0 <= INTERRUPT_CORE0() + (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "INTERRUPT_CORE1 peripheral singleton"] INTERRUPT_CORE1 <= INTERRUPT_CORE1() + (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "INTPRI peripheral singleton"] INTPRI <= INTPRI() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "IO_MUX peripheral singleton"] + IO_MUX <= IO_MUX() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "KEYMNG peripheral singleton"] KEYMNG <= KEYMNG(KM : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }) (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "LEDC peripheral singleton"] + LEDC <= LEDC() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "LPWR peripheral singleton"] LPWR <= LP_CLKRST() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "LP_ANA peripheral singleton"] + LP_ANA <= LP_ANA() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "LP_AON peripheral singleton"] LP_AON <= LP_AON() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "LP_CLKRST peripheral singleton"] LP_CLKRST <= LP_CLKRST() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "LP_GPIO peripheral singleton"] + LP_GPIO <= LP_GPIO() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc + = "LP_IO_MUX peripheral singleton"] LP_IO_MUX <= LP_IO_MUX() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "LP_PERI peripheral singleton"] + LP_PERI <= LP_PERI() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc + = "LP_TEE peripheral singleton"] LP_TEE <= LP_TEE() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "LP_WDT peripheral singleton"] + LP_WDT <= LP_WDT() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "MCPWM0 peripheral singleton"] MCPWM0 <= MCPWM0(MCPWM0 : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }) (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "MCPWM1 peripheral singleton"] + MCPWM1 <= MCPWM1(MCPWM1 : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt }) (unstable))); _for_each_inner_peripheral!((@ peri_type + #[doc = "MEM_MONITOR peripheral singleton"] MEM_MONITOR <= MEM_MONITOR() + (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "MODEM_LPCON peripheral singleton"] MODEM_LPCON <= MODEM_LPCON() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "MODEM_SYSCON peripheral singleton"] MODEM_SYSCON <= MODEM_SYSCON() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "PARL_IO peripheral singleton"] + PARL_IO <= PARL_IO(PARL_IO_RX : { bind_rx_interrupt, enable_rx_interrupt, + disable_rx_interrupt }, PARL_IO_TX : { bind_tx_interrupt, enable_tx_interrupt, + disable_tx_interrupt }) (unstable))); _for_each_inner_peripheral!((@ peri_type + #[doc = "PAU peripheral singleton"] PAU <= PAU(PAU : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }) (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "PCNT peripheral singleton"] + PCNT <= PCNT(PCNT : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt }) (unstable))); _for_each_inner_peripheral!((@ peri_type + #[doc = "PCR peripheral singleton"] PCR <= PCR() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "PMU peripheral singleton"] PMU + <= PMU(PMU : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt + }) (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "PVT peripheral singleton"] PVT <= PVT() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "RMT peripheral singleton"] RMT + <= RMT(RMT : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt + }) (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "RNG peripheral singleton"] RNG <= RNG() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "SHA peripheral singleton"] SHA + <= SHA(SHA : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt + }) (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "RTC_TIMER peripheral singleton"] RTC_TIMER <= LP_TIMER() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "SPI0 peripheral singleton"] + SPI0 <= SPI0() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "SPI1 peripheral singleton"] SPI1 <= SPI1() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "SPI2 peripheral singleton"] + SPI2 <= SPI2(GPSPI2 : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt }))); _for_each_inner_peripheral!((@ peri_type #[doc = + "SPI3 peripheral singleton"] SPI3 <= SPI3(GPSPI3 : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }))); + _for_each_inner_peripheral!((@ peri_type #[doc = "SYSTEM peripheral singleton"] + SYSTEM <= PCR() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "SYSTIMER peripheral singleton"] SYSTIMER <= SYSTIMER() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "TEE peripheral singleton"] TEE + <= TEE() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "TIMG0 peripheral singleton"] TIMG0 <= TIMG0() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "TIMG1 peripheral singleton"] + TIMG1 <= TIMG1() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "TOUCH peripheral singleton"] TOUCH <= TOUCH(TOUCH : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }) (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "TOUCH_AON peripheral singleton"] TOUCH_AON <= TOUCH_AON() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "TWAI0 peripheral singleton"] + TWAI0 <= TWAI0(TWAI0 : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt }, TWAI0_TIMER : { bind_timer_interrupt, + enable_timer_interrupt, disable_timer_interrupt }) (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "UART0 peripheral singleton"] + UART0 <= UART0(UART0 : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt }))); _for_each_inner_peripheral!((@ peri_type #[doc = + "UART1 peripheral singleton"] UART1 <= UART1(UART1 : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }))); + _for_each_inner_peripheral!((@ peri_type #[doc = "UHCI0 peripheral singleton"] + UHCI0 <= UHCI0() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "USB_DEVICE peripheral singleton"] USB_DEVICE <= USB_DEVICE(USB_DEVICE : { + bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) + (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "USB_FS peripheral singleton"] USB_FS <= USB0(USB_OTG11 : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }) (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "USB_WRAP peripheral singleton"] + USB_WRAP <= USB_WRAP() (unstable))); _for_each_inner_peripheral!((@ peri_type + #[doc = "ZERO_DET peripheral singleton"] ZERO_DET <= ZERO_DET(ZERO_DET : { + bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) + (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "ADC1 peripheral singleton"] ADC1 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "BT peripheral singleton"] BT <= + virtual(BT_BB : { bind_bb_interrupt, enable_bb_interrupt, disable_bb_interrupt }, + LP_RTC_BLE_TIMER : { bind_lp_timer_interrupt, enable_lp_timer_interrupt, + disable_lp_timer_interrupt }, BT_MAC : { bind_mac_interrupt, + enable_mac_interrupt, disable_mac_interrupt }) (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "CPU_CTRL peripheral singleton"] + CPU_CTRL <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type + #[doc = "IPC peripheral singleton"] IPC <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "FLASH peripheral singleton"] + FLASH <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "FROM_CPU_INTR0 peripheral singleton"] FROM_CPU_INTR0 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "FROM_CPU_INTR1 peripheral singleton"] FROM_CPU_INTR1 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "FROM_CPU_INTR2 peripheral singleton"] FROM_CPU_INTR2 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "FROM_CPU_INTR3 peripheral singleton"] FROM_CPU_INTR3 <= virtual() (unstable))); + _for_each_inner_peripheral!((GPIO0)); _for_each_inner_peripheral!((GPIO1)); + _for_each_inner_peripheral!((GPIO2)); _for_each_inner_peripheral!((GPIO3)); + _for_each_inner_peripheral!((#[cfg(not(use_xtal32k))] GPIO4)); + _for_each_inner_peripheral!((#[cfg(not(use_xtal32k))] GPIO5)); + _for_each_inner_peripheral!((GPIO6)); _for_each_inner_peripheral!((GPIO7)); + _for_each_inner_peripheral!((GPIO8)); _for_each_inner_peripheral!((GPIO9)); + _for_each_inner_peripheral!((GPIO10)); _for_each_inner_peripheral!((GPIO11)); + _for_each_inner_peripheral!((GPIO12)); _for_each_inner_peripheral!((GPIO13)); + _for_each_inner_peripheral!((GPIO14)); _for_each_inner_peripheral!((GPIO15)); + _for_each_inner_peripheral!((GPIO16)); _for_each_inner_peripheral!((GPIO17)); + _for_each_inner_peripheral!((GPIO18)); _for_each_inner_peripheral!((GPIO19)); + _for_each_inner_peripheral!((GPIO20)); _for_each_inner_peripheral!((GPIO21)); + _for_each_inner_peripheral!((GPIO22)); _for_each_inner_peripheral!((GPIO23)); + _for_each_inner_peripheral!((GPIO24)); _for_each_inner_peripheral!((GPIO25)); + _for_each_inner_peripheral!((GPIO26)); _for_each_inner_peripheral!((GPIO27)); + _for_each_inner_peripheral!((GPIO28)); _for_each_inner_peripheral!((GPIO29)); + _for_each_inner_peripheral!((GPIO30)); _for_each_inner_peripheral!((GPIO31)); + _for_each_inner_peripheral!((GPIO32)); _for_each_inner_peripheral!((GPIO33)); + _for_each_inner_peripheral!((GPIO34)); _for_each_inner_peripheral!((GPIO35)); + _for_each_inner_peripheral!((GPIO36)); _for_each_inner_peripheral!((GPIO37)); + _for_each_inner_peripheral!((GPIO38)); _for_each_inner_peripheral!((GPIO39)); + _for_each_inner_peripheral!((DMA_CH0(unstable))); + _for_each_inner_peripheral!((DMA_CH1(unstable))); + _for_each_inner_peripheral!((DMA_CH2(unstable))); + _for_each_inner_peripheral!((DMA_CH3(unstable))); + _for_each_inner_peripheral!((DMA_CH4(unstable))); + _for_each_inner_peripheral!((AES(unstable))); + _for_each_inner_peripheral!((APB_SARADC(unstable))); + _for_each_inner_peripheral!((ASRC(unstable))); + _for_each_inner_peripheral!((BUS_MONITOR(unstable))); + _for_each_inner_peripheral!((CACHE(unstable))); + _for_each_inner_peripheral!((CLIC(unstable))); + _for_each_inner_peripheral!((CLINT(unstable))); + _for_each_inner_peripheral!((CLINT_OTHER_CORE(unstable))); + _for_each_inner_peripheral!((CPU_APM(unstable))); + _for_each_inner_peripheral!((DMA(unstable))); + _for_each_inner_peripheral!((ECC(unstable))); + _for_each_inner_peripheral!((ECDSA(unstable))); + _for_each_inner_peripheral!((ETM(unstable))); + _for_each_inner_peripheral!((GPIO(unstable))); + _for_each_inner_peripheral!((GPIO_DEDICATED(unstable))); + _for_each_inner_peripheral!((GPIO_SD(unstable))); + _for_each_inner_peripheral!((HMAC(unstable))); + _for_each_inner_peripheral!((HP_APM(unstable))); + _for_each_inner_peripheral!((HP_SYS(unstable))); + _for_each_inner_peripheral!((HUK(unstable))); + _for_each_inner_peripheral!((I2C_ANA_MST(unstable))); + _for_each_inner_peripheral!((I2S0(unstable))); + _for_each_inner_peripheral!((I2C0)); _for_each_inner_peripheral!((I2C1)); + _for_each_inner_peripheral!((IEEE802154(unstable))); + _for_each_inner_peripheral!((INTERRUPT_CORE0(unstable))); + _for_each_inner_peripheral!((INTERRUPT_CORE1(unstable))); + _for_each_inner_peripheral!((INTPRI(unstable))); + _for_each_inner_peripheral!((IO_MUX(unstable))); + _for_each_inner_peripheral!((KEYMNG(unstable))); + _for_each_inner_peripheral!((LEDC(unstable))); + _for_each_inner_peripheral!((LPWR(unstable))); + _for_each_inner_peripheral!((LP_ANA(unstable))); + _for_each_inner_peripheral!((LP_AON(unstable))); + _for_each_inner_peripheral!((LP_CLKRST(unstable))); + _for_each_inner_peripheral!((LP_GPIO(unstable))); + _for_each_inner_peripheral!((LP_IO_MUX(unstable))); + _for_each_inner_peripheral!((LP_PERI(unstable))); + _for_each_inner_peripheral!((LP_TEE(unstable))); + _for_each_inner_peripheral!((LP_WDT(unstable))); + _for_each_inner_peripheral!((MCPWM0(unstable))); + _for_each_inner_peripheral!((MCPWM1(unstable))); + _for_each_inner_peripheral!((MEM_MONITOR(unstable))); + _for_each_inner_peripheral!((MODEM_LPCON(unstable))); + _for_each_inner_peripheral!((MODEM_SYSCON(unstable))); + _for_each_inner_peripheral!((PARL_IO(unstable))); + _for_each_inner_peripheral!((PAU(unstable))); + _for_each_inner_peripheral!((PCNT(unstable))); + _for_each_inner_peripheral!((PCR(unstable))); + _for_each_inner_peripheral!((PMU(unstable))); + _for_each_inner_peripheral!((PVT(unstable))); + _for_each_inner_peripheral!((RMT(unstable))); + _for_each_inner_peripheral!((RNG(unstable))); + _for_each_inner_peripheral!((SHA(unstable))); + _for_each_inner_peripheral!((RTC_TIMER(unstable))); + _for_each_inner_peripheral!((SPI0(unstable))); + _for_each_inner_peripheral!((SPI1(unstable))); + _for_each_inner_peripheral!((SPI2)); _for_each_inner_peripheral!((SPI3)); + _for_each_inner_peripheral!((SYSTEM(unstable))); + _for_each_inner_peripheral!((SYSTIMER(unstable))); + _for_each_inner_peripheral!((TEE(unstable))); + _for_each_inner_peripheral!((TIMG0(unstable))); + _for_each_inner_peripheral!((TIMG1(unstable))); + _for_each_inner_peripheral!((TOUCH(unstable))); + _for_each_inner_peripheral!((TOUCH_AON(unstable))); + _for_each_inner_peripheral!((TWAI0(unstable))); + _for_each_inner_peripheral!((UART0)); _for_each_inner_peripheral!((UART1)); + _for_each_inner_peripheral!((UHCI0(unstable))); + _for_each_inner_peripheral!((USB_DEVICE(unstable))); + _for_each_inner_peripheral!((USB_FS(unstable))); + _for_each_inner_peripheral!((ZERO_DET(unstable))); + _for_each_inner_peripheral!((ADC1(unstable))); + _for_each_inner_peripheral!((BT(unstable))); + _for_each_inner_peripheral!((CPU_CTRL(unstable))); + _for_each_inner_peripheral!((IPC(unstable))); + _for_each_inner_peripheral!((FLASH(unstable))); + _for_each_inner_peripheral!((FROM_CPU_INTR0(unstable))); + _for_each_inner_peripheral!((FROM_CPU_INTR1(unstable))); + _for_each_inner_peripheral!((FROM_CPU_INTR2(unstable))); + _for_each_inner_peripheral!((FROM_CPU_INTR3(unstable))); + _for_each_inner_peripheral!((SPI3, Spi3, 0, AhbGdmaChannel)); + _for_each_inner_peripheral!((SPI2, Spi2, 1, AhbGdmaChannel)); + _for_each_inner_peripheral!((UHCI0, Uhci0, 2, AhbGdmaChannel)); + _for_each_inner_peripheral!((I2S0, I2s0, 3, AhbGdmaChannel)); + _for_each_inner_peripheral!((AES, Aes, 4, AhbGdmaChannel)); + _for_each_inner_peripheral!((SHA, Sha, 7, AhbGdmaChannel)); + _for_each_inner_peripheral!((PARL_IO, ParlIo, 9, AhbGdmaChannel)); + _for_each_inner_peripheral!((all(@ peri_type #[doc = + "GPIO0 peripheral singleton"] GPIO0 <= virtual()), (@ peri_type #[doc = + "GPIO1 peripheral singleton"] GPIO1 <= virtual()), (@ peri_type #[doc = + "GPIO2 peripheral singleton"] GPIO2 <= virtual()), (@ peri_type #[doc = + "GPIO3 peripheral singleton"] GPIO3 <= virtual()), (@ peri_type #[doc = + "GPIO4 peripheral singleton"] GPIO4 <= virtual()), (@ peri_type #[doc = + "GPIO5 peripheral singleton"] GPIO5 <= virtual()), (@ peri_type #[doc = + "GPIO6 peripheral singleton (Limitations exist)"] #[doc = ""] #[doc = + "
"] #[doc = + "This pin may be available with certain limitations. Check your hardware to make sure whether you can use it."] + #[doc = "
    "] #[doc = + "
  • This pin may be reserved for interfacing with SPI flash.
  • "] #[doc = + "
"] #[doc = "
"] GPIO6 <= virtual()), (@ peri_type #[doc = + "GPIO7 peripheral singleton (Limitations exist)"] #[doc = ""] #[doc = + "
"] #[doc = + "This pin may be available with certain limitations. Check your hardware to make sure whether you can use it."] + #[doc = "
    "] #[doc = + "
  • This pin may be reserved for interfacing with SPI flash.
  • "] #[doc = + "
"] #[doc = "
"] GPIO7 <= virtual()), (@ peri_type #[doc = + "GPIO8 peripheral singleton (Limitations exist)"] #[doc = ""] #[doc = + "
"] #[doc = + "This pin may be available with certain limitations. Check your hardware to make sure whether you can use it."] + #[doc = "
    "] #[doc = + "
  • This pin may be reserved for interfacing with SPI flash.
  • "] #[doc = + "
"] #[doc = "
"] GPIO8 <= virtual()), (@ peri_type #[doc = + "GPIO9 peripheral singleton (Limitations exist)"] #[doc = ""] #[doc = + "
"] #[doc = + "This pin may be available with certain limitations. Check your hardware to make sure whether you can use it."] + #[doc = "
    "] #[doc = + "
  • This pin may be reserved for interfacing with SPI flash.
  • "] #[doc = + "
"] #[doc = "
"] GPIO9 <= virtual()), (@ peri_type #[doc = + "GPIO10 peripheral singleton (Limitations exist)"] #[doc = ""] #[doc = + "
"] #[doc = + "This pin may be available with certain limitations. Check your hardware to make sure whether you can use it."] + #[doc = "
    "] #[doc = + "
  • This pin may be reserved for interfacing with SPI flash.
  • "] #[doc = + "
"] #[doc = "
"] GPIO10 <= virtual()), (@ peri_type #[doc = + "GPIO11 peripheral singleton (Limitations exist)"] #[doc = ""] #[doc = + "
"] #[doc = + "This pin may be available with certain limitations. Check your hardware to make sure whether you can use it."] + #[doc = "
    "] #[doc = + "
  • This pin may be reserved for interfacing with SPI flash.
  • "] #[doc = + "
"] #[doc = "
"] GPIO11 <= virtual()), (@ peri_type #[doc = + "GPIO12 peripheral singleton (Limitations exist)"] #[doc = ""] #[doc = + "
"] #[doc = + "This pin may be available with certain limitations. Check your hardware to make sure whether you can use it."] + #[doc = "
    "] #[doc = + "
  • This pin may be reserved for interfacing with SPI flash.
  • "] #[doc = + "
"] #[doc = "
"] GPIO12 <= virtual()), (@ peri_type #[doc = + "GPIO13 peripheral singleton (Limitations exist)"] #[doc = ""] #[doc = + "
"] #[doc = + "This pin may be available with certain limitations. Check your hardware to make sure whether you can use it."] + #[doc = "
    "] #[doc = + "
  • These pins may be used to debug the chip using USB.
  • "] #[doc = "
"] + #[doc = "
"] GPIO13 <= virtual()), (@ peri_type #[doc = + "GPIO14 peripheral singleton (Limitations exist)"] #[doc = ""] #[doc = + "
"] #[doc = + "This pin may be available with certain limitations. Check your hardware to make sure whether you can use it."] + #[doc = "
    "] #[doc = + "
  • These pins may be used to debug the chip using USB.
  • "] #[doc = "
"] + #[doc = "
"] GPIO14 <= virtual()), (@ peri_type #[doc = + "GPIO15 peripheral singleton"] GPIO15 <= virtual()), (@ peri_type #[doc = + "GPIO16 peripheral singleton"] GPIO16 <= virtual()), (@ peri_type #[doc = + "GPIO17 peripheral singleton"] GPIO17 <= virtual()), (@ peri_type #[doc = + "GPIO18 peripheral singleton"] GPIO18 <= virtual()), (@ peri_type #[doc = + "GPIO19 peripheral singleton"] GPIO19 <= virtual()), (@ peri_type #[doc = + "GPIO20 peripheral singleton"] GPIO20 <= virtual()), (@ peri_type #[doc = + "GPIO21 peripheral singleton"] GPIO21 <= virtual()), (@ peri_type #[doc = + "GPIO22 peripheral singleton"] GPIO22 <= virtual()), (@ peri_type #[doc = + "GPIO23 peripheral singleton (Limitations exist)"] #[doc = ""] #[doc = + "
"] #[doc = + "This pin may be available with certain limitations. Check your hardware to make sure whether you can use it."] + #[doc = "
    "] #[doc = + "
  • By default, this pin is used by the UART programming interface.
  • "] #[doc + = "
"] #[doc = "
"] GPIO23 <= virtual()), (@ peri_type #[doc = + "GPIO24 peripheral singleton (Limitations exist)"] #[doc = ""] #[doc = + "
"] #[doc = + "This pin may be available with certain limitations. Check your hardware to make sure whether you can use it."] + #[doc = "
    "] #[doc = + "
  • By default, this pin is used by the UART programming interface.
  • "] #[doc + = "
"] #[doc = "
"] GPIO24 <= virtual()), (@ peri_type #[doc = + "GPIO25 peripheral singleton (Limitations exist)"] #[doc = ""] #[doc = + "
"] #[doc = + "This pin may be available with certain limitations. Check your hardware to make sure whether you can use it."] + #[doc = "
    "] #[doc = + "
  • This pin is a strapping pin, it determines how the chip boots.
  • "] #[doc + = "
"] #[doc = "
"] GPIO25 <= virtual()), (@ peri_type #[doc = + "GPIO26 peripheral singleton"] GPIO26 <= virtual()), (@ peri_type #[doc = + "GPIO27 peripheral singleton"] GPIO27 <= virtual()), (@ peri_type #[doc = + "GPIO28 peripheral singleton (Limitations exist)"] #[doc = ""] #[doc = + "
"] #[doc = + "This pin may be available with certain limitations. Check your hardware to make sure whether you can use it."] + #[doc = "
    "] #[doc = + "
  • These pins may be used to debug the chip using an external JTAG debugger.
  • "] + #[doc = "
"] #[doc = "
"] GPIO28 <= virtual()), (@ peri_type #[doc = + "GPIO29 peripheral singleton (Limitations exist)"] #[doc = ""] #[doc = + "
"] #[doc = + "This pin may be available with certain limitations. Check your hardware to make sure whether you can use it."] + #[doc = "
    "] #[doc = + "
  • These pins may be used to debug the chip using an external JTAG debugger.
  • "] + #[doc = "
"] #[doc = "
"] GPIO29 <= virtual()), (@ peri_type #[doc = + "GPIO30 peripheral singleton (Limitations exist)"] #[doc = ""] #[doc = + "
"] #[doc = + "This pin may be available with certain limitations. Check your hardware to make sure whether you can use it."] + #[doc = "
    "] #[doc = + "
  • These pins may be used to debug the chip using an external JTAG debugger.
  • "] + #[doc = "
"] #[doc = "
"] GPIO30 <= virtual()), (@ peri_type #[doc = + "GPIO31 peripheral singleton (Limitations exist)"] #[doc = ""] #[doc = + "
"] #[doc = + "This pin may be available with certain limitations. Check your hardware to make sure whether you can use it."] + #[doc = "
    "] #[doc = + "
  • These pins may be used to debug the chip using an external JTAG debugger.
  • "] + #[doc = "
"] #[doc = "
"] GPIO31 <= virtual()), (@ peri_type #[doc = + "GPIO32 peripheral singleton"] GPIO32 <= virtual()), (@ peri_type #[doc = + "GPIO33 peripheral singleton"] GPIO33 <= virtual()), (@ peri_type #[doc = + "GPIO34 peripheral singleton"] GPIO34 <= virtual()), (@ peri_type #[doc = + "GPIO35 peripheral singleton"] GPIO35 <= virtual()), (@ peri_type #[doc = + "GPIO36 peripheral singleton (Limitations exist)"] #[doc = ""] #[doc = + "
"] #[doc = + "This pin may be available with certain limitations. Check your hardware to make sure whether you can use it."] + #[doc = "
    "] #[doc = + "
  • This pin is a strapping pin, it determines how the chip boots.
  • "] #[doc + = "
"] #[doc = "
"] GPIO36 <= virtual()), (@ peri_type #[doc = + "GPIO37 peripheral singleton"] GPIO37 <= virtual()), (@ peri_type #[doc = + "GPIO38 peripheral singleton"] GPIO38 <= virtual()), (@ peri_type #[doc = + "GPIO39 peripheral singleton"] GPIO39 <= virtual()), (@ peri_type #[doc = + "DMA_CH0 peripheral singleton"] DMA_CH0 <= virtual(DMA_IN_CH0 : { + bind_dma_in_interrupt, enable_dma_in_interrupt, disable_dma_in_interrupt }, + DMA_OUT_CH0 : { bind_dma_out_interrupt, enable_dma_out_interrupt, + disable_dma_out_interrupt }) (unstable)), (@ peri_type #[doc = + "DMA_CH1 peripheral singleton"] DMA_CH1 <= virtual(DMA_IN_CH1 : { + bind_dma_in_interrupt, enable_dma_in_interrupt, disable_dma_in_interrupt }, + DMA_OUT_CH1 : { bind_dma_out_interrupt, enable_dma_out_interrupt, + disable_dma_out_interrupt }) (unstable)), (@ peri_type #[doc = + "DMA_CH2 peripheral singleton"] DMA_CH2 <= virtual(DMA_IN_CH2 : { + bind_dma_in_interrupt, enable_dma_in_interrupt, disable_dma_in_interrupt }, + DMA_OUT_CH2 : { bind_dma_out_interrupt, enable_dma_out_interrupt, + disable_dma_out_interrupt }) (unstable)), (@ peri_type #[doc = + "DMA_CH3 peripheral singleton"] DMA_CH3 <= virtual(DMA_IN_CH3 : { + bind_dma_in_interrupt, enable_dma_in_interrupt, disable_dma_in_interrupt }, + DMA_OUT_CH3 : { bind_dma_out_interrupt, enable_dma_out_interrupt, + disable_dma_out_interrupt }) (unstable)), (@ peri_type #[doc = + "DMA_CH4 peripheral singleton"] DMA_CH4 <= virtual(DMA_IN_CH4 : { + bind_dma_in_interrupt, enable_dma_in_interrupt, disable_dma_in_interrupt }, + DMA_OUT_CH4 : { bind_dma_out_interrupt, enable_dma_out_interrupt, + disable_dma_out_interrupt }) (unstable)), (@ peri_type #[doc = + "AES peripheral singleton"] AES <= AES(AES : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc + = "APB_SARADC peripheral singleton"] APB_SARADC <= APB_SARADC(APB_ADC : { + bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) + (unstable)), (@ peri_type #[doc = "ASRC peripheral singleton"] ASRC <= + ASRC(ASRC_CHNL0 : { bind_chnl0_interrupt, enable_chnl0_interrupt, + disable_chnl0_interrupt }, ASRC_CHNL1 : { bind_chnl1_interrupt, + enable_chnl1_interrupt, disable_chnl1_interrupt }) (unstable)), (@ peri_type + #[doc = "BUS_MONITOR peripheral singleton"] BUS_MONITOR <= + BUS_MONITOR(BUS_MONITOR : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt }) (unstable)), (@ peri_type #[doc = + "CACHE peripheral singleton"] CACHE <= CACHE(CACHE : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc + = "CLIC peripheral singleton"] CLIC <= CLIC() (unstable)), (@ peri_type #[doc = + "CLINT peripheral singleton"] CLINT <= CLINT() (unstable)), (@ peri_type #[doc = + "CLINT_OTHER_CORE peripheral singleton"] CLINT_OTHER_CORE <= CLINT_OTHER_CORE() + (unstable)), (@ peri_type #[doc = "CPU_APM peripheral singleton"] CPU_APM <= + CPU_APM() (unstable)), (@ peri_type #[doc = "DMA peripheral singleton"] DMA <= + DMA() (unstable)), (@ peri_type #[doc = "ECC peripheral singleton"] ECC <= + ECC(ECC : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) + (unstable)), (@ peri_type #[doc = "ECDSA peripheral singleton"] ECDSA <= + ECDSA(ECDSA : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt }) (unstable)), (@ peri_type #[doc = + "EFUSE peripheral singleton"] EFUSE <= EFUSE() (unstable)), (@ peri_type #[doc = + "ETM peripheral singleton"] ETM <= SOC_ETM() (unstable)), (@ peri_type #[doc = + "GPIO peripheral singleton"] GPIO <= GPIO() (unstable)), (@ peri_type #[doc = + "GPIO_DEDICATED peripheral singleton"] GPIO_DEDICATED <= virtual() (unstable)), + (@ peri_type #[doc = "GPIO_SD peripheral singleton"] GPIO_SD <= GPIO_SD() + (unstable)), (@ peri_type #[doc = "HMAC peripheral singleton"] HMAC <= HMAC() + (unstable)), (@ peri_type #[doc = "HP_APM peripheral singleton"] HP_APM <= + HP_APM() (unstable)), (@ peri_type #[doc = "HP_SYS peripheral singleton"] HP_SYS + <= HP_SYS() (unstable)), (@ peri_type #[doc = "HUK peripheral singleton"] HUK <= + HUK(HUK : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) + (unstable)), (@ peri_type #[doc = "I2C_ANA_MST peripheral singleton"] I2C_ANA_MST + <= I2C_ANA_MST() (unstable)), (@ peri_type #[doc = "I2S0 peripheral singleton"] + I2S0 <= I2S0(I2S : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt }) (unstable)), (@ peri_type #[doc = + "I2C0 peripheral singleton"] I2C0 <= I2C0(I2C_EXT0 : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt })), (@ peri_type #[doc = + "I2C1 peripheral singleton"] I2C1 <= I2C1(I2C_EXT1 : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt })), (@ peri_type #[doc = + "IEEE802154 peripheral singleton"] IEEE802154 <= IEEE802154(ZB_MAC : { + bind_mac_interrupt, enable_mac_interrupt, disable_mac_interrupt }) (unstable)), + (@ peri_type #[doc = "INTERRUPT_CORE0 peripheral singleton"] INTERRUPT_CORE0 <= + INTERRUPT_CORE0() (unstable)), (@ peri_type #[doc = + "INTERRUPT_CORE1 peripheral singleton"] INTERRUPT_CORE1 <= INTERRUPT_CORE1() + (unstable)), (@ peri_type #[doc = "INTPRI peripheral singleton"] INTPRI <= + INTPRI() (unstable)), (@ peri_type #[doc = "IO_MUX peripheral singleton"] IO_MUX + <= IO_MUX() (unstable)), (@ peri_type #[doc = "KEYMNG peripheral singleton"] + KEYMNG <= KEYMNG(KM : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt }) (unstable)), (@ peri_type #[doc = + "LEDC peripheral singleton"] LEDC <= LEDC() (unstable)), (@ peri_type #[doc = + "LPWR peripheral singleton"] LPWR <= LP_CLKRST() (unstable)), (@ peri_type #[doc + = "LP_ANA peripheral singleton"] LP_ANA <= LP_ANA() (unstable)), (@ peri_type + #[doc = "LP_AON peripheral singleton"] LP_AON <= LP_AON() (unstable)), (@ + peri_type #[doc = "LP_CLKRST peripheral singleton"] LP_CLKRST <= LP_CLKRST() + (unstable)), (@ peri_type #[doc = "LP_GPIO peripheral singleton"] LP_GPIO <= + LP_GPIO() (unstable)), (@ peri_type #[doc = "LP_IO_MUX peripheral singleton"] + LP_IO_MUX <= LP_IO_MUX() (unstable)), (@ peri_type #[doc = + "LP_PERI peripheral singleton"] LP_PERI <= LP_PERI() (unstable)), (@ peri_type + #[doc = "LP_TEE peripheral singleton"] LP_TEE <= LP_TEE() (unstable)), (@ + peri_type #[doc = "LP_WDT peripheral singleton"] LP_WDT <= LP_WDT() (unstable)), + (@ peri_type #[doc = "MCPWM0 peripheral singleton"] MCPWM0 <= MCPWM0(MCPWM0 : { + bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) + (unstable)), (@ peri_type #[doc = "MCPWM1 peripheral singleton"] MCPWM1 <= + MCPWM1(MCPWM1 : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt }) (unstable)), (@ peri_type #[doc = + "MEM_MONITOR peripheral singleton"] MEM_MONITOR <= MEM_MONITOR() (unstable)), (@ + peri_type #[doc = "MODEM_LPCON peripheral singleton"] MODEM_LPCON <= + MODEM_LPCON() (unstable)), (@ peri_type #[doc = + "MODEM_SYSCON peripheral singleton"] MODEM_SYSCON <= MODEM_SYSCON() (unstable)), + (@ peri_type #[doc = "PARL_IO peripheral singleton"] PARL_IO <= + PARL_IO(PARL_IO_RX : { bind_rx_interrupt, enable_rx_interrupt, + disable_rx_interrupt }, PARL_IO_TX : { bind_tx_interrupt, enable_tx_interrupt, + disable_tx_interrupt }) (unstable)), (@ peri_type #[doc = + "PAU peripheral singleton"] PAU <= PAU(PAU : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc + = "PCNT peripheral singleton"] PCNT <= PCNT(PCNT : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc + = "PCR peripheral singleton"] PCR <= PCR() (unstable)), (@ peri_type #[doc = + "PMU peripheral singleton"] PMU <= PMU(PMU : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc + = "PVT peripheral singleton"] PVT <= PVT() (unstable)), (@ peri_type #[doc = + "RMT peripheral singleton"] RMT <= RMT(RMT : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc + = "RNG peripheral singleton"] RNG <= RNG() (unstable)), (@ peri_type #[doc = + "SHA peripheral singleton"] SHA <= SHA(SHA : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc + = "RTC_TIMER peripheral singleton"] RTC_TIMER <= LP_TIMER() (unstable)), (@ + peri_type #[doc = "SPI0 peripheral singleton"] SPI0 <= SPI0() (unstable)), (@ + peri_type #[doc = "SPI1 peripheral singleton"] SPI1 <= SPI1() (unstable)), (@ + peri_type #[doc = "SPI2 peripheral singleton"] SPI2 <= SPI2(GPSPI2 : { + bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt })), (@ + peri_type #[doc = "SPI3 peripheral singleton"] SPI3 <= SPI3(GPSPI3 : { + bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt })), (@ + peri_type #[doc = "SYSTEM peripheral singleton"] SYSTEM <= PCR() (unstable)), (@ + peri_type #[doc = "SYSTIMER peripheral singleton"] SYSTIMER <= SYSTIMER() + (unstable)), (@ peri_type #[doc = "TEE peripheral singleton"] TEE <= TEE() + (unstable)), (@ peri_type #[doc = "TIMG0 peripheral singleton"] TIMG0 <= TIMG0() + (unstable)), (@ peri_type #[doc = "TIMG1 peripheral singleton"] TIMG1 <= TIMG1() + (unstable)), (@ peri_type #[doc = "TOUCH peripheral singleton"] TOUCH <= + TOUCH(TOUCH : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt }) (unstable)), (@ peri_type #[doc = + "TOUCH_AON peripheral singleton"] TOUCH_AON <= TOUCH_AON() (unstable)), (@ + peri_type #[doc = "TWAI0 peripheral singleton"] TWAI0 <= TWAI0(TWAI0 : { + bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }, TWAI0_TIMER + : { bind_timer_interrupt, enable_timer_interrupt, disable_timer_interrupt }) + (unstable)), (@ peri_type #[doc = "UART0 peripheral singleton"] UART0 <= + UART0(UART0 : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt })), (@ peri_type #[doc = "UART1 peripheral singleton"] + UART1 <= UART1(UART1 : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt })), (@ peri_type #[doc = "UHCI0 peripheral singleton"] + UHCI0 <= UHCI0() (unstable)), (@ peri_type #[doc = + "USB_DEVICE peripheral singleton"] USB_DEVICE <= USB_DEVICE(USB_DEVICE : { + bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) + (unstable)), (@ peri_type #[doc = "USB_FS peripheral singleton"] USB_FS <= + USB0(USB_OTG11 : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt }) (unstable)), (@ peri_type #[doc = + "USB_WRAP peripheral singleton"] USB_WRAP <= USB_WRAP() (unstable)), (@ peri_type + #[doc = "ZERO_DET peripheral singleton"] ZERO_DET <= ZERO_DET(ZERO_DET : { + bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) + (unstable)), (@ peri_type #[doc = "ADC1 peripheral singleton"] ADC1 <= virtual() + (unstable)), (@ peri_type #[doc = "BT peripheral singleton"] BT <= virtual(BT_BB + : { bind_bb_interrupt, enable_bb_interrupt, disable_bb_interrupt }, + LP_RTC_BLE_TIMER : { bind_lp_timer_interrupt, enable_lp_timer_interrupt, + disable_lp_timer_interrupt }, BT_MAC : { bind_mac_interrupt, + enable_mac_interrupt, disable_mac_interrupt }) (unstable)), (@ peri_type #[doc = + "CPU_CTRL peripheral singleton"] CPU_CTRL <= virtual() (unstable)), (@ peri_type + #[doc = "IPC peripheral singleton"] IPC <= virtual() (unstable)), (@ peri_type + #[doc = "FLASH peripheral singleton"] FLASH <= virtual() (unstable)), (@ + peri_type #[doc = "FROM_CPU_INTR0 peripheral singleton"] FROM_CPU_INTR0 <= + virtual() (unstable)), (@ peri_type #[doc = + "FROM_CPU_INTR1 peripheral singleton"] FROM_CPU_INTR1 <= virtual() (unstable)), + (@ peri_type #[doc = "FROM_CPU_INTR2 peripheral singleton"] FROM_CPU_INTR2 <= + virtual() (unstable)), (@ peri_type #[doc = + "FROM_CPU_INTR3 peripheral singleton"] FROM_CPU_INTR3 <= virtual() (unstable)))); + _for_each_inner_peripheral!((singletons(GPIO0), (GPIO1), (GPIO2), (GPIO3), + (#[cfg(not(use_xtal32k))] GPIO4), (#[cfg(not(use_xtal32k))] GPIO5), (GPIO6), + (GPIO7), (GPIO8), (GPIO9), (GPIO10), (GPIO11), (GPIO12), (GPIO13), (GPIO14), + (GPIO15), (GPIO16), (GPIO17), (GPIO18), (GPIO19), (GPIO20), (GPIO21), (GPIO22), + (GPIO23), (GPIO24), (GPIO25), (GPIO26), (GPIO27), (GPIO28), (GPIO29), (GPIO30), + (GPIO31), (GPIO32), (GPIO33), (GPIO34), (GPIO35), (GPIO36), (GPIO37), (GPIO38), + (GPIO39), (DMA_CH0(unstable)), (DMA_CH1(unstable)), (DMA_CH2(unstable)), + (DMA_CH3(unstable)), (DMA_CH4(unstable)), (AES(unstable)), + (APB_SARADC(unstable)), (ASRC(unstable)), (BUS_MONITOR(unstable)), + (CACHE(unstable)), (CLIC(unstable)), (CLINT(unstable)), + (CLINT_OTHER_CORE(unstable)), (CPU_APM(unstable)), (DMA(unstable)), + (ECC(unstable)), (ECDSA(unstable)), (ETM(unstable)), (GPIO(unstable)), + (GPIO_DEDICATED(unstable)), (GPIO_SD(unstable)), (HMAC(unstable)), + (HP_APM(unstable)), (HP_SYS(unstable)), (HUK(unstable)), (I2C_ANA_MST(unstable)), + (I2S0(unstable)), (I2C0), (I2C1), (IEEE802154(unstable)), + (INTERRUPT_CORE0(unstable)), (INTERRUPT_CORE1(unstable)), (INTPRI(unstable)), + (IO_MUX(unstable)), (KEYMNG(unstable)), (LEDC(unstable)), (LPWR(unstable)), + (LP_ANA(unstable)), (LP_AON(unstable)), (LP_CLKRST(unstable)), + (LP_GPIO(unstable)), (LP_IO_MUX(unstable)), (LP_PERI(unstable)), + (LP_TEE(unstable)), (LP_WDT(unstable)), (MCPWM0(unstable)), (MCPWM1(unstable)), + (MEM_MONITOR(unstable)), (MODEM_LPCON(unstable)), (MODEM_SYSCON(unstable)), + (PARL_IO(unstable)), (PAU(unstable)), (PCNT(unstable)), (PCR(unstable)), + (PMU(unstable)), (PVT(unstable)), (RMT(unstable)), (RNG(unstable)), + (SHA(unstable)), (RTC_TIMER(unstable)), (SPI0(unstable)), (SPI1(unstable)), + (SPI2), (SPI3), (SYSTEM(unstable)), (SYSTIMER(unstable)), (TEE(unstable)), + (TIMG0(unstable)), (TIMG1(unstable)), (TOUCH(unstable)), (TOUCH_AON(unstable)), + (TWAI0(unstable)), (UART0), (UART1), (UHCI0(unstable)), (USB_DEVICE(unstable)), + (USB_FS(unstable)), (ZERO_DET(unstable)), (ADC1(unstable)), (BT(unstable)), + (CPU_CTRL(unstable)), (IPC(unstable)), (FLASH(unstable)), + (FROM_CPU_INTR0(unstable)), (FROM_CPU_INTR1(unstable)), + (FROM_CPU_INTR2(unstable)), (FROM_CPU_INTR3(unstable)))); + _for_each_inner_peripheral!((dma_eligible(SPI3, Spi3, 0, AhbGdmaChannel), (SPI2, + Spi2, 1, AhbGdmaChannel), (UHCI0, Uhci0, 2, AhbGdmaChannel), (I2S0, I2s0, 3, + AhbGdmaChannel), (AES, Aes, 4, AhbGdmaChannel), (SHA, Sha, 7, AhbGdmaChannel), + (PARL_IO, ParlIo, 9, AhbGdmaChannel))); + }; +} +/// This macro can be used to generate code for each `GPIOn` instance. +/// +/// For an explanation on the general syntax, as well as usage of individual/repeated +/// matchers, refer to [the crate-level documentation][crate#for_each-macros]. +/// +/// This macro has one option for its "Individual matcher" case: +/// +/// Syntax: `($n:literal, $gpio:ident ($($digital_input_function:ident => +/// $digital_input_signal:ident)*) ($($digital_output_function:ident => +/// $digital_output_signal:ident)*) ($([$pin_attribute:ident])*))` +/// +/// Macro fragments: +/// +/// - `$n`: the number of the GPIO. For `GPIO0`, `$n` is 0. +/// - `$gpio`: the name of the GPIO. +/// - `$digital_input_function`: the number of the digital function, as an identifier (i.e. for +/// function 0 this is `_0`). +/// - `$digital_input_function`: the name of the digital function, as an identifier. +/// - `$digital_output_function`: the number of the digital function, as an identifier (i.e. for +/// function 0 this is `_0`). +/// - `$digital_output_function`: the name of the digital function, as an identifier. +/// - `$pin_attribute`: `Input` and/or `Output`, marks the possible directions of the GPIO. +/// Bracketed so that they can also be matched as optional fragments. Order is always Input first. +/// +/// Example data: `(0, GPIO0 (_5 => EMAC_TX_CLK) (_1 => CLK_OUT1 _5 => EMAC_TX_CLK) ([Input] +/// [Output]))` +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! for_each_gpio { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _for_each_inner_gpio { $(($pattern) => $code;)* ($other : tt) => {} + } _for_each_inner_gpio!((0, GPIO0() () ([Input] [Output]))); + _for_each_inner_gpio!((1, GPIO1() () ([Input] [Output]))); + _for_each_inner_gpio!((2, GPIO2() () ([Input] [Output]))); + _for_each_inner_gpio!((3, GPIO3() () ([Input] [Output]))); + _for_each_inner_gpio!((4, GPIO4() () ([Input] [Output]))); + _for_each_inner_gpio!((5, GPIO5() () ([Input] [Output]))); + _for_each_inner_gpio!((6, GPIO6() () ([Input] [Output]))); + _for_each_inner_gpio!((7, GPIO7() () ([Input] [Output]))); + _for_each_inner_gpio!((8, GPIO8() () ([Input] [Output]))); + _for_each_inner_gpio!((9, GPIO9() () ([Input] [Output]))); + _for_each_inner_gpio!((10, GPIO10() () ([Input] [Output]))); + _for_each_inner_gpio!((11, GPIO11() () ([Input] [Output]))); + _for_each_inner_gpio!((12, GPIO12() () ([Input] [Output]))); + _for_each_inner_gpio!((13, GPIO13() () ([Input] [Output]))); + _for_each_inner_gpio!((14, GPIO14() () ([Input] [Output]))); + _for_each_inner_gpio!((15, GPIO15(_2 => FSPIQ) (_2 => FSPIQ) ([Input] + [Output]))); _for_each_inner_gpio!((16, GPIO16(_2 => FSPICLK) (_2 => FSPICLK) + ([Input] [Output]))); _for_each_inner_gpio!((17, GPIO17(_2 => FSPID) (_2 => + FSPID) ([Input] [Output]))); _for_each_inner_gpio!((18, GPIO18(_2 => FSPIWP) (_2 + => FSPIWP) ([Input] [Output]))); _for_each_inner_gpio!((19, GPIO19(_2 => FSPIHD) + (_2 => FSPIHD) ([Input] [Output]))); _for_each_inner_gpio!((20, GPIO20(_2 => + FSPICS0) (_2 => FSPICS0) ([Input] [Output]))); _for_each_inner_gpio!((21, + GPIO21() () ([Input] [Output]))); _for_each_inner_gpio!((22, GPIO22() () ([Input] + [Output]))); _for_each_inner_gpio!((23, GPIO23(_0 => U0RXD) () ([Input] + [Output]))); _for_each_inner_gpio!((24, GPIO24() (_0 => U0TXD) ([Input] + [Output]))); _for_each_inner_gpio!((25, GPIO25() () ([Input] [Output]))); + _for_each_inner_gpio!((26, GPIO26() () ([Input] [Output]))); + _for_each_inner_gpio!((27, GPIO27() () ([Input] [Output]))); + _for_each_inner_gpio!((28, GPIO28(_0 => MTMS) () ([Input] [Output]))); + _for_each_inner_gpio!((29, GPIO29(_0 => MTDI) () ([Input] [Output]))); + _for_each_inner_gpio!((30, GPIO30(_0 => MTCK) () ([Input] [Output]))); + _for_each_inner_gpio!((31, GPIO31() (_0 => MTDO) ([Input] [Output]))); + _for_each_inner_gpio!((32, GPIO32(_2 => FSPICLK) (_2 => FSPICLK) ([Input] + [Output]))); _for_each_inner_gpio!((33, GPIO33(_2 => FSPID) (_2 => FSPID) + ([Input] [Output]))); _for_each_inner_gpio!((34, GPIO34() () ([Input] + [Output]))); _for_each_inner_gpio!((35, GPIO35() () ([Input] [Output]))); + _for_each_inner_gpio!((36, GPIO36(_2 => FSPIQ) (_2 => FSPIQ) ([Input] + [Output]))); _for_each_inner_gpio!((37, GPIO37(_2 => FSPIWP) (_2 => FSPIWP) + ([Input] [Output]))); _for_each_inner_gpio!((38, GPIO38(_2 => FSPIHD) (_2 => + FSPIHD) ([Input] [Output]))); _for_each_inner_gpio!((39, GPIO39(_2 => FSPICS0) + (_2 => FSPICS0) ([Input] [Output]))); _for_each_inner_gpio!((all(0, GPIO0() () + ([Input] [Output])), (1, GPIO1() () ([Input] [Output])), (2, GPIO2() () ([Input] + [Output])), (3, GPIO3() () ([Input] [Output])), (4, GPIO4() () ([Input] + [Output])), (5, GPIO5() () ([Input] [Output])), (6, GPIO6() () ([Input] + [Output])), (7, GPIO7() () ([Input] [Output])), (8, GPIO8() () ([Input] + [Output])), (9, GPIO9() () ([Input] [Output])), (10, GPIO10() () ([Input] + [Output])), (11, GPIO11() () ([Input] [Output])), (12, GPIO12() () ([Input] + [Output])), (13, GPIO13() () ([Input] [Output])), (14, GPIO14() () ([Input] + [Output])), (15, GPIO15(_2 => FSPIQ) (_2 => FSPIQ) ([Input] [Output])), (16, + GPIO16(_2 => FSPICLK) (_2 => FSPICLK) ([Input] [Output])), (17, GPIO17(_2 => + FSPID) (_2 => FSPID) ([Input] [Output])), (18, GPIO18(_2 => FSPIWP) (_2 => + FSPIWP) ([Input] [Output])), (19, GPIO19(_2 => FSPIHD) (_2 => FSPIHD) ([Input] + [Output])), (20, GPIO20(_2 => FSPICS0) (_2 => FSPICS0) ([Input] [Output])), (21, + GPIO21() () ([Input] [Output])), (22, GPIO22() () ([Input] [Output])), (23, + GPIO23(_0 => U0RXD) () ([Input] [Output])), (24, GPIO24() (_0 => U0TXD) ([Input] + [Output])), (25, GPIO25() () ([Input] [Output])), (26, GPIO26() () ([Input] + [Output])), (27, GPIO27() () ([Input] [Output])), (28, GPIO28(_0 => MTMS) () + ([Input] [Output])), (29, GPIO29(_0 => MTDI) () ([Input] [Output])), (30, + GPIO30(_0 => MTCK) () ([Input] [Output])), (31, GPIO31() (_0 => MTDO) ([Input] + [Output])), (32, GPIO32(_2 => FSPICLK) (_2 => FSPICLK) ([Input] [Output])), (33, + GPIO33(_2 => FSPID) (_2 => FSPID) ([Input] [Output])), (34, GPIO34() () ([Input] + [Output])), (35, GPIO35() () ([Input] [Output])), (36, GPIO36(_2 => FSPIQ) (_2 => + FSPIQ) ([Input] [Output])), (37, GPIO37(_2 => FSPIWP) (_2 => FSPIWP) ([Input] + [Output])), (38, GPIO38(_2 => FSPIHD) (_2 => FSPIHD) ([Input] [Output])), (39, + GPIO39(_2 => FSPICS0) (_2 => FSPICS0) ([Input] [Output])))); + }; +} +/// This macro can be used to generate code for each analog function of each GPIO. +/// +/// For an explanation on the general syntax, as well as usage of individual/repeated +/// matchers, refer to [the crate-level documentation][crate#for_each-macros]. +/// +/// This macro has two options for its "Individual matcher" case: +/// +/// - `all`: `($signal:ident, $gpio:ident)` - simple case where you only need identifiers +/// - group: `(($signal:ident, $group:ident $(, $number:literal)+), $gpio:ident)` - expanded signal +/// case, where you need the number(s) of a signal, or the general group to which the signal +/// belongs. For example, in case of `ADC2_CH3` the expanded form looks like `(ADC2_CH3, ADCn_CHm, +/// 2, 3)`. +/// +/// Macro fragments: +/// +/// - `$signal`: the name of the signal. +/// - `$group`: the name of the signal, with numbers replaced by placeholders. For `ADC2_CH3` this +/// is `ADCn_CHm`. +/// - `$number`: the numbers extracted from `$signal`. +/// - `$gpio`: the name of the GPIO. +/// +/// Example data: +/// - `(ADC2_CH5, GPIO12)` +/// - `((ADC2_CH5, ADCn_CHm, 2, 5), GPIO12)` +/// +/// The expanded syntax is only available when the signal has at least one numbered component. +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! for_each_analog_function { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _for_each_inner_analog_function { $(($pattern) => $code;)* ($other : + tt) => {} } _for_each_inner_analog_function!((ZCD0, GPIO0)); + _for_each_inner_analog_function!((ZCD1, GPIO1)); + _for_each_inner_analog_function!((ZCD2, GPIO2)); + _for_each_inner_analog_function!((ZCD3, GPIO3)); + _for_each_inner_analog_function!((XTAL_32K_N, GPIO4)); + _for_each_inner_analog_function!((XTAL_32K_P, GPIO5)); + _for_each_inner_analog_function!((USJ_DM, GPIO13)); + _for_each_inner_analog_function!((USJ_DP, GPIO14)); + _for_each_inner_analog_function!((USB_FS_DM, GPIO21)); + _for_each_inner_analog_function!((USB_FS_DP, GPIO22)); + _for_each_inner_analog_function!((ADC1_CH0, GPIO28)); + _for_each_inner_analog_function!((ADC1_CH1, GPIO29)); + _for_each_inner_analog_function!((ADC1_CH2, GPIO30)); + _for_each_inner_analog_function!((ADC1_CH3, GPIO31)); + _for_each_inner_analog_function!((ADC1_CH4, GPIO32)); + _for_each_inner_analog_function!(((ZCD0, ZCDn, 0), GPIO0)); + _for_each_inner_analog_function!(((ZCD1, ZCDn, 1), GPIO1)); + _for_each_inner_analog_function!(((ZCD2, ZCDn, 2), GPIO2)); + _for_each_inner_analog_function!(((ZCD3, ZCDn, 3), GPIO3)); + _for_each_inner_analog_function!(((ADC1_CH0, ADCn_CHm, 1, 0), GPIO28)); + _for_each_inner_analog_function!(((ADC1_CH1, ADCn_CHm, 1, 1), GPIO29)); + _for_each_inner_analog_function!(((ADC1_CH2, ADCn_CHm, 1, 2), GPIO30)); + _for_each_inner_analog_function!(((ADC1_CH3, ADCn_CHm, 1, 3), GPIO31)); + _for_each_inner_analog_function!(((ADC1_CH4, ADCn_CHm, 1, 4), GPIO32)); + _for_each_inner_analog_function!((all(ZCD0, GPIO0), (ZCD1, GPIO1), (ZCD2, GPIO2), + (ZCD3, GPIO3), (XTAL_32K_N, GPIO4), (XTAL_32K_P, GPIO5), (USJ_DM, GPIO13), + (USJ_DP, GPIO14), (USB_FS_DM, GPIO21), (USB_FS_DP, GPIO22), (ADC1_CH0, GPIO28), + (ADC1_CH1, GPIO29), (ADC1_CH2, GPIO30), (ADC1_CH3, GPIO31), (ADC1_CH4, GPIO32))); + _for_each_inner_analog_function!((ZCDn((ZCD0, ZCDn, 0), GPIO0), ((ZCD1, ZCDn, 1), + GPIO1), ((ZCD2, ZCDn, 2), GPIO2), ((ZCD3, ZCDn, 3), GPIO3))); + _for_each_inner_analog_function!((ADCn_CHm((ADC1_CH0, ADCn_CHm, 1, 0), GPIO28), + ((ADC1_CH1, ADCn_CHm, 1, 1), GPIO29), ((ADC1_CH2, ADCn_CHm, 1, 2), GPIO30), + ((ADC1_CH3, ADCn_CHm, 1, 3), GPIO31), ((ADC1_CH4, ADCn_CHm, 1, 4), GPIO32))); + }; +} +/// This macro can be used to generate code for each LP function of each GPIO. +/// +/// For an explanation on the general syntax, as well as usage of individual/repeated +/// matchers, refer to [the crate-level documentation][crate#for_each-macros]. +/// +/// This macro has two options for its "Individual matcher" case: +/// +/// - `all`: `($signal:ident, $gpio:ident, $af:ident)` - simple case where you only need +/// identifiers, and maybe the function. +/// - group: `(($signal:ident, $group:ident $(, $number:literal)+), $gpio:ident, $af:ident, ($( +/// $lp_input_af:ident => $lp_input_signal:ident )*) ($( $lp_output_af:ident => +/// $lp_output_signal:ident )*))` - expanded signal case, where you need the number(s) of a +/// signal, or the general group to which the signal belongs. Every expanded branch ends with the +/// pad's LP input and output function groups (empty on chips without an LP GPIO matrix). +/// +/// Macro fragments: +/// +/// - `$signal`: the name of the signal. +/// - `$group`: the name of the signal, with numbers replaced by placeholders. For `ADC2_CH3` this +/// is `ADCn_CHm`. +/// - `$number`: the numbers extracted from `$signal`. +/// - `$gpio`: the name of the GPIO. +/// - `$af`: the LP IO MUX function, as an identifier (i.e. for function 0 this is `_0`). This is +/// the name of an `LpFunction` variant, and its number is the value to write to the pad's +/// function select field. +/// - `$lp_input_af`: the LP IO MUX function for an LP peripheral input on this pad. +/// - `$lp_input_signal`: the LP peripheral input signal name. +/// - `$lp_output_af`: the LP IO MUX function for an LP peripheral output on this pad. +/// - `$lp_output_signal`: the LP peripheral output signal name. +/// +/// Example data: +/// - `(LP_GPIO15, GPIO12, _0)` +/// - `((LP_GPIO15, LP_GPIOn, 15), GPIO12, _0, () ())` +/// - `((LP_GPIO14, LP_GPIOn, 14), GPIO14, _1, () (_0 => LP_UART_TXD))` +/// - `((SAR_I2C_SCL_1, SAR_I2C_SCL_n, 1), GPIO2, _3, () ())` +/// +/// The expanded syntax is only available when the signal has at least one numbered component. +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! for_each_lp_function { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _for_each_inner_lp_function { $(($pattern) => $code;)* ($other : tt) + => {} } _for_each_inner_lp_function!((LP_GPIO0, GPIO0, _1)); + _for_each_inner_lp_function!((LP_GPIO1, GPIO1, _1)); + _for_each_inner_lp_function!((LP_GPIO2, GPIO2, _1)); + _for_each_inner_lp_function!((LP_GPIO3, GPIO3, _1)); + _for_each_inner_lp_function!((LP_GPIO4, GPIO4, _1)); + _for_each_inner_lp_function!((LP_GPIO5, GPIO5, _1)); + _for_each_inner_lp_function!(((LP_GPIO0, LP_GPIOn, 0), GPIO0, _1, () ())); + _for_each_inner_lp_function!(((LP_GPIO1, LP_GPIOn, 1), GPIO1, _1, () ())); + _for_each_inner_lp_function!(((LP_GPIO2, LP_GPIOn, 2), GPIO2, _1, () ())); + _for_each_inner_lp_function!(((LP_GPIO3, LP_GPIOn, 3), GPIO3, _1, () ())); + _for_each_inner_lp_function!(((LP_GPIO4, LP_GPIOn, 4), GPIO4, _1, () ())); + _for_each_inner_lp_function!(((LP_GPIO5, LP_GPIOn, 5), GPIO5, _1, () ())); + _for_each_inner_lp_function!((all(LP_GPIO0, GPIO0, _1), (LP_GPIO1, GPIO1, _1), + (LP_GPIO2, GPIO2, _1), (LP_GPIO3, GPIO3, _1), (LP_GPIO4, GPIO4, _1), (LP_GPIO5, + GPIO5, _1))); _for_each_inner_lp_function!((LP_GPIOn((LP_GPIO0, LP_GPIOn, 0), + GPIO0, _1, () ()), ((LP_GPIO1, LP_GPIOn, 1), GPIO1, _1, () ()), ((LP_GPIO2, + LP_GPIOn, 2), GPIO2, _1, () ()), ((LP_GPIO3, LP_GPIOn, 3), GPIO3, _1, () ()), + ((LP_GPIO4, LP_GPIOn, 4), GPIO4, _1, () ()), ((LP_GPIO5, LP_GPIOn, 5), GPIO5, _1, + () ()))); + }; +} +/// This macro can be used to generate code for each IOMUX digital function of each GPIO. +/// +/// IOMUX functions are the alternate digital functions configured via the IO_MUX registers. +/// Use this to implement signal-specific traits for peripherals whose pins must bypass the +/// GPIO matrix (e.g., EMAC, USB). +/// +/// For an explanation on the general syntax, as well as usage of individual/repeated +/// matchers, refer to [the crate-level documentation][crate#for_each-macros]. +/// +/// This macro has two options for its "Individual matcher" case: +/// +/// - `all`: `($signal:ident, $gpio:ident, $af:ident)` - simple case where you only need +/// identifiers, and maybe the alternate function. +/// - group: `(($signal:ident, $group:ident $(, $number:literal)+), $gpio:ident, $af:ident)` - +/// expanded signal case, where you need the number(s) of a signal, or the general group to which +/// the signal belongs. +/// +/// Macro fragments: +/// +/// - `$signal`: the name of the signal. +/// - `$group`: the name of the signal, with numbers replaced by placeholders. +/// - `$number`: the numbers extracted from `$signal`. +/// - `$gpio`: the name of the GPIO. +/// - `$af`: the alternate function number, as an identifier (e.g. `_5`). +/// +/// Example data: +/// - `(EMAC_RXD0, GPIO25, _5)` +/// - `((EMAC_RXDn, EMAC_RXDn, 0), GPIO25, _5)` +/// +/// The expanded syntax is only available when the signal has at least one numbered component. +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! for_each_iomux_function { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _for_each_inner_iomux_function { $(($pattern) => $code;)* ($other : + tt) => {} } _for_each_inner_iomux_function!((FSPIQ, GPIO15, _2)); + _for_each_inner_iomux_function!((FSPICLK, GPIO16, _2)); + _for_each_inner_iomux_function!((FSPID, GPIO17, _2)); + _for_each_inner_iomux_function!((FSPIWP, GPIO18, _2)); + _for_each_inner_iomux_function!((FSPIHD, GPIO19, _2)); + _for_each_inner_iomux_function!((FSPICS0, GPIO20, _2)); + _for_each_inner_iomux_function!((U0RXD, GPIO23, _0)); + _for_each_inner_iomux_function!((U0TXD, GPIO24, _0)); + _for_each_inner_iomux_function!((MTMS, GPIO28, _0)); + _for_each_inner_iomux_function!((MTDI, GPIO29, _0)); + _for_each_inner_iomux_function!((MTCK, GPIO30, _0)); + _for_each_inner_iomux_function!((MTDO, GPIO31, _0)); + _for_each_inner_iomux_function!((FSPICLK, GPIO32, _2)); + _for_each_inner_iomux_function!((FSPID, GPIO33, _2)); + _for_each_inner_iomux_function!((FSPIQ, GPIO36, _2)); + _for_each_inner_iomux_function!((FSPIWP, GPIO37, _2)); + _for_each_inner_iomux_function!((FSPIHD, GPIO38, _2)); + _for_each_inner_iomux_function!((FSPICS0, GPIO39, _2)); + _for_each_inner_iomux_function!(((FSPICS0, FSPICSn, 0), GPIO20, _2)); + _for_each_inner_iomux_function!(((FSPICS0, FSPICSn, 0), GPIO39, _2)); + _for_each_inner_iomux_function!((all(FSPIQ, GPIO15, _2), (FSPICLK, GPIO16, _2), + (FSPID, GPIO17, _2), (FSPIWP, GPIO18, _2), (FSPIHD, GPIO19, _2), (FSPICS0, + GPIO20, _2), (U0RXD, GPIO23, _0), (U0TXD, GPIO24, _0), (MTMS, GPIO28, _0), (MTDI, + GPIO29, _0), (MTCK, GPIO30, _0), (MTDO, GPIO31, _0), (FSPICLK, GPIO32, _2), + (FSPID, GPIO33, _2), (FSPIQ, GPIO36, _2), (FSPIWP, GPIO37, _2), (FSPIHD, GPIO38, + _2), (FSPICS0, GPIO39, _2))); _for_each_inner_iomux_function!((FSPICSn((FSPICS0, + FSPICSn, 0), GPIO20, _2), ((FSPICS0, FSPICSn, 0), GPIO39, _2))); + }; +} +/// Returns the name of the GPIO that provides the given signal, as a string. +/// +/// The macro takes the name of a direct function - a digital IO MUX function, an analog +/// function, or an LP IO MUX function - and expands to a string literal like `"GPIO4"`. It +/// is meant to keep documentation free of per-chip pin lists. +/// +/// Signals that are not wired to a pad on this chip have to be routed through the GPIO +/// matrix, which can reach any pad. The macro has no pad to return for those, so it accepts +/// an optional fallback to expand to instead. The fallback is not validated. +/// +/// If multiple pads provide the signal, the macro returns one that is not reserved for some +/// other purpose, such as booting or interfacing with flash. +/// +/// Example usage: +/// - `gpio_for_signal!(ADC1_CH0)` +/// - `gpio_for_signal!(LP_I2C_SDA, "GPIO6")` +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! gpio_for_signal { + (ZCD0 $(, $_fallback:literal)?) => { + "GPIO0" + }; + (LP_GPIO0 $(, $_fallback:literal)?) => { + "GPIO0" + }; + (ZCD1 $(, $_fallback:literal)?) => { + "GPIO1" + }; + (LP_GPIO1 $(, $_fallback:literal)?) => { + "GPIO1" + }; + (ZCD2 $(, $_fallback:literal)?) => { + "GPIO2" + }; + (LP_GPIO2 $(, $_fallback:literal)?) => { + "GPIO2" + }; + (ZCD3 $(, $_fallback:literal)?) => { + "GPIO3" + }; + (LP_GPIO3 $(, $_fallback:literal)?) => { + "GPIO3" + }; + (XTAL_32K_N $(, $_fallback:literal)?) => { + "GPIO4" + }; + (LP_GPIO4 $(, $_fallback:literal)?) => { + "GPIO4" + }; + (XTAL_32K_P $(, $_fallback:literal)?) => { + "GPIO5" + }; + (LP_GPIO5 $(, $_fallback:literal)?) => { + "GPIO5" + }; + (USJ_DM $(, $_fallback:literal)?) => { + "GPIO13" + }; + (USJ_DP $(, $_fallback:literal)?) => { + "GPIO14" + }; + (FSPIQ $(, $_fallback:literal)?) => { + "GPIO15" + }; + (FSPICLK $(, $_fallback:literal)?) => { + "GPIO16" + }; + (FSPID $(, $_fallback:literal)?) => { + "GPIO17" + }; + (FSPIWP $(, $_fallback:literal)?) => { + "GPIO18" + }; + (FSPIHD $(, $_fallback:literal)?) => { + "GPIO19" + }; + (FSPICS0 $(, $_fallback:literal)?) => { + "GPIO20" + }; + (USB_FS_DM $(, $_fallback:literal)?) => { + "GPIO21" + }; + (USB_FS_DP $(, $_fallback:literal)?) => { + "GPIO22" + }; + (U0RXD $(, $_fallback:literal)?) => { + "GPIO23" + }; + (U0TXD $(, $_fallback:literal)?) => { + "GPIO24" + }; + (MTMS $(, $_fallback:literal)?) => { + "GPIO28" + }; + (ADC1_CH0 $(, $_fallback:literal)?) => { + "GPIO28" + }; + (MTDI $(, $_fallback:literal)?) => { + "GPIO29" + }; + (ADC1_CH1 $(, $_fallback:literal)?) => { + "GPIO29" + }; + (MTCK $(, $_fallback:literal)?) => { + "GPIO30" + }; + (ADC1_CH2 $(, $_fallback:literal)?) => { + "GPIO30" + }; + (MTDO $(, $_fallback:literal)?) => { + "GPIO31" + }; + (ADC1_CH3 $(, $_fallback:literal)?) => { + "GPIO31" + }; + (ADC1_CH4 $(, $_fallback:literal)?) => { + "GPIO32" + }; + ($_signal:ident, $fallback:literal) => { + $fallback + }; +} +/// Defines the `InputSignal` and `OutputSignal` enums. +/// +/// This macro is intended to be called in esp-hal only. +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! define_io_mux_signals { + () => { + #[allow(non_camel_case_types, clippy::upper_case_acronyms)] + #[derive(Debug, PartialEq, Copy, Clone)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + #[doc(hidden)] + pub enum InputSignal { + EXT_ADC_START = 0, + U0RXD = 8, + U0CTS = 9, + U0DSR = 10, + U1RXD = 11, + U1CTS = 12, + U1DSR = 13, + I2S_MCLK = 14, + I2SO_BCK = 15, + I2SO_WS = 16, + I2SI_SD = 17, + I2SI_BCK = 18, + I2SI_WS = 19, + CPU_GPIO_0 = 29, + CPU_GPIO_1 = 30, + CPU_GPIO_2 = 31, + CPU_GPIO_3 = 32, + CPU_GPIO_4 = 33, + CPU_GPIO_5 = 34, + CPU_GPIO_6 = 35, + CPU_GPIO_7 = 36, + USB_JTAG_TDO_BRIDGE = 37, + USB_FS_IDDIG = 43, + USB_FS_AVALID = 44, + USB_FS_SRP_BVALID = 45, + USB_FS_VBUSVALID = 46, + USB_FS_SRP_SESSEND = 47, + I2CEXT0_SCL = 49, + I2CEXT0_SDA = 50, + PARL_RX_DATA0 = 51, + PARL_RX_DATA1 = 52, + PARL_RX_DATA2 = 53, + PARL_RX_DATA3 = 54, + PARL_RX_DATA4 = 55, + PARL_RX_DATA5 = 56, + PARL_RX_DATA6 = 57, + PARL_RX_DATA7 = 58, + FSPICLK = 59, + FSPIQ = 60, + FSPID = 61, + FSPIHD = 62, + FSPIWP = 63, + FSPICS0 = 64, + PARL_RX_CLK = 65, + PARL_TX_CLK = 66, + RMT_SIG_0 = 67, + RMT_SIG_1 = 68, + TWAI0_RX = 69, + PCNT0_RST = 77, + PCNT1_RST = 78, + PCNT2_RST = 79, + PCNT3_RST = 80, + PWM0_SYNC0 = 81, + PWM0_SYNC1 = 82, + PWM0_SYNC2 = 83, + PWM0_F0 = 84, + PWM0_F1 = 85, + PWM0_F2 = 86, + PWM0_CAP0 = 87, + PWM0_CAP1 = 88, + PWM0_CAP2 = 89, + SIG_IN_FUNC97 = 97, + SIG_IN_FUNC98 = 98, + SIG_IN_FUNC99 = 99, + SIG_IN_FUNC100 = 100, + PCNT0_SIG_CH0 = 102, + PCNT0_SIG_CH1 = 103, + PCNT0_CTRL_CH0 = 104, + PCNT0_CTRL_CH1 = 105, + PCNT1_SIG_CH0 = 106, + PCNT1_SIG_CH1 = 107, + PCNT1_CTRL_CH0 = 108, + PCNT1_CTRL_CH1 = 109, + PCNT2_SIG_CH0 = 110, + PCNT2_SIG_CH1 = 111, + PCNT2_CTRL_CH0 = 112, + PCNT2_CTRL_CH1 = 113, + PCNT3_SIG_CH0 = 114, + PCNT3_SIG_CH1 = 115, + PCNT3_CTRL_CH0 = 116, + PCNT3_CTRL_CH1 = 117, + PWM1_SYNC0 = 155, + PWM1_SYNC1 = 156, + PWM1_SYNC2 = 157, + PWM1_F0 = 158, + PWM1_F1 = 159, + PWM1_F2 = 160, + PWM1_CAP0 = 161, + PWM1_CAP1 = 162, + PWM1_CAP2 = 163, + I2CEXT1_SCL = 164, + I2CEXT1_SDA = 165, + FSPI3CLK = 166, + FSPI3Q = 167, + FSPI3D = 168, + FSPI3HD = 169, + FSPI3WP = 170, + FSPI3CS0 = 171, + CPU_GPIO_8 = 182, + CPU_GPIO_9 = 183, + CPU_GPIO_10 = 184, + CPU_GPIO_11 = 185, + CPU_GPIO_12 = 186, + CPU_GPIO_13 = 187, + CPU_GPIO_14 = 188, + CPU_GPIO_15 = 189, + MTDI, + MTCK, + MTMS, + } + #[allow(non_camel_case_types, clippy::upper_case_acronyms)] + #[derive(Debug, PartialEq, Copy, Clone)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + #[doc(hidden)] + pub enum OutputSignal { + LEDC_LS_SIG0 = 0, + LEDC_LS_SIG1 = 1, + LEDC_LS_SIG2 = 2, + LEDC_LS_SIG3 = 3, + LEDC_LS_SIG4 = 4, + LEDC_LS_SIG5 = 5, + LEDC_LS_SIG6 = 6, + LEDC_LS_SIG7 = 7, + U0TXD = 8, + U0RTS = 9, + U0DTR = 10, + U1TXD = 11, + U1RTS = 12, + U1DTR = 13, + I2S_MCLK = 14, + I2SO_BCK = 15, + I2SO_WS = 16, + I2SO_SD = 17, + I2SI_BCK = 18, + I2SI_WS = 19, + I2SO_SD1 = 20, + CPU_GPIO_0 = 29, + CPU_GPIO_1 = 30, + CPU_GPIO_2 = 31, + CPU_GPIO_3 = 32, + CPU_GPIO_4 = 33, + CPU_GPIO_5 = 34, + CPU_GPIO_6 = 35, + CPU_GPIO_7 = 36, + USB_JTAG_TRST = 37, + USB_SRP_DISCHRGVBUS = 43, + USB_OTG_IDPULLUP = 44, + USB_OTG_DPPULLDOWN = 45, + USB_OTG_DMPULLDOWN = 46, + USB_OTG_DRVVBUS = 47, + USB_SRP_CHRGVBUS = 48, + I2CEXT0_SCL = 49, + I2CEXT0_SDA = 50, + PARL_TX_DATA0 = 51, + PARL_TX_DATA1 = 52, + PARL_TX_DATA2 = 53, + PARL_TX_DATA3 = 54, + PARL_TX_DATA4 = 55, + PARL_TX_DATA5 = 56, + PARL_TX_DATA6 = 57, + PARL_TX_DATA7 = 58, + FSPICLK = 59, + FSPIQ = 60, + FSPID = 61, + FSPIHD = 62, + FSPIWP = 63, + FSPICS0 = 64, + PARL_RX_CLK = 65, + PARL_TX_CLK = 66, + RMT_SIG_0 = 67, + RMT_SIG_1 = 68, + TWAI0_TX = 69, + PARL_TX_CS = 70, + GPIO_SD0 = 77, + GPIO_SD1 = 78, + GPIO_SD2 = 79, + GPIO_SD3 = 80, + PWM0_0A = 81, + PWM0_0B = 82, + PWM0_1A = 83, + PWM0_1B = 84, + PWM0_2A = 85, + PWM0_2B = 86, + CLK_OUT_OUT1 = 94, + CLK_OUT_OUT2 = 95, + CLK_OUT_OUT3 = 96, + SIG_IN_FUNC97 = 97, + SIG_IN_FUNC98 = 98, + SIG_IN_FUNC99 = 99, + SIG_IN_FUNC100 = 100, + FSPICS1 = 102, + FSPICS2 = 103, + FSPICS3 = 104, + FSPICS4 = 105, + FSPICS5 = 106, + ANT_SEL0 = 139, + ANT_SEL1 = 140, + ANT_SEL2 = 141, + ANT_SEL3 = 142, + ANT_SEL4 = 143, + ANT_SEL5 = 144, + ANT_SEL6 = 145, + ANT_SEL7 = 146, + ANT_SEL8 = 147, + ANT_SEL9 = 148, + ANT_SEL10 = 149, + ANT_SEL11 = 150, + ANT_SEL12 = 151, + ANT_SEL13 = 152, + ANT_SEL14 = 153, + ANT_SEL15 = 154, + PWM1_0A = 155, + PWM1_0B = 156, + PWM1_1A = 157, + PWM1_1B = 158, + PWM1_2A = 159, + PWM1_2B = 160, + I2CEXT1_SCL = 164, + I2CEXT1_SDA = 165, + FSPI3CLK = 166, + FSPI3Q = 167, + FSPI3D = 168, + FSPI3HD = 169, + FSPI3WP = 170, + FSPI3CS0 = 171, + FSPI3CS1 = 172, + FSPI3CS2 = 173, + CPU_GPIO_8 = 182, + CPU_GPIO_9 = 183, + CPU_GPIO_10 = 184, + CPU_GPIO_11 = 185, + CPU_GPIO_12 = 186, + CPU_GPIO_13 = 187, + CPU_GPIO_14 = 188, + CPU_GPIO_15 = 189, + GPIO = 256, + MTDO, + } + }; +} +/// Defines the `LpFunction` enum. +/// +/// The enum only contains the LP IO MUX functions that the chip implements. It is +/// empty on chips without an LP IO peripheral. +/// +/// This macro is intended to be called in esp-hal only. +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! define_lp_functions { + () => { + /// LP IO MUX function of a pad. + /// + /// This is the low-power counterpart of `AlternateFunction`: it selects which function + /// drives a pad while the pad belongs to the low-power domain. + #[derive(Debug, Eq, PartialEq, Copy, Clone, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + #[doc(hidden)] + pub enum LpFunction { + /// LP IO MUX function 1. + _1 = 1, + } + impl LpFunction { + /// The function that connects the pad to the LP GPIO peripheral. + pub const LP_GPIO: Self = Self::_1; + } + }; +} +/// Defines and implements the `io_mux_reg` function. +/// +/// The generated function has the following signature: +/// +/// ```rust,ignore +/// pub(crate) fn io_mux_reg(gpio_num: u8) -> &'static crate::pac::io_mux::GPIO0 { +/// // ... +/// # unimplemented!() +/// } +/// ``` +/// +/// This macro is intended to be called in esp-hal only. +#[macro_export] +#[expect(clippy::crate_in_macro_def)] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! define_io_mux_reg { + () => { + pub(crate) fn io_mux_reg(gpio_num: u8) -> &'static crate::pac::io_mux::GPIO { + crate::peripherals::IO_MUX::regs().gpio(gpio_num as usize) + } + }; +} diff --git a/esp-metadata-generated/src/_generated_esp32p4.rs b/esp-metadata-generated/src/_generated_esp32p4.rs index 3beacdc5ddb..5ae929c9760 100644 --- a/esp-metadata-generated/src/_generated_esp32p4.rs +++ b/esp-metadata-generated/src/_generated_esp32p4.rs @@ -88,6 +88,9 @@ macro_rules! property { ("gpio.func_in_sel_offset", str) => { stringify!(1) }; + ("gpio.need_soft_isolate_during_pd") => { + false + }; ("gpio.has_bank_1") => { true }; @@ -247,17 +250,11 @@ macro_rules! property { ("i2s.version", str) => { stringify!(3) }; - ("i2s.default_clock_source") => { - 3 - }; - ("i2s.default_clock_source", str) => { - stringify!(3) - }; ("i2s.mclk_divider_bit_width") => { - 6 + 9 }; ("i2s.mclk_divider_bit_width", str) => { - stringify!(6) + stringify!(9) }; ("i2s.max_ws_width") => { 128 @@ -355,6 +352,48 @@ macro_rules! property { ("ethernet.mii_via_gpio_matrix") => { true }; + ("ethernet.rx_store_and_forward") => { + false + }; + ("ethernet.rx_checksum_offload") => { + true + }; + ("ethernet.tx_checksum_offload") => { + false + }; + ("ethernet.dma_burst_len") => { + 32 + }; + ("ethernet.dma_burst_len", str) => { + stringify!(32) + }; + ("ethernet.has_rgmii") => { + false + }; + ("adc.line_calibration") => { + true + }; + ("adc.curve_calibration") => { + true + }; + ("adc.basic_calibration") => { + true + }; + ("adc.calibration_v1_scheme_supported") => { + true + }; + ("adc.channel_compensation") => { + true + }; + ("adc.pcr_clock") => { + false + }; + ("adc.pcr_sar_clk_div") => { + false + }; + ("adc.sar_power_override") => { + false + }; ("sdm.channel_count") => { 8 }; @@ -367,6 +406,9 @@ macro_rules! property { ("timergroup.timg_has_divcnt_rst") => { true }; + ("timergroup.wdt_has_conf_update") => { + true + }; ("aes.has_split_text_registers") => { true }; @@ -395,10 +437,10 @@ macro_rules! property { stringify!(16) }; ("rng.trng_supported") => { - false + true }; ("rng.is_lp_sys") => { - true + false }; ("rsa.version") => { 3 @@ -473,10 +515,10 @@ macro_rules! property { stringify!(65536) }; ("mmu.entry_num") => { - 512 + 1024 }; ("mmu.entry_num", str) => { - stringify!(512) + stringify!(1024) }; ("psram.octal_spi") => { true @@ -508,6 +550,9 @@ macro_rules! property { ("soc.cpu_has_csr_pc") => { false }; + ("soc.cpu_has_zcmp_workaround") => { + true + }; ("soc.multi_core_enabled") => { true }; @@ -523,6 +568,12 @@ macro_rules! property { ("soc.cpu_mcause_mask", str) => { stringify!(63) }; + ("soc.cpu_pmp_granularity") => { + 128 + }; + ("soc.cpu_pmp_granularity", str) => { + stringify!(128) + }; ("clock_tree.iomux_function_clock.source") => { [crate ::soc::clocks::IomuxFunctionClockSource::XtalClk, crate ::soc::clocks::IomuxFunctionClockSource::PllF80m] @@ -552,16 +603,22 @@ macro_rules! property { ::soc::clocks::LpFastClkConfig::XtalD2] }; ("clock_tree.lp_slow_clk") => { - [crate ::soc::clocks::LpSlowClkConfig::RcSlow, crate + [crate ::soc::clocks::LpSlowClkConfig::RcSlow, #[cfg(use_xtal32k)] crate ::soc::clocks::LpSlowClkConfig::Xtal32k, crate ::soc::clocks::LpSlowClkConfig::OscSlow] }; + ("clock_tree.crypto_clk") => { + [crate ::soc::clocks::CryptoClkConfig::Xtal, crate + ::soc::clocks::CryptoClkConfig::RcFast, crate + ::soc::clocks::CryptoClkConfig::PllF240m, crate + ::soc::clocks::CryptoClkConfig::PllF160m] + }; ("clock_tree.timg_calibration_clock") => { [crate ::soc::clocks::TimgCalibrationClockConfig::MpllClk, crate ::soc::clocks::TimgCalibrationClockConfig::SpllClk, crate ::soc::clocks::TimgCalibrationClockConfig::CpllClk, crate ::soc::clocks::TimgCalibrationClockConfig::RcFastDivClk, crate - ::soc::clocks::TimgCalibrationClockConfig::RcSlowClk, crate + ::soc::clocks::TimgCalibrationClockConfig::RcSlowClk, #[cfg(use_xtal32k)] crate ::soc::clocks::TimgCalibrationClockConfig::Xtal32kClk] }; ("clock_tree.psram.function_clock") => { @@ -611,6 +668,36 @@ macro_rules! property { ::soc::clocks::SpiFunctionClockConfig::RcFast, crate ::soc::clocks::SpiFunctionClockConfig::Spll] }; + ("clock_tree.i2s.tx_clk.sclk") => { + [crate ::soc::clocks::I2sClkSclk::Xtal, crate + ::soc::clocks::I2sClkSclk::PllF160m] + }; + ("clock_tree.i2s.tx_clk.div_num") => { + (1, 255) + }; + ("clock_tree.i2s.tx_clk.div_a") => { + (1, 511) + }; + ("clock_tree.i2s.tx_clk.div_b") => { + (0, 511) + }; + ("clock_tree.i2s.rx_clk.sclk") => { + [crate ::soc::clocks::I2sClkSclk::Xtal, crate + ::soc::clocks::I2sClkSclk::PllF160m] + }; + ("clock_tree.i2s.rx_clk.div_num") => { + (1, 255) + }; + ("clock_tree.i2s.rx_clk.div_a") => { + (1, 511) + }; + ("clock_tree.i2s.rx_clk.div_b") => { + (0, 511) + }; + ("clock_tree.i2s.mclk_out") => { + [crate ::soc::clocks::I2sMclkOutConfig::Tx, crate + ::soc::clocks::I2sMclkOutConfig::Rx] + }; ("clock_tree.mipi_dsi.dpi_clk.sclk") => { [crate ::soc::clocks::MipiDsiDpiClkSclk::Xtal, crate ::soc::clocks::MipiDsiDpiClkSclk::PllF240m, crate @@ -1489,6 +1576,7 @@ macro_rules! for_each_classified_interrupt { ([reserved 5] 6), ([reserved 6] 7), ([reserved 7] 8), ([reserved 8] 9), ([reserved 9] 10), ([reserved 10] 11), ([reserved 11] 12), ([reserved 12] 13), ([reserved 13] 14), ([reserved 14] 15))); + _for_each_inner_classified_interrupt!((context_switch)); }; } #[macro_export] @@ -1571,6 +1659,7 @@ macro_rules! for_each_sw_interrupt { /// /// // XTAL32K_CLK /// +/// #[cfg(use_xtal32k)] /// fn enable_xtal32k_clk_impl(_clocks: &mut ClockTree, _en: bool) { /// todo!() /// } @@ -1623,6 +1712,12 @@ macro_rules! for_each_sw_interrupt { /// todo!() /// } /// +/// // SPLL_D3_CLOCK +/// +/// fn enable_spll_d3_clock_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// /// // IOMUX_FUNCTION_CLOCK /// /// fn configure_iomux_function_clock_impl( @@ -1749,6 +1844,20 @@ macro_rules! for_each_sw_interrupt { /// todo!() /// } /// +/// // CRYPTO_CLK +/// +/// fn enable_crypto_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_crypto_clk_impl( +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: CryptoClkConfig, +/// ) { +/// todo!() +/// } +/// /// // TIMG_CALIBRATION_CLOCK /// /// fn enable_timg_calibration_clock_impl(_clocks: &mut ClockTree, _en: bool) { @@ -1864,6 +1973,52 @@ macro_rules! for_each_sw_interrupt { /// todo!() /// } /// } +/// impl I2sInstance { +/// // I2S_TX_CLK +/// +/// fn enable_tx_clk_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_tx_clk_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: I2sClkConfig, +/// ) { +/// todo!() +/// } +/// +/// // I2S_RX_CLK +/// +/// fn enable_rx_clk_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_rx_clk_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: I2sClkConfig, +/// ) { +/// todo!() +/// } +/// +/// // I2S_MCLK_OUT +/// +/// fn enable_mclk_out_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_mclk_out_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: I2sMclkOutConfig, +/// ) { +/// todo!() +/// } +/// } /// impl MipiDsiInstance { /// // MIPI_DSI_DPI_CLK /// @@ -1979,6 +2134,13 @@ macro_rules! define_clock_tree_types { } #[derive(Clone, Copy, PartialEq, Eq, Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum I2sInstance { + I2s0 = 0, + I2s1 = 1, + I2s2 = 2, + } + #[derive(Clone, Copy, PartialEq, Eq, Debug)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum MipiDsiInstance { MipiDsi = 0, } @@ -2061,10 +2223,10 @@ macro_rules! define_clock_tree_types { ); Self { source, div_num } } - pub(crate) fn source(self) -> IomuxFunctionClockSource { + pub fn source(self) -> IomuxFunctionClockSource { self.source } - pub(crate) fn div_num(self) -> u32 { + pub fn div_num(self) -> u32 { self.div_num as u32 } } @@ -2101,7 +2263,7 @@ macro_rules! define_clock_tree_types { ); Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -2127,7 +2289,7 @@ macro_rules! define_clock_tree_types { ); Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -2153,7 +2315,7 @@ macro_rules! define_clock_tree_types { ); Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -2179,7 +2341,7 @@ macro_rules! define_clock_tree_types { ); Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -2198,11 +2360,25 @@ macro_rules! define_clock_tree_types { pub enum LpSlowClkConfig { /// Selects `RC_SLOW_CLK`. RcSlow, + #[cfg(use_xtal32k)] /// Selects `XTAL32K_CLK`. Xtal32k, /// Selects `OSC_SLOW_CLK`. OscSlow, } + /// The list of clock signals that the `CRYPTO_CLK` multiplexer can output. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum CryptoClkConfig { + /// Selects `XTAL_CLK`. + Xtal, + /// Selects `RC_FAST_CLK`. + RcFast, + /// Selects `PLL_F240M`. + PllF240m, + /// Selects `PLL_F160M`. + PllF160m, + } /// The list of clock signals that the `TIMG_CALIBRATION_CLOCK` multiplexer can output. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] @@ -2217,6 +2393,7 @@ macro_rules! define_clock_tree_types { RcFastDivClk, /// Selects `LP_SLOW_CLK`. RcSlowClk, + #[cfg(use_xtal32k)] /// Selects `XTAL32K_CLK`. Xtal32kClk, } @@ -2278,10 +2455,10 @@ macro_rules! define_clock_tree_types { ); Self { sclk, div_num } } - pub(crate) fn sclk(self) -> UartFunctionClockSclk { + pub fn sclk(self) -> UartFunctionClockSclk { self.sclk } - pub(crate) fn div_num(self) -> u32 { + pub fn div_num(self) -> u32 { self.div_num as u32 } } @@ -2319,10 +2496,10 @@ macro_rules! define_clock_tree_types { integral, } } - pub(crate) fn fractional(self) -> u32 { + pub fn fractional(self) -> u32 { self.fractional as u32 } - pub(crate) fn integral(self) -> u32 { + pub fn integral(self) -> u32 { self.integral as u32 } } @@ -2330,12 +2507,12 @@ macro_rules! define_clock_tree_types { #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum SpiFunctionClockConfig { - #[default] /// Selects `XTAL_CLK`. Xtal, /// Selects `RC_FAST_CLK`. RcFast, - /// Selects `SPLL_CLK`. + #[default] + /// Selects `SPLL_D3_CLOCK`. Spll, } #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] @@ -2370,12 +2547,88 @@ macro_rules! define_clock_tree_types { ); Self { sclk, div_num } } - pub(crate) fn sclk(self) -> I2cFunctionClockSclk { + pub fn sclk(self) -> I2cFunctionClockSclk { + self.sclk + } + pub fn div_num(self) -> u32 { + self.div_num as u32 + } + } + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum I2sClkSclk { + /// Selects `XTAL_CLK`. + Xtal, + #[default] + /// Selects `PLL_F160M`. + PllF160m, + } + /// Configures the `I2S0_TX_CLK` clock node. + /// + /// The output is calculated as `OUTPUT = (sclk * div_a) / (div_num * div_a + div_b)`. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub struct I2sClkConfig { + sclk: I2sClkSclk, + div_num: u32, + div_a: u32, + div_b: u32, + } + impl I2sClkConfig { + /// Creates a new configuration for the TX_CLK clock node. + /// + /// ## Panics + /// + /// Panics if the div_num value is outside the + /// valid range (1 ..= 255). + /// + /// Panics if the div_a value is outside the + /// valid range (1 ..= 511). + /// + /// Panics if the div_b value is outside the + /// valid range (0 ..= 511). + pub const fn new(sclk: I2sClkSclk, div_num: u32, div_a: u32, div_b: u32) -> Self { + ::core::assert!( + div_num >= 1 && div_num <= 255, + "`I2S0_TX_CLK` div_num must be between 1 and 255 (inclusive)." + ); + ::core::assert!( + div_a >= 1 && div_a <= 511, + "`I2S0_TX_CLK` div_a must be between 1 and 511 (inclusive)." + ); + ::core::assert!( + div_b <= 511, + "`I2S0_TX_CLK` div_b must be between 0 and 511 (inclusive)." + ); + Self { + sclk, + div_num, + div_a, + div_b, + } + } + pub fn sclk(self) -> I2sClkSclk { self.sclk } - pub(crate) fn div_num(self) -> u32 { + pub fn div_num(self) -> u32 { self.div_num as u32 } + pub fn div_a(self) -> u32 { + self.div_a as u32 + } + pub fn div_b(self) -> u32 { + self.div_b as u32 + } + } + /// The list of clock signals that the `I2S0_MCLK_OUT` multiplexer can output. + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum I2sMclkOutConfig { + /// Selects `TX_CLK`. + Tx, + #[default] + /// Selects `RX_CLK`. + Rx, } #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] @@ -2411,10 +2664,10 @@ macro_rules! define_clock_tree_types { ); Self { sclk, div_num } } - pub(crate) fn sclk(self) -> MipiDsiDpiClkSclk { + pub fn sclk(self) -> MipiDsiDpiClkSclk { self.sclk } - pub(crate) fn div_num(self) -> u32 { + pub fn div_num(self) -> u32 { self.div_num as u32 } } @@ -2454,10 +2707,10 @@ macro_rules! define_clock_tree_types { ); Self { sclk, div_num } } - pub(crate) fn sclk(self) -> MipiDsiPhyPllRefclkSclk { + pub fn sclk(self) -> MipiDsiPhyPllRefclkSclk { self.sclk } - pub(crate) fn div_num(self) -> u32 { + pub fn div_num(self) -> u32 { self.div_num as u32 } } @@ -2511,6 +2764,7 @@ macro_rules! define_clock_tree_types { apb_clk: Option, lp_fast_clk: Option, lp_slow_clk: Option, + crypto_clk: Option, timg_calibration_clock: Option, timg_function_clock: [Option; 2], timg_wdt_clock: [Option; 2], @@ -2518,6 +2772,9 @@ macro_rules! define_clock_tree_types { uart_baud_rate_generator: [Option; 5], spi_function_clock: [Option; 2], i2c_function_clock: [Option; 2], + i2s_tx_clk: [Option; 3], + i2s_rx_clk: [Option; 3], + i2s_mclk_out: [Option; 3], mipi_dsi_dpi_clk: [Option; 1], mipi_dsi_phy_pll_refclk: [Option; 1], mipi_dsi_phy_cfg_clk: [Option; 1], @@ -2527,13 +2784,18 @@ macro_rules! define_clock_tree_types { spll_clk_refcount: u32, mpll_clk_refcount: u32, rc_fast_clk_refcount: u32, + #[cfg(use_xtal32k)] xtal32k_clk_refcount: u32, rc32k_clk_refcount: u32, pll_f80m_refcount: u32, pll_f120m_refcount: u32, + pll_f160m_refcount: u32, + pll_f240m_refcount: u32, + spll_d3_clock_refcount: u32, pll_f50m_refcount: u32, apb_clk_refcount: u32, lp_fast_clk_refcount: u32, + crypto_clk_refcount: u32, timg_calibration_clock_refcount: u32, sdm_function_clock_refcount: [u32; 1], timg_function_clock_refcount: [u32; 2], @@ -2542,6 +2804,9 @@ macro_rules! define_clock_tree_types { uart_baud_rate_generator_refcount: [u32; 5], spi_function_clock_refcount: [u32; 2], i2c_function_clock_refcount: [u32; 2], + i2s_tx_clk_refcount: [u32; 3], + i2s_rx_clk_refcount: [u32; 3], + i2s_mclk_out_refcount: [u32; 3], mipi_dsi_dpi_clk_refcount: [u32; 1], mipi_dsi_phy_pll_refclk_refcount: [u32; 1], mipi_dsi_phy_cfg_clk_refcount: [u32; 1], @@ -2593,6 +2858,10 @@ macro_rules! define_clock_tree_types { pub fn lp_slow_clk(&self) -> Option { self.lp_slow_clk } + /// Returns the current configuration of the CRYPTO_CLK clock tree node + pub fn crypto_clk(&self) -> Option { + self.crypto_clk + } /// Returns the current configuration of the TIMG_CALIBRATION_CLOCK clock tree node pub fn timg_calibration_clock(&self) -> Option { self.timg_calibration_clock @@ -2669,6 +2938,42 @@ macro_rules! define_clock_tree_types { pub fn i2c1_function_clock(&self) -> Option { self.i2c_function_clock[I2cInstance::I2c1 as usize] } + /// Returns the current configuration of the I2S0_TX_CLK clock tree node + pub fn i2s0_tx_clk(&self) -> Option { + self.i2s_tx_clk[I2sInstance::I2s0 as usize] + } + /// Returns the current configuration of the I2S0_RX_CLK clock tree node + pub fn i2s0_rx_clk(&self) -> Option { + self.i2s_rx_clk[I2sInstance::I2s0 as usize] + } + /// Returns the current configuration of the I2S0_MCLK_OUT clock tree node + pub fn i2s0_mclk_out(&self) -> Option { + self.i2s_mclk_out[I2sInstance::I2s0 as usize] + } + /// Returns the current configuration of the I2S1_TX_CLK clock tree node + pub fn i2s1_tx_clk(&self) -> Option { + self.i2s_tx_clk[I2sInstance::I2s1 as usize] + } + /// Returns the current configuration of the I2S1_RX_CLK clock tree node + pub fn i2s1_rx_clk(&self) -> Option { + self.i2s_rx_clk[I2sInstance::I2s1 as usize] + } + /// Returns the current configuration of the I2S1_MCLK_OUT clock tree node + pub fn i2s1_mclk_out(&self) -> Option { + self.i2s_mclk_out[I2sInstance::I2s1 as usize] + } + /// Returns the current configuration of the I2S2_TX_CLK clock tree node + pub fn i2s2_tx_clk(&self) -> Option { + self.i2s_tx_clk[I2sInstance::I2s2 as usize] + } + /// Returns the current configuration of the I2S2_RX_CLK clock tree node + pub fn i2s2_rx_clk(&self) -> Option { + self.i2s_rx_clk[I2sInstance::I2s2 as usize] + } + /// Returns the current configuration of the I2S2_MCLK_OUT clock tree node + pub fn i2s2_mclk_out(&self) -> Option { + self.i2s_mclk_out[I2sInstance::I2s2 as usize] + } /// Returns the current configuration of the MIPI_DSI_DPI_CLK clock tree node pub fn mipi_dsi_dpi_clk(&self) -> Option { self.mipi_dsi_dpi_clk[MipiDsiInstance::MipiDsi as usize] @@ -2702,6 +3007,7 @@ macro_rules! define_clock_tree_types { apb_clk: None, lp_fast_clk: None, lp_slow_clk: None, + crypto_clk: None, timg_calibration_clock: None, timg_function_clock: [None; 2], timg_wdt_clock: [None; 2], @@ -2709,6 +3015,9 @@ macro_rules! define_clock_tree_types { uart_baud_rate_generator: [None; 5], spi_function_clock: [None; 2], i2c_function_clock: [None; 2], + i2s_tx_clk: [None; 3], + i2s_rx_clk: [None; 3], + i2s_mclk_out: [None; 3], mipi_dsi_dpi_clk: [None; 1], mipi_dsi_phy_pll_refclk: [None; 1], mipi_dsi_phy_cfg_clk: [None; 1], @@ -2718,13 +3027,18 @@ macro_rules! define_clock_tree_types { spll_clk_refcount: 0, mpll_clk_refcount: 0, rc_fast_clk_refcount: 0, + #[cfg(use_xtal32k)] xtal32k_clk_refcount: 0, rc32k_clk_refcount: 0, pll_f80m_refcount: 0, pll_f120m_refcount: 0, + pll_f160m_refcount: 0, + pll_f240m_refcount: 0, + spll_d3_clock_refcount: 0, pll_f50m_refcount: 0, apb_clk_refcount: 0, lp_fast_clk_refcount: 0, + crypto_clk_refcount: 0, timg_calibration_clock_refcount: 0, sdm_function_clock_refcount: [0; 1], timg_function_clock_refcount: [0; 2], @@ -2733,6 +3047,9 @@ macro_rules! define_clock_tree_types { uart_baud_rate_generator_refcount: [0; 5], spi_function_clock_refcount: [0; 2], i2c_function_clock_refcount: [0; 2], + i2s_tx_clk_refcount: [0; 3], + i2s_rx_clk_refcount: [0; 3], + i2s_mclk_out_refcount: [0; 3], mipi_dsi_dpi_clk_refcount: [0; 1], mipi_dsi_phy_pll_refclk_refcount: [0; 1], mipi_dsi_phy_cfg_clk_refcount: [0; 1], @@ -2759,6 +3076,8 @@ macro_rules! define_clock_tree_types { ::core::sync::atomic::AtomicU32::new(0); static LP_SLOW_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); + static CRYPTO_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(0); static TIMG_CALIBRATION_CLOCK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); static TIMG_FUNCTION_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 2] = @@ -2773,6 +3092,12 @@ macro_rules! define_clock_tree_types { [const { ::core::sync::atomic::AtomicU32::new(0) }; 2]; static I2C_FUNCTION_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 2] = [const { ::core::sync::atomic::AtomicU32::new(0) }; 2]; + static I2S_TX_CLK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 3] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 3]; + static I2S_RX_CLK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 3] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 3]; + static I2S_MCLK_OUT_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 3] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 3]; static MIPI_DSI_DPI_CLK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; static MIPI_DSI_PHY_PLL_REFCLK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = @@ -2783,6 +3108,174 @@ macro_rules! define_clock_tree_types { [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; static PSRAM_FUNCTION_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; + /// The clock sources of the device. + /// + /// A clock source is a node of the clock tree that other nodes derive their output + /// from. Ask a node which source it runs on with its `..._root_source` function. + #[derive(Debug, enumset::EnumSetType)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum ClockSource { + /// `XTAL_CLK`. + XtalClk, + /// `RC_FAST_CLK`. + RcFastClk, + #[cfg(use_xtal32k)] + /// `XTAL32K_CLK`. + Xtal32kClk, + /// `OSC_SLOW_CLK`. + OscSlowClk, + /// `RC_SLOW_CLK`. + RcSlowClk, + /// `RC32K_CLK`. + Rc32kClk, + } + /// Returns the clock source that `XTAL_CLK` currently runs on. + pub fn xtal_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::XtalClk) + } + /// Returns the clock source that `CPLL_CLK` currently runs on. + pub fn cpll_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `SPLL_CLK` currently runs on. + pub fn spll_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `MPLL_CLK` currently runs on. + pub fn mpll_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `RC_FAST_CLK` currently runs on. + pub fn rc_fast_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::RcFastClk) + } + #[cfg(use_xtal32k)] + /// Returns the clock source that `XTAL32K_CLK` currently runs on. + pub fn xtal32k_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::Xtal32kClk) + } + /// Returns the clock source that `OSC_SLOW_CLK` currently runs on. + pub fn osc_slow_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::OscSlowClk) + } + /// Returns the clock source that `RC_SLOW_CLK` currently runs on. + pub fn rc_slow_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::RcSlowClk) + } + /// Returns the clock source that `RC32K_CLK` currently runs on. + pub fn rc32k_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::Rc32kClk) + } + /// Returns the clock source that `PLL_F20M` currently runs on. + pub fn pll_f20m_root_source(clocks: &mut ClockTree) -> Option { + spll_clk_root_source(clocks) + } + /// Returns the clock source that `PLL_F80M` currently runs on. + pub fn pll_f80m_root_source(clocks: &mut ClockTree) -> Option { + spll_clk_root_source(clocks) + } + /// Returns the clock source that `PLL_F120M` currently runs on. + pub fn pll_f120m_root_source(clocks: &mut ClockTree) -> Option { + spll_clk_root_source(clocks) + } + /// Returns the clock source that `PLL_F160M` currently runs on. + pub fn pll_f160m_root_source(clocks: &mut ClockTree) -> Option { + spll_clk_root_source(clocks) + } + /// Returns the clock source that `PLL_F240M` currently runs on. + pub fn pll_f240m_root_source(clocks: &mut ClockTree) -> Option { + spll_clk_root_source(clocks) + } + /// Returns the clock source that `SPLL_D3_CLOCK` currently runs on. + pub fn spll_d3_clock_root_source(clocks: &mut ClockTree) -> Option { + spll_clk_root_source(clocks) + } + /// Returns the clock source that `IOMUX_FUNCTION_CLOCK` currently runs on. + pub fn iomux_function_clock_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.iomux_function_clock?; + match config.source() { + IomuxFunctionClockSource::XtalClk => xtal_clk_root_source(clocks), + IomuxFunctionClockSource::PllF80m => pll_f80m_root_source(clocks), + } + } + /// Returns the clock source that `PLL_F25M` currently runs on. + pub fn pll_f25m_root_source(clocks: &mut ClockTree) -> Option { + mpll_clk_root_source(clocks) + } + /// Returns the clock source that `PLL_F50M` currently runs on. + pub fn pll_f50m_root_source(clocks: &mut ClockTree) -> Option { + mpll_clk_root_source(clocks) + } + /// Returns the clock source that `XTAL_D2_CLK` currently runs on. + pub fn xtal_d2_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `CPU_ROOT_CLK` currently runs on. + pub fn cpu_root_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.cpu_root_clk?; + match config { + CpuRootClkConfig::Xtal => xtal_clk_root_source(clocks), + CpuRootClkConfig::Cpll => cpll_clk_root_source(clocks), + CpuRootClkConfig::RcFast => rc_fast_clk_root_source(clocks), + } + } + /// Returns the clock source that `CPU_CLK` currently runs on. + pub fn cpu_clk_root_source(clocks: &mut ClockTree) -> Option { + cpu_root_clk_root_source(clocks) + } + /// Returns the clock source that `MEM_CLK` currently runs on. + pub fn mem_clk_root_source(clocks: &mut ClockTree) -> Option { + cpu_clk_root_source(clocks) + } + /// Returns the clock source that `SYS_CLK` currently runs on. + pub fn sys_clk_root_source(clocks: &mut ClockTree) -> Option { + mem_clk_root_source(clocks) + } + /// Returns the clock source that `APB_CLK` currently runs on. + pub fn apb_clk_root_source(clocks: &mut ClockTree) -> Option { + sys_clk_root_source(clocks) + } + /// Returns the clock source that `LP_FAST_CLK` currently runs on. + pub fn lp_fast_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.lp_fast_clk?; + match config { + LpFastClkConfig::RcFast => rc_fast_clk_root_source(clocks), + LpFastClkConfig::XtalD2 => xtal_d2_clk_root_source(clocks), + } + } + /// Returns the clock source that `LP_SLOW_CLK` currently runs on. + pub fn lp_slow_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.lp_slow_clk?; + match config { + LpSlowClkConfig::RcSlow => rc_slow_clk_root_source(clocks), + #[cfg(use_xtal32k)] + LpSlowClkConfig::Xtal32k => xtal32k_clk_root_source(clocks), + LpSlowClkConfig::OscSlow => osc_slow_clk_root_source(clocks), + } + } + /// Returns the clock source that `CRYPTO_CLK` currently runs on. + pub fn crypto_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.crypto_clk?; + match config { + CryptoClkConfig::Xtal => xtal_clk_root_source(clocks), + CryptoClkConfig::RcFast => rc_fast_clk_root_source(clocks), + CryptoClkConfig::PllF240m => pll_f240m_root_source(clocks), + CryptoClkConfig::PllF160m => pll_f160m_root_source(clocks), + } + } + /// Returns the clock source that `TIMG_CALIBRATION_CLOCK` currently runs on. + pub fn timg_calibration_clock_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.timg_calibration_clock?; + match config { + TimgCalibrationClockConfig::MpllClk => mpll_clk_root_source(clocks), + TimgCalibrationClockConfig::SpllClk => spll_clk_root_source(clocks), + TimgCalibrationClockConfig::CpllClk => cpll_clk_root_source(clocks), + TimgCalibrationClockConfig::RcFastDivClk => rc_fast_clk_root_source(clocks), + TimgCalibrationClockConfig::RcSlowClk => lp_slow_clk_root_source(clocks), + #[cfg(use_xtal32k)] + TimgCalibrationClockConfig::Xtal32kClk => xtal32k_clk_root_source(clocks), + } + } fn request_xtal_clk(_clocks: &mut ClockTree) {} fn release_xtal_clk(_clocks: &mut ClockTree) {} pub fn xtal_clk_frequency() -> u32 { @@ -2812,8 +3305,7 @@ macro_rules! define_clock_tree_types { release_xtal_clk(clocks); } } - #[allow(unused_variables)] - pub fn cpll_clk_config_frequency(clocks: &mut ClockTree, config: CpllClkConfig) -> u32 { + pub fn cpll_clk_config_frequency(config: CpllClkConfig) -> u32 { config.value() } pub fn cpll_clk_frequency() -> u32 { @@ -2868,8 +3360,7 @@ macro_rules! define_clock_tree_types { release_xtal_clk(clocks); } } - #[allow(unused_variables)] - pub fn mpll_clk_config_frequency(clocks: &mut ClockTree, config: MpllClkConfig) -> u32 { + pub fn mpll_clk_config_frequency(config: MpllClkConfig) -> u32 { config.value() } pub fn mpll_clk_frequency() -> u32 { @@ -2892,9 +3383,31 @@ macro_rules! define_clock_tree_types { enable_rc_fast_clk_impl(clocks, false); } } - pub fn rc_fast_clk_frequency() -> u32 { + static RC_FAST_CLK_FREQUENCY: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(rc_fast_clk_nominal_frequency()); + pub const fn rc_fast_clk_nominal_frequency() -> u32 { 20000000 } + pub fn rc_fast_clk_frequency() -> u32 { + RC_FAST_CLK_FREQUENCY.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn set_rc_fast_clk_frequency(clocks: &mut ClockTree, frequency: u32) { + if !(10000000..=30000000).contains(&frequency) { + warn!( + "Ignoring out-of-range RC_FAST_CLK frequency: {} Hz", + frequency + ); + return; + } + debug!( + "Updating RC_FAST_CLK frequency to {} Hz (nominal {} Hz)", + frequency, + rc_fast_clk_nominal_frequency() + ); + RC_FAST_CLK_FREQUENCY.store(frequency, ::core::sync::atomic::Ordering::Release); + refresh_rc_fast_clk_downstream(clocks); + } + #[cfg(use_xtal32k)] pub fn request_xtal32k_clk(clocks: &mut ClockTree) { trace!("Requesting XTAL32K_CLK"); if increment_reference_count(&mut clocks.xtal32k_clk_refcount) { @@ -2902,6 +3415,7 @@ macro_rules! define_clock_tree_types { enable_xtal32k_clk_impl(clocks, true); } } + #[cfg(use_xtal32k)] pub fn release_xtal32k_clk(clocks: &mut ClockTree) { trace!("Releasing XTAL32K_CLK"); if decrement_reference_count(&mut clocks.xtal32k_clk_refcount) { @@ -2909,16 +3423,15 @@ macro_rules! define_clock_tree_types { enable_xtal32k_clk_impl(clocks, false); } } + #[cfg(use_xtal32k)] pub fn xtal32k_clk_frequency() -> u32 { 32768 } pub fn request_osc_slow_clk(clocks: &mut ClockTree) { - trace!("Requesting OSC_SLOW_CLK"); trace!("Enabling OSC_SLOW_CLK"); enable_osc_slow_clk_impl(clocks, true); } pub fn release_osc_slow_clk(clocks: &mut ClockTree) { - trace!("Releasing OSC_SLOW_CLK"); trace!("Disabling OSC_SLOW_CLK"); enable_osc_slow_clk_impl(clocks, false); } @@ -2926,18 +3439,37 @@ macro_rules! define_clock_tree_types { 32768 } pub fn request_rc_slow_clk(clocks: &mut ClockTree) { - trace!("Requesting RC_SLOW_CLK"); trace!("Enabling RC_SLOW_CLK"); enable_rc_slow_clk_impl(clocks, true); } pub fn release_rc_slow_clk(clocks: &mut ClockTree) { - trace!("Releasing RC_SLOW_CLK"); trace!("Disabling RC_SLOW_CLK"); enable_rc_slow_clk_impl(clocks, false); } - pub fn rc_slow_clk_frequency() -> u32 { + static RC_SLOW_CLK_FREQUENCY: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(rc_slow_clk_nominal_frequency()); + pub const fn rc_slow_clk_nominal_frequency() -> u32 { 136000 } + pub fn rc_slow_clk_frequency() -> u32 { + RC_SLOW_CLK_FREQUENCY.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn set_rc_slow_clk_frequency(clocks: &mut ClockTree, frequency: u32) { + if !(68000..=204000).contains(&frequency) { + warn!( + "Ignoring out-of-range RC_SLOW_CLK frequency: {} Hz", + frequency + ); + return; + } + debug!( + "Updating RC_SLOW_CLK frequency to {} Hz (nominal {} Hz)", + frequency, + rc_slow_clk_nominal_frequency() + ); + RC_SLOW_CLK_FREQUENCY.store(frequency, ::core::sync::atomic::Ordering::Release); + refresh_rc_slow_clk_downstream(clocks); + } pub fn request_rc32k_clk(clocks: &mut ClockTree) { trace!("Requesting RC32K_CLK"); if increment_reference_count(&mut clocks.rc32k_clk_refcount) { @@ -2956,13 +3488,11 @@ macro_rules! define_clock_tree_types { 32768 } pub fn request_pll_f20m(clocks: &mut ClockTree) { - trace!("Requesting PLL_F20M"); trace!("Enabling PLL_F20M"); request_spll_clk(clocks); enable_pll_f20m_impl(clocks, true); } pub fn release_pll_f20m(clocks: &mut ClockTree) { - trace!("Releasing PLL_F20M"); trace!("Disabling PLL_F20M"); enable_pll_f20m_impl(clocks, false); release_spll_clk(clocks); @@ -3019,15 +3549,19 @@ macro_rules! define_clock_tree_types { } pub fn request_pll_f160m(clocks: &mut ClockTree) { trace!("Requesting PLL_F160M"); - trace!("Enabling PLL_F160M"); - request_spll_clk(clocks); - enable_pll_f160m_impl(clocks, true); + if increment_reference_count(&mut clocks.pll_f160m_refcount) { + trace!("Enabling PLL_F160M"); + request_spll_clk(clocks); + enable_pll_f160m_impl(clocks, true); + } } pub fn release_pll_f160m(clocks: &mut ClockTree) { trace!("Releasing PLL_F160M"); - trace!("Disabling PLL_F160M"); - enable_pll_f160m_impl(clocks, false); - release_spll_clk(clocks); + if decrement_reference_count(&mut clocks.pll_f160m_refcount) { + trace!("Disabling PLL_F160M"); + enable_pll_f160m_impl(clocks, false); + release_spll_clk(clocks); + } } pub fn pll_f160m_frequency() -> u32 { (spll_clk_frequency() / 3) @@ -3037,15 +3571,19 @@ macro_rules! define_clock_tree_types { } pub fn request_pll_f240m(clocks: &mut ClockTree) { trace!("Requesting PLL_F240M"); - trace!("Enabling PLL_F240M"); - request_spll_clk(clocks); - enable_pll_f240m_impl(clocks, true); + if increment_reference_count(&mut clocks.pll_f240m_refcount) { + trace!("Enabling PLL_F240M"); + request_spll_clk(clocks); + enable_pll_f240m_impl(clocks, true); + } } pub fn release_pll_f240m(clocks: &mut ClockTree) { trace!("Releasing PLL_F240M"); - trace!("Disabling PLL_F240M"); - enable_pll_f240m_impl(clocks, false); - release_spll_clk(clocks); + if decrement_reference_count(&mut clocks.pll_f240m_refcount) { + trace!("Disabling PLL_F240M"); + enable_pll_f240m_impl(clocks, false); + release_spll_clk(clocks); + } } pub fn pll_f240m_frequency() -> u32 { (spll_clk_frequency() / 2) @@ -3053,6 +3591,28 @@ macro_rules! define_clock_tree_types { pub fn pll_f240m_source_frequency() -> u32 { spll_clk_frequency() } + pub fn request_spll_d3_clock(clocks: &mut ClockTree) { + trace!("Requesting SPLL_D3_CLOCK"); + if increment_reference_count(&mut clocks.spll_d3_clock_refcount) { + trace!("Enabling SPLL_D3_CLOCK"); + request_spll_clk(clocks); + enable_spll_d3_clock_impl(clocks, true); + } + } + pub fn release_spll_d3_clock(clocks: &mut ClockTree) { + trace!("Releasing SPLL_D3_CLOCK"); + if decrement_reference_count(&mut clocks.spll_d3_clock_refcount) { + trace!("Disabling SPLL_D3_CLOCK"); + enable_spll_d3_clock_impl(clocks, false); + release_spll_clk(clocks); + } + } + pub fn spll_d3_clock_frequency() -> u32 { + (spll_clk_frequency() / 3) + } + pub fn spll_d3_clock_source_frequency() -> u32 { + spll_clk_frequency() + } pub fn configure_iomux_function_clock( clocks: &mut ClockTree, config: IomuxFunctionClockConfig, @@ -3078,11 +3638,7 @@ macro_rules! define_clock_tree_types { } fn request_iomux_function_clock(_clocks: &mut ClockTree) {} fn release_iomux_function_clock(_clocks: &mut ClockTree) {} - #[allow(unused_variables)] - pub fn iomux_function_clock_config_frequency( - clocks: &mut ClockTree, - config: IomuxFunctionClockConfig, - ) -> u32 { + pub fn iomux_function_clock_config_frequency(config: IomuxFunctionClockConfig) -> u32 { (match config.source { IomuxFunctionClockSource::XtalClk => xtal_clk_frequency(), IomuxFunctionClockSource::PllF80m => pll_f80m_frequency(), @@ -3098,13 +3654,11 @@ macro_rules! define_clock_tree_types { } } pub fn request_pll_f25m(clocks: &mut ClockTree) { - trace!("Requesting PLL_F25M"); trace!("Enabling PLL_F25M"); request_mpll_clk(clocks); enable_pll_f25m_impl(clocks, true); } pub fn release_pll_f25m(clocks: &mut ClockTree) { - trace!("Releasing PLL_F25M"); trace!("Disabling PLL_F25M"); enable_pll_f25m_impl(clocks, false); release_mpll_clk(clocks); @@ -3138,13 +3692,11 @@ macro_rules! define_clock_tree_types { mpll_clk_frequency() } pub fn request_xtal_d2_clk(clocks: &mut ClockTree) { - trace!("Requesting XTAL_D2_CLK"); trace!("Enabling XTAL_D2_CLK"); request_xtal_clk(clocks); enable_xtal_d2_clk_impl(clocks, true); } pub fn release_xtal_d2_clk(clocks: &mut ClockTree) { - trace!("Releasing XTAL_D2_CLK"); trace!("Disabling XTAL_D2_CLK"); enable_xtal_d2_clk_impl(clocks, false); release_xtal_clk(clocks); @@ -3176,7 +3728,6 @@ macro_rules! define_clock_tree_types { clocks.cpu_root_clk } pub fn request_cpu_root_clk(clocks: &mut ClockTree) { - trace!("Requesting CPU_ROOT_CLK"); trace!("Enabling CPU_ROOT_CLK"); match unwrap!(clocks.cpu_root_clk) { CpuRootClkConfig::Xtal => request_xtal_clk(clocks), @@ -3186,7 +3737,6 @@ macro_rules! define_clock_tree_types { enable_cpu_root_clk_impl(clocks, true); } pub fn release_cpu_root_clk(clocks: &mut ClockTree) { - trace!("Releasing CPU_ROOT_CLK"); trace!("Disabling CPU_ROOT_CLK"); enable_cpu_root_clk_impl(clocks, false); match unwrap!(clocks.cpu_root_clk) { @@ -3195,11 +3745,7 @@ macro_rules! define_clock_tree_types { CpuRootClkConfig::RcFast => release_rc_fast_clk(clocks), } } - #[allow(unused_variables)] - pub fn cpu_root_clk_config_frequency( - clocks: &mut ClockTree, - config: CpuRootClkConfig, - ) -> u32 { + pub fn cpu_root_clk_config_frequency(config: CpuRootClkConfig) -> u32 { match config { CpuRootClkConfig::Xtal => xtal_clk_frequency(), CpuRootClkConfig::Cpll => cpll_clk_frequency(), @@ -3210,11 +3756,7 @@ macro_rules! define_clock_tree_types { CPU_ROOT_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn cpu_root_clk_source_frequency(source: CpuRootClkConfig) -> u32 { - match source { - CpuRootClkConfig::Xtal => xtal_clk_frequency(), - CpuRootClkConfig::Cpll => cpll_clk_frequency(), - CpuRootClkConfig::RcFast => rc_fast_clk_frequency(), - } + cpu_root_clk_config_frequency(source) } pub fn configure_cpu_clk(clocks: &mut ClockTree, config: CpuClkConfig) { let old_config = clocks.cpu_clk.replace(config); @@ -3225,19 +3767,16 @@ macro_rules! define_clock_tree_types { clocks.cpu_clk } pub fn request_cpu_clk(clocks: &mut ClockTree) { - trace!("Requesting CPU_CLK"); trace!("Enabling CPU_CLK"); request_cpu_root_clk(clocks); enable_cpu_clk_impl(clocks, true); } pub fn release_cpu_clk(clocks: &mut ClockTree) { - trace!("Releasing CPU_CLK"); trace!("Disabling CPU_CLK"); enable_cpu_clk_impl(clocks, false); release_cpu_root_clk(clocks); } - #[allow(unused_variables)] - pub fn cpu_clk_config_frequency(clocks: &mut ClockTree, config: CpuClkConfig) -> u32 { + pub fn cpu_clk_config_frequency(config: CpuClkConfig) -> u32 { (cpu_root_clk_frequency() / (config.divisor() + 1)) } pub fn cpu_clk_frequency() -> u32 { @@ -3255,19 +3794,16 @@ macro_rules! define_clock_tree_types { clocks.mem_clk } pub fn request_mem_clk(clocks: &mut ClockTree) { - trace!("Requesting MEM_CLK"); trace!("Enabling MEM_CLK"); request_cpu_clk(clocks); enable_mem_clk_impl(clocks, true); } pub fn release_mem_clk(clocks: &mut ClockTree) { - trace!("Releasing MEM_CLK"); trace!("Disabling MEM_CLK"); enable_mem_clk_impl(clocks, false); release_cpu_clk(clocks); } - #[allow(unused_variables)] - pub fn mem_clk_config_frequency(clocks: &mut ClockTree, config: MemClkConfig) -> u32 { + pub fn mem_clk_config_frequency(config: MemClkConfig) -> u32 { (cpu_clk_frequency() / (config.divisor() + 1)) } pub fn mem_clk_frequency() -> u32 { @@ -3285,19 +3821,16 @@ macro_rules! define_clock_tree_types { clocks.sys_clk } pub fn request_sys_clk(clocks: &mut ClockTree) { - trace!("Requesting SYS_CLK"); trace!("Enabling SYS_CLK"); request_mem_clk(clocks); enable_sys_clk_impl(clocks, true); } pub fn release_sys_clk(clocks: &mut ClockTree) { - trace!("Releasing SYS_CLK"); trace!("Disabling SYS_CLK"); enable_sys_clk_impl(clocks, false); release_mem_clk(clocks); } - #[allow(unused_variables)] - pub fn sys_clk_config_frequency(clocks: &mut ClockTree, config: SysClkConfig) -> u32 { + pub fn sys_clk_config_frequency(config: SysClkConfig) -> u32 { (mem_clk_frequency() / (config.divisor() + 1)) } pub fn sys_clk_frequency() -> u32 { @@ -3330,8 +3863,7 @@ macro_rules! define_clock_tree_types { release_sys_clk(clocks); } } - #[allow(unused_variables)] - pub fn apb_clk_config_frequency(clocks: &mut ClockTree, config: ApbClkConfig) -> u32 { + pub fn apb_clk_config_frequency(config: ApbClkConfig) -> u32 { (sys_clk_frequency() / (config.divisor() + 1)) } pub fn apb_clk_frequency() -> u32 { @@ -3343,20 +3875,19 @@ macro_rules! define_clock_tree_types { pub fn configure_lp_fast_clk(clocks: &mut ClockTree, new_selector: LpFastClkConfig) { let old_selector = clocks.lp_fast_clk.replace(new_selector); refresh_lp_fast_clk_downstream(clocks); - if clocks.lp_fast_clk_refcount > 0 { + let active = clocks.lp_fast_clk_refcount > 0; + if active { match new_selector { LpFastClkConfig::RcFast => request_rc_fast_clk(clocks), LpFastClkConfig::XtalD2 => request_xtal_d2_clk(clocks), } - configure_lp_fast_clk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - LpFastClkConfig::RcFast => release_rc_fast_clk(clocks), - LpFastClkConfig::XtalD2 => release_xtal_d2_clk(clocks), - } + } + configure_lp_fast_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + LpFastClkConfig::RcFast => release_rc_fast_clk(clocks), + LpFastClkConfig::XtalD2 => release_xtal_d2_clk(clocks), } - } else { - configure_lp_fast_clk_impl(clocks, old_selector, new_selector); } } pub fn lp_fast_clk_config(clocks: &mut ClockTree) -> Option { @@ -3384,11 +3915,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn lp_fast_clk_config_frequency( - clocks: &mut ClockTree, - config: LpFastClkConfig, - ) -> u32 { + pub fn lp_fast_clk_config_frequency(config: LpFastClkConfig) -> u32 { match config { LpFastClkConfig::RcFast => rc_fast_clk_frequency(), LpFastClkConfig::XtalD2 => xtal_d2_clk_frequency(), @@ -3398,16 +3925,14 @@ macro_rules! define_clock_tree_types { LP_FAST_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn lp_fast_clk_source_frequency(source: LpFastClkConfig) -> u32 { - match source { - LpFastClkConfig::RcFast => rc_fast_clk_frequency(), - LpFastClkConfig::XtalD2 => xtal_d2_clk_frequency(), - } + lp_fast_clk_config_frequency(source) } pub fn configure_lp_slow_clk(clocks: &mut ClockTree, new_selector: LpSlowClkConfig) { let old_selector = clocks.lp_slow_clk.replace(new_selector); refresh_lp_slow_clk_downstream(clocks); match new_selector { LpSlowClkConfig::RcSlow => request_rc_slow_clk(clocks), + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => request_xtal32k_clk(clocks), LpSlowClkConfig::OscSlow => request_osc_slow_clk(clocks), } @@ -3415,6 +3940,7 @@ macro_rules! define_clock_tree_types { if let Some(old_selector) = old_selector { match old_selector { LpSlowClkConfig::RcSlow => release_rc_slow_clk(clocks), + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => release_xtal32k_clk(clocks), LpSlowClkConfig::OscSlow => release_osc_slow_clk(clocks), } @@ -3424,32 +3950,29 @@ macro_rules! define_clock_tree_types { clocks.lp_slow_clk } pub fn request_lp_slow_clk(clocks: &mut ClockTree) { - trace!("Requesting LP_SLOW_CLK"); trace!("Enabling LP_SLOW_CLK"); match unwrap!(clocks.lp_slow_clk) { LpSlowClkConfig::RcSlow => request_rc_slow_clk(clocks), + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => request_xtal32k_clk(clocks), LpSlowClkConfig::OscSlow => request_osc_slow_clk(clocks), } enable_lp_slow_clk_impl(clocks, true); } pub fn release_lp_slow_clk(clocks: &mut ClockTree) { - trace!("Releasing LP_SLOW_CLK"); trace!("Disabling LP_SLOW_CLK"); enable_lp_slow_clk_impl(clocks, false); match unwrap!(clocks.lp_slow_clk) { LpSlowClkConfig::RcSlow => release_rc_slow_clk(clocks), + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => release_xtal32k_clk(clocks), LpSlowClkConfig::OscSlow => release_osc_slow_clk(clocks), } } - #[allow(unused_variables)] - pub fn lp_slow_clk_config_frequency( - clocks: &mut ClockTree, - config: LpSlowClkConfig, - ) -> u32 { + pub fn lp_slow_clk_config_frequency(config: LpSlowClkConfig) -> u32 { match config { LpSlowClkConfig::RcSlow => rc_slow_clk_frequency(), + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => xtal32k_clk_frequency(), LpSlowClkConfig::OscSlow => osc_slow_clk_frequency(), } @@ -3458,40 +3981,102 @@ macro_rules! define_clock_tree_types { LP_SLOW_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn lp_slow_clk_source_frequency(source: LpSlowClkConfig) -> u32 { - match source { - LpSlowClkConfig::RcSlow => rc_slow_clk_frequency(), - LpSlowClkConfig::Xtal32k => xtal32k_clk_frequency(), - LpSlowClkConfig::OscSlow => osc_slow_clk_frequency(), + lp_slow_clk_config_frequency(source) + } + pub fn configure_crypto_clk(clocks: &mut ClockTree, new_selector: CryptoClkConfig) { + let old_selector = clocks.crypto_clk.replace(new_selector); + refresh_crypto_clk_downstream(clocks); + let active = clocks.crypto_clk_refcount > 0; + if active { + match new_selector { + CryptoClkConfig::Xtal => request_xtal_clk(clocks), + CryptoClkConfig::RcFast => request_rc_fast_clk(clocks), + CryptoClkConfig::PllF240m => request_pll_f240m(clocks), + CryptoClkConfig::PllF160m => request_pll_f160m(clocks), + } + } + configure_crypto_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + CryptoClkConfig::Xtal => release_xtal_clk(clocks), + CryptoClkConfig::RcFast => release_rc_fast_clk(clocks), + CryptoClkConfig::PllF240m => release_pll_f240m(clocks), + CryptoClkConfig::PllF160m => release_pll_f160m(clocks), + } + } + } + pub fn crypto_clk_config(clocks: &mut ClockTree) -> Option { + clocks.crypto_clk + } + pub fn request_crypto_clk(clocks: &mut ClockTree) { + trace!("Requesting CRYPTO_CLK"); + if increment_reference_count(&mut clocks.crypto_clk_refcount) { + trace!("Enabling CRYPTO_CLK"); + match unwrap!(clocks.crypto_clk) { + CryptoClkConfig::Xtal => request_xtal_clk(clocks), + CryptoClkConfig::RcFast => request_rc_fast_clk(clocks), + CryptoClkConfig::PllF240m => request_pll_f240m(clocks), + CryptoClkConfig::PllF160m => request_pll_f160m(clocks), + } + enable_crypto_clk_impl(clocks, true); + } + } + pub fn release_crypto_clk(clocks: &mut ClockTree) { + trace!("Releasing CRYPTO_CLK"); + if decrement_reference_count(&mut clocks.crypto_clk_refcount) { + trace!("Disabling CRYPTO_CLK"); + enable_crypto_clk_impl(clocks, false); + match unwrap!(clocks.crypto_clk) { + CryptoClkConfig::Xtal => release_xtal_clk(clocks), + CryptoClkConfig::RcFast => release_rc_fast_clk(clocks), + CryptoClkConfig::PllF240m => release_pll_f240m(clocks), + CryptoClkConfig::PllF160m => release_pll_f160m(clocks), + } } } + pub fn crypto_clk_config_frequency(config: CryptoClkConfig) -> u32 { + match config { + CryptoClkConfig::Xtal => xtal_clk_frequency(), + CryptoClkConfig::RcFast => rc_fast_clk_frequency(), + CryptoClkConfig::PllF240m => pll_f240m_frequency(), + CryptoClkConfig::PllF160m => pll_f160m_frequency(), + } + } + pub fn crypto_clk_frequency() -> u32 { + CRYPTO_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn crypto_clk_source_frequency(source: CryptoClkConfig) -> u32 { + crypto_clk_config_frequency(source) + } pub fn configure_timg_calibration_clock( clocks: &mut ClockTree, new_selector: TimgCalibrationClockConfig, ) { let old_selector = clocks.timg_calibration_clock.replace(new_selector); refresh_timg_calibration_clock_downstream(clocks); - if clocks.timg_calibration_clock_refcount > 0 { + let active = clocks.timg_calibration_clock_refcount > 0; + if active { match new_selector { TimgCalibrationClockConfig::MpllClk => request_mpll_clk(clocks), TimgCalibrationClockConfig::SpllClk => request_spll_clk(clocks), TimgCalibrationClockConfig::CpllClk => request_cpll_clk(clocks), TimgCalibrationClockConfig::RcFastDivClk => request_rc_fast_clk(clocks), TimgCalibrationClockConfig::RcSlowClk => request_lp_slow_clk(clocks), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => request_xtal32k_clk(clocks), } - configure_timg_calibration_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - TimgCalibrationClockConfig::MpllClk => release_mpll_clk(clocks), - TimgCalibrationClockConfig::SpllClk => release_spll_clk(clocks), - TimgCalibrationClockConfig::CpllClk => release_cpll_clk(clocks), - TimgCalibrationClockConfig::RcFastDivClk => release_rc_fast_clk(clocks), - TimgCalibrationClockConfig::RcSlowClk => release_lp_slow_clk(clocks), - TimgCalibrationClockConfig::Xtal32kClk => release_xtal32k_clk(clocks), - } + } + configure_timg_calibration_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + TimgCalibrationClockConfig::MpllClk => release_mpll_clk(clocks), + TimgCalibrationClockConfig::SpllClk => release_spll_clk(clocks), + TimgCalibrationClockConfig::CpllClk => release_cpll_clk(clocks), + TimgCalibrationClockConfig::RcFastDivClk => release_rc_fast_clk(clocks), + TimgCalibrationClockConfig::RcSlowClk => release_lp_slow_clk(clocks), + #[cfg(use_xtal32k)] + TimgCalibrationClockConfig::Xtal32kClk => release_xtal32k_clk(clocks), } - } else { - configure_timg_calibration_clock_impl(clocks, old_selector, new_selector); } } pub fn timg_calibration_clock_config( @@ -3510,6 +4095,7 @@ macro_rules! define_clock_tree_types { TimgCalibrationClockConfig::CpllClk => request_cpll_clk(clocks), TimgCalibrationClockConfig::RcFastDivClk => request_rc_fast_clk(clocks), TimgCalibrationClockConfig::RcSlowClk => request_lp_slow_clk(clocks), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => request_xtal32k_clk(clocks), } enable_timg_calibration_clock_impl(clocks, true); @@ -3527,21 +4113,19 @@ macro_rules! define_clock_tree_types { TimgCalibrationClockConfig::CpllClk => release_cpll_clk(clocks), TimgCalibrationClockConfig::RcFastDivClk => release_rc_fast_clk(clocks), TimgCalibrationClockConfig::RcSlowClk => release_lp_slow_clk(clocks), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => release_xtal32k_clk(clocks), } } } - #[allow(unused_variables)] - pub fn timg_calibration_clock_config_frequency( - clocks: &mut ClockTree, - config: TimgCalibrationClockConfig, - ) -> u32 { + pub fn timg_calibration_clock_config_frequency(config: TimgCalibrationClockConfig) -> u32 { match config { TimgCalibrationClockConfig::MpllClk => mpll_clk_frequency(), TimgCalibrationClockConfig::SpllClk => spll_clk_frequency(), TimgCalibrationClockConfig::CpllClk => cpll_clk_frequency(), TimgCalibrationClockConfig::RcFastDivClk => rc_fast_clk_frequency(), TimgCalibrationClockConfig::RcSlowClk => lp_slow_clk_frequency(), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => xtal32k_clk_frequency(), } } @@ -3549,14 +4133,7 @@ macro_rules! define_clock_tree_types { TIMG_CALIBRATION_CLOCK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn timg_calibration_clock_source_frequency(source: TimgCalibrationClockConfig) -> u32 { - match source { - TimgCalibrationClockConfig::MpllClk => mpll_clk_frequency(), - TimgCalibrationClockConfig::SpllClk => spll_clk_frequency(), - TimgCalibrationClockConfig::CpllClk => cpll_clk_frequency(), - TimgCalibrationClockConfig::RcFastDivClk => rc_fast_clk_frequency(), - TimgCalibrationClockConfig::RcSlowClk => lp_slow_clk_frequency(), - TimgCalibrationClockConfig::Xtal32kClk => xtal32k_clk_frequency(), - } + timg_calibration_clock_config_frequency(source) } impl SdmInstance { pub fn request_function_clock(self, clocks: &mut ClockTree) { @@ -3592,22 +4169,21 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.timg_function_clock[self as usize].replace(new_selector); refresh_timg_function_clock_downstream(clocks, self); - if clocks.timg_function_clock_refcount[self as usize] > 0 { + let active = clocks.timg_function_clock_refcount[self as usize] > 0; + if active { match new_selector { TimgFunctionClockConfig::XtalClk => request_xtal_clk(clocks), TimgFunctionClockConfig::RcFastClk => request_rc_fast_clk(clocks), TimgFunctionClockConfig::PllF80m => request_pll_f80m(clocks), } - self.configure_function_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - TimgFunctionClockConfig::XtalClk => release_xtal_clk(clocks), - TimgFunctionClockConfig::RcFastClk => release_rc_fast_clk(clocks), - TimgFunctionClockConfig::PllF80m => release_pll_f80m(clocks), - } + } + self.configure_function_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + TimgFunctionClockConfig::XtalClk => release_xtal_clk(clocks), + TimgFunctionClockConfig::RcFastClk => release_rc_fast_clk(clocks), + TimgFunctionClockConfig::PllF80m => release_pll_f80m(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_selector, new_selector); } } pub fn function_clock_config( @@ -3644,11 +4220,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: TimgFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: TimgFunctionClockConfig) -> u32 { match config { TimgFunctionClockConfig::XtalClk => xtal_clk_frequency(), TimgFunctionClockConfig::RcFastClk => rc_fast_clk_frequency(), @@ -3660,11 +4232,7 @@ macro_rules! define_clock_tree_types { .load(::core::sync::atomic::Ordering::Acquire) } pub fn function_clock_source_frequency(source: TimgFunctionClockConfig) -> u32 { - match source { - TimgFunctionClockConfig::XtalClk => xtal_clk_frequency(), - TimgFunctionClockConfig::RcFastClk => rc_fast_clk_frequency(), - TimgFunctionClockConfig::PllF80m => pll_f80m_frequency(), - } + Self::function_clock_config_frequency(source) } pub fn configure_wdt_clock( self, @@ -3673,22 +4241,21 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.timg_wdt_clock[self as usize].replace(new_selector); refresh_timg_wdt_clock_downstream(clocks, self); - if clocks.timg_wdt_clock_refcount[self as usize] > 0 { + let active = clocks.timg_wdt_clock_refcount[self as usize] > 0; + if active { match new_selector { TimgWdtClockConfig::XtalClk => request_xtal_clk(clocks), TimgWdtClockConfig::PllF80m => request_pll_f80m(clocks), TimgWdtClockConfig::RcFastClk => request_rc_fast_clk(clocks), } - self.configure_wdt_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - TimgWdtClockConfig::XtalClk => release_xtal_clk(clocks), - TimgWdtClockConfig::PllF80m => release_pll_f80m(clocks), - TimgWdtClockConfig::RcFastClk => release_rc_fast_clk(clocks), - } + } + self.configure_wdt_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + TimgWdtClockConfig::XtalClk => release_xtal_clk(clocks), + TimgWdtClockConfig::PllF80m => release_pll_f80m(clocks), + TimgWdtClockConfig::RcFastClk => release_rc_fast_clk(clocks), } - } else { - self.configure_wdt_clock_impl(clocks, old_selector, new_selector); } } pub fn wdt_clock_config(self, clocks: &mut ClockTree) -> Option { @@ -3718,11 +4285,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn wdt_clock_config_frequency( - clocks: &mut ClockTree, - config: TimgWdtClockConfig, - ) -> u32 { + pub fn wdt_clock_config_frequency(config: TimgWdtClockConfig) -> u32 { match config { TimgWdtClockConfig::XtalClk => xtal_clk_frequency(), TimgWdtClockConfig::PllF80m => pll_f80m_frequency(), @@ -3734,11 +4297,7 @@ macro_rules! define_clock_tree_types { .load(::core::sync::atomic::Ordering::Acquire) } pub fn wdt_clock_source_frequency(source: TimgWdtClockConfig) -> u32 { - match source { - TimgWdtClockConfig::XtalClk => xtal_clk_frequency(), - TimgWdtClockConfig::PllF80m => pll_f80m_frequency(), - TimgWdtClockConfig::RcFastClk => rc_fast_clk_frequency(), - } + Self::wdt_clock_config_frequency(source) } } impl UartInstance { @@ -3749,22 +4308,21 @@ macro_rules! define_clock_tree_types { ) { let old_config = clocks.uart_function_clock[self as usize].replace(config); refresh_uart_function_clock_downstream(clocks, self); - if clocks.uart_function_clock_refcount[self as usize] > 0 { + let active = clocks.uart_function_clock_refcount[self as usize] > 0; + if active { match config.sclk { UartFunctionClockSclk::Xtal => request_xtal_clk(clocks), UartFunctionClockSclk::PllF80m => request_pll_f80m(clocks), UartFunctionClockSclk::RcFast => request_rc_fast_clk(clocks), } - self.configure_function_clock_impl(clocks, old_config, config); - if let Some(old_config) = old_config { - match old_config.sclk { - UartFunctionClockSclk::Xtal => release_xtal_clk(clocks), - UartFunctionClockSclk::PllF80m => release_pll_f80m(clocks), - UartFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), - } + } + self.configure_function_clock_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + UartFunctionClockSclk::Xtal => release_xtal_clk(clocks), + UartFunctionClockSclk::PllF80m => release_pll_f80m(clocks), + UartFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_config, config); } } pub fn function_clock_config( @@ -3801,11 +4359,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: UartFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: UartFunctionClockConfig) -> u32 { (match config.sclk { UartFunctionClockSclk::Xtal => xtal_clk_frequency(), UartFunctionClockSclk::PllF80m => pll_f80m_frequency(), @@ -3858,10 +4412,8 @@ macro_rules! define_clock_tree_types { self.release_function_clock(clocks); } } - #[allow(unused_variables)] pub fn baud_rate_generator_config_frequency( self, - clocks: &mut ClockTree, config: UartBaudRateGeneratorConfig, ) -> u32 { ((self.function_clock_frequency() * 16) @@ -3880,22 +4432,21 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.spi_function_clock[self as usize].replace(new_selector); refresh_spi_function_clock_downstream(clocks, self); - if clocks.spi_function_clock_refcount[self as usize] > 0 { + let active = clocks.spi_function_clock_refcount[self as usize] > 0; + if active { match new_selector { SpiFunctionClockConfig::Xtal => request_xtal_clk(clocks), SpiFunctionClockConfig::RcFast => request_rc_fast_clk(clocks), - SpiFunctionClockConfig::Spll => request_spll_clk(clocks), + SpiFunctionClockConfig::Spll => request_spll_d3_clock(clocks), } - self.configure_function_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - SpiFunctionClockConfig::Xtal => release_xtal_clk(clocks), - SpiFunctionClockConfig::RcFast => release_rc_fast_clk(clocks), - SpiFunctionClockConfig::Spll => release_spll_clk(clocks), - } + } + self.configure_function_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + SpiFunctionClockConfig::Xtal => release_xtal_clk(clocks), + SpiFunctionClockConfig::RcFast => release_rc_fast_clk(clocks), + SpiFunctionClockConfig::Spll => release_spll_d3_clock(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_selector, new_selector); } } pub fn function_clock_config( @@ -3912,7 +4463,7 @@ macro_rules! define_clock_tree_types { match unwrap!(clocks.spi_function_clock[self as usize]) { SpiFunctionClockConfig::Xtal => request_xtal_clk(clocks), SpiFunctionClockConfig::RcFast => request_rc_fast_clk(clocks), - SpiFunctionClockConfig::Spll => request_spll_clk(clocks), + SpiFunctionClockConfig::Spll => request_spll_d3_clock(clocks), } self.enable_function_clock_impl(clocks, true); } @@ -3926,19 +4477,15 @@ macro_rules! define_clock_tree_types { match unwrap!(clocks.spi_function_clock[self as usize]) { SpiFunctionClockConfig::Xtal => release_xtal_clk(clocks), SpiFunctionClockConfig::RcFast => release_rc_fast_clk(clocks), - SpiFunctionClockConfig::Spll => release_spll_clk(clocks), + SpiFunctionClockConfig::Spll => release_spll_d3_clock(clocks), } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: SpiFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: SpiFunctionClockConfig) -> u32 { match config { SpiFunctionClockConfig::Xtal => xtal_clk_frequency(), SpiFunctionClockConfig::RcFast => rc_fast_clk_frequency(), - SpiFunctionClockConfig::Spll => spll_clk_frequency(), + SpiFunctionClockConfig::Spll => spll_d3_clock_frequency(), } } pub fn function_clock_frequency(self) -> u32 { @@ -3946,11 +4493,7 @@ macro_rules! define_clock_tree_types { .load(::core::sync::atomic::Ordering::Acquire) } pub fn function_clock_source_frequency(source: SpiFunctionClockConfig) -> u32 { - match source { - SpiFunctionClockConfig::Xtal => xtal_clk_frequency(), - SpiFunctionClockConfig::RcFast => rc_fast_clk_frequency(), - SpiFunctionClockConfig::Spll => spll_clk_frequency(), - } + Self::function_clock_config_frequency(source) } } impl I2cInstance { @@ -3961,20 +4504,19 @@ macro_rules! define_clock_tree_types { ) { let old_config = clocks.i2c_function_clock[self as usize].replace(config); refresh_i2c_function_clock_downstream(clocks, self); - if clocks.i2c_function_clock_refcount[self as usize] > 0 { + let active = clocks.i2c_function_clock_refcount[self as usize] > 0; + if active { match config.sclk { I2cFunctionClockSclk::Xtal => request_xtal_clk(clocks), I2cFunctionClockSclk::RcFast => request_rc_fast_clk(clocks), } - self.configure_function_clock_impl(clocks, old_config, config); - if let Some(old_config) = old_config { - match old_config.sclk { - I2cFunctionClockSclk::Xtal => release_xtal_clk(clocks), - I2cFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), - } + } + self.configure_function_clock_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + I2cFunctionClockSclk::Xtal => release_xtal_clk(clocks), + I2cFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_config, config); } } pub fn function_clock_config( @@ -4007,11 +4549,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: I2cFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: I2cFunctionClockConfig) -> u32 { (match config.sclk { I2cFunctionClockSclk::Xtal => xtal_clk_frequency(), I2cFunctionClockSclk::RcFast => rc_fast_clk_frequency(), @@ -4028,26 +4566,209 @@ macro_rules! define_clock_tree_types { } } } + impl I2sInstance { + pub fn configure_tx_clk(self, clocks: &mut ClockTree, config: I2sClkConfig) { + let old_config = clocks.i2s_tx_clk[self as usize].replace(config); + refresh_i2s_tx_clk_downstream(clocks, self); + let active = clocks.i2s_tx_clk_refcount[self as usize] > 0; + if active { + match config.sclk { + I2sClkSclk::Xtal => request_xtal_clk(clocks), + I2sClkSclk::PllF160m => request_pll_f160m(clocks), + } + } + self.configure_tx_clk_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + I2sClkSclk::Xtal => release_xtal_clk(clocks), + I2sClkSclk::PllF160m => release_pll_f160m(clocks), + } + } + } + pub fn tx_clk_config(self, clocks: &mut ClockTree) -> Option { + clocks.i2s_tx_clk[self as usize] + } + pub fn request_tx_clk(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::TX_CLK", self); + if increment_reference_count(&mut clocks.i2s_tx_clk_refcount[self as usize]) { + trace!("Enabling {:?}::TX_CLK", self); + crate::rtc_cntl::WakeLock::acquire(); + match unwrap!(clocks.i2s_tx_clk[self as usize]).sclk { + I2sClkSclk::Xtal => request_xtal_clk(clocks), + I2sClkSclk::PllF160m => request_pll_f160m(clocks), + } + self.enable_tx_clk_impl(clocks, true); + } + } + pub fn release_tx_clk(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::TX_CLK", self); + if decrement_reference_count(&mut clocks.i2s_tx_clk_refcount[self as usize]) { + trace!("Disabling {:?}::TX_CLK", self); + crate::rtc_cntl::WakeLock::release(); + self.enable_tx_clk_impl(clocks, false); + match unwrap!(clocks.i2s_tx_clk[self as usize]).sclk { + I2sClkSclk::Xtal => release_xtal_clk(clocks), + I2sClkSclk::PllF160m => release_pll_f160m(clocks), + } + } + } + pub fn tx_clk_config_frequency(config: I2sClkConfig) -> u32 { + (((match config.sclk { + I2sClkSclk::Xtal => xtal_clk_frequency(), + I2sClkSclk::PllF160m => pll_f160m_frequency(), + } as u64) + * (config.div_a() as u64)) + / (((config.div_num() * config.div_a()) + config.div_b()) as u64)) + as u32 + } + pub fn tx_clk_frequency(self) -> u32 { + I2S_TX_CLK_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) + } + pub fn tx_clk_source_frequency(sclk: I2sClkSclk) -> u32 { + match sclk { + I2sClkSclk::Xtal => xtal_clk_frequency(), + I2sClkSclk::PllF160m => pll_f160m_frequency(), + } + } + pub fn configure_rx_clk(self, clocks: &mut ClockTree, config: I2sClkConfig) { + let old_config = clocks.i2s_rx_clk[self as usize].replace(config); + refresh_i2s_rx_clk_downstream(clocks, self); + let active = clocks.i2s_rx_clk_refcount[self as usize] > 0; + if active { + match config.sclk { + I2sClkSclk::Xtal => request_xtal_clk(clocks), + I2sClkSclk::PllF160m => request_pll_f160m(clocks), + } + } + self.configure_rx_clk_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + I2sClkSclk::Xtal => release_xtal_clk(clocks), + I2sClkSclk::PllF160m => release_pll_f160m(clocks), + } + } + } + pub fn rx_clk_config(self, clocks: &mut ClockTree) -> Option { + clocks.i2s_rx_clk[self as usize] + } + pub fn request_rx_clk(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::RX_CLK", self); + if increment_reference_count(&mut clocks.i2s_rx_clk_refcount[self as usize]) { + trace!("Enabling {:?}::RX_CLK", self); + crate::rtc_cntl::WakeLock::acquire(); + match unwrap!(clocks.i2s_rx_clk[self as usize]).sclk { + I2sClkSclk::Xtal => request_xtal_clk(clocks), + I2sClkSclk::PllF160m => request_pll_f160m(clocks), + } + self.enable_rx_clk_impl(clocks, true); + } + } + pub fn release_rx_clk(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::RX_CLK", self); + if decrement_reference_count(&mut clocks.i2s_rx_clk_refcount[self as usize]) { + trace!("Disabling {:?}::RX_CLK", self); + crate::rtc_cntl::WakeLock::release(); + self.enable_rx_clk_impl(clocks, false); + match unwrap!(clocks.i2s_rx_clk[self as usize]).sclk { + I2sClkSclk::Xtal => release_xtal_clk(clocks), + I2sClkSclk::PllF160m => release_pll_f160m(clocks), + } + } + } + pub fn rx_clk_config_frequency(config: I2sClkConfig) -> u32 { + (((match config.sclk { + I2sClkSclk::Xtal => xtal_clk_frequency(), + I2sClkSclk::PllF160m => pll_f160m_frequency(), + } as u64) + * (config.div_a() as u64)) + / (((config.div_num() * config.div_a()) + config.div_b()) as u64)) + as u32 + } + pub fn rx_clk_frequency(self) -> u32 { + I2S_RX_CLK_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) + } + pub fn rx_clk_source_frequency(sclk: I2sClkSclk) -> u32 { + match sclk { + I2sClkSclk::Xtal => xtal_clk_frequency(), + I2sClkSclk::PllF160m => pll_f160m_frequency(), + } + } + pub fn configure_mclk_out( + self, + clocks: &mut ClockTree, + new_selector: I2sMclkOutConfig, + ) { + let old_selector = clocks.i2s_mclk_out[self as usize].replace(new_selector); + refresh_i2s_mclk_out_downstream(clocks, self); + let active = clocks.i2s_mclk_out_refcount[self as usize] > 0; + if active { + match new_selector { + I2sMclkOutConfig::Tx => self.request_tx_clk(clocks), + I2sMclkOutConfig::Rx => self.request_rx_clk(clocks), + } + } + self.configure_mclk_out_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + I2sMclkOutConfig::Tx => self.release_tx_clk(clocks), + I2sMclkOutConfig::Rx => self.release_rx_clk(clocks), + } + } + } + pub fn mclk_out_config(self, clocks: &mut ClockTree) -> Option { + clocks.i2s_mclk_out[self as usize] + } + pub fn request_mclk_out(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::MCLK_OUT", self); + if increment_reference_count(&mut clocks.i2s_mclk_out_refcount[self as usize]) { + trace!("Enabling {:?}::MCLK_OUT", self); + match unwrap!(clocks.i2s_mclk_out[self as usize]) { + I2sMclkOutConfig::Tx => self.request_tx_clk(clocks), + I2sMclkOutConfig::Rx => self.request_rx_clk(clocks), + } + self.enable_mclk_out_impl(clocks, true); + } + } + pub fn release_mclk_out(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::MCLK_OUT", self); + if decrement_reference_count(&mut clocks.i2s_mclk_out_refcount[self as usize]) { + trace!("Disabling {:?}::MCLK_OUT", self); + self.enable_mclk_out_impl(clocks, false); + match unwrap!(clocks.i2s_mclk_out[self as usize]) { + I2sMclkOutConfig::Tx => self.release_tx_clk(clocks), + I2sMclkOutConfig::Rx => self.release_rx_clk(clocks), + } + } + } + pub fn mclk_out_config_frequency(self, config: I2sMclkOutConfig) -> u32 { + match config { + I2sMclkOutConfig::Tx => self.tx_clk_frequency(), + I2sMclkOutConfig::Rx => self.rx_clk_frequency(), + } + } + pub fn mclk_out_frequency(self) -> u32 { + I2S_MCLK_OUT_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) + } + } impl MipiDsiInstance { pub fn configure_dpi_clk(self, clocks: &mut ClockTree, config: MipiDsiDpiClkConfig) { let old_config = clocks.mipi_dsi_dpi_clk[self as usize].replace(config); refresh_mipi_dsi_dpi_clk_downstream(clocks, self); - if clocks.mipi_dsi_dpi_clk_refcount[self as usize] > 0 { + let active = clocks.mipi_dsi_dpi_clk_refcount[self as usize] > 0; + if active { match config.sclk { MipiDsiDpiClkSclk::Xtal => request_xtal_clk(clocks), MipiDsiDpiClkSclk::PllF240m => request_pll_f240m(clocks), MipiDsiDpiClkSclk::PllF160m => request_pll_f160m(clocks), } - self.configure_dpi_clk_impl(clocks, old_config, config); - if let Some(old_config) = old_config { - match old_config.sclk { - MipiDsiDpiClkSclk::Xtal => release_xtal_clk(clocks), - MipiDsiDpiClkSclk::PllF240m => release_pll_f240m(clocks), - MipiDsiDpiClkSclk::PllF160m => release_pll_f160m(clocks), - } + } + self.configure_dpi_clk_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + MipiDsiDpiClkSclk::Xtal => release_xtal_clk(clocks), + MipiDsiDpiClkSclk::PllF240m => release_pll_f240m(clocks), + MipiDsiDpiClkSclk::PllF160m => release_pll_f160m(clocks), } - } else { - self.configure_dpi_clk_impl(clocks, old_config, config); } } pub fn dpi_clk_config(self, clocks: &mut ClockTree) -> Option { @@ -4077,11 +4798,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn dpi_clk_config_frequency( - clocks: &mut ClockTree, - config: MipiDsiDpiClkConfig, - ) -> u32 { + pub fn dpi_clk_config_frequency(config: MipiDsiDpiClkConfig) -> u32 { (match config.sclk { MipiDsiDpiClkSclk::Xtal => xtal_clk_frequency(), MipiDsiDpiClkSclk::PllF240m => pll_f240m_frequency(), @@ -4106,24 +4823,23 @@ macro_rules! define_clock_tree_types { ) { let old_config = clocks.mipi_dsi_phy_pll_refclk[self as usize].replace(config); refresh_mipi_dsi_phy_pll_refclk_downstream(clocks, self); - if clocks.mipi_dsi_phy_pll_refclk_refcount[self as usize] > 0 { + let active = clocks.mipi_dsi_phy_pll_refclk_refcount[self as usize] > 0; + if active { match config.sclk { MipiDsiPhyPllRefclkSclk::Xtal => request_xtal_clk(clocks), MipiDsiPhyPllRefclkSclk::Cpll => request_cpll_clk(clocks), MipiDsiPhyPllRefclkSclk::Spll => request_spll_clk(clocks), MipiDsiPhyPllRefclkSclk::Mpll => request_mpll_clk(clocks), } - self.configure_phy_pll_refclk_impl(clocks, old_config, config); - if let Some(old_config) = old_config { - match old_config.sclk { - MipiDsiPhyPllRefclkSclk::Xtal => release_xtal_clk(clocks), - MipiDsiPhyPllRefclkSclk::Cpll => release_cpll_clk(clocks), - MipiDsiPhyPllRefclkSclk::Spll => release_spll_clk(clocks), - MipiDsiPhyPllRefclkSclk::Mpll => release_mpll_clk(clocks), - } + } + self.configure_phy_pll_refclk_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + MipiDsiPhyPllRefclkSclk::Xtal => release_xtal_clk(clocks), + MipiDsiPhyPllRefclkSclk::Cpll => release_cpll_clk(clocks), + MipiDsiPhyPllRefclkSclk::Spll => release_spll_clk(clocks), + MipiDsiPhyPllRefclkSclk::Mpll => release_mpll_clk(clocks), } - } else { - self.configure_phy_pll_refclk_impl(clocks, old_config, config); } } pub fn phy_pll_refclk_config( @@ -4162,11 +4878,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn phy_pll_refclk_config_frequency( - clocks: &mut ClockTree, - config: MipiDsiPhyPllRefclkConfig, - ) -> u32 { + pub fn phy_pll_refclk_config_frequency(config: MipiDsiPhyPllRefclkConfig) -> u32 { (match config.sclk { MipiDsiPhyPllRefclkSclk::Xtal => xtal_clk_frequency(), MipiDsiPhyPllRefclkSclk::Cpll => cpll_clk_frequency(), @@ -4193,22 +4905,21 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.mipi_dsi_phy_cfg_clk[self as usize].replace(new_selector); refresh_mipi_dsi_phy_cfg_clk_downstream(clocks, self); - if clocks.mipi_dsi_phy_cfg_clk_refcount[self as usize] > 0 { + let active = clocks.mipi_dsi_phy_cfg_clk_refcount[self as usize] > 0; + if active { match new_selector { MipiDsiPhyCfgClkConfig::PllF20m => request_pll_f20m(clocks), MipiDsiPhyCfgClkConfig::RcFast => request_rc_fast_clk(clocks), MipiDsiPhyCfgClkConfig::PllF25m => request_pll_f25m(clocks), } - self.configure_phy_cfg_clk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - MipiDsiPhyCfgClkConfig::PllF20m => release_pll_f20m(clocks), - MipiDsiPhyCfgClkConfig::RcFast => release_rc_fast_clk(clocks), - MipiDsiPhyCfgClkConfig::PllF25m => release_pll_f25m(clocks), - } + } + self.configure_phy_cfg_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + MipiDsiPhyCfgClkConfig::PllF20m => release_pll_f20m(clocks), + MipiDsiPhyCfgClkConfig::RcFast => release_rc_fast_clk(clocks), + MipiDsiPhyCfgClkConfig::PllF25m => release_pll_f25m(clocks), } - } else { - self.configure_phy_cfg_clk_impl(clocks, old_selector, new_selector); } } pub fn phy_cfg_clk_config( @@ -4245,11 +4956,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn phy_cfg_clk_config_frequency( - clocks: &mut ClockTree, - config: MipiDsiPhyCfgClkConfig, - ) -> u32 { + pub fn phy_cfg_clk_config_frequency(config: MipiDsiPhyCfgClkConfig) -> u32 { match config { MipiDsiPhyCfgClkConfig::PllF20m => pll_f20m_frequency(), MipiDsiPhyCfgClkConfig::RcFast => rc_fast_clk_frequency(), @@ -4261,33 +4968,28 @@ macro_rules! define_clock_tree_types { .load(::core::sync::atomic::Ordering::Acquire) } pub fn phy_cfg_clk_source_frequency(source: MipiDsiPhyCfgClkConfig) -> u32 { - match source { - MipiDsiPhyCfgClkConfig::PllF20m => pll_f20m_frequency(), - MipiDsiPhyCfgClkConfig::RcFast => rc_fast_clk_frequency(), - MipiDsiPhyCfgClkConfig::PllF25m => pll_f25m_frequency(), - } + Self::phy_cfg_clk_config_frequency(source) } } impl RmtInstance { pub fn configure_sclk(self, clocks: &mut ClockTree, new_selector: RmtSclkConfig) { let old_selector = clocks.rmt_sclk[self as usize].replace(new_selector); refresh_rmt_sclk_downstream(clocks, self); - if clocks.rmt_sclk_refcount[self as usize] > 0 { + let active = clocks.rmt_sclk_refcount[self as usize] > 0; + if active { match new_selector { RmtSclkConfig::PllF80m => request_pll_f80m(clocks), RmtSclkConfig::RcFastClk => request_rc_fast_clk(clocks), RmtSclkConfig::XtalClk => request_xtal_clk(clocks), } - self.configure_sclk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - RmtSclkConfig::PllF80m => release_pll_f80m(clocks), - RmtSclkConfig::RcFastClk => release_rc_fast_clk(clocks), - RmtSclkConfig::XtalClk => release_xtal_clk(clocks), - } + } + self.configure_sclk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + RmtSclkConfig::PllF80m => release_pll_f80m(clocks), + RmtSclkConfig::RcFastClk => release_rc_fast_clk(clocks), + RmtSclkConfig::XtalClk => release_xtal_clk(clocks), } - } else { - self.configure_sclk_impl(clocks, old_selector, new_selector); } } pub fn sclk_config(self, clocks: &mut ClockTree) -> Option { @@ -4319,8 +5021,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn sclk_config_frequency(clocks: &mut ClockTree, config: RmtSclkConfig) -> u32 { + pub fn sclk_config_frequency(config: RmtSclkConfig) -> u32 { match config { RmtSclkConfig::PllF80m => pll_f80m_frequency(), RmtSclkConfig::RcFastClk => rc_fast_clk_frequency(), @@ -4331,11 +5032,7 @@ macro_rules! define_clock_tree_types { RMT_SCLK_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) } pub fn sclk_source_frequency(source: RmtSclkConfig) -> u32 { - match source { - RmtSclkConfig::PllF80m => pll_f80m_frequency(), - RmtSclkConfig::RcFastClk => rc_fast_clk_frequency(), - RmtSclkConfig::XtalClk => xtal_clk_frequency(), - } + Self::sclk_config_frequency(source) } } impl PsramInstance { @@ -4346,24 +5043,23 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.psram_function_clock[self as usize].replace(new_selector); refresh_psram_function_clock_downstream(clocks, self); - if clocks.psram_function_clock_refcount[self as usize] > 0 { + let active = clocks.psram_function_clock_refcount[self as usize] > 0; + if active { match new_selector { PsramFunctionClockConfig::Xtal => request_xtal_clk(clocks), PsramFunctionClockConfig::Mpll => request_mpll_clk(clocks), PsramFunctionClockConfig::Spll => request_spll_clk(clocks), PsramFunctionClockConfig::Cpll => request_cpll_clk(clocks), } - self.configure_function_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - PsramFunctionClockConfig::Xtal => release_xtal_clk(clocks), - PsramFunctionClockConfig::Mpll => release_mpll_clk(clocks), - PsramFunctionClockConfig::Spll => release_spll_clk(clocks), - PsramFunctionClockConfig::Cpll => release_cpll_clk(clocks), - } + } + self.configure_function_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + PsramFunctionClockConfig::Xtal => release_xtal_clk(clocks), + PsramFunctionClockConfig::Mpll => release_mpll_clk(clocks), + PsramFunctionClockConfig::Spll => release_spll_clk(clocks), + PsramFunctionClockConfig::Cpll => release_cpll_clk(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_selector, new_selector); } } pub fn function_clock_config( @@ -4402,11 +5098,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: PsramFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: PsramFunctionClockConfig) -> u32 { match config { PsramFunctionClockConfig::Xtal => xtal_clk_frequency(), PsramFunctionClockConfig::Mpll => mpll_clk_frequency(), @@ -4419,12 +5111,7 @@ macro_rules! define_clock_tree_types { .load(::core::sync::atomic::Ordering::Acquire) } pub fn function_clock_source_frequency(source: PsramFunctionClockConfig) -> u32 { - match source { - PsramFunctionClockConfig::Xtal => xtal_clk_frequency(), - PsramFunctionClockConfig::Mpll => mpll_clk_frequency(), - PsramFunctionClockConfig::Spll => spll_clk_frequency(), - PsramFunctionClockConfig::Cpll => cpll_clk_frequency(), - } + Self::function_clock_config_frequency(source) } } /// Clock tree configuration. @@ -4458,6 +5145,8 @@ macro_rules! define_clock_tree_types { pub lp_fast_clk: Option, /// `LP_SLOW_CLK` configuration. pub lp_slow_clk: Option, + /// `CRYPTO_CLK` configuration. + pub crypto_clk: Option, /// `TIMG_CALIBRATION_CLOCK` configuration. pub timg_calibration_clock: Option, } @@ -4493,6 +5182,9 @@ macro_rules! define_clock_tree_types { if let Some(config) = self.lp_slow_clk { configure_lp_slow_clk(clocks, config); } + if let Some(config) = self.crypto_clk { + configure_crypto_clk(clocks, config); + } if let Some(config) = self.timg_calibration_clock { configure_timg_calibration_clock(clocks, config); } @@ -4511,7 +5203,7 @@ macro_rules! define_clock_tree_types { fn refresh_cpll_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.cpll_clk { CPLL_CLK_FREQ_CACHE.store( - cpll_clk_config_frequency(clocks, config), + cpll_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4527,7 +5219,7 @@ macro_rules! define_clock_tree_types { fn refresh_mpll_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.mpll_clk { MPLL_CLK_FREQ_CACHE.store( - mpll_clk_config_frequency(clocks, config), + mpll_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4540,10 +5232,44 @@ macro_rules! define_clock_tree_types { refresh_psram_function_clock_downstream(clocks, child_instance); } } + fn refresh_rc_fast_clk_downstream(clocks: &mut ClockTree) { + refresh_cpu_root_clk_downstream(clocks); + refresh_lp_fast_clk_downstream(clocks); + refresh_crypto_clk_downstream(clocks); + refresh_timg_calibration_clock_downstream(clocks); + for child_instance in [TimgInstance::Timg0, TimgInstance::Timg1] { + refresh_timg_function_clock_downstream(clocks, child_instance); + refresh_timg_wdt_clock_downstream(clocks, child_instance); + } + for child_instance in [ + UartInstance::Uart0, + UartInstance::Uart1, + UartInstance::Uart2, + UartInstance::Uart3, + UartInstance::Uart4, + ] { + refresh_uart_function_clock_downstream(clocks, child_instance); + } + for child_instance in [SpiInstance::Spi2, SpiInstance::Spi3] { + refresh_spi_function_clock_downstream(clocks, child_instance); + } + for child_instance in [I2cInstance::I2c0, I2cInstance::I2c1] { + refresh_i2c_function_clock_downstream(clocks, child_instance); + } + for child_instance in [MipiDsiInstance::MipiDsi] { + refresh_mipi_dsi_phy_cfg_clk_downstream(clocks, child_instance); + } + for child_instance in [RmtInstance::Rmt] { + refresh_rmt_sclk_downstream(clocks, child_instance); + } + } + fn refresh_rc_slow_clk_downstream(clocks: &mut ClockTree) { + refresh_lp_slow_clk_downstream(clocks); + } fn refresh_iomux_function_clock_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.iomux_function_clock { IOMUX_FUNCTION_CLOCK_FREQ_CACHE.store( - iomux_function_clock_config_frequency(clocks, config), + iomux_function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4551,7 +5277,7 @@ macro_rules! define_clock_tree_types { fn refresh_cpu_root_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.cpu_root_clk { CPU_ROOT_CLK_FREQ_CACHE.store( - cpu_root_clk_config_frequency(clocks, config), + cpu_root_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4560,7 +5286,7 @@ macro_rules! define_clock_tree_types { fn refresh_cpu_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.cpu_clk { CPU_CLK_FREQ_CACHE.store( - cpu_clk_config_frequency(clocks, config), + cpu_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4569,7 +5295,7 @@ macro_rules! define_clock_tree_types { fn refresh_mem_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.mem_clk { MEM_CLK_FREQ_CACHE.store( - mem_clk_config_frequency(clocks, config), + mem_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4578,7 +5304,7 @@ macro_rules! define_clock_tree_types { fn refresh_sys_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.sys_clk { SYS_CLK_FREQ_CACHE.store( - sys_clk_config_frequency(clocks, config), + sys_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4587,7 +5313,7 @@ macro_rules! define_clock_tree_types { fn refresh_apb_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.apb_clk { APB_CLK_FREQ_CACHE.store( - apb_clk_config_frequency(clocks, config), + apb_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4595,7 +5321,7 @@ macro_rules! define_clock_tree_types { fn refresh_lp_fast_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.lp_fast_clk { LP_FAST_CLK_FREQ_CACHE.store( - lp_fast_clk_config_frequency(clocks, config), + lp_fast_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4603,16 +5329,24 @@ macro_rules! define_clock_tree_types { fn refresh_lp_slow_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.lp_slow_clk { LP_SLOW_CLK_FREQ_CACHE.store( - lp_slow_clk_config_frequency(clocks, config), + lp_slow_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } refresh_timg_calibration_clock_downstream(clocks); } + fn refresh_crypto_clk_downstream(clocks: &mut ClockTree) { + if let Some(config) = clocks.crypto_clk { + CRYPTO_CLK_FREQ_CACHE.store( + crypto_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } fn refresh_timg_calibration_clock_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.timg_calibration_clock { TIMG_CALIBRATION_CLOCK_FREQ_CACHE.store( - timg_calibration_clock_config_frequency(clocks, config), + timg_calibration_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4620,7 +5354,7 @@ macro_rules! define_clock_tree_types { fn refresh_timg_function_clock_downstream(clocks: &mut ClockTree, instance: TimgInstance) { if let Some(config) = clocks.timg_function_clock[instance as usize] { TIMG_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - TimgInstance::function_clock_config_frequency(clocks, config), + TimgInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4628,7 +5362,7 @@ macro_rules! define_clock_tree_types { fn refresh_timg_wdt_clock_downstream(clocks: &mut ClockTree, instance: TimgInstance) { if let Some(config) = clocks.timg_wdt_clock[instance as usize] { TIMG_WDT_CLOCK_FREQ_CACHE[instance as usize].store( - TimgInstance::wdt_clock_config_frequency(clocks, config), + TimgInstance::wdt_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4636,7 +5370,7 @@ macro_rules! define_clock_tree_types { fn refresh_uart_function_clock_downstream(clocks: &mut ClockTree, instance: UartInstance) { if let Some(config) = clocks.uart_function_clock[instance as usize] { UART_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - UartInstance::function_clock_config_frequency(clocks, config), + UartInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4648,7 +5382,7 @@ macro_rules! define_clock_tree_types { ) { if let Some(config) = clocks.uart_baud_rate_generator[instance as usize] { UART_BAUD_RATE_GENERATOR_FREQ_CACHE[instance as usize].store( - instance.baud_rate_generator_config_frequency(clocks, config), + instance.baud_rate_generator_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4656,7 +5390,7 @@ macro_rules! define_clock_tree_types { fn refresh_spi_function_clock_downstream(clocks: &mut ClockTree, instance: SpiInstance) { if let Some(config) = clocks.spi_function_clock[instance as usize] { SPI_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - SpiInstance::function_clock_config_frequency(clocks, config), + SpiInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4664,7 +5398,33 @@ macro_rules! define_clock_tree_types { fn refresh_i2c_function_clock_downstream(clocks: &mut ClockTree, instance: I2cInstance) { if let Some(config) = clocks.i2c_function_clock[instance as usize] { I2C_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - I2cInstance::function_clock_config_frequency(clocks, config), + I2cInstance::function_clock_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + fn refresh_i2s_tx_clk_downstream(clocks: &mut ClockTree, instance: I2sInstance) { + if let Some(config) = clocks.i2s_tx_clk[instance as usize] { + I2S_TX_CLK_FREQ_CACHE[instance as usize].store( + I2sInstance::tx_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + refresh_i2s_mclk_out_downstream(clocks, instance); + } + fn refresh_i2s_rx_clk_downstream(clocks: &mut ClockTree, instance: I2sInstance) { + if let Some(config) = clocks.i2s_rx_clk[instance as usize] { + I2S_RX_CLK_FREQ_CACHE[instance as usize].store( + I2sInstance::rx_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + refresh_i2s_mclk_out_downstream(clocks, instance); + } + fn refresh_i2s_mclk_out_downstream(clocks: &mut ClockTree, instance: I2sInstance) { + if let Some(config) = clocks.i2s_mclk_out[instance as usize] { + I2S_MCLK_OUT_FREQ_CACHE[instance as usize].store( + instance.mclk_out_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4672,7 +5432,7 @@ macro_rules! define_clock_tree_types { fn refresh_mipi_dsi_dpi_clk_downstream(clocks: &mut ClockTree, instance: MipiDsiInstance) { if let Some(config) = clocks.mipi_dsi_dpi_clk[instance as usize] { MIPI_DSI_DPI_CLK_FREQ_CACHE[instance as usize].store( - MipiDsiInstance::dpi_clk_config_frequency(clocks, config), + MipiDsiInstance::dpi_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4683,7 +5443,7 @@ macro_rules! define_clock_tree_types { ) { if let Some(config) = clocks.mipi_dsi_phy_pll_refclk[instance as usize] { MIPI_DSI_PHY_PLL_REFCLK_FREQ_CACHE[instance as usize].store( - MipiDsiInstance::phy_pll_refclk_config_frequency(clocks, config), + MipiDsiInstance::phy_pll_refclk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4694,7 +5454,7 @@ macro_rules! define_clock_tree_types { ) { if let Some(config) = clocks.mipi_dsi_phy_cfg_clk[instance as usize] { MIPI_DSI_PHY_CFG_CLK_FREQ_CACHE[instance as usize].store( - MipiDsiInstance::phy_cfg_clk_config_frequency(clocks, config), + MipiDsiInstance::phy_cfg_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4702,7 +5462,7 @@ macro_rules! define_clock_tree_types { fn refresh_rmt_sclk_downstream(clocks: &mut ClockTree, instance: RmtInstance) { if let Some(config) = clocks.rmt_sclk[instance as usize] { RMT_SCLK_FREQ_CACHE[instance as usize].store( - RmtInstance::sclk_config_frequency(clocks, config), + RmtInstance::sclk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4713,7 +5473,7 @@ macro_rules! define_clock_tree_types { ) { if let Some(config) = clocks.psram_function_clock[instance as usize] { PSRAM_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - PsramInstance::function_clock_config_frequency(clocks, config), + PsramInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -5402,16 +6162,16 @@ macro_rules! implement_peripheral_clocks { #[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] macro_rules! memory_range { ("DRAM") => { - 0x4FF40000..0x4FFC0000 + 0x4FF40000..0x4FFADFC0 }; (size as str, "DRAM") => { - "524288" + "450496" }; ("DRAM2_UNINIT") => { - 0x4FF00000..0x4FF40000 + 0x4FFADFC0..0x4FFBEFC0 }; (size as str, "DRAM2_UNINIT") => { - "262144" + "69632" }; ("IROM") => { 0x40000000..0x44000000 @@ -5605,6 +6365,57 @@ macro_rules! for_each_spi_slave { (SPI3, Spi3, SPI3_CK, SPI3_D, SPI3_Q, SPI3_CS))); }; } +/// This macro can be used to generate code for each PCNT unit. +/// +/// For an explanation on the general syntax, as well as usage of individual/repeated +/// matchers, refer to [the crate-level documentation][crate#for_each-macros]. +/// +/// This macro has four options for its "Individual matcher" case: +/// +/// - `names`: `($instance:ident)` +/// - `all`: `($peri:ident, $variant:ident, $sys:ident, $regs:ident, $unit:literal, +/// $interrupt:ident, $sig_ch0:ident, $sig_ch1:ident, $ctrl_ch0:ident, $ctrl_ch1:ident)` +/// - `interrupt`: `($interrupt:ident)` (repeated: one ident per unique IRQ) +/// - `regs`: `($regs:ident)` (repeated: one ident per register block) +/// +/// Macro fragments: +/// +/// - `$peri`: unit singleton name (`PCNT0_UNIT0`, `PCNT1_UNIT0`, …) +/// - `$variant`: `AnyPcntUnit` enum variant (`Pcnt0Unit0`, `Pcnt1Unit0`, …) +/// - `$sys`: `esp_hal::system::Peripheral` variant for clocks +/// - `$regs`: register-block singleton (`PCNT`, `PCNT1`) +/// - `$unit`: hardware unit index within that register block +/// - `$interrupt`: shared peripheral interrupt +/// - `$sig_ch0`, `$sig_ch1`, `$ctrl_ch0`, `$ctrl_ch1`: GPIO matrix input signals +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! for_each_pcnt_unit { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _for_each_inner_pcnt_unit { $(($pattern) => $code;)* ($other : tt) + => {} } _for_each_inner_pcnt_unit!((PCNT0_UNIT0)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT2)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT3)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT0, Pcnt0Unit0, Pcnt, PCNT, 0, PCNT, + PCNT0_SIG_CH0, PCNT0_SIG_CH1, PCNT0_CTRL_CH0, PCNT0_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT1, Pcnt0Unit1, Pcnt, PCNT, 1, PCNT, + PCNT1_SIG_CH0, PCNT1_SIG_CH1, PCNT1_CTRL_CH0, PCNT1_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT2, Pcnt0Unit2, Pcnt, PCNT, 2, PCNT, + PCNT2_SIG_CH0, PCNT2_SIG_CH1, PCNT2_CTRL_CH0, PCNT2_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT3, Pcnt0Unit3, Pcnt, PCNT, 3, PCNT, + PCNT3_SIG_CH0, PCNT3_SIG_CH1, PCNT3_CTRL_CH0, PCNT3_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT)); _for_each_inner_pcnt_unit!((PCNT)); + _for_each_inner_pcnt_unit!((names(PCNT0_UNIT0), (PCNT0_UNIT1), (PCNT0_UNIT2), + (PCNT0_UNIT3))); _for_each_inner_pcnt_unit!((all(PCNT0_UNIT0, Pcnt0Unit0, Pcnt, + PCNT, 0, PCNT, PCNT0_SIG_CH0, PCNT0_SIG_CH1, PCNT0_CTRL_CH0, PCNT0_CTRL_CH1), + (PCNT0_UNIT1, Pcnt0Unit1, Pcnt, PCNT, 1, PCNT, PCNT1_SIG_CH0, PCNT1_SIG_CH1, + PCNT1_CTRL_CH0, PCNT1_CTRL_CH1), (PCNT0_UNIT2, Pcnt0Unit2, Pcnt, PCNT, 2, PCNT, + PCNT2_SIG_CH0, PCNT2_SIG_CH1, PCNT2_CTRL_CH0, PCNT2_CTRL_CH1), (PCNT0_UNIT3, + Pcnt0Unit3, Pcnt, PCNT, 3, PCNT, PCNT3_SIG_CH0, PCNT3_SIG_CH1, PCNT3_CTRL_CH0, + PCNT3_CTRL_CH1))); _for_each_inner_pcnt_unit!((interrupt(PCNT))); + _for_each_inner_pcnt_unit!((regs(PCNT))); + }; +} #[macro_export] #[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] macro_rules! for_each_peripheral { @@ -5795,6 +6606,14 @@ macro_rules! for_each_peripheral { _for_each_inner_peripheral!((@ peri_type #[doc = "VDMA_CH2 peripheral singleton"] VDMA_CH2 <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "VDMA_CH3 peripheral singleton"] VDMA_CH3 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT0_UNIT0 peripheral singleton"] PCNT0_UNIT0 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT0_UNIT1 peripheral singleton"] PCNT0_UNIT1 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT0_UNIT2 peripheral singleton"] PCNT0_UNIT2 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT0_UNIT3 peripheral singleton"] PCNT0_UNIT3 <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "SDM_CH0 peripheral singleton"] SDM_CH0 <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "SDM_CH1 peripheral singleton"] SDM_CH1 <= virtual() (unstable))); @@ -5817,7 +6636,7 @@ macro_rules! for_each_peripheral { HP_SYS <= HP_SYS() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "HP_SYS_CLKRST peripheral singleton"] HP_SYS_CLKRST <= HP_SYS_CLKRST() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "RNG peripheral singleton"] RNG <= LP_SYS() (unstable))); + "RNG peripheral singleton"] RNG <= LP_TRNG() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "INTERRUPT_CORE0 peripheral singleton"] INTERRUPT_CORE0 <= INTERRUPT_CORE0() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = @@ -5825,9 +6644,15 @@ macro_rules! for_each_peripheral { (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "LP_I2C_ANA_MST peripheral singleton"] LP_I2C_ANA_MST <= LP_I2C_ANA_MST() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "CLIC peripheral singleton"] CLIC <= CLIC() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "IO_MUX peripheral singleton"] - IO_MUX <= IO_MUX() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "CACHE peripheral singleton"] CACHE <= CACHE() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "CLIC peripheral singleton"] + CLIC <= CLIC() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "CLINT peripheral singleton"] CLINT <= CLINT() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "CLINT_OTHER_CORE peripheral singleton"] CLINT_OTHER_CORE <= CLINT_OTHER_CORE() + (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "IO_MUX peripheral singleton"] IO_MUX <= IO_MUX() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "IOMUX_MSPI_PIN peripheral singleton"] IOMUX_MSPI_PIN <= IOMUX_MSPI_PIN() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "LP_I2C0 peripheral singleton"] LP_I2C0 <= LP_I2C0() (unstable))); @@ -5847,69 +6672,72 @@ macro_rules! for_each_peripheral { "LPWR peripheral singleton"] LPWR <= LP_SYS() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "PMU peripheral singleton"] PMU <= PMU() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "SYSTIMER peripheral singleton"] SYSTIMER <= SYSTIMER() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "TIMG0 peripheral singleton"] - TIMG0 <= TIMG0() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "TIMG1 peripheral singleton"] TIMG1 <= TIMG1() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "UART0 peripheral singleton"] - UART0 <= UART0(UART0 : { bind_peri_interrupt, enable_peri_interrupt, - disable_peri_interrupt }))); _for_each_inner_peripheral!((@ peri_type #[doc = - "UART1 peripheral singleton"] UART1 <= UART1(UART1 : { bind_peri_interrupt, + "PAU peripheral singleton"] PAU <= PAU() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "SYSTIMER peripheral singleton"] + SYSTIMER <= SYSTIMER() (unstable))); _for_each_inner_peripheral!((@ peri_type + #[doc = "TIMG0 peripheral singleton"] TIMG0 <= TIMG0() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "TIMG1 peripheral singleton"] + TIMG1 <= TIMG1() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "UART0 peripheral singleton"] UART0 <= UART0(UART0 : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }))); - _for_each_inner_peripheral!((@ peri_type #[doc = "UART2 peripheral singleton"] - UART2 <= UART2(UART2 : { bind_peri_interrupt, enable_peri_interrupt, + _for_each_inner_peripheral!((@ peri_type #[doc = "UART1 peripheral singleton"] + UART1 <= UART1(UART1 : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }))); _for_each_inner_peripheral!((@ peri_type #[doc = - "UART3 peripheral singleton"] UART3 <= UART3(UART3 : { bind_peri_interrupt, + "UART2 peripheral singleton"] UART2 <= UART2(UART2 : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }))); - _for_each_inner_peripheral!((@ peri_type #[doc = "UART4 peripheral singleton"] - UART4 <= UART4(UART4 : { bind_peri_interrupt, enable_peri_interrupt, - disable_peri_interrupt }))); _for_each_inner_peripheral!((@ peri_type #[doc = - "UHCI0 peripheral singleton"] UHCI0 <= UHCI0() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "SPI0 peripheral singleton"] - SPI0 <= SPI0() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "SPI1 peripheral singleton"] SPI1 <= SPI1() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "MEMSPI2 peripheral singleton"] - MEMSPI2 <= MEMSPI2() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc - = "MEMSPI3 peripheral singleton"] MEMSPI3 <= MEMSPI3() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "SPI2 peripheral singleton"] - SPI2 <= SPI2(SPI2 : { bind_peri_interrupt, enable_peri_interrupt, + _for_each_inner_peripheral!((@ peri_type #[doc = "UART3 peripheral singleton"] + UART3 <= UART3(UART3 : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }))); _for_each_inner_peripheral!((@ peri_type #[doc = - "SPI3 peripheral singleton"] SPI3 <= SPI3(SPI3 : { bind_peri_interrupt, + "UART4 peripheral singleton"] UART4 <= UART4(UART4 : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }))); - _for_each_inner_peripheral!((@ peri_type #[doc = "I2C0 peripheral singleton"] - I2C0 <= I2C0(I2C0 : { bind_peri_interrupt, enable_peri_interrupt, + _for_each_inner_peripheral!((@ peri_type #[doc = "UHCI0 peripheral singleton"] + UHCI0 <= UHCI0() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "SPI0 peripheral singleton"] SPI0 <= SPI0() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "SPI1 peripheral singleton"] + SPI1 <= SPI1() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "MEMSPI2 peripheral singleton"] MEMSPI2 <= MEMSPI2() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "MEMSPI3 peripheral singleton"] + MEMSPI3 <= MEMSPI3() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc + = "SPI2 peripheral singleton"] SPI2 <= SPI2(SPI2 : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }))); + _for_each_inner_peripheral!((@ peri_type #[doc = "SPI3 peripheral singleton"] + SPI3 <= SPI3(SPI3 : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }))); _for_each_inner_peripheral!((@ peri_type #[doc = - "I2C1 peripheral singleton"] I2C1 <= I2C1(I2C1 : { bind_peri_interrupt, + "I2C0 peripheral singleton"] I2C0 <= I2C0(I2C0 : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }))); - _for_each_inner_peripheral!((@ peri_type #[doc = "I2S0 peripheral singleton"] - I2S0 <= I2S0(I2S0 : { bind_peri_interrupt, enable_peri_interrupt, + _for_each_inner_peripheral!((@ peri_type #[doc = "I2C1 peripheral singleton"] + I2C1 <= I2C1(I2C1 : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt }))); _for_each_inner_peripheral!((@ peri_type #[doc = + "I2S0 peripheral singleton"] I2S0 <= I2S0(I2S0 : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }) (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "I2S1 peripheral singleton"] + I2S1 <= I2S1(I2S1 : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) (unstable))); _for_each_inner_peripheral!((@ peri_type - #[doc = "I2S1 peripheral singleton"] I2S1 <= I2S1(I2S1 : { bind_peri_interrupt, + #[doc = "I2S2 peripheral singleton"] I2S2 <= I2S2(I2S2 : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "I2S2 peripheral singleton"] - I2S2 <= I2S2(I2S2 : { bind_peri_interrupt, enable_peri_interrupt, + _for_each_inner_peripheral!((@ peri_type #[doc = "TWAI0 peripheral singleton"] + TWAI0 <= TWAI0(TWAI0 : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) (unstable))); _for_each_inner_peripheral!((@ peri_type - #[doc = "TWAI0 peripheral singleton"] TWAI0 <= TWAI0(TWAI0 : { + #[doc = "TWAI1 peripheral singleton"] TWAI1 <= TWAI1(TWAI1 : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "TWAI1 peripheral singleton"] TWAI1 <= TWAI1(TWAI1 : { bind_peri_interrupt, + "TWAI2 peripheral singleton"] TWAI2 <= TWAI2(TWAI2 : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "TWAI2 peripheral singleton"] - TWAI2 <= TWAI2(TWAI2 : { bind_peri_interrupt, enable_peri_interrupt, + _for_each_inner_peripheral!((@ peri_type #[doc = "DMA peripheral singleton"] DMA + <= AHB_DMA() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "AXI_GDMA peripheral singleton"] AXI_GDMA <= AXI_DMA() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "ETH peripheral singleton"] ETH + <= virtual(ETH_MAC : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) (unstable))); _for_each_inner_peripheral!((@ peri_type - #[doc = "DMA peripheral singleton"] DMA <= AHB_DMA() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "AXI_GDMA peripheral singleton"] - AXI_GDMA <= AXI_DMA() (unstable))); _for_each_inner_peripheral!((@ peri_type - #[doc = "ETH peripheral singleton"] ETH <= virtual() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "EMAC_DMA peripheral singleton"] - EMAC_DMA <= EMAC_DMA() (unstable))); _for_each_inner_peripheral!((@ peri_type - #[doc = "EMAC_MAC peripheral singleton"] EMAC_MAC <= EMAC_MAC() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "MIPI_DSI peripheral singleton"] - MIPI_DSI <= virtual(DSI_BRIDGE : { bind_bridge_interrupt, - enable_bridge_interrupt, disable_bridge_interrupt }, DSI : { bind_dsi_interrupt, - enable_dsi_interrupt, disable_dsi_interrupt }) (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "VDMA peripheral singleton"] - VDMA <= DMA() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + #[doc = "EMAC_DMA peripheral singleton"] EMAC_DMA <= GMAC_DMA() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "EMAC_MAC peripheral singleton"] + EMAC_MAC <= GMAC() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "MIPI_DSI peripheral singleton"] MIPI_DSI <= virtual(DSI_BRIDGE : { + bind_bridge_interrupt, enable_bridge_interrupt, disable_bridge_interrupt }, DSI : + { bind_dsi_interrupt, enable_dsi_interrupt, disable_dsi_interrupt }) + (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "VDMA peripheral singleton"] VDMA <= DMA() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "MIPI_DSI_HOST peripheral singleton"] MIPI_DSI_HOST <= MIPI_DSI_HOST() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "MIPI_DSI_BRIDGE peripheral singleton"] MIPI_DSI_BRIDGE <= MIPI_DSI_BRIDGE() @@ -5932,7 +6760,7 @@ macro_rules! for_each_peripheral { #[doc = "APB_SARADC peripheral singleton"] APB_SARADC <= ADC() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "LP_ADC peripheral singleton"] LP_ADC <= LP_ADC() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "RMT peripheral singleton"] RMT <= virtual(RMT : { bind_peri_interrupt, + "RMT peripheral singleton"] RMT <= RMT(RMT : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "AES peripheral singleton"] AES <= AES(AES : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt @@ -5961,8 +6789,10 @@ macro_rules! for_each_peripheral { "GPIO_DEDICATED peripheral singleton"] GPIO_DEDICATED <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "CPU_CTRL peripheral singleton"] CPU_CTRL <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type - #[doc = "FROM_CPU_INTR0 peripheral singleton"] FROM_CPU_INTR0 <= virtual() - (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + #[doc = "IPC peripheral singleton"] IPC <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "FROM_CPU_INTR0 peripheral singleton"] FROM_CPU_INTR0 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "FROM_CPU_INTR1 peripheral singleton"] FROM_CPU_INTR1 <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "FROM_CPU_INTR2 peripheral singleton"] FROM_CPU_INTR2 <= virtual() (unstable))); @@ -6006,6 +6836,10 @@ macro_rules! for_each_peripheral { _for_each_inner_peripheral!((VDMA_CH1(unstable))); _for_each_inner_peripheral!((VDMA_CH2(unstable))); _for_each_inner_peripheral!((VDMA_CH3(unstable))); + _for_each_inner_peripheral!((PCNT0_UNIT0(unstable))); + _for_each_inner_peripheral!((PCNT0_UNIT1(unstable))); + _for_each_inner_peripheral!((PCNT0_UNIT2(unstable))); + _for_each_inner_peripheral!((PCNT0_UNIT3(unstable))); _for_each_inner_peripheral!((SDM_CH0(unstable))); _for_each_inner_peripheral!((SDM_CH1(unstable))); _for_each_inner_peripheral!((SDM_CH2(unstable))); @@ -6024,6 +6858,8 @@ macro_rules! for_each_peripheral { _for_each_inner_peripheral!((INTERRUPT_CORE1(unstable))); _for_each_inner_peripheral!((LP_I2C_ANA_MST(unstable))); _for_each_inner_peripheral!((CLIC(unstable))); + _for_each_inner_peripheral!((CLINT(unstable))); + _for_each_inner_peripheral!((CLINT_OTHER_CORE(unstable))); _for_each_inner_peripheral!((IO_MUX(unstable))); _for_each_inner_peripheral!((LP_I2C0(unstable))); _for_each_inner_peripheral!((LP_AON(unstable))); @@ -6036,6 +6872,7 @@ macro_rules! for_each_peripheral { _for_each_inner_peripheral!((LP_WDT(unstable))); _for_each_inner_peripheral!((LPWR(unstable))); _for_each_inner_peripheral!((PMU(unstable))); + _for_each_inner_peripheral!((PAU(unstable))); _for_each_inner_peripheral!((SYSTIMER(unstable))); _for_each_inner_peripheral!((TIMG0(unstable))); _for_each_inner_peripheral!((TIMG1(unstable))); @@ -6076,6 +6913,7 @@ macro_rules! for_each_peripheral { _for_each_inner_peripheral!((PSRAM(unstable))); _for_each_inner_peripheral!((GPIO_DEDICATED(unstable))); _for_each_inner_peripheral!((CPU_CTRL(unstable))); + _for_each_inner_peripheral!((IPC(unstable))); _for_each_inner_peripheral!((FROM_CPU_INTR0(unstable))); _for_each_inner_peripheral!((FROM_CPU_INTR1(unstable))); _for_each_inner_peripheral!((FROM_CPU_INTR2(unstable))); @@ -6237,7 +7075,12 @@ macro_rules! for_each_peripheral { #[doc = "VDMA_CH1 peripheral singleton"] VDMA_CH1 <= virtual() (unstable)), (@ peri_type #[doc = "VDMA_CH2 peripheral singleton"] VDMA_CH2 <= virtual() (unstable)), (@ peri_type #[doc = "VDMA_CH3 peripheral singleton"] VDMA_CH3 <= - virtual() (unstable)), (@ peri_type #[doc = "SDM_CH0 peripheral singleton"] + virtual() (unstable)), (@ peri_type #[doc = "PCNT0_UNIT0 peripheral singleton"] + PCNT0_UNIT0 <= virtual() (unstable)), (@ peri_type #[doc = + "PCNT0_UNIT1 peripheral singleton"] PCNT0_UNIT1 <= virtual() (unstable)), (@ + peri_type #[doc = "PCNT0_UNIT2 peripheral singleton"] PCNT0_UNIT2 <= virtual() + (unstable)), (@ peri_type #[doc = "PCNT0_UNIT3 peripheral singleton"] PCNT0_UNIT3 + <= virtual() (unstable)), (@ peri_type #[doc = "SDM_CH0 peripheral singleton"] SDM_CH0 <= virtual() (unstable)), (@ peri_type #[doc = "SDM_CH1 peripheral singleton"] SDM_CH1 <= virtual() (unstable)), (@ peri_type #[doc = "SDM_CH2 peripheral singleton"] SDM_CH2 <= virtual() (unstable)), (@ @@ -6254,96 +7097,100 @@ macro_rules! for_each_peripheral { HP_SYS() (unstable)), (@ peri_type #[doc = "HP_SYS peripheral singleton"] HP_SYS <= HP_SYS() (unstable)), (@ peri_type #[doc = "HP_SYS_CLKRST peripheral singleton"] HP_SYS_CLKRST <= HP_SYS_CLKRST() - (unstable)), (@ peri_type #[doc = "RNG peripheral singleton"] RNG <= LP_SYS() + (unstable)), (@ peri_type #[doc = "RNG peripheral singleton"] RNG <= LP_TRNG() (unstable)), (@ peri_type #[doc = "INTERRUPT_CORE0 peripheral singleton"] INTERRUPT_CORE0 <= INTERRUPT_CORE0() (unstable)), (@ peri_type #[doc = "INTERRUPT_CORE1 peripheral singleton"] INTERRUPT_CORE1 <= INTERRUPT_CORE1() (unstable)), (@ peri_type #[doc = "LP_I2C_ANA_MST peripheral singleton"] LP_I2C_ANA_MST <= LP_I2C_ANA_MST() (unstable)), (@ peri_type #[doc = + "CACHE peripheral singleton"] CACHE <= CACHE() (unstable)), (@ peri_type #[doc = "CLIC peripheral singleton"] CLIC <= CLIC() (unstable)), (@ peri_type #[doc = - "IO_MUX peripheral singleton"] IO_MUX <= IO_MUX() (unstable)), (@ peri_type #[doc - = "IOMUX_MSPI_PIN peripheral singleton"] IOMUX_MSPI_PIN <= IOMUX_MSPI_PIN() - (unstable)), (@ peri_type #[doc = "LP_I2C0 peripheral singleton"] LP_I2C0 <= - LP_I2C0() (unstable)), (@ peri_type #[doc = "LP_AON peripheral singleton"] LP_AON - <= LP_SYS() (unstable)), (@ peri_type #[doc = - "LP_AON_CLKRST peripheral singleton"] LP_AON_CLKRST <= LP_AON_CLKRST() - (unstable)), (@ peri_type #[doc = "LP_SYS peripheral singleton"] LP_SYS <= - LP_SYS() (unstable)), (@ peri_type #[doc = "LP_GPIO peripheral singleton"] - LP_GPIO <= LP_GPIO() (unstable)), (@ peri_type #[doc = - "LP_IO_MUX peripheral singleton"] LP_IO_MUX <= LP_IO_MUX() (unstable)), (@ - peri_type #[doc = "LP_PERI peripheral singleton"] LP_PERI <= LP_PERI() + "CLINT peripheral singleton"] CLINT <= CLINT() (unstable)), (@ peri_type #[doc = + "CLINT_OTHER_CORE peripheral singleton"] CLINT_OTHER_CORE <= CLINT_OTHER_CORE() + (unstable)), (@ peri_type #[doc = "IO_MUX peripheral singleton"] IO_MUX <= + IO_MUX() (unstable)), (@ peri_type #[doc = "IOMUX_MSPI_PIN peripheral singleton"] + IOMUX_MSPI_PIN <= IOMUX_MSPI_PIN() (unstable)), (@ peri_type #[doc = + "LP_I2C0 peripheral singleton"] LP_I2C0 <= LP_I2C0() (unstable)), (@ peri_type + #[doc = "LP_AON peripheral singleton"] LP_AON <= LP_SYS() (unstable)), (@ + peri_type #[doc = "LP_AON_CLKRST peripheral singleton"] LP_AON_CLKRST <= + LP_AON_CLKRST() (unstable)), (@ peri_type #[doc = "LP_SYS peripheral singleton"] + LP_SYS <= LP_SYS() (unstable)), (@ peri_type #[doc = + "LP_GPIO peripheral singleton"] LP_GPIO <= LP_GPIO() (unstable)), (@ peri_type + #[doc = "LP_IO_MUX peripheral singleton"] LP_IO_MUX <= LP_IO_MUX() (unstable)), + (@ peri_type #[doc = "LP_PERI peripheral singleton"] LP_PERI <= LP_PERI() (unstable)), (@ peri_type #[doc = "RTC_TIMER peripheral singleton"] RTC_TIMER <= LP_TIMER() (unstable)), (@ peri_type #[doc = "LP_WDT peripheral singleton"] LP_WDT <= LP_WDT() (unstable)), (@ peri_type #[doc = "LPWR peripheral singleton"] LPWR <= LP_SYS() (unstable)), (@ peri_type #[doc = "PMU peripheral singleton"] - PMU <= PMU() (unstable)), (@ peri_type #[doc = "SYSTIMER peripheral singleton"] - SYSTIMER <= SYSTIMER() (unstable)), (@ peri_type #[doc = - "TIMG0 peripheral singleton"] TIMG0 <= TIMG0() (unstable)), (@ peri_type #[doc = - "TIMG1 peripheral singleton"] TIMG1 <= TIMG1() (unstable)), (@ peri_type #[doc = - "UART0 peripheral singleton"] UART0 <= UART0(UART0 : { bind_peri_interrupt, - enable_peri_interrupt, disable_peri_interrupt })), (@ peri_type #[doc = - "UART1 peripheral singleton"] UART1 <= UART1(UART1 : { bind_peri_interrupt, + PMU <= PMU() (unstable)), (@ peri_type #[doc = "PAU peripheral singleton"] PAU <= + PAU() (unstable)), (@ peri_type #[doc = "SYSTIMER peripheral singleton"] SYSTIMER + <= SYSTIMER() (unstable)), (@ peri_type #[doc = "TIMG0 peripheral singleton"] + TIMG0 <= TIMG0() (unstable)), (@ peri_type #[doc = "TIMG1 peripheral singleton"] + TIMG1 <= TIMG1() (unstable)), (@ peri_type #[doc = "UART0 peripheral singleton"] + UART0 <= UART0(UART0 : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt })), (@ peri_type #[doc = "UART1 peripheral singleton"] + UART1 <= UART1(UART1 : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt })), (@ peri_type #[doc = "UART2 peripheral singleton"] + UART2 <= UART2(UART2 : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt })), (@ peri_type #[doc = "UART3 peripheral singleton"] + UART3 <= UART3(UART3 : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt })), (@ peri_type #[doc = "UART4 peripheral singleton"] + UART4 <= UART4(UART4 : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt })), (@ peri_type #[doc = "UHCI0 peripheral singleton"] + UHCI0 <= UHCI0() (unstable)), (@ peri_type #[doc = "SPI0 peripheral singleton"] + SPI0 <= SPI0() (unstable)), (@ peri_type #[doc = "SPI1 peripheral singleton"] + SPI1 <= SPI1() (unstable)), (@ peri_type #[doc = "MEMSPI2 peripheral singleton"] + MEMSPI2 <= MEMSPI2() (unstable)), (@ peri_type #[doc = + "MEMSPI3 peripheral singleton"] MEMSPI3 <= MEMSPI3() (unstable)), (@ peri_type + #[doc = "SPI2 peripheral singleton"] SPI2 <= SPI2(SPI2 : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt })), (@ peri_type #[doc = - "UART2 peripheral singleton"] UART2 <= UART2(UART2 : { bind_peri_interrupt, + "SPI3 peripheral singleton"] SPI3 <= SPI3(SPI3 : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt })), (@ peri_type #[doc = - "UART3 peripheral singleton"] UART3 <= UART3(UART3 : { bind_peri_interrupt, + "I2C0 peripheral singleton"] I2C0 <= I2C0(I2C0 : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt })), (@ peri_type #[doc = - "UART4 peripheral singleton"] UART4 <= UART4(UART4 : { bind_peri_interrupt, + "I2C1 peripheral singleton"] I2C1 <= I2C1(I2C1 : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt })), (@ peri_type #[doc = - "UHCI0 peripheral singleton"] UHCI0 <= UHCI0() (unstable)), (@ peri_type #[doc = - "SPI0 peripheral singleton"] SPI0 <= SPI0() (unstable)), (@ peri_type #[doc = - "SPI1 peripheral singleton"] SPI1 <= SPI1() (unstable)), (@ peri_type #[doc = - "MEMSPI2 peripheral singleton"] MEMSPI2 <= MEMSPI2() (unstable)), (@ peri_type - #[doc = "MEMSPI3 peripheral singleton"] MEMSPI3 <= MEMSPI3() (unstable)), (@ - peri_type #[doc = "SPI2 peripheral singleton"] SPI2 <= SPI2(SPI2 : { - bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt })), (@ - peri_type #[doc = "SPI3 peripheral singleton"] SPI3 <= SPI3(SPI3 : { - bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt })), (@ - peri_type #[doc = "I2C0 peripheral singleton"] I2C0 <= I2C0(I2C0 : { - bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt })), (@ - peri_type #[doc = "I2C1 peripheral singleton"] I2C1 <= I2C1(I2C1 : { - bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt })), (@ - peri_type #[doc = "I2S0 peripheral singleton"] I2S0 <= I2S0(I2S0 : { - bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) - (unstable)), (@ peri_type #[doc = "I2S1 peripheral singleton"] I2S1 <= I2S1(I2S1 - : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) - (unstable)), (@ peri_type #[doc = "I2S2 peripheral singleton"] I2S2 <= I2S2(I2S2 - : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) - (unstable)), (@ peri_type #[doc = "TWAI0 peripheral singleton"] TWAI0 <= - TWAI0(TWAI0 : { bind_peri_interrupt, enable_peri_interrupt, - disable_peri_interrupt }) (unstable)), (@ peri_type #[doc = - "TWAI1 peripheral singleton"] TWAI1 <= TWAI1(TWAI1 : { bind_peri_interrupt, + "I2S0 peripheral singleton"] I2S0 <= I2S0(I2S0 : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc + = "I2S1 peripheral singleton"] I2S1 <= I2S1(I2S1 : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc + = "I2S2 peripheral singleton"] I2S2 <= I2S2(I2S2 : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc + = "TWAI0 peripheral singleton"] TWAI0 <= TWAI0(TWAI0 : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc + = "TWAI1 peripheral singleton"] TWAI1 <= TWAI1(TWAI1 : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc = "TWAI2 peripheral singleton"] TWAI2 <= TWAI2(TWAI2 : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc = "DMA peripheral singleton"] DMA <= AHB_DMA() (unstable)), (@ peri_type #[doc = "AXI_GDMA peripheral singleton"] AXI_GDMA <= AXI_DMA() (unstable)), (@ peri_type - #[doc = "ETH peripheral singleton"] ETH <= virtual() (unstable)), (@ peri_type - #[doc = "EMAC_DMA peripheral singleton"] EMAC_DMA <= EMAC_DMA() (unstable)), (@ - peri_type #[doc = "EMAC_MAC peripheral singleton"] EMAC_MAC <= EMAC_MAC() - (unstable)), (@ peri_type #[doc = "MIPI_DSI peripheral singleton"] MIPI_DSI <= - virtual(DSI_BRIDGE : { bind_bridge_interrupt, enable_bridge_interrupt, - disable_bridge_interrupt }, DSI : { bind_dsi_interrupt, enable_dsi_interrupt, - disable_dsi_interrupt }) (unstable)), (@ peri_type #[doc = - "VDMA peripheral singleton"] VDMA <= DMA() (unstable)), (@ peri_type #[doc = - "MIPI_DSI_HOST peripheral singleton"] MIPI_DSI_HOST <= MIPI_DSI_HOST() - (unstable)), (@ peri_type #[doc = "MIPI_DSI_BRIDGE peripheral singleton"] - MIPI_DSI_BRIDGE <= MIPI_DSI_BRIDGE() (unstable)), (@ peri_type #[doc = - "USB_DEVICE peripheral singleton"] USB_DEVICE <= USB_DEVICE(USB_DEVICE : { + #[doc = "ETH peripheral singleton"] ETH <= virtual(ETH_MAC : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) - (unstable)), (@ peri_type #[doc = "SDHOST peripheral singleton"] SDHOST <= - SDHOST() (unstable)), (@ peri_type #[doc = "LEDC peripheral singleton"] LEDC <= - LEDC(LEDC : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt - }) (unstable)), (@ peri_type #[doc = "MCPWM0 peripheral singleton"] MCPWM0 <= - MCPWM0(PWM0 : { bind_peri_interrupt, enable_peri_interrupt, + (unstable)), (@ peri_type #[doc = "EMAC_DMA peripheral singleton"] EMAC_DMA <= + GMAC_DMA() (unstable)), (@ peri_type #[doc = "EMAC_MAC peripheral singleton"] + EMAC_MAC <= GMAC() (unstable)), (@ peri_type #[doc = + "MIPI_DSI peripheral singleton"] MIPI_DSI <= virtual(DSI_BRIDGE : { + bind_bridge_interrupt, enable_bridge_interrupt, disable_bridge_interrupt }, DSI : + { bind_dsi_interrupt, enable_dsi_interrupt, disable_dsi_interrupt }) (unstable)), + (@ peri_type #[doc = "VDMA peripheral singleton"] VDMA <= DMA() (unstable)), (@ + peri_type #[doc = "MIPI_DSI_HOST peripheral singleton"] MIPI_DSI_HOST <= + MIPI_DSI_HOST() (unstable)), (@ peri_type #[doc = + "MIPI_DSI_BRIDGE peripheral singleton"] MIPI_DSI_BRIDGE <= MIPI_DSI_BRIDGE() + (unstable)), (@ peri_type #[doc = "USB_DEVICE peripheral singleton"] USB_DEVICE + <= USB_DEVICE(USB_DEVICE : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc = - "MCPWM1 peripheral singleton"] MCPWM1 <= MCPWM1(PWM1 : { bind_peri_interrupt, + "SDHOST peripheral singleton"] SDHOST <= SDHOST() (unstable)), (@ peri_type #[doc + = "LEDC peripheral singleton"] LEDC <= LEDC(LEDC : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc + = "MCPWM0 peripheral singleton"] MCPWM0 <= MCPWM0(PWM0 : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc + = "MCPWM1 peripheral singleton"] MCPWM1 <= MCPWM1(PWM1 : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc = "PCNT peripheral singleton"] PCNT <= PCNT(PCNT : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc = "APB_SARADC peripheral singleton"] APB_SARADC <= ADC() (unstable)), (@ peri_type #[doc = "LP_ADC peripheral singleton"] LP_ADC <= LP_ADC() (unstable)), - (@ peri_type #[doc = "RMT peripheral singleton"] RMT <= virtual(RMT : { + (@ peri_type #[doc = "RMT peripheral singleton"] RMT <= RMT(RMT : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc = "AES peripheral singleton"] AES <= AES(AES : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) @@ -6366,6 +7213,7 @@ macro_rules! for_each_peripheral { (unstable)), (@ peri_type #[doc = "GPIO_DEDICATED peripheral singleton"] GPIO_DEDICATED <= virtual() (unstable)), (@ peri_type #[doc = "CPU_CTRL peripheral singleton"] CPU_CTRL <= virtual() (unstable)), (@ peri_type + #[doc = "IPC peripheral singleton"] IPC <= virtual() (unstable)), (@ peri_type #[doc = "FROM_CPU_INTR0 peripheral singleton"] FROM_CPU_INTR0 <= virtual() (unstable)), (@ peri_type #[doc = "FROM_CPU_INTR1 peripheral singleton"] FROM_CPU_INTR1 <= virtual() (unstable)), (@ peri_type #[doc = @@ -6381,17 +7229,19 @@ macro_rules! for_each_peripheral { (GPIO51), (GPIO52), (GPIO53), (GPIO54), (DMA_CH0(unstable)), (DMA_CH1(unstable)), (DMA_CH2(unstable)), (DMA_AXI_CH0(unstable)), (DMA_AXI_CH1(unstable)), (DMA_AXI_CH2(unstable)), (VDMA_CH0(unstable)), (VDMA_CH1(unstable)), - (VDMA_CH2(unstable)), (VDMA_CH3(unstable)), (SDM_CH0(unstable)), - (SDM_CH1(unstable)), (SDM_CH2(unstable)), (SDM_CH3(unstable)), - (SDM_CH4(unstable)), (SDM_CH5(unstable)), (SDM_CH6(unstable)), - (SDM_CH7(unstable)), (GPIO(unstable)), (GPIO_SD(unstable)), (SYSTEM(unstable)), - (HP_SYS(unstable)), (HP_SYS_CLKRST(unstable)), (RNG(unstable)), - (INTERRUPT_CORE0(unstable)), (INTERRUPT_CORE1(unstable)), - (LP_I2C_ANA_MST(unstable)), (CLIC(unstable)), (IO_MUX(unstable)), - (LP_I2C0(unstable)), (LP_AON(unstable)), (LP_AON_CLKRST(unstable)), - (LP_SYS(unstable)), (LP_GPIO(unstable)), (LP_IO_MUX(unstable)), - (LP_PERI(unstable)), (RTC_TIMER(unstable)), (LP_WDT(unstable)), (LPWR(unstable)), - (PMU(unstable)), (SYSTIMER(unstable)), (TIMG0(unstable)), (TIMG1(unstable)), + (VDMA_CH2(unstable)), (VDMA_CH3(unstable)), (PCNT0_UNIT0(unstable)), + (PCNT0_UNIT1(unstable)), (PCNT0_UNIT2(unstable)), (PCNT0_UNIT3(unstable)), + (SDM_CH0(unstable)), (SDM_CH1(unstable)), (SDM_CH2(unstable)), + (SDM_CH3(unstable)), (SDM_CH4(unstable)), (SDM_CH5(unstable)), + (SDM_CH6(unstable)), (SDM_CH7(unstable)), (GPIO(unstable)), (GPIO_SD(unstable)), + (SYSTEM(unstable)), (HP_SYS(unstable)), (HP_SYS_CLKRST(unstable)), + (RNG(unstable)), (INTERRUPT_CORE0(unstable)), (INTERRUPT_CORE1(unstable)), + (LP_I2C_ANA_MST(unstable)), (CLIC(unstable)), (CLINT(unstable)), + (CLINT_OTHER_CORE(unstable)), (IO_MUX(unstable)), (LP_I2C0(unstable)), + (LP_AON(unstable)), (LP_AON_CLKRST(unstable)), (LP_SYS(unstable)), + (LP_GPIO(unstable)), (LP_IO_MUX(unstable)), (LP_PERI(unstable)), + (RTC_TIMER(unstable)), (LP_WDT(unstable)), (LPWR(unstable)), (PMU(unstable)), + (PAU(unstable)), (SYSTIMER(unstable)), (TIMG0(unstable)), (TIMG1(unstable)), (UART0), (UART1), (UART2), (UART3), (UART4), (UHCI0(unstable)), (SPI2), (SPI3), (I2C0), (I2C1), (I2S0(unstable)), (I2S1(unstable)), (I2S2(unstable)), (TWAI0(unstable)), (TWAI1(unstable)), (TWAI2(unstable)), (DMA(unstable)), @@ -6401,13 +7251,13 @@ macro_rules! for_each_peripheral { (RMT(unstable)), (AES(unstable)), (SHA(unstable)), (RSA(unstable)), (ECC(unstable)), (USB_FS(unstable)), (USB_HS(unstable)), (ADC1(unstable)), (ADC2(unstable)), (FLASH(unstable)), (PSRAM(unstable)), - (GPIO_DEDICATED(unstable)), (CPU_CTRL(unstable)), (FROM_CPU_INTR0(unstable)), - (FROM_CPU_INTR1(unstable)), (FROM_CPU_INTR2(unstable)), - (FROM_CPU_INTR3(unstable)))); _for_each_inner_peripheral!((dma_eligible(SPI2, - Spi2, 1, AxiGdmaChannel), (UHCI0, Uhci0, 2, AhbGdmaChannel), (SPI3, Spi3, 2, - AxiGdmaChannel), (I2S0, I2s0, 3, AhbGdmaChannel), (I2S1, I2s1, 4, - AhbGdmaChannel), (AES, Aes, 4, AxiGdmaChannel), (I2S2, I2s2, 5, AhbGdmaChannel), - (SHA, Sha, 5, AxiGdmaChannel))); + (GPIO_DEDICATED(unstable)), (CPU_CTRL(unstable)), (IPC(unstable)), + (FROM_CPU_INTR0(unstable)), (FROM_CPU_INTR1(unstable)), + (FROM_CPU_INTR2(unstable)), (FROM_CPU_INTR3(unstable)))); + _for_each_inner_peripheral!((dma_eligible(SPI2, Spi2, 1, AxiGdmaChannel), (UHCI0, + Uhci0, 2, AhbGdmaChannel), (SPI3, Spi3, 2, AxiGdmaChannel), (I2S0, I2s0, 3, + AhbGdmaChannel), (I2S1, I2s1, 4, AhbGdmaChannel), (AES, Aes, 4, AxiGdmaChannel), + (I2S2, I2s2, 5, AhbGdmaChannel), (SHA, Sha, 5, AxiGdmaChannel))); }; } /// This macro can be used to generate code for each `GPIOn` instance. @@ -7509,6 +8359,22 @@ macro_rules! define_io_mux_signals { I3C_SLV_SCL = 136, I3C_SLV_SDA = 137, USB_JTAG_TDO_BRIDGE = 140, + PCNT0_SIG_CH0 = 141, + PCNT1_SIG_CH0 = 142, + PCNT2_SIG_CH0 = 143, + PCNT3_SIG_CH0 = 144, + PCNT0_SIG_CH1 = 145, + PCNT1_SIG_CH1 = 146, + PCNT2_SIG_CH1 = 147, + PCNT3_SIG_CH1 = 148, + PCNT0_CTRL_CH0 = 149, + PCNT1_CTRL_CH0 = 150, + PCNT2_CTRL_CH0 = 151, + PCNT3_CTRL_CH0 = 152, + PCNT0_CTRL_CH1 = 153, + PCNT1_CTRL_CH1 = 154, + PCNT2_CTRL_CH1 = 155, + PCNT3_CTRL_CH1 = 156, CAM_PCLK = 158, CAM_H_ENABLE = 159, CAM_H_SYNC = 160, @@ -7521,24 +8387,24 @@ macro_rules! define_io_mux_signals { EMAC_RXER = 183, EMAC_RX_CLK = 184, EMAC_TX_CLK = 185, - PARLIO_RX_CLK = 186, - PARLIO_TX_CLK = 187, - PARLIO_RX_DATA0 = 188, - PARLIO_RX_DATA1 = 189, - PARLIO_RX_DATA2 = 190, - PARLIO_RX_DATA3 = 191, - PARLIO_RX_DATA4 = 192, - PARLIO_RX_DATA5 = 193, - PARLIO_RX_DATA6 = 194, - PARLIO_RX_DATA7 = 195, - PARLIO_RX_DATA8 = 196, - PARLIO_RX_DATA9 = 197, - PARLIO_RX_DATA10 = 198, - PARLIO_RX_DATA11 = 199, - PARLIO_RX_DATA12 = 200, - PARLIO_RX_DATA13 = 201, - PARLIO_RX_DATA14 = 202, - PARLIO_RX_DATA15 = 203, + PARL_RX_CLK = 186, + PARL_TX_CLK = 187, + PARL_RX_DATA0 = 188, + PARL_RX_DATA1 = 189, + PARL_RX_DATA2 = 190, + PARL_RX_DATA3 = 191, + PARL_RX_DATA4 = 192, + PARL_RX_DATA5 = 193, + PARL_RX_DATA6 = 194, + PARL_RX_DATA7 = 195, + PARL_RX_DATA8 = 196, + PARL_RX_DATA9 = 197, + PARL_RX_DATA10 = 198, + PARL_RX_DATA11 = 199, + PARL_RX_DATA12 = 200, + PARL_RX_DATA13 = 201, + PARL_RX_DATA14 = 202, + PARL_RX_DATA15 = 203, CPU_GPIO_0 = 214, CPU_GPIO_1 = 215, CPU_GPIO_2 = 216, @@ -7748,24 +8614,24 @@ macro_rules! define_io_mux_signals { EMAC_TXD2 = 181, EMAC_TXD3 = 182, EMAC_TXER = 183, - PARLIO_RX_CLK = 186, - PARLIO_TX_CLK = 187, - PARLIO_TX_DATA0 = 188, - PARLIO_TX_DATA1 = 189, - PARLIO_TX_DATA2 = 190, - PARLIO_TX_DATA3 = 191, - PARLIO_TX_DATA4 = 192, - PARLIO_TX_DATA5 = 193, - PARLIO_TX_DATA6 = 194, - PARLIO_TX_DATA7 = 195, - PARLIO_TX_DATA8 = 196, - PARLIO_TX_DATA9 = 197, - PARLIO_TX_DATA10 = 198, - PARLIO_TX_DATA11 = 199, - PARLIO_TX_DATA12 = 200, - PARLIO_TX_DATA13 = 201, - PARLIO_TX_DATA14 = 202, - PARLIO_TX_DATA15 = 203, + PARL_RX_CLK = 186, + PARL_TX_CLK = 187, + PARL_TX_DATA0 = 188, + PARL_TX_DATA1 = 189, + PARL_TX_DATA2 = 190, + PARL_TX_DATA3 = 191, + PARL_TX_DATA4 = 192, + PARL_TX_DATA5 = 193, + PARL_TX_DATA6 = 194, + PARL_TX_DATA7 = 195, + PARL_TX_DATA8 = 196, + PARL_TX_DATA9 = 197, + PARL_TX_DATA10 = 198, + PARL_TX_DATA11 = 199, + PARL_TX_DATA12 = 200, + PARL_TX_DATA13 = 201, + PARL_TX_DATA14 = 202, + PARL_TX_DATA15 = 203, CONSTANT0 = 212, CONSTANT1 = 213, CPU_GPIO_0 = 214, @@ -7784,7 +8650,7 @@ macro_rules! define_io_mux_signals { CPU_GPIO_13 = 227, CPU_GPIO_14 = 228, CPU_GPIO_15 = 229, - PARLIO_TX_CS = 242, + PARL_TX_CS = 242, EMAC_PTP_PPS = 243, ANA_COMP0 = 244, ANA_COMP1 = 245, diff --git a/esp-metadata-generated/src/_generated_esp32s2.rs b/esp-metadata-generated/src/_generated_esp32s2.rs index 8460f4fbd06..83ca4783af0 100644 --- a/esp-metadata-generated/src/_generated_esp32s2.rs +++ b/esp-metadata-generated/src/_generated_esp32s2.rs @@ -88,6 +88,9 @@ macro_rules! property { ("gpio.func_in_sel_offset", str) => { stringify!(0) }; + ("gpio.need_soft_isolate_during_pd") => { + false + }; ("gpio.has_bank_1") => { true }; @@ -241,12 +244,6 @@ macro_rules! property { ("i2s.version", str) => { stringify!(1) }; - ("i2s.default_clock_source") => { - 2 - }; - ("i2s.default_clock_source", str) => { - stringify!(2) - }; ("i2s.mclk_divider_bit_width") => { 6 }; @@ -337,9 +334,42 @@ macro_rules! property { ("wifi.csi_supported") => { true }; + ("wifi.has_nan") => { + true + }; + ("wifi.has_ftm") => { + true + }; ("phy.combo_module") => { false }; + ("adc.controller") => { + "rtc" + }; + ("adc.line_calibration") => { + true + }; + ("adc.curve_calibration") => { + false + }; + ("adc.basic_calibration") => { + true + }; + ("adc.calibration_v1_scheme_supported") => { + true + }; + ("adc.channel_compensation") => { + false + }; + ("adc.pcr_clock") => { + false + }; + ("adc.pcr_sar_clk_div") => { + false + }; + ("adc.sar_power_override") => { + false + }; ("ledc.version") => { 2 }; @@ -364,6 +394,9 @@ macro_rules! property { ("timergroup.timg_has_divcnt_rst") => { false }; + ("timergroup.wdt_has_conf_update") => { + false + }; ("aes.has_split_text_registers") => { true }; @@ -481,6 +514,9 @@ macro_rules! property { ("soc.cpu_has_csr_pc") => { false }; + ("soc.cpu_has_zcmp_workaround") => { + false + }; ("soc.multi_core_enabled") => { false }; @@ -496,6 +532,12 @@ macro_rules! property { ("soc.cpu_mcause_mask", str) => { stringify!(0) }; + ("soc.cpu_pmp_granularity") => { + 4 + }; + ("soc.cpu_pmp_granularity", str) => { + stringify!(4) + }; ("clock_tree.cpu_pll_div_in") => { [crate ::soc::clocks::CpuPllDivInConfig::Pll, crate ::soc::clocks::CpuPllDivInConfig::Apll] @@ -532,7 +574,7 @@ macro_rules! property { crate ::soc::clocks::RefTickConfig::RcFast] }; ("clock_tree.rtc_slow_clk") => { - [crate ::soc::clocks::RtcSlowClkConfig::Xtal32k, crate + [#[cfg(use_xtal32k)] crate ::soc::clocks::RtcSlowClkConfig::Xtal32k, crate ::soc::clocks::RtcSlowClkConfig::RcSlow, crate ::soc::clocks::RtcSlowClkConfig::RcFast] }; @@ -542,8 +584,8 @@ macro_rules! property { }; ("clock_tree.timg_calibration_clock") => { [crate ::soc::clocks::TimgCalibrationClockConfig::RtcClk, crate - ::soc::clocks::TimgCalibrationClockConfig::RcFastDivClk, crate - ::soc::clocks::TimgCalibrationClockConfig::Xtal32kClk] + ::soc::clocks::TimgCalibrationClockConfig::RcFastDivClk, #[cfg(use_xtal32k)] + crate ::soc::clocks::TimgCalibrationClockConfig::Xtal32kClk] }; ("clock_tree.timg.function_clock") => { [crate ::soc::clocks::TimgFunctionClockConfig::XtalClk, crate @@ -567,6 +609,19 @@ macro_rules! property { [crate ::soc::clocks::I2cFunctionClockSclk::Apb, crate ::soc::clocks::I2cFunctionClockSclk::RefTick] }; + ("clock_tree.i2s.mclk.sclk") => { + [crate ::soc::clocks::I2sMclkSclk::PllF160m, crate + ::soc::clocks::I2sMclkSclk::Apll] + }; + ("clock_tree.i2s.mclk.div_num") => { + (1, 255) + }; + ("clock_tree.i2s.mclk.div_a") => { + (1, 63) + }; + ("clock_tree.i2s.mclk.div_b") => { + (0, 63) + }; } #[macro_export] #[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] @@ -1117,6 +1172,12 @@ macro_rules! for_each_sw_interrupt { /// todo!() /// } /// +/// // PLL_F160M_CLK +/// +/// fn enable_pll_f160m_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// /// // RC_FAST_CLK /// /// fn enable_rc_fast_clk_impl(_clocks: &mut ClockTree, _en: bool) { @@ -1259,6 +1320,7 @@ macro_rules! for_each_sw_interrupt { /// /// // XTAL32K_CLK /// +/// #[cfg(use_xtal32k)] /// fn enable_xtal32k_clk_impl(_clocks: &mut ClockTree, _en: bool) { /// todo!() /// } @@ -1352,6 +1414,22 @@ macro_rules! for_each_sw_interrupt { /// todo!() /// } /// } +/// impl I2sInstance { +/// // I2S_MCLK +/// +/// fn enable_mclk_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_mclk_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: I2sMclkConfig, +/// ) { +/// todo!() +/// } +/// } /// impl RmtInstance { /// // RMT_SCLK /// @@ -1444,6 +1522,11 @@ macro_rules! define_clock_tree_types { } #[derive(Clone, Copy, PartialEq, Eq, Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum I2sInstance { + I2s0 = 0, + } + #[derive(Clone, Copy, PartialEq, Eq, Debug)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum RmtInstance { Rmt = 0, } @@ -1567,7 +1650,7 @@ macro_rules! define_clock_tree_types { pub const fn new(divisor: CpuPllDivDivisor) -> Self { Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -1602,7 +1685,7 @@ macro_rules! define_clock_tree_types { ); Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -1654,7 +1737,7 @@ macro_rules! define_clock_tree_types { ); Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -1680,7 +1763,7 @@ macro_rules! define_clock_tree_types { ); Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -1701,6 +1784,7 @@ macro_rules! define_clock_tree_types { #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum RtcSlowClkConfig { + #[cfg(use_xtal32k)] /// Selects `XTAL32K_CLK`. Xtal32k, /// Selects `RC_SLOW_CLK`. @@ -1733,6 +1817,7 @@ macro_rules! define_clock_tree_types { RtcClk, /// Selects `RC_FAST_DIV_CLK`. RcFastDivClk, + #[cfg(use_xtal32k)] /// Selects `XTAL32K_CLK`. Xtal32kClk, } @@ -1758,10 +1843,76 @@ macro_rules! define_clock_tree_types { pub const fn new(sclk: I2cFunctionClockSclk) -> Self { Self { sclk } } - pub(crate) fn sclk(self) -> I2cFunctionClockSclk { + pub fn sclk(self) -> I2cFunctionClockSclk { self.sclk } } + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum I2sMclkSclk { + #[default] + /// Selects `PLL_F160M_CLK`. + PllF160m, + /// Selects `APLL_CLK`. + Apll, + } + /// Configures the `I2S0_MCLK` clock node. + /// + /// The output is calculated as `OUTPUT = (sclk * div_a) / (div_num * div_a + div_b)`. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub struct I2sMclkConfig { + sclk: I2sMclkSclk, + div_num: u32, + div_a: u32, + div_b: u32, + } + impl I2sMclkConfig { + /// Creates a new configuration for the MCLK clock node. + /// + /// ## Panics + /// + /// Panics if the div_num value is outside the + /// valid range (1 ..= 255). + /// + /// Panics if the div_a value is outside the + /// valid range (1 ..= 63). + /// + /// Panics if the div_b value is outside the + /// valid range (0 ..= 63). + pub const fn new(sclk: I2sMclkSclk, div_num: u32, div_a: u32, div_b: u32) -> Self { + ::core::assert!( + div_num >= 1 && div_num <= 255, + "`I2S0_MCLK` div_num must be between 1 and 255 (inclusive)." + ); + ::core::assert!( + div_a >= 1 && div_a <= 63, + "`I2S0_MCLK` div_a must be between 1 and 63 (inclusive)." + ); + ::core::assert!( + div_b <= 63, + "`I2S0_MCLK` div_b must be between 0 and 63 (inclusive)." + ); + Self { + sclk, + div_num, + div_a, + div_b, + } + } + pub fn sclk(self) -> I2sMclkSclk { + self.sclk + } + pub fn div_num(self) -> u32 { + self.div_num as u32 + } + pub fn div_a(self) -> u32 { + self.div_a as u32 + } + pub fn div_b(self) -> u32 { + self.div_b as u32 + } + } /// The list of clock signals that the `RMT_SCLK` multiplexer can output. #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] @@ -1812,7 +1963,7 @@ macro_rules! define_clock_tree_types { pub const fn new(sclk: UartFunctionClockSclk) -> Self { Self { sclk } } - pub(crate) fn sclk(self) -> UartFunctionClockSclk { + pub fn sclk(self) -> UartFunctionClockSclk { self.sclk } } @@ -1851,10 +2002,10 @@ macro_rules! define_clock_tree_types { integral, } } - pub(crate) fn fractional(self) -> u32 { + pub fn fractional(self) -> u32 { self.fractional as u32 } - pub(crate) fn integral(self) -> u32 { + pub fn integral(self) -> u32 { self.integral as u32 } } @@ -1876,14 +2027,17 @@ macro_rules! define_clock_tree_types { rtc_fast_clk: Option, timg_calibration_clock: Option, i2c_function_clock: [Option; 2], + i2s_mclk: [Option; 1], rmt_sclk: [Option; 1], timg_function_clock: [Option; 2], uart_function_clock: [Option; 2], uart_baud_rate_generator: [Option; 2], pll_clk_refcount: u32, + apll_clk_refcount: u32, rc_fast_clk_refcount: u32, apb_clk_refcount: u32, ref_tick_refcount: u32, + #[cfg(use_xtal32k)] xtal32k_clk_refcount: u32, rc_fast_div_clk_refcount: u32, rtc_fast_clk_refcount: u32, @@ -1891,6 +2045,7 @@ macro_rules! define_clock_tree_types { timg_calibration_clock_refcount: u32, sdm_function_clock_refcount: [u32; 1], i2c_function_clock_refcount: [u32; 2], + i2s_mclk_refcount: [u32; 1], rmt_sclk_refcount: [u32; 1], spi_function_clock_refcount: [u32; 2], timg_function_clock_refcount: [u32; 2], @@ -1971,6 +2126,10 @@ macro_rules! define_clock_tree_types { pub fn i2c1_function_clock(&self) -> Option { self.i2c_function_clock[I2cInstance::I2c1 as usize] } + /// Returns the current configuration of the I2S0_MCLK clock tree node + pub fn i2s0_mclk(&self) -> Option { + self.i2s_mclk[I2sInstance::I2s0 as usize] + } /// Returns the current configuration of the RMT_SCLK clock tree node pub fn rmt_sclk(&self) -> Option { self.rmt_sclk[RmtInstance::Rmt as usize] @@ -2018,14 +2177,17 @@ macro_rules! define_clock_tree_types { rtc_fast_clk: None, timg_calibration_clock: None, i2c_function_clock: [None; 2], + i2s_mclk: [None; 1], rmt_sclk: [None; 1], timg_function_clock: [None; 2], uart_function_clock: [None; 2], uart_baud_rate_generator: [None; 2], pll_clk_refcount: 0, + apll_clk_refcount: 0, rc_fast_clk_refcount: 0, apb_clk_refcount: 0, ref_tick_refcount: 0, + #[cfg(use_xtal32k)] xtal32k_clk_refcount: 0, rc_fast_div_clk_refcount: 0, rtc_fast_clk_refcount: 0, @@ -2033,6 +2195,7 @@ macro_rules! define_clock_tree_types { timg_calibration_clock_refcount: 0, sdm_function_clock_refcount: [0; 1], i2c_function_clock_refcount: [0; 2], + i2s_mclk_refcount: [0; 1], rmt_sclk_refcount: [0; 1], spi_function_clock_refcount: [0; 2], timg_function_clock_refcount: [0; 2], @@ -2066,6 +2229,8 @@ macro_rules! define_clock_tree_types { ::core::sync::atomic::AtomicU32::new(0); static TIMG_CALIBRATION_CLOCK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); + static I2S_MCLK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; static APB_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); static REF_TICK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = @@ -2080,6 +2245,162 @@ macro_rules! define_clock_tree_types { [const { ::core::sync::atomic::AtomicU32::new(0) }; 2]; static UART_BAUD_RATE_GENERATOR_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 2] = [const { ::core::sync::atomic::AtomicU32::new(0) }; 2]; + /// The clock sources of the device. + /// + /// A clock source is a node of the clock tree that other nodes derive their output + /// from. Ask a node which source it runs on with its `..._root_source` function. + #[derive(Debug, enumset::EnumSetType)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum ClockSource { + /// `XTAL_CLK`. + XtalClk, + /// `RC_FAST_CLK`. + RcFastClk, + #[cfg(use_xtal32k)] + /// `XTAL32K_CLK`. + Xtal32kClk, + /// `RC_SLOW_CLK`. + RcSlowClk, + } + /// Returns the clock source that `XTAL_CLK` currently runs on. + pub fn xtal_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::XtalClk) + } + /// Returns the clock source that `PLL_CLK` currently runs on. + pub fn pll_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `APLL_CLK` currently runs on. + pub fn apll_clk_root_source(clocks: &mut ClockTree) -> Option { + pll_clk_root_source(clocks) + } + /// Returns the clock source that `PLL_F160M_CLK` currently runs on. + pub fn pll_f160m_clk_root_source(clocks: &mut ClockTree) -> Option { + pll_clk_root_source(clocks) + } + /// Returns the clock source that `RC_FAST_CLK` currently runs on. + pub fn rc_fast_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::RcFastClk) + } + /// Returns the clock source that `CPU_PLL_DIV_IN` currently runs on. + pub fn cpu_pll_div_in_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.cpu_pll_div_in?; + match config { + CpuPllDivInConfig::Pll => pll_clk_root_source(clocks), + CpuPllDivInConfig::Apll => apll_clk_root_source(clocks), + } + } + /// Returns the clock source that `CPU_PLL_DIV` currently runs on. + pub fn cpu_pll_div_root_source(clocks: &mut ClockTree) -> Option { + cpu_pll_div_in_root_source(clocks) + } + /// Returns the clock source that `SYSTEM_PRE_DIV_IN` currently runs on. + pub fn system_pre_div_in_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.system_pre_div_in?; + match config { + SystemPreDivInConfig::Xtal => xtal_clk_root_source(clocks), + SystemPreDivInConfig::RcFast => rc_fast_clk_root_source(clocks), + } + } + /// Returns the clock source that `SYSTEM_PRE_DIV` currently runs on. + pub fn system_pre_div_root_source(clocks: &mut ClockTree) -> Option { + system_pre_div_in_root_source(clocks) + } + /// Returns the clock source that `REF_TICK_XTAL` currently runs on. + pub fn ref_tick_xtal_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `REF_TICK_CK8M` currently runs on. + pub fn ref_tick_ck8m_root_source(clocks: &mut ClockTree) -> Option { + rc_fast_clk_root_source(clocks) + } + /// Returns the clock source that `CPU_CLK` currently runs on. + pub fn cpu_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.cpu_clk?; + match config { + CpuClkConfig::Xtal => system_pre_div_root_source(clocks), + CpuClkConfig::RcFast => system_pre_div_root_source(clocks), + CpuClkConfig::Apll => cpu_pll_div_root_source(clocks), + CpuClkConfig::Pll => cpu_pll_div_root_source(clocks), + } + } + /// Returns the clock source that `APB_CLK_CPU_DIV2` currently runs on. + pub fn apb_clk_cpu_div2_root_source(clocks: &mut ClockTree) -> Option { + cpu_clk_root_source(clocks) + } + /// Returns the clock source that `APB_CLK_80M` currently runs on. + pub fn apb_clk_80m_root_source(clocks: &mut ClockTree) -> Option { + cpu_clk_root_source(clocks) + } + #[cfg(use_xtal32k)] + /// Returns the clock source that `XTAL32K_CLK` currently runs on. + pub fn xtal32k_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::Xtal32kClk) + } + /// Returns the clock source that `RC_SLOW_CLK` currently runs on. + pub fn rc_slow_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::RcSlowClk) + } + /// Returns the clock source that `RC_FAST_DIV_CLK` currently runs on. + pub fn rc_fast_div_clk_root_source(clocks: &mut ClockTree) -> Option { + rc_fast_clk_root_source(clocks) + } + /// Returns the clock source that `XTAL_DIV_CLK` currently runs on. + pub fn xtal_div_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `RTC_SLOW_CLK` currently runs on. + pub fn rtc_slow_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.rtc_slow_clk?; + match config { + #[cfg(use_xtal32k)] + RtcSlowClkConfig::Xtal32k => xtal32k_clk_root_source(clocks), + RtcSlowClkConfig::RcSlow => rc_slow_clk_root_source(clocks), + RtcSlowClkConfig::RcFast => rc_fast_div_clk_root_source(clocks), + } + } + /// Returns the clock source that `RTC_FAST_CLK` currently runs on. + pub fn rtc_fast_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.rtc_fast_clk?; + match config { + RtcFastClkConfig::Xtal => xtal_div_clk_root_source(clocks), + RtcFastClkConfig::Rc => rc_fast_clk_root_source(clocks), + } + } + /// Returns the clock source that `UART_MEM_CLK` currently runs on. + pub fn uart_mem_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `TIMG_CALIBRATION_CLOCK` currently runs on. + pub fn timg_calibration_clock_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.timg_calibration_clock?; + match config { + TimgCalibrationClockConfig::RtcClk => rtc_slow_clk_root_source(clocks), + TimgCalibrationClockConfig::RcFastDivClk => rc_fast_div_clk_root_source(clocks), + #[cfg(use_xtal32k)] + TimgCalibrationClockConfig::Xtal32kClk => xtal32k_clk_root_source(clocks), + } + } + /// Returns the clock source that `APB_CLK` currently runs on. + pub fn apb_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.apb_clk?; + match config { + ApbClkConfig::Pll => apb_clk_80m_root_source(clocks), + ApbClkConfig::Apll => apb_clk_cpu_div2_root_source(clocks), + ApbClkConfig::Xtal => cpu_clk_root_source(clocks), + ApbClkConfig::RcFast => cpu_clk_root_source(clocks), + } + } + /// Returns the clock source that `REF_TICK` currently runs on. + pub fn ref_tick_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.ref_tick?; + match config { + RefTickConfig::Pll => ref_tick_xtal_root_source(clocks), + RefTickConfig::Apll => ref_tick_xtal_root_source(clocks), + RefTickConfig::Xtal => ref_tick_xtal_root_source(clocks), + RefTickConfig::RcFast => ref_tick_ck8m_root_source(clocks), + } + } pub fn configure_xtal_clk(clocks: &mut ClockTree, config: XtalClkConfig) { let old_config = clocks.xtal_clk.replace(config); refresh_xtal_clk_downstream(clocks); @@ -2090,8 +2411,7 @@ macro_rules! define_clock_tree_types { } fn request_xtal_clk(_clocks: &mut ClockTree) {} fn release_xtal_clk(_clocks: &mut ClockTree) {} - #[allow(unused_variables)] - pub fn xtal_clk_config_frequency(clocks: &mut ClockTree, config: XtalClkConfig) -> u32 { + pub fn xtal_clk_config_frequency(config: XtalClkConfig) -> u32 { config.value() } pub fn xtal_clk_frequency() -> u32 { @@ -2121,8 +2441,7 @@ macro_rules! define_clock_tree_types { release_xtal_clk(clocks); } } - #[allow(unused_variables)] - pub fn pll_clk_config_frequency(clocks: &mut ClockTree, config: PllClkConfig) -> u32 { + pub fn pll_clk_config_frequency(config: PllClkConfig) -> u32 { config.value() } pub fn pll_clk_frequency() -> u32 { @@ -2141,18 +2460,21 @@ macro_rules! define_clock_tree_types { } pub fn request_apll_clk(clocks: &mut ClockTree) { trace!("Requesting APLL_CLK"); - trace!("Enabling APLL_CLK"); - request_pll_clk(clocks); - enable_apll_clk_impl(clocks, true); + if increment_reference_count(&mut clocks.apll_clk_refcount) { + trace!("Enabling APLL_CLK"); + request_pll_clk(clocks); + enable_apll_clk_impl(clocks, true); + } } pub fn release_apll_clk(clocks: &mut ClockTree) { trace!("Releasing APLL_CLK"); - trace!("Disabling APLL_CLK"); - enable_apll_clk_impl(clocks, false); - release_pll_clk(clocks); + if decrement_reference_count(&mut clocks.apll_clk_refcount) { + trace!("Disabling APLL_CLK"); + enable_apll_clk_impl(clocks, false); + release_pll_clk(clocks); + } } - #[allow(unused_variables)] - pub fn apll_clk_config_frequency(clocks: &mut ClockTree, config: ApllClkConfig) -> u32 { + pub fn apll_clk_config_frequency(config: ApllClkConfig) -> u32 { config.value() } pub fn apll_clk_frequency() -> u32 { @@ -2161,6 +2483,22 @@ macro_rules! define_clock_tree_types { pub fn apll_clk_source_frequency() -> u32 { pll_clk_frequency() } + pub fn request_pll_f160m_clk(clocks: &mut ClockTree) { + trace!("Enabling PLL_F160M_CLK"); + request_pll_clk(clocks); + enable_pll_f160m_clk_impl(clocks, true); + } + pub fn release_pll_f160m_clk(clocks: &mut ClockTree) { + trace!("Disabling PLL_F160M_CLK"); + enable_pll_f160m_clk_impl(clocks, false); + release_pll_clk(clocks); + } + pub fn pll_f160m_clk_frequency() -> u32 { + 160000000 + } + pub fn pll_f160m_clk_source_frequency() -> u32 { + pll_clk_frequency() + } pub fn request_rc_fast_clk(clocks: &mut ClockTree) { trace!("Requesting RC_FAST_CLK"); if increment_reference_count(&mut clocks.rc_fast_clk_refcount) { @@ -2175,9 +2513,30 @@ macro_rules! define_clock_tree_types { enable_rc_fast_clk_impl(clocks, false); } } - pub fn rc_fast_clk_frequency() -> u32 { + static RC_FAST_CLK_FREQUENCY: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(rc_fast_clk_nominal_frequency()); + pub const fn rc_fast_clk_nominal_frequency() -> u32 { 8000000 } + pub fn rc_fast_clk_frequency() -> u32 { + RC_FAST_CLK_FREQUENCY.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn set_rc_fast_clk_frequency(clocks: &mut ClockTree, frequency: u32) { + if !(4000000..=12000000).contains(&frequency) { + warn!( + "Ignoring out-of-range RC_FAST_CLK frequency: {} Hz", + frequency + ); + return; + } + debug!( + "Updating RC_FAST_CLK frequency to {} Hz (nominal {} Hz)", + frequency, + rc_fast_clk_nominal_frequency() + ); + RC_FAST_CLK_FREQUENCY.store(frequency, ::core::sync::atomic::Ordering::Release); + refresh_rc_fast_clk_downstream(clocks); + } pub fn configure_cpu_pll_div_in(clocks: &mut ClockTree, new_selector: CpuPllDivInConfig) { let old_selector = clocks.cpu_pll_div_in.replace(new_selector); refresh_cpu_pll_div_in_downstream(clocks); @@ -2197,7 +2556,6 @@ macro_rules! define_clock_tree_types { clocks.cpu_pll_div_in } pub fn request_cpu_pll_div_in(clocks: &mut ClockTree) { - trace!("Requesting CPU_PLL_DIV_IN"); trace!("Enabling CPU_PLL_DIV_IN"); match unwrap!(clocks.cpu_pll_div_in) { CpuPllDivInConfig::Pll => request_pll_clk(clocks), @@ -2206,7 +2564,6 @@ macro_rules! define_clock_tree_types { enable_cpu_pll_div_in_impl(clocks, true); } pub fn release_cpu_pll_div_in(clocks: &mut ClockTree) { - trace!("Releasing CPU_PLL_DIV_IN"); trace!("Disabling CPU_PLL_DIV_IN"); enable_cpu_pll_div_in_impl(clocks, false); match unwrap!(clocks.cpu_pll_div_in) { @@ -2214,11 +2571,7 @@ macro_rules! define_clock_tree_types { CpuPllDivInConfig::Apll => release_apll_clk(clocks), } } - #[allow(unused_variables)] - pub fn cpu_pll_div_in_config_frequency( - clocks: &mut ClockTree, - config: CpuPllDivInConfig, - ) -> u32 { + pub fn cpu_pll_div_in_config_frequency(config: CpuPllDivInConfig) -> u32 { match config { CpuPllDivInConfig::Pll => pll_clk_frequency(), CpuPllDivInConfig::Apll => apll_clk_frequency(), @@ -2228,10 +2581,7 @@ macro_rules! define_clock_tree_types { CPU_PLL_DIV_IN_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn cpu_pll_div_in_source_frequency(source: CpuPllDivInConfig) -> u32 { - match source { - CpuPllDivInConfig::Pll => pll_clk_frequency(), - CpuPllDivInConfig::Apll => apll_clk_frequency(), - } + cpu_pll_div_in_config_frequency(source) } pub fn configure_cpu_pll_div(clocks: &mut ClockTree, config: CpuPllDivConfig) { let old_config = clocks.cpu_pll_div.replace(config); @@ -2242,22 +2592,16 @@ macro_rules! define_clock_tree_types { clocks.cpu_pll_div } pub fn request_cpu_pll_div(clocks: &mut ClockTree) { - trace!("Requesting CPU_PLL_DIV"); trace!("Enabling CPU_PLL_DIV"); request_cpu_pll_div_in(clocks); enable_cpu_pll_div_impl(clocks, true); } pub fn release_cpu_pll_div(clocks: &mut ClockTree) { - trace!("Releasing CPU_PLL_DIV"); trace!("Disabling CPU_PLL_DIV"); enable_cpu_pll_div_impl(clocks, false); release_cpu_pll_div_in(clocks); } - #[allow(unused_variables)] - pub fn cpu_pll_div_config_frequency( - clocks: &mut ClockTree, - config: CpuPllDivConfig, - ) -> u32 { + pub fn cpu_pll_div_config_frequency(config: CpuPllDivConfig) -> u32 { (cpu_pll_div_in_frequency() / config.divisor()) } pub fn cpu_pll_div_frequency() -> u32 { @@ -2288,7 +2632,6 @@ macro_rules! define_clock_tree_types { clocks.system_pre_div_in } pub fn request_system_pre_div_in(clocks: &mut ClockTree) { - trace!("Requesting SYSTEM_PRE_DIV_IN"); trace!("Enabling SYSTEM_PRE_DIV_IN"); match unwrap!(clocks.system_pre_div_in) { SystemPreDivInConfig::Xtal => request_xtal_clk(clocks), @@ -2297,7 +2640,6 @@ macro_rules! define_clock_tree_types { enable_system_pre_div_in_impl(clocks, true); } pub fn release_system_pre_div_in(clocks: &mut ClockTree) { - trace!("Releasing SYSTEM_PRE_DIV_IN"); trace!("Disabling SYSTEM_PRE_DIV_IN"); enable_system_pre_div_in_impl(clocks, false); match unwrap!(clocks.system_pre_div_in) { @@ -2305,11 +2647,7 @@ macro_rules! define_clock_tree_types { SystemPreDivInConfig::RcFast => release_rc_fast_clk(clocks), } } - #[allow(unused_variables)] - pub fn system_pre_div_in_config_frequency( - clocks: &mut ClockTree, - config: SystemPreDivInConfig, - ) -> u32 { + pub fn system_pre_div_in_config_frequency(config: SystemPreDivInConfig) -> u32 { match config { SystemPreDivInConfig::Xtal => xtal_clk_frequency(), SystemPreDivInConfig::RcFast => rc_fast_clk_frequency(), @@ -2319,10 +2657,7 @@ macro_rules! define_clock_tree_types { SYSTEM_PRE_DIV_IN_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn system_pre_div_in_source_frequency(source: SystemPreDivInConfig) -> u32 { - match source { - SystemPreDivInConfig::Xtal => xtal_clk_frequency(), - SystemPreDivInConfig::RcFast => rc_fast_clk_frequency(), - } + system_pre_div_in_config_frequency(source) } pub fn configure_system_pre_div(clocks: &mut ClockTree, config: SystemPreDivConfig) { let old_config = clocks.system_pre_div.replace(config); @@ -2333,22 +2668,16 @@ macro_rules! define_clock_tree_types { clocks.system_pre_div } pub fn request_system_pre_div(clocks: &mut ClockTree) { - trace!("Requesting SYSTEM_PRE_DIV"); trace!("Enabling SYSTEM_PRE_DIV"); request_system_pre_div_in(clocks); enable_system_pre_div_impl(clocks, true); } pub fn release_system_pre_div(clocks: &mut ClockTree) { - trace!("Releasing SYSTEM_PRE_DIV"); trace!("Disabling SYSTEM_PRE_DIV"); enable_system_pre_div_impl(clocks, false); release_system_pre_div_in(clocks); } - #[allow(unused_variables)] - pub fn system_pre_div_config_frequency( - clocks: &mut ClockTree, - config: SystemPreDivConfig, - ) -> u32 { + pub fn system_pre_div_config_frequency(config: SystemPreDivConfig) -> u32 { (system_pre_div_in_frequency() / (config.divisor() + 1)) } pub fn system_pre_div_frequency() -> u32 { @@ -2360,24 +2689,23 @@ macro_rules! define_clock_tree_types { pub fn configure_apb_clk(clocks: &mut ClockTree, new_selector: ApbClkConfig) { let old_selector = clocks.apb_clk.replace(new_selector); refresh_apb_clk_downstream(clocks); - if clocks.apb_clk_refcount > 0 { + let active = clocks.apb_clk_refcount > 0; + if active { match new_selector { ApbClkConfig::Pll => request_apb_clk_80m(clocks), ApbClkConfig::Apll => request_apb_clk_cpu_div2(clocks), ApbClkConfig::Xtal => request_cpu_clk(clocks), ApbClkConfig::RcFast => request_cpu_clk(clocks), } - configure_apb_clk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - ApbClkConfig::Pll => release_apb_clk_80m(clocks), - ApbClkConfig::Apll => release_apb_clk_cpu_div2(clocks), - ApbClkConfig::Xtal => release_cpu_clk(clocks), - ApbClkConfig::RcFast => release_cpu_clk(clocks), - } + } + configure_apb_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + ApbClkConfig::Pll => release_apb_clk_80m(clocks), + ApbClkConfig::Apll => release_apb_clk_cpu_div2(clocks), + ApbClkConfig::Xtal => release_cpu_clk(clocks), + ApbClkConfig::RcFast => release_cpu_clk(clocks), } - } else { - configure_apb_clk_impl(clocks, old_selector, new_selector); } } pub fn apb_clk_config(clocks: &mut ClockTree) -> Option { @@ -2409,8 +2737,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn apb_clk_config_frequency(clocks: &mut ClockTree, config: ApbClkConfig) -> u32 { + pub fn apb_clk_config_frequency(config: ApbClkConfig) -> u32 { match config { ApbClkConfig::Pll => apb_clk_80m_frequency(), ApbClkConfig::Apll => apb_clk_cpu_div2_frequency(), @@ -2422,34 +2749,28 @@ macro_rules! define_clock_tree_types { APB_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn apb_clk_source_frequency(source: ApbClkConfig) -> u32 { - match source { - ApbClkConfig::Pll => apb_clk_80m_frequency(), - ApbClkConfig::Apll => apb_clk_cpu_div2_frequency(), - ApbClkConfig::Xtal => cpu_clk_frequency(), - ApbClkConfig::RcFast => cpu_clk_frequency(), - } + apb_clk_config_frequency(source) } pub fn configure_ref_tick(clocks: &mut ClockTree, new_selector: RefTickConfig) { let old_selector = clocks.ref_tick.replace(new_selector); refresh_ref_tick_downstream(clocks); - if clocks.ref_tick_refcount > 0 { + let active = clocks.ref_tick_refcount > 0; + if active { match new_selector { RefTickConfig::Pll => request_ref_tick_xtal(clocks), RefTickConfig::Apll => request_ref_tick_xtal(clocks), RefTickConfig::Xtal => request_ref_tick_xtal(clocks), RefTickConfig::RcFast => request_ref_tick_ck8m(clocks), } - configure_ref_tick_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - RefTickConfig::Pll => release_ref_tick_xtal(clocks), - RefTickConfig::Apll => release_ref_tick_xtal(clocks), - RefTickConfig::Xtal => release_ref_tick_xtal(clocks), - RefTickConfig::RcFast => release_ref_tick_ck8m(clocks), - } + } + configure_ref_tick_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + RefTickConfig::Pll => release_ref_tick_xtal(clocks), + RefTickConfig::Apll => release_ref_tick_xtal(clocks), + RefTickConfig::Xtal => release_ref_tick_xtal(clocks), + RefTickConfig::RcFast => release_ref_tick_ck8m(clocks), } - } else { - configure_ref_tick_impl(clocks, old_selector, new_selector); } } pub fn ref_tick_config(clocks: &mut ClockTree) -> Option { @@ -2481,8 +2802,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn ref_tick_config_frequency(clocks: &mut ClockTree, config: RefTickConfig) -> u32 { + pub fn ref_tick_config_frequency(config: RefTickConfig) -> u32 { match config { RefTickConfig::Pll => ref_tick_xtal_frequency(), RefTickConfig::Apll => ref_tick_xtal_frequency(), @@ -2494,12 +2814,7 @@ macro_rules! define_clock_tree_types { REF_TICK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn ref_tick_source_frequency(source: RefTickConfig) -> u32 { - match source { - RefTickConfig::Pll => ref_tick_xtal_frequency(), - RefTickConfig::Apll => ref_tick_xtal_frequency(), - RefTickConfig::Xtal => ref_tick_xtal_frequency(), - RefTickConfig::RcFast => ref_tick_ck8m_frequency(), - } + ref_tick_config_frequency(source) } pub fn configure_ref_tick_xtal(clocks: &mut ClockTree, config: RefTickXtalConfig) { let old_config = clocks.ref_tick_xtal.replace(config); @@ -2510,22 +2825,16 @@ macro_rules! define_clock_tree_types { clocks.ref_tick_xtal } pub fn request_ref_tick_xtal(clocks: &mut ClockTree) { - trace!("Requesting REF_TICK_XTAL"); trace!("Enabling REF_TICK_XTAL"); request_xtal_clk(clocks); enable_ref_tick_xtal_impl(clocks, true); } pub fn release_ref_tick_xtal(clocks: &mut ClockTree) { - trace!("Releasing REF_TICK_XTAL"); trace!("Disabling REF_TICK_XTAL"); enable_ref_tick_xtal_impl(clocks, false); release_xtal_clk(clocks); } - #[allow(unused_variables)] - pub fn ref_tick_xtal_config_frequency( - clocks: &mut ClockTree, - config: RefTickXtalConfig, - ) -> u32 { + pub fn ref_tick_xtal_config_frequency(config: RefTickXtalConfig) -> u32 { (xtal_clk_frequency() / (config.divisor() + 1)) } pub fn ref_tick_xtal_frequency() -> u32 { @@ -2543,22 +2852,16 @@ macro_rules! define_clock_tree_types { clocks.ref_tick_ck8m } pub fn request_ref_tick_ck8m(clocks: &mut ClockTree) { - trace!("Requesting REF_TICK_CK8M"); trace!("Enabling REF_TICK_CK8M"); request_rc_fast_clk(clocks); enable_ref_tick_ck8m_impl(clocks, true); } pub fn release_ref_tick_ck8m(clocks: &mut ClockTree) { - trace!("Releasing REF_TICK_CK8M"); trace!("Disabling REF_TICK_CK8M"); enable_ref_tick_ck8m_impl(clocks, false); release_rc_fast_clk(clocks); } - #[allow(unused_variables)] - pub fn ref_tick_ck8m_config_frequency( - clocks: &mut ClockTree, - config: RefTickCk8mConfig, - ) -> u32 { + pub fn ref_tick_ck8m_config_frequency(config: RefTickCk8mConfig) -> u32 { (rc_fast_clk_frequency() / (config.divisor() + 1)) } pub fn ref_tick_ck8m_frequency() -> u32 { @@ -2625,8 +2928,7 @@ macro_rules! define_clock_tree_types { } fn request_cpu_clk(_clocks: &mut ClockTree) {} fn release_cpu_clk(_clocks: &mut ClockTree) {} - #[allow(unused_variables)] - pub fn cpu_clk_config_frequency(clocks: &mut ClockTree, config: CpuClkConfig) -> u32 { + pub fn cpu_clk_config_frequency(config: CpuClkConfig) -> u32 { match config { CpuClkConfig::Xtal => system_pre_div_frequency(), CpuClkConfig::RcFast => system_pre_div_frequency(), @@ -2638,13 +2940,11 @@ macro_rules! define_clock_tree_types { CPU_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn request_apb_clk_cpu_div2(clocks: &mut ClockTree) { - trace!("Requesting APB_CLK_CPU_DIV2"); trace!("Enabling APB_CLK_CPU_DIV2"); request_cpu_clk(clocks); enable_apb_clk_cpu_div2_impl(clocks, true); } pub fn release_apb_clk_cpu_div2(clocks: &mut ClockTree) { - trace!("Releasing APB_CLK_CPU_DIV2"); trace!("Disabling APB_CLK_CPU_DIV2"); enable_apb_clk_cpu_div2_impl(clocks, false); release_cpu_clk(clocks); @@ -2656,13 +2956,11 @@ macro_rules! define_clock_tree_types { cpu_clk_frequency() } pub fn request_apb_clk_80m(clocks: &mut ClockTree) { - trace!("Requesting APB_CLK_80M"); trace!("Enabling APB_CLK_80M"); request_cpu_clk(clocks); enable_apb_clk_80m_impl(clocks, true); } pub fn release_apb_clk_80m(clocks: &mut ClockTree) { - trace!("Releasing APB_CLK_80M"); trace!("Disabling APB_CLK_80M"); enable_apb_clk_80m_impl(clocks, false); release_cpu_clk(clocks); @@ -2673,6 +2971,7 @@ macro_rules! define_clock_tree_types { pub fn apb_clk_80m_source_frequency() -> u32 { cpu_clk_frequency() } + #[cfg(use_xtal32k)] pub fn request_xtal32k_clk(clocks: &mut ClockTree) { trace!("Requesting XTAL32K_CLK"); if increment_reference_count(&mut clocks.xtal32k_clk_refcount) { @@ -2680,6 +2979,7 @@ macro_rules! define_clock_tree_types { enable_xtal32k_clk_impl(clocks, true); } } + #[cfg(use_xtal32k)] pub fn release_xtal32k_clk(clocks: &mut ClockTree) { trace!("Releasing XTAL32K_CLK"); if decrement_reference_count(&mut clocks.xtal32k_clk_refcount) { @@ -2687,22 +2987,42 @@ macro_rules! define_clock_tree_types { enable_xtal32k_clk_impl(clocks, false); } } + #[cfg(use_xtal32k)] pub fn xtal32k_clk_frequency() -> u32 { 32768 } pub fn request_rc_slow_clk(clocks: &mut ClockTree) { - trace!("Requesting RC_SLOW_CLK"); trace!("Enabling RC_SLOW_CLK"); enable_rc_slow_clk_impl(clocks, true); } pub fn release_rc_slow_clk(clocks: &mut ClockTree) { - trace!("Releasing RC_SLOW_CLK"); trace!("Disabling RC_SLOW_CLK"); enable_rc_slow_clk_impl(clocks, false); } - pub fn rc_slow_clk_frequency() -> u32 { + static RC_SLOW_CLK_FREQUENCY: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(rc_slow_clk_nominal_frequency()); + pub const fn rc_slow_clk_nominal_frequency() -> u32 { 90000 } + pub fn rc_slow_clk_frequency() -> u32 { + RC_SLOW_CLK_FREQUENCY.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn set_rc_slow_clk_frequency(clocks: &mut ClockTree, frequency: u32) { + if !(45000..=135000).contains(&frequency) { + warn!( + "Ignoring out-of-range RC_SLOW_CLK frequency: {} Hz", + frequency + ); + return; + } + debug!( + "Updating RC_SLOW_CLK frequency to {} Hz (nominal {} Hz)", + frequency, + rc_slow_clk_nominal_frequency() + ); + RC_SLOW_CLK_FREQUENCY.store(frequency, ::core::sync::atomic::Ordering::Release); + refresh_rc_slow_clk_downstream(clocks); + } pub fn request_rc_fast_div_clk(clocks: &mut ClockTree) { trace!("Requesting RC_FAST_DIV_CLK"); if increment_reference_count(&mut clocks.rc_fast_div_clk_refcount) { @@ -2726,13 +3046,11 @@ macro_rules! define_clock_tree_types { rc_fast_clk_frequency() } pub fn request_xtal_div_clk(clocks: &mut ClockTree) { - trace!("Requesting XTAL_DIV_CLK"); trace!("Enabling XTAL_DIV_CLK"); request_xtal_clk(clocks); enable_xtal_div_clk_impl(clocks, true); } pub fn release_xtal_div_clk(clocks: &mut ClockTree) { - trace!("Releasing XTAL_DIV_CLK"); trace!("Disabling XTAL_DIV_CLK"); enable_xtal_div_clk_impl(clocks, false); release_xtal_clk(clocks); @@ -2747,6 +3065,7 @@ macro_rules! define_clock_tree_types { let old_selector = clocks.rtc_slow_clk.replace(new_selector); refresh_rtc_slow_clk_downstream(clocks); match new_selector { + #[cfg(use_xtal32k)] RtcSlowClkConfig::Xtal32k => request_xtal32k_clk(clocks), RtcSlowClkConfig::RcSlow => request_rc_slow_clk(clocks), RtcSlowClkConfig::RcFast => request_rc_fast_div_clk(clocks), @@ -2754,6 +3073,7 @@ macro_rules! define_clock_tree_types { configure_rtc_slow_clk_impl(clocks, old_selector, new_selector); if let Some(old_selector) = old_selector { match old_selector { + #[cfg(use_xtal32k)] RtcSlowClkConfig::Xtal32k => release_xtal32k_clk(clocks), RtcSlowClkConfig::RcSlow => release_rc_slow_clk(clocks), RtcSlowClkConfig::RcFast => release_rc_fast_div_clk(clocks), @@ -2764,9 +3084,9 @@ macro_rules! define_clock_tree_types { clocks.rtc_slow_clk } pub fn request_rtc_slow_clk(clocks: &mut ClockTree) { - trace!("Requesting RTC_SLOW_CLK"); trace!("Enabling RTC_SLOW_CLK"); match unwrap!(clocks.rtc_slow_clk) { + #[cfg(use_xtal32k)] RtcSlowClkConfig::Xtal32k => request_xtal32k_clk(clocks), RtcSlowClkConfig::RcSlow => request_rc_slow_clk(clocks), RtcSlowClkConfig::RcFast => request_rc_fast_div_clk(clocks), @@ -2774,21 +3094,18 @@ macro_rules! define_clock_tree_types { enable_rtc_slow_clk_impl(clocks, true); } pub fn release_rtc_slow_clk(clocks: &mut ClockTree) { - trace!("Releasing RTC_SLOW_CLK"); trace!("Disabling RTC_SLOW_CLK"); enable_rtc_slow_clk_impl(clocks, false); match unwrap!(clocks.rtc_slow_clk) { + #[cfg(use_xtal32k)] RtcSlowClkConfig::Xtal32k => release_xtal32k_clk(clocks), RtcSlowClkConfig::RcSlow => release_rc_slow_clk(clocks), RtcSlowClkConfig::RcFast => release_rc_fast_div_clk(clocks), } } - #[allow(unused_variables)] - pub fn rtc_slow_clk_config_frequency( - clocks: &mut ClockTree, - config: RtcSlowClkConfig, - ) -> u32 { + pub fn rtc_slow_clk_config_frequency(config: RtcSlowClkConfig) -> u32 { match config { + #[cfg(use_xtal32k)] RtcSlowClkConfig::Xtal32k => xtal32k_clk_frequency(), RtcSlowClkConfig::RcSlow => rc_slow_clk_frequency(), RtcSlowClkConfig::RcFast => rc_fast_div_clk_frequency(), @@ -2798,29 +3115,24 @@ macro_rules! define_clock_tree_types { RTC_SLOW_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn rtc_slow_clk_source_frequency(source: RtcSlowClkConfig) -> u32 { - match source { - RtcSlowClkConfig::Xtal32k => xtal32k_clk_frequency(), - RtcSlowClkConfig::RcSlow => rc_slow_clk_frequency(), - RtcSlowClkConfig::RcFast => rc_fast_div_clk_frequency(), - } + rtc_slow_clk_config_frequency(source) } pub fn configure_rtc_fast_clk(clocks: &mut ClockTree, new_selector: RtcFastClkConfig) { let old_selector = clocks.rtc_fast_clk.replace(new_selector); refresh_rtc_fast_clk_downstream(clocks); - if clocks.rtc_fast_clk_refcount > 0 { + let active = clocks.rtc_fast_clk_refcount > 0; + if active { match new_selector { RtcFastClkConfig::Xtal => request_xtal_div_clk(clocks), RtcFastClkConfig::Rc => request_rc_fast_clk(clocks), } - configure_rtc_fast_clk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - RtcFastClkConfig::Xtal => release_xtal_div_clk(clocks), - RtcFastClkConfig::Rc => release_rc_fast_clk(clocks), - } + } + configure_rtc_fast_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + RtcFastClkConfig::Xtal => release_xtal_div_clk(clocks), + RtcFastClkConfig::Rc => release_rc_fast_clk(clocks), } - } else { - configure_rtc_fast_clk_impl(clocks, old_selector, new_selector); } } pub fn rtc_fast_clk_config(clocks: &mut ClockTree) -> Option { @@ -2848,11 +3160,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn rtc_fast_clk_config_frequency( - clocks: &mut ClockTree, - config: RtcFastClkConfig, - ) -> u32 { + pub fn rtc_fast_clk_config_frequency(config: RtcFastClkConfig) -> u32 { match config { RtcFastClkConfig::Xtal => xtal_div_clk_frequency(), RtcFastClkConfig::Rc => rc_fast_clk_frequency(), @@ -2862,10 +3170,7 @@ macro_rules! define_clock_tree_types { RTC_FAST_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn rtc_fast_clk_source_frequency(source: RtcFastClkConfig) -> u32 { - match source { - RtcFastClkConfig::Xtal => xtal_div_clk_frequency(), - RtcFastClkConfig::Rc => rc_fast_clk_frequency(), - } + rtc_fast_clk_config_frequency(source) } pub fn request_uart_mem_clk(clocks: &mut ClockTree) { trace!("Requesting UART_MEM_CLK"); @@ -2897,22 +3202,23 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.timg_calibration_clock.replace(new_selector); refresh_timg_calibration_clock_downstream(clocks); - if clocks.timg_calibration_clock_refcount > 0 { + let active = clocks.timg_calibration_clock_refcount > 0; + if active { match new_selector { TimgCalibrationClockConfig::RtcClk => request_rtc_slow_clk(clocks), TimgCalibrationClockConfig::RcFastDivClk => request_rc_fast_div_clk(clocks), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => request_xtal32k_clk(clocks), } - configure_timg_calibration_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - TimgCalibrationClockConfig::RtcClk => release_rtc_slow_clk(clocks), - TimgCalibrationClockConfig::RcFastDivClk => release_rc_fast_div_clk(clocks), - TimgCalibrationClockConfig::Xtal32kClk => release_xtal32k_clk(clocks), - } + } + configure_timg_calibration_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + TimgCalibrationClockConfig::RtcClk => release_rtc_slow_clk(clocks), + TimgCalibrationClockConfig::RcFastDivClk => release_rc_fast_div_clk(clocks), + #[cfg(use_xtal32k)] + TimgCalibrationClockConfig::Xtal32kClk => release_xtal32k_clk(clocks), } - } else { - configure_timg_calibration_clock_impl(clocks, old_selector, new_selector); } } pub fn timg_calibration_clock_config( @@ -2928,6 +3234,7 @@ macro_rules! define_clock_tree_types { match unwrap!(clocks.timg_calibration_clock) { TimgCalibrationClockConfig::RtcClk => request_rtc_slow_clk(clocks), TimgCalibrationClockConfig::RcFastDivClk => request_rc_fast_div_clk(clocks), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => request_xtal32k_clk(clocks), } enable_timg_calibration_clock_impl(clocks, true); @@ -2942,18 +3249,16 @@ macro_rules! define_clock_tree_types { match unwrap!(clocks.timg_calibration_clock) { TimgCalibrationClockConfig::RtcClk => release_rtc_slow_clk(clocks), TimgCalibrationClockConfig::RcFastDivClk => release_rc_fast_div_clk(clocks), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => release_xtal32k_clk(clocks), } } } - #[allow(unused_variables)] - pub fn timg_calibration_clock_config_frequency( - clocks: &mut ClockTree, - config: TimgCalibrationClockConfig, - ) -> u32 { + pub fn timg_calibration_clock_config_frequency(config: TimgCalibrationClockConfig) -> u32 { match config { TimgCalibrationClockConfig::RtcClk => rtc_slow_clk_frequency(), TimgCalibrationClockConfig::RcFastDivClk => rc_fast_div_clk_frequency(), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => xtal32k_clk_frequency(), } } @@ -2961,11 +3266,7 @@ macro_rules! define_clock_tree_types { TIMG_CALIBRATION_CLOCK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn timg_calibration_clock_source_frequency(source: TimgCalibrationClockConfig) -> u32 { - match source { - TimgCalibrationClockConfig::RtcClk => rtc_slow_clk_frequency(), - TimgCalibrationClockConfig::RcFastDivClk => rc_fast_div_clk_frequency(), - TimgCalibrationClockConfig::Xtal32kClk => xtal32k_clk_frequency(), - } + timg_calibration_clock_config_frequency(source) } impl SdmInstance { pub fn request_function_clock(self, clocks: &mut ClockTree) { @@ -3001,20 +3302,19 @@ macro_rules! define_clock_tree_types { ) { let old_config = clocks.i2c_function_clock[self as usize].replace(config); refresh_i2c_function_clock_downstream(clocks, self); - if clocks.i2c_function_clock_refcount[self as usize] > 0 { + let active = clocks.i2c_function_clock_refcount[self as usize] > 0; + if active { match config.sclk { I2cFunctionClockSclk::Apb => request_apb_clk(clocks), I2cFunctionClockSclk::RefTick => request_ref_tick(clocks), } - self.configure_function_clock_impl(clocks, old_config, config); - if let Some(old_config) = old_config { - match old_config.sclk { - I2cFunctionClockSclk::Apb => release_apb_clk(clocks), - I2cFunctionClockSclk::RefTick => release_ref_tick(clocks), - } + } + self.configure_function_clock_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + I2cFunctionClockSclk::Apb => release_apb_clk(clocks), + I2cFunctionClockSclk::RefTick => release_ref_tick(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_config, config); } } pub fn function_clock_config( @@ -3049,11 +3349,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: I2cFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: I2cFunctionClockConfig) -> u32 { match config.sclk { I2cFunctionClockSclk::Apb => apb_clk_frequency(), I2cFunctionClockSclk::RefTick => ref_tick_frequency(), @@ -3070,24 +3366,88 @@ macro_rules! define_clock_tree_types { } } } + impl I2sInstance { + pub fn configure_mclk(self, clocks: &mut ClockTree, config: I2sMclkConfig) { + let old_config = clocks.i2s_mclk[self as usize].replace(config); + refresh_i2s_mclk_downstream(clocks, self); + let active = clocks.i2s_mclk_refcount[self as usize] > 0; + if active { + match config.sclk { + I2sMclkSclk::PllF160m => request_pll_f160m_clk(clocks), + I2sMclkSclk::Apll => request_apll_clk(clocks), + } + } + self.configure_mclk_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + I2sMclkSclk::PllF160m => release_pll_f160m_clk(clocks), + I2sMclkSclk::Apll => release_apll_clk(clocks), + } + } + } + pub fn mclk_config(self, clocks: &mut ClockTree) -> Option { + clocks.i2s_mclk[self as usize] + } + pub fn request_mclk(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::MCLK", self); + if increment_reference_count(&mut clocks.i2s_mclk_refcount[self as usize]) { + trace!("Enabling {:?}::MCLK", self); + crate::rtc_cntl::WakeLock::acquire(); + match unwrap!(clocks.i2s_mclk[self as usize]).sclk { + I2sMclkSclk::PllF160m => request_pll_f160m_clk(clocks), + I2sMclkSclk::Apll => request_apll_clk(clocks), + } + self.enable_mclk_impl(clocks, true); + } + } + pub fn release_mclk(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::MCLK", self); + if decrement_reference_count(&mut clocks.i2s_mclk_refcount[self as usize]) { + trace!("Disabling {:?}::MCLK", self); + crate::rtc_cntl::WakeLock::release(); + self.enable_mclk_impl(clocks, false); + match unwrap!(clocks.i2s_mclk[self as usize]).sclk { + I2sMclkSclk::PllF160m => release_pll_f160m_clk(clocks), + I2sMclkSclk::Apll => release_apll_clk(clocks), + } + } + } + pub fn mclk_config_frequency(config: I2sMclkConfig) -> u32 { + (((match config.sclk { + I2sMclkSclk::PllF160m => pll_f160m_clk_frequency(), + I2sMclkSclk::Apll => apll_clk_frequency(), + } as u64) + * (config.div_a() as u64)) + / (((config.div_num() * config.div_a()) + config.div_b()) as u64)) + as u32 + } + pub fn mclk_frequency(self) -> u32 { + I2S_MCLK_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) + } + pub fn mclk_source_frequency(sclk: I2sMclkSclk) -> u32 { + match sclk { + I2sMclkSclk::PllF160m => pll_f160m_clk_frequency(), + I2sMclkSclk::Apll => apll_clk_frequency(), + } + } + } impl RmtInstance { pub fn configure_sclk(self, clocks: &mut ClockTree, new_selector: RmtSclkConfig) { let old_selector = clocks.rmt_sclk[self as usize].replace(new_selector); refresh_rmt_sclk_downstream(clocks, self); - if clocks.rmt_sclk_refcount[self as usize] > 0 { + let active = clocks.rmt_sclk_refcount[self as usize] > 0; + if active { match new_selector { RmtSclkConfig::RefTick => request_ref_tick(clocks), RmtSclkConfig::ApbClk => request_apb_clk(clocks), } - self.configure_sclk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - RmtSclkConfig::RefTick => release_ref_tick(clocks), - RmtSclkConfig::ApbClk => release_apb_clk(clocks), - } + } + self.configure_sclk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + RmtSclkConfig::RefTick => release_ref_tick(clocks), + RmtSclkConfig::ApbClk => release_apb_clk(clocks), } - } else { - self.configure_sclk_impl(clocks, old_selector, new_selector); } } pub fn sclk_config(self, clocks: &mut ClockTree) -> Option { @@ -3117,8 +3477,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn sclk_config_frequency(clocks: &mut ClockTree, config: RmtSclkConfig) -> u32 { + pub fn sclk_config_frequency(config: RmtSclkConfig) -> u32 { match config { RmtSclkConfig::RefTick => ref_tick_frequency(), RmtSclkConfig::ApbClk => apb_clk_frequency(), @@ -3128,10 +3487,7 @@ macro_rules! define_clock_tree_types { RMT_SCLK_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) } pub fn sclk_source_frequency(source: RmtSclkConfig) -> u32 { - match source { - RmtSclkConfig::RefTick => ref_tick_frequency(), - RmtSclkConfig::ApbClk => apb_clk_frequency(), - } + Self::sclk_config_frequency(source) } } impl SpiInstance { @@ -3172,20 +3528,19 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.timg_function_clock[self as usize].replace(new_selector); refresh_timg_function_clock_downstream(clocks, self); - if clocks.timg_function_clock_refcount[self as usize] > 0 { + let active = clocks.timg_function_clock_refcount[self as usize] > 0; + if active { match new_selector { TimgFunctionClockConfig::XtalClk => request_xtal_clk(clocks), TimgFunctionClockConfig::ApbClk => request_apb_clk(clocks), } - self.configure_function_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - TimgFunctionClockConfig::XtalClk => release_xtal_clk(clocks), - TimgFunctionClockConfig::ApbClk => release_apb_clk(clocks), - } + } + self.configure_function_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + TimgFunctionClockConfig::XtalClk => release_xtal_clk(clocks), + TimgFunctionClockConfig::ApbClk => release_apb_clk(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_selector, new_selector); } } pub fn function_clock_config( @@ -3220,11 +3575,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: TimgFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: TimgFunctionClockConfig) -> u32 { match config { TimgFunctionClockConfig::XtalClk => xtal_clk_frequency(), TimgFunctionClockConfig::ApbClk => apb_clk_frequency(), @@ -3235,10 +3586,7 @@ macro_rules! define_clock_tree_types { .load(::core::sync::atomic::Ordering::Acquire) } pub fn function_clock_source_frequency(source: TimgFunctionClockConfig) -> u32 { - match source { - TimgFunctionClockConfig::XtalClk => xtal_clk_frequency(), - TimgFunctionClockConfig::ApbClk => apb_clk_frequency(), - } + Self::function_clock_config_frequency(source) } } impl UartInstance { @@ -3249,20 +3597,19 @@ macro_rules! define_clock_tree_types { ) { let old_config = clocks.uart_function_clock[self as usize].replace(config); refresh_uart_function_clock_downstream(clocks, self); - if clocks.uart_function_clock_refcount[self as usize] > 0 { + let active = clocks.uart_function_clock_refcount[self as usize] > 0; + if active { match config.sclk { UartFunctionClockSclk::Apb => request_apb_clk(clocks), UartFunctionClockSclk::RefTick => request_ref_tick(clocks), } - self.configure_function_clock_impl(clocks, old_config, config); - if let Some(old_config) = old_config { - match old_config.sclk { - UartFunctionClockSclk::Apb => release_apb_clk(clocks), - UartFunctionClockSclk::RefTick => release_ref_tick(clocks), - } + } + self.configure_function_clock_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + UartFunctionClockSclk::Apb => release_apb_clk(clocks), + UartFunctionClockSclk::RefTick => release_ref_tick(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_config, config); } } pub fn function_clock_config( @@ -3297,11 +3644,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: UartFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: UartFunctionClockConfig) -> u32 { match config.sclk { UartFunctionClockSclk::Apb => apb_clk_frequency(), UartFunctionClockSclk::RefTick => ref_tick_frequency(), @@ -3352,10 +3695,8 @@ macro_rules! define_clock_tree_types { self.release_function_clock(clocks); } } - #[allow(unused_variables)] pub fn baud_rate_generator_config_frequency( self, - clocks: &mut ClockTree, config: UartBaudRateGeneratorConfig, ) -> u32 { ((self.function_clock_frequency() * 16) @@ -3462,7 +3803,7 @@ macro_rules! define_clock_tree_types { fn refresh_xtal_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.xtal_clk { XTAL_CLK_FREQ_CACHE.store( - xtal_clk_config_frequency(clocks, config), + xtal_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3477,26 +3818,39 @@ macro_rules! define_clock_tree_types { fn refresh_pll_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.pll_clk { PLL_CLK_FREQ_CACHE.store( - pll_clk_config_frequency(clocks, config), + pll_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } refresh_apll_clk_downstream(clocks); refresh_cpu_pll_div_in_downstream(clocks); + for child_instance in [I2sInstance::I2s0] { + refresh_i2s_mclk_downstream(clocks, child_instance); + } } fn refresh_apll_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.apll_clk { APLL_CLK_FREQ_CACHE.store( - apll_clk_config_frequency(clocks, config), + apll_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } refresh_cpu_pll_div_in_downstream(clocks); + for child_instance in [I2sInstance::I2s0] { + refresh_i2s_mclk_downstream(clocks, child_instance); + } + } + fn refresh_rc_fast_clk_downstream(clocks: &mut ClockTree) { + refresh_system_pre_div_in_downstream(clocks); + refresh_ref_tick_ck8m_downstream(clocks); + refresh_rtc_slow_clk_downstream(clocks); + refresh_rtc_fast_clk_downstream(clocks); + refresh_timg_calibration_clock_downstream(clocks); } fn refresh_cpu_pll_div_in_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.cpu_pll_div_in { CPU_PLL_DIV_IN_FREQ_CACHE.store( - cpu_pll_div_in_config_frequency(clocks, config), + cpu_pll_div_in_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3505,7 +3859,7 @@ macro_rules! define_clock_tree_types { fn refresh_cpu_pll_div_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.cpu_pll_div { CPU_PLL_DIV_FREQ_CACHE.store( - cpu_pll_div_config_frequency(clocks, config), + cpu_pll_div_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3514,7 +3868,7 @@ macro_rules! define_clock_tree_types { fn refresh_system_pre_div_in_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.system_pre_div_in { SYSTEM_PRE_DIV_IN_FREQ_CACHE.store( - system_pre_div_in_config_frequency(clocks, config), + system_pre_div_in_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3523,7 +3877,7 @@ macro_rules! define_clock_tree_types { fn refresh_system_pre_div_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.system_pre_div { SYSTEM_PRE_DIV_FREQ_CACHE.store( - system_pre_div_config_frequency(clocks, config), + system_pre_div_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3532,7 +3886,7 @@ macro_rules! define_clock_tree_types { fn refresh_ref_tick_xtal_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.ref_tick_xtal { REF_TICK_XTAL_FREQ_CACHE.store( - ref_tick_xtal_config_frequency(clocks, config), + ref_tick_xtal_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3541,7 +3895,7 @@ macro_rules! define_clock_tree_types { fn refresh_ref_tick_ck8m_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.ref_tick_ck8m { REF_TICK_CK8M_FREQ_CACHE.store( - ref_tick_ck8m_config_frequency(clocks, config), + ref_tick_ck8m_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3550,16 +3904,19 @@ macro_rules! define_clock_tree_types { fn refresh_cpu_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.cpu_clk { CPU_CLK_FREQ_CACHE.store( - cpu_clk_config_frequency(clocks, config), + cpu_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } refresh_apb_clk_downstream(clocks); } + fn refresh_rc_slow_clk_downstream(clocks: &mut ClockTree) { + refresh_rtc_slow_clk_downstream(clocks); + } fn refresh_rtc_slow_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.rtc_slow_clk { RTC_SLOW_CLK_FREQ_CACHE.store( - rtc_slow_clk_config_frequency(clocks, config), + rtc_slow_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3568,7 +3925,7 @@ macro_rules! define_clock_tree_types { fn refresh_rtc_fast_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.rtc_fast_clk { RTC_FAST_CLK_FREQ_CACHE.store( - rtc_fast_clk_config_frequency(clocks, config), + rtc_fast_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3576,7 +3933,15 @@ macro_rules! define_clock_tree_types { fn refresh_timg_calibration_clock_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.timg_calibration_clock { TIMG_CALIBRATION_CLOCK_FREQ_CACHE.store( - timg_calibration_clock_config_frequency(clocks, config), + timg_calibration_clock_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + fn refresh_i2s_mclk_downstream(clocks: &mut ClockTree, instance: I2sInstance) { + if let Some(config) = clocks.i2s_mclk[instance as usize] { + I2S_MCLK_FREQ_CACHE[instance as usize].store( + I2sInstance::mclk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3584,7 +3949,7 @@ macro_rules! define_clock_tree_types { fn refresh_apb_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.apb_clk { APB_CLK_FREQ_CACHE.store( - apb_clk_config_frequency(clocks, config), + apb_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3604,7 +3969,7 @@ macro_rules! define_clock_tree_types { fn refresh_ref_tick_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.ref_tick { REF_TICK_FREQ_CACHE.store( - ref_tick_config_frequency(clocks, config), + ref_tick_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3621,7 +3986,7 @@ macro_rules! define_clock_tree_types { fn refresh_i2c_function_clock_downstream(clocks: &mut ClockTree, instance: I2cInstance) { if let Some(config) = clocks.i2c_function_clock[instance as usize] { I2C_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - I2cInstance::function_clock_config_frequency(clocks, config), + I2cInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3629,7 +3994,7 @@ macro_rules! define_clock_tree_types { fn refresh_rmt_sclk_downstream(clocks: &mut ClockTree, instance: RmtInstance) { if let Some(config) = clocks.rmt_sclk[instance as usize] { RMT_SCLK_FREQ_CACHE[instance as usize].store( - RmtInstance::sclk_config_frequency(clocks, config), + RmtInstance::sclk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3637,7 +4002,7 @@ macro_rules! define_clock_tree_types { fn refresh_timg_function_clock_downstream(clocks: &mut ClockTree, instance: TimgInstance) { if let Some(config) = clocks.timg_function_clock[instance as usize] { TIMG_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - TimgInstance::function_clock_config_frequency(clocks, config), + TimgInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3645,7 +4010,7 @@ macro_rules! define_clock_tree_types { fn refresh_uart_function_clock_downstream(clocks: &mut ClockTree, instance: UartInstance) { if let Some(config) = clocks.uart_function_clock[instance as usize] { UART_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - UartInstance::function_clock_config_frequency(clocks, config), + UartInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3657,7 +4022,7 @@ macro_rules! define_clock_tree_types { ) { if let Some(config) = clocks.uart_baud_rate_generator[instance as usize] { UART_BAUD_RATE_GENERATOR_FREQ_CACHE[instance as usize].store( - instance.baud_rate_generator_config_frequency(clocks, config), + instance.baud_rate_generator_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4325,6 +4690,57 @@ macro_rules! for_each_spi_slave { (SPI3, Spi3, SPI3_CLK, SPI3_D, SPI3_Q, SPI3_CS0))); }; } +/// This macro can be used to generate code for each PCNT unit. +/// +/// For an explanation on the general syntax, as well as usage of individual/repeated +/// matchers, refer to [the crate-level documentation][crate#for_each-macros]. +/// +/// This macro has four options for its "Individual matcher" case: +/// +/// - `names`: `($instance:ident)` +/// - `all`: `($peri:ident, $variant:ident, $sys:ident, $regs:ident, $unit:literal, +/// $interrupt:ident, $sig_ch0:ident, $sig_ch1:ident, $ctrl_ch0:ident, $ctrl_ch1:ident)` +/// - `interrupt`: `($interrupt:ident)` (repeated: one ident per unique IRQ) +/// - `regs`: `($regs:ident)` (repeated: one ident per register block) +/// +/// Macro fragments: +/// +/// - `$peri`: unit singleton name (`PCNT0_UNIT0`, `PCNT1_UNIT0`, …) +/// - `$variant`: `AnyPcntUnit` enum variant (`Pcnt0Unit0`, `Pcnt1Unit0`, …) +/// - `$sys`: `esp_hal::system::Peripheral` variant for clocks +/// - `$regs`: register-block singleton (`PCNT`, `PCNT1`) +/// - `$unit`: hardware unit index within that register block +/// - `$interrupt`: shared peripheral interrupt +/// - `$sig_ch0`, `$sig_ch1`, `$ctrl_ch0`, `$ctrl_ch1`: GPIO matrix input signals +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! for_each_pcnt_unit { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _for_each_inner_pcnt_unit { $(($pattern) => $code;)* ($other : tt) + => {} } _for_each_inner_pcnt_unit!((PCNT0_UNIT0)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT2)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT3)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT0, Pcnt0Unit0, Pcnt, PCNT, 0, PCNT, + PCNT0_SIG_CH0, PCNT0_SIG_CH1, PCNT0_CTRL_CH0, PCNT0_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT1, Pcnt0Unit1, Pcnt, PCNT, 1, PCNT, + PCNT1_SIG_CH0, PCNT1_SIG_CH1, PCNT1_CTRL_CH0, PCNT1_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT2, Pcnt0Unit2, Pcnt, PCNT, 2, PCNT, + PCNT2_SIG_CH0, PCNT2_SIG_CH1, PCNT2_CTRL_CH0, PCNT2_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT3, Pcnt0Unit3, Pcnt, PCNT, 3, PCNT, + PCNT3_SIG_CH0, PCNT3_SIG_CH1, PCNT3_CTRL_CH0, PCNT3_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT)); _for_each_inner_pcnt_unit!((PCNT)); + _for_each_inner_pcnt_unit!((names(PCNT0_UNIT0), (PCNT0_UNIT1), (PCNT0_UNIT2), + (PCNT0_UNIT3))); _for_each_inner_pcnt_unit!((all(PCNT0_UNIT0, Pcnt0Unit0, Pcnt, + PCNT, 0, PCNT, PCNT0_SIG_CH0, PCNT0_SIG_CH1, PCNT0_CTRL_CH0, PCNT0_CTRL_CH1), + (PCNT0_UNIT1, Pcnt0Unit1, Pcnt, PCNT, 1, PCNT, PCNT1_SIG_CH0, PCNT1_SIG_CH1, + PCNT1_CTRL_CH0, PCNT1_CTRL_CH1), (PCNT0_UNIT2, Pcnt0Unit2, Pcnt, PCNT, 2, PCNT, + PCNT2_SIG_CH0, PCNT2_SIG_CH1, PCNT2_CTRL_CH0, PCNT2_CTRL_CH1), (PCNT0_UNIT3, + Pcnt0Unit3, Pcnt, PCNT, 3, PCNT, PCNT3_SIG_CH0, PCNT3_SIG_CH1, PCNT3_CTRL_CH0, + PCNT3_CTRL_CH1))); _for_each_inner_pcnt_unit!((interrupt(PCNT))); + _for_each_inner_pcnt_unit!((regs(PCNT))); + }; +} #[macro_export] #[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] macro_rules! for_each_peripheral { @@ -4532,6 +4948,14 @@ macro_rules! for_each_peripheral { (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "DMA_COPY peripheral singleton"] DMA_COPY <= COPY_DMA(DMA_COPY : { bind_dma_interrupt, enable_dma_interrupt, disable_dma_interrupt }) (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT0_UNIT0 peripheral singleton"] PCNT0_UNIT0 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT0_UNIT1 peripheral singleton"] PCNT0_UNIT1 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT0_UNIT2 peripheral singleton"] PCNT0_UNIT2 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT0_UNIT3 peripheral singleton"] PCNT0_UNIT3 <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "SDM_CH0 peripheral singleton"] SDM_CH0 <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "SDM_CH1 peripheral singleton"] SDM_CH1 <= virtual() (unstable))); @@ -4578,8 +5002,9 @@ macro_rules! for_each_peripheral { LEDC <= LEDC() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "NRX peripheral singleton"] NRX <= NRX() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "PCNT peripheral singleton"] - PCNT <= PCNT() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "PMS peripheral singleton"] PMS <= PMS() (unstable))); + PCNT <= PCNT(PCNT : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt }) (unstable))); _for_each_inner_peripheral!((@ peri_type + #[doc = "PMS peripheral singleton"] PMS <= PMS() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "RMT peripheral singleton"] RMT <= RMT() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "RNG peripheral singleton"] RNG <= RNG() (unstable))); @@ -4679,6 +5104,10 @@ macro_rules! for_each_peripheral { _for_each_inner_peripheral!((DMA_I2S0(unstable))); _for_each_inner_peripheral!((DMA_CRYPTO(unstable))); _for_each_inner_peripheral!((DMA_COPY(unstable))); + _for_each_inner_peripheral!((PCNT0_UNIT0(unstable))); + _for_each_inner_peripheral!((PCNT0_UNIT1(unstable))); + _for_each_inner_peripheral!((PCNT0_UNIT2(unstable))); + _for_each_inner_peripheral!((PCNT0_UNIT3(unstable))); _for_each_inner_peripheral!((SDM_CH0(unstable))); _for_each_inner_peripheral!((SDM_CH1(unstable))); _for_each_inner_peripheral!((SDM_CH2(unstable))); @@ -4915,17 +5344,22 @@ macro_rules! for_each_peripheral { disable_dma_interrupt }) (unstable)), (@ peri_type #[doc = "DMA_COPY peripheral singleton"] DMA_COPY <= COPY_DMA(DMA_COPY : { bind_dma_interrupt, enable_dma_interrupt, disable_dma_interrupt }) (unstable)), - (@ peri_type #[doc = "SDM_CH0 peripheral singleton"] SDM_CH0 <= virtual() - (unstable)), (@ peri_type #[doc = "SDM_CH1 peripheral singleton"] SDM_CH1 <= - virtual() (unstable)), (@ peri_type #[doc = "SDM_CH2 peripheral singleton"] - SDM_CH2 <= virtual() (unstable)), (@ peri_type #[doc = - "SDM_CH3 peripheral singleton"] SDM_CH3 <= virtual() (unstable)), (@ peri_type - #[doc = "SDM_CH4 peripheral singleton"] SDM_CH4 <= virtual() (unstable)), (@ - peri_type #[doc = "SDM_CH5 peripheral singleton"] SDM_CH5 <= virtual() - (unstable)), (@ peri_type #[doc = "SDM_CH6 peripheral singleton"] SDM_CH6 <= - virtual() (unstable)), (@ peri_type #[doc = "SDM_CH7 peripheral singleton"] - SDM_CH7 <= virtual() (unstable)), (@ peri_type #[doc = - "AES peripheral singleton"] AES <= AES(AES : { bind_peri_interrupt, + (@ peri_type #[doc = "PCNT0_UNIT0 peripheral singleton"] PCNT0_UNIT0 <= virtual() + (unstable)), (@ peri_type #[doc = "PCNT0_UNIT1 peripheral singleton"] PCNT0_UNIT1 + <= virtual() (unstable)), (@ peri_type #[doc = + "PCNT0_UNIT2 peripheral singleton"] PCNT0_UNIT2 <= virtual() (unstable)), (@ + peri_type #[doc = "PCNT0_UNIT3 peripheral singleton"] PCNT0_UNIT3 <= virtual() + (unstable)), (@ peri_type #[doc = "SDM_CH0 peripheral singleton"] SDM_CH0 <= + virtual() (unstable)), (@ peri_type #[doc = "SDM_CH1 peripheral singleton"] + SDM_CH1 <= virtual() (unstable)), (@ peri_type #[doc = + "SDM_CH2 peripheral singleton"] SDM_CH2 <= virtual() (unstable)), (@ peri_type + #[doc = "SDM_CH3 peripheral singleton"] SDM_CH3 <= virtual() (unstable)), (@ + peri_type #[doc = "SDM_CH4 peripheral singleton"] SDM_CH4 <= virtual() + (unstable)), (@ peri_type #[doc = "SDM_CH5 peripheral singleton"] SDM_CH5 <= + virtual() (unstable)), (@ peri_type #[doc = "SDM_CH6 peripheral singleton"] + SDM_CH6 <= virtual() (unstable)), (@ peri_type #[doc = + "SDM_CH7 peripheral singleton"] SDM_CH7 <= virtual() (unstable)), (@ peri_type + #[doc = "AES peripheral singleton"] AES <= AES(AES : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc = "APB_SARADC peripheral singleton"] APB_SARADC <= APB_SARADC() (unstable)), (@ peri_type #[doc = "DS peripheral singleton"] DS <= DS() (unstable)), (@ peri_type @@ -4949,7 +5383,8 @@ macro_rules! for_each_peripheral { (unstable)), (@ peri_type #[doc = "IO_MUX peripheral singleton"] IO_MUX <= IO_MUX() (unstable)), (@ peri_type #[doc = "LEDC peripheral singleton"] LEDC <= LEDC() (unstable)), (@ peri_type #[doc = "NRX peripheral singleton"] NRX <= NRX() - (unstable)), (@ peri_type #[doc = "PCNT peripheral singleton"] PCNT <= PCNT() + (unstable)), (@ peri_type #[doc = "PCNT peripheral singleton"] PCNT <= PCNT(PCNT + : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc = "PMS peripheral singleton"] PMS <= PMS() (unstable)), (@ peri_type #[doc = "RMT peripheral singleton"] RMT <= RMT() (unstable)), (@ peri_type #[doc = "RNG peripheral singleton"] RNG <= RNG() @@ -5012,21 +5447,22 @@ macro_rules! for_each_peripheral { (GPIO33), (GPIO34), (GPIO35), (GPIO36), (GPIO37), (GPIO38), (GPIO39), (GPIO40), (GPIO41), (GPIO42), (GPIO43), (GPIO44), (GPIO45), (GPIO46), (DMA_SPI2(unstable)), (DMA_SPI3(unstable)), (DMA_I2S0(unstable)), (DMA_CRYPTO(unstable)), - (DMA_COPY(unstable)), (SDM_CH0(unstable)), (SDM_CH1(unstable)), - (SDM_CH2(unstable)), (SDM_CH3(unstable)), (SDM_CH4(unstable)), - (SDM_CH5(unstable)), (SDM_CH6(unstable)), (SDM_CH7(unstable)), (AES(unstable)), - (APB_SARADC(unstable)), (DS(unstable)), (EXTMEM(unstable)), (FE(unstable)), - (FE2(unstable)), (GPIO(unstable)), (GPIO_SD(unstable)), (HMAC(unstable)), - (I2C_ANA_MST(unstable)), (I2C0), (I2C1), (I2S0(unstable)), - (INTERRUPT_CORE0(unstable)), (IO_MUX(unstable)), (LEDC(unstable)), - (NRX(unstable)), (PCNT(unstable)), (PMS(unstable)), (RMT(unstable)), - (RNG(unstable)), (RSA(unstable)), (LPWR(unstable)), (RTC_TIMER(unstable)), - (LP_I2C0(unstable)), (RTC_IO(unstable)), (SENS(unstable)), (SHA(unstable)), - (SPI0(unstable)), (SPI1(unstable)), (SPI2), (SPI3), (SYSCON(unstable)), - (SYSTEM(unstable)), (SYSTIMER(unstable)), (TIMG0(unstable)), (TIMG1(unstable)), - (TWAI0(unstable)), (UART0), (UART1), (UHCI0(unstable)), (USB_FS(unstable)), - (XTS_AES(unstable)), (WIFI), (ADC1(unstable)), (ADC2(unstable)), - (DAC1(unstable)), (DAC2(unstable)), (FLASH(unstable)), + (DMA_COPY(unstable)), (PCNT0_UNIT0(unstable)), (PCNT0_UNIT1(unstable)), + (PCNT0_UNIT2(unstable)), (PCNT0_UNIT3(unstable)), (SDM_CH0(unstable)), + (SDM_CH1(unstable)), (SDM_CH2(unstable)), (SDM_CH3(unstable)), + (SDM_CH4(unstable)), (SDM_CH5(unstable)), (SDM_CH6(unstable)), + (SDM_CH7(unstable)), (AES(unstable)), (APB_SARADC(unstable)), (DS(unstable)), + (EXTMEM(unstable)), (FE(unstable)), (FE2(unstable)), (GPIO(unstable)), + (GPIO_SD(unstable)), (HMAC(unstable)), (I2C_ANA_MST(unstable)), (I2C0), (I2C1), + (I2S0(unstable)), (INTERRUPT_CORE0(unstable)), (IO_MUX(unstable)), + (LEDC(unstable)), (NRX(unstable)), (PCNT(unstable)), (PMS(unstable)), + (RMT(unstable)), (RNG(unstable)), (RSA(unstable)), (LPWR(unstable)), + (RTC_TIMER(unstable)), (LP_I2C0(unstable)), (RTC_IO(unstable)), (SENS(unstable)), + (SHA(unstable)), (SPI0(unstable)), (SPI1(unstable)), (SPI2), (SPI3), + (SYSCON(unstable)), (SYSTEM(unstable)), (SYSTIMER(unstable)), (TIMG0(unstable)), + (TIMG1(unstable)), (TWAI0(unstable)), (UART0), (UART1), (UHCI0(unstable)), + (USB_FS(unstable)), (XTS_AES(unstable)), (WIFI), (ADC1(unstable)), + (ADC2(unstable)), (DAC1(unstable)), (DAC2(unstable)), (FLASH(unstable)), (GPIO_DEDICATED(unstable)), (PSRAM(unstable)), (ULP_RISCV_CORE(unstable)), (FROM_CPU_INTR0(unstable)), (FROM_CPU_INTR1(unstable)), (FROM_CPU_INTR2(unstable)), (FROM_CPU_INTR3(unstable)))); diff --git a/esp-metadata-generated/src/_generated_esp32s3.rs b/esp-metadata-generated/src/_generated_esp32s3.rs index 31d0c5657aa..1fb983c3917 100644 --- a/esp-metadata-generated/src/_generated_esp32s3.rs +++ b/esp-metadata-generated/src/_generated_esp32s3.rs @@ -88,6 +88,9 @@ macro_rules! property { ("gpio.func_in_sel_offset", str) => { stringify!(0) }; + ("gpio.need_soft_isolate_during_pd") => { + false + }; ("gpio.has_bank_1") => { true }; @@ -241,17 +244,11 @@ macro_rules! property { ("i2s.version", str) => { stringify!(2) }; - ("i2s.default_clock_source") => { - 2 - }; - ("i2s.default_clock_source", str) => { - stringify!(2) - }; ("i2s.mclk_divider_bit_width") => { - 6 + 9 }; ("i2s.mclk_divider_bit_width", str) => { - stringify!(6) + stringify!(9) }; ("i2s.max_ws_width") => { 128 @@ -358,6 +355,12 @@ macro_rules! property { ("wifi.csi_supported") => { true }; + ("wifi.has_nan") => { + false + }; + ("wifi.has_ftm") => { + true + }; ("phy.combo_module") => { true }; @@ -367,6 +370,39 @@ macro_rules! property { ("phy.backed_up_digital_register_count", str) => { stringify!(21) }; + ("rgb_display.output_lines") => { + 16 + }; + ("rgb_display.output_lines", str) => { + stringify!(16) + }; + ("adc.controller") => { + "rtc" + }; + ("adc.line_calibration") => { + true + }; + ("adc.curve_calibration") => { + true + }; + ("adc.basic_calibration") => { + true + }; + ("adc.calibration_v1_scheme_supported") => { + true + }; + ("adc.channel_compensation") => { + false + }; + ("adc.pcr_clock") => { + false + }; + ("adc.pcr_sar_clk_div") => { + false + }; + ("adc.sar_power_override") => { + false + }; ("ledc.version") => { 2 }; @@ -391,6 +427,9 @@ macro_rules! property { ("timergroup.timg_has_divcnt_rst") => { false }; + ("timergroup.wdt_has_conf_update") => { + false + }; ("aes.has_split_text_registers") => { true }; @@ -451,6 +490,18 @@ macro_rules! property { ("sleep.deep_sleep_needs_gpio_isolation") => { true }; + ("sleep.cpu_retention_mem_size") => { + 8800 + }; + ("sleep.cpu_retention_mem_align") => { + 16 + }; + ("sleep.cpu_retention_mem_start") => { + 1070104576 + }; + ("sleep.cpu_retention_mem_end") => { + 1070530560 + }; ("assist_debug.has_sp_monitor") => { false }; @@ -520,6 +571,9 @@ macro_rules! property { ("soc.cpu_has_csr_pc") => { false }; + ("soc.cpu_has_zcmp_workaround") => { + false + }; ("soc.multi_core_enabled") => { true }; @@ -535,6 +589,12 @@ macro_rules! property { ("soc.cpu_mcause_mask", str) => { stringify!(0) }; + ("soc.cpu_pmp_granularity") => { + 4 + }; + ("soc.cpu_pmp_granularity", str) => { + stringify!(4) + }; ("clock_tree.system_pre_div_in") => { [crate ::soc::clocks::SystemPreDivInConfig::Xtal, crate ::soc::clocks::SystemPreDivInConfig::RcFast] @@ -557,24 +617,28 @@ macro_rules! property { (0, 3) }; ("clock_tree.rtc_slow_clk") => { - [crate ::soc::clocks::RtcSlowClkConfig::Xtal32k, crate + [#[cfg(use_xtal32k)] crate ::soc::clocks::RtcSlowClkConfig::Xtal32k, crate ::soc::clocks::RtcSlowClkConfig::RcSlow, crate ::soc::clocks::RtcSlowClkConfig::RcFast] }; + ("clock_tree.ble_lp_clk") => { + [crate ::soc::clocks::BleLpClkConfig::Xtal, crate + ::soc::clocks::BleLpClkConfig::RtcSlow] + }; ("clock_tree.rtc_fast_clk") => { [crate ::soc::clocks::RtcFastClkConfig::Xtal, crate ::soc::clocks::RtcFastClkConfig::Rc] }; ("clock_tree.low_power_clk") => { [crate ::soc::clocks::LowPowerClkConfig::Xtal, crate - ::soc::clocks::LowPowerClkConfig::RcFast, crate + ::soc::clocks::LowPowerClkConfig::RcFast, #[cfg(use_xtal32k)] crate ::soc::clocks::LowPowerClkConfig::Xtal32k, crate ::soc::clocks::LowPowerClkConfig::RtcSlow] }; ("clock_tree.timg_calibration_clock") => { [crate ::soc::clocks::TimgCalibrationClockConfig::RcSlowClk, crate - ::soc::clocks::TimgCalibrationClockConfig::RcFastDivClk, crate - ::soc::clocks::TimgCalibrationClockConfig::Xtal32kClk] + ::soc::clocks::TimgCalibrationClockConfig::RcFastDivClk, #[cfg(use_xtal32k)] + crate ::soc::clocks::TimgCalibrationClockConfig::Xtal32kClk] }; ("clock_tree.timg.function_clock") => { [crate ::soc::clocks::TimgFunctionClockConfig::XtalClk, crate @@ -638,6 +702,36 @@ macro_rules! property { [crate ::soc::clocks::SpiFunctionClockConfig::Xtal, crate ::soc::clocks::SpiFunctionClockConfig::Apb] }; + ("clock_tree.i2s.tx_clk.sclk") => { + [crate ::soc::clocks::I2sClkSclk::Xtal, crate ::soc::clocks::I2sClkSclk::PllD2, + crate ::soc::clocks::I2sClkSclk::Pll160m] + }; + ("clock_tree.i2s.tx_clk.div_num") => { + (1, 255) + }; + ("clock_tree.i2s.tx_clk.div_a") => { + (1, 511) + }; + ("clock_tree.i2s.tx_clk.div_b") => { + (0, 511) + }; + ("clock_tree.i2s.rx_clk.sclk") => { + [crate ::soc::clocks::I2sClkSclk::Xtal, crate ::soc::clocks::I2sClkSclk::PllD2, + crate ::soc::clocks::I2sClkSclk::Pll160m] + }; + ("clock_tree.i2s.rx_clk.div_num") => { + (1, 255) + }; + ("clock_tree.i2s.rx_clk.div_a") => { + (1, 511) + }; + ("clock_tree.i2s.rx_clk.div_b") => { + (0, 511) + }; + ("clock_tree.i2s.mclk_out") => { + [crate ::soc::clocks::I2sMclkOutConfig::Tx, crate + ::soc::clocks::I2sMclkOutConfig::Rx] + }; } #[macro_export] #[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] @@ -1370,6 +1464,7 @@ macro_rules! for_each_sw_interrupt { /// /// // XTAL32K_CLK /// +/// #[cfg(use_xtal32k)] /// fn enable_xtal32k_clk_impl(_clocks: &mut ClockTree, _en: bool) { /// todo!() /// } @@ -1518,6 +1613,26 @@ macro_rules! for_each_sw_interrupt { /// todo!() /// } /// +/// // BLE_LP_XTAL_CLK +/// +/// fn enable_ble_lp_xtal_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// // BLE_LP_CLK +/// +/// fn enable_ble_lp_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_ble_lp_clk_impl( +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: BleLpClkConfig, +/// ) { +/// todo!() +/// } +/// /// // RTC_FAST_CLK /// /// fn enable_rtc_fast_clk_impl(_clocks: &mut ClockTree, _en: bool) { @@ -1589,6 +1704,52 @@ macro_rules! for_each_sw_interrupt { /// todo!() /// } /// } +/// impl I2sInstance { +/// // I2S_TX_CLK +/// +/// fn enable_tx_clk_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_tx_clk_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: I2sClkConfig, +/// ) { +/// todo!() +/// } +/// +/// // I2S_RX_CLK +/// +/// fn enable_rx_clk_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_rx_clk_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: I2sClkConfig, +/// ) { +/// todo!() +/// } +/// +/// // I2S_MCLK_OUT +/// +/// fn enable_mclk_out_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_mclk_out_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: I2sMclkOutConfig, +/// ) { +/// todo!() +/// } +/// } /// impl LcdCamInstance { /// // LCD_CAM_LCD_CLOCK /// @@ -1728,6 +1889,12 @@ macro_rules! define_clock_tree_types { } #[derive(Clone, Copy, PartialEq, Eq, Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum I2sInstance { + I2s0 = 0, + I2s1 = 1, + } + #[derive(Clone, Copy, PartialEq, Eq, Debug)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum LcdCamInstance { LcdCam = 0, } @@ -1823,7 +1990,7 @@ macro_rules! define_clock_tree_types { ); Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -1898,7 +2065,7 @@ macro_rules! define_clock_tree_types { ); Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -1906,6 +2073,7 @@ macro_rules! define_clock_tree_types { #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum RtcSlowClkConfig { + #[cfg(use_xtal32k)] /// Selects `XTAL32K_CLK`. Xtal32k, /// Selects `RC_SLOW_CLK`. @@ -1913,6 +2081,15 @@ macro_rules! define_clock_tree_types { /// Selects `RC_FAST_DIV_CLK`. RcFast, } + /// The list of clock signals that the `BLE_LP_CLK` multiplexer can output. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum BleLpClkConfig { + /// Selects `BLE_LP_XTAL_CLK`. + Xtal, + /// Selects `RTC_SLOW_CLK`. + RtcSlow, + } /// The list of clock signals that the `RTC_FAST_CLK` multiplexer can output. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] @@ -1930,6 +2107,7 @@ macro_rules! define_clock_tree_types { Xtal, /// Selects `RC_FAST_CLK`. RcFast, + #[cfg(use_xtal32k)] /// Selects `XTAL32K_CLK`. Xtal32k, /// Selects `RTC_SLOW_CLK`. @@ -1951,6 +2129,7 @@ macro_rules! define_clock_tree_types { RcSlowClk, /// Selects `RC_FAST_DIV_CLK`. RcFastDivClk, + #[cfg(use_xtal32k)] /// Selects `XTAL32K_CLK`. Xtal32kClk, } @@ -1986,12 +2165,90 @@ macro_rules! define_clock_tree_types { ); Self { sclk, div_num } } - pub(crate) fn sclk(self) -> I2cFunctionClockSclk { + pub fn sclk(self) -> I2cFunctionClockSclk { + self.sclk + } + pub fn div_num(self) -> u32 { + self.div_num as u32 + } + } + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum I2sClkSclk { + /// Selects `XTAL_CLK`. + Xtal, + /// Selects `PLL_D2`. + PllD2, + #[default] + /// Selects `PLL_160M`. + Pll160m, + } + /// Configures the `I2S0_TX_CLK` clock node. + /// + /// The output is calculated as `OUTPUT = (sclk * div_a) / (div_num * div_a + div_b)`. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub struct I2sClkConfig { + sclk: I2sClkSclk, + div_num: u32, + div_a: u32, + div_b: u32, + } + impl I2sClkConfig { + /// Creates a new configuration for the TX_CLK clock node. + /// + /// ## Panics + /// + /// Panics if the div_num value is outside the + /// valid range (1 ..= 255). + /// + /// Panics if the div_a value is outside the + /// valid range (1 ..= 511). + /// + /// Panics if the div_b value is outside the + /// valid range (0 ..= 511). + pub const fn new(sclk: I2sClkSclk, div_num: u32, div_a: u32, div_b: u32) -> Self { + ::core::assert!( + div_num >= 1 && div_num <= 255, + "`I2S0_TX_CLK` div_num must be between 1 and 255 (inclusive)." + ); + ::core::assert!( + div_a >= 1 && div_a <= 511, + "`I2S0_TX_CLK` div_a must be between 1 and 511 (inclusive)." + ); + ::core::assert!( + div_b <= 511, + "`I2S0_TX_CLK` div_b must be between 0 and 511 (inclusive)." + ); + Self { + sclk, + div_num, + div_a, + div_b, + } + } + pub fn sclk(self) -> I2sClkSclk { self.sclk } - pub(crate) fn div_num(self) -> u32 { + pub fn div_num(self) -> u32 { self.div_num as u32 } + pub fn div_a(self) -> u32 { + self.div_a as u32 + } + pub fn div_b(self) -> u32 { + self.div_b as u32 + } + } + /// The list of clock signals that the `I2S0_MCLK_OUT` multiplexer can output. + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum I2sMclkOutConfig { + /// Selects `TX_CLK`. + Tx, + #[default] + /// Selects `RX_CLK`. + Rx, } #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] @@ -2053,16 +2310,16 @@ macro_rules! define_clock_tree_types { div_b, } } - pub(crate) fn sclk(self) -> LcdCamLcdClockSclk { + pub fn sclk(self) -> LcdCamLcdClockSclk { self.sclk } - pub(crate) fn div_num(self) -> u32 { + pub fn div_num(self) -> u32 { self.div_num as u32 } - pub(crate) fn div_a(self) -> u32 { + pub fn div_a(self) -> u32 { self.div_a as u32 } - pub(crate) fn div_b(self) -> u32 { + pub fn div_b(self) -> u32 { self.div_b as u32 } } @@ -2126,16 +2383,16 @@ macro_rules! define_clock_tree_types { div_b, } } - pub(crate) fn sclk(self) -> LcdCamCamClockSclk { + pub fn sclk(self) -> LcdCamCamClockSclk { self.sclk } - pub(crate) fn div_num(self) -> u32 { + pub fn div_num(self) -> u32 { self.div_num as u32 } - pub(crate) fn div_a(self) -> u32 { + pub fn div_a(self) -> u32 { self.div_a as u32 } - pub(crate) fn div_b(self) -> u32 { + pub fn div_b(self) -> u32 { self.div_b as u32 } } @@ -2163,9 +2420,9 @@ macro_rules! define_clock_tree_types { #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum SpiFunctionClockConfig { - #[default] /// Selects `XTAL_CLK`. Xtal, + #[default] /// Selects `APB_CLK`. Apb, } @@ -2213,10 +2470,10 @@ macro_rules! define_clock_tree_types { ); Self { sclk, div_num } } - pub(crate) fn sclk(self) -> UartFunctionClockSclk { + pub fn sclk(self) -> UartFunctionClockSclk { self.sclk } - pub(crate) fn div_num(self) -> u32 { + pub fn div_num(self) -> u32 { self.div_num as u32 } } @@ -2254,10 +2511,10 @@ macro_rules! define_clock_tree_types { integral, } } - pub(crate) fn fractional(self) -> u32 { + pub fn fractional(self) -> u32 { self.fractional as u32 } - pub(crate) fn integral(self) -> u32 { + pub fn integral(self) -> u32 { self.integral as u32 } } @@ -2273,10 +2530,14 @@ macro_rules! define_clock_tree_types { cpu_clk: Option, rc_fast_clk_div_n: Option, rtc_slow_clk: Option, + ble_lp_clk: Option, rtc_fast_clk: Option, low_power_clk: Option, timg_calibration_clock: Option, i2c_function_clock: [Option; 2], + i2s_tx_clk: [Option; 2], + i2s_rx_clk: [Option; 2], + i2s_mclk_out: [Option; 2], lcd_cam_lcd_clock: [Option; 1], lcd_cam_cam_clock: [Option; 1], rmt_sclk: [Option; 1], @@ -2286,6 +2547,7 @@ macro_rules! define_clock_tree_types { uart_baud_rate_generator: [Option; 3], pll_clk_refcount: u32, rc_fast_clk_refcount: u32, + #[cfg(use_xtal32k)] xtal32k_clk_refcount: u32, rc_slow_clk_refcount: u32, rc_fast_div_clk_refcount: u32, @@ -2293,12 +2555,17 @@ macro_rules! define_clock_tree_types { crypto_pwm_clk_refcount: u32, pll_d2_refcount: u32, pll_160m_refcount: u32, + rtc_slow_clk_refcount: u32, + ble_lp_clk_refcount: u32, rtc_fast_clk_refcount: u32, low_power_clk_refcount: u32, uart_mem_clk_refcount: u32, timg_calibration_clock_refcount: u32, sdm_function_clock_refcount: [u32; 1], i2c_function_clock_refcount: [u32; 2], + i2s_tx_clk_refcount: [u32; 2], + i2s_rx_clk_refcount: [u32; 2], + i2s_mclk_out_refcount: [u32; 2], lcd_cam_lcd_clock_refcount: [u32; 1], lcd_cam_cam_clock_refcount: [u32; 1], mcpwm_function_clock_refcount: [u32; 2], @@ -2354,6 +2621,10 @@ macro_rules! define_clock_tree_types { pub fn rtc_slow_clk(&self) -> Option { self.rtc_slow_clk } + /// Returns the current configuration of the BLE_LP_CLK clock tree node + pub fn ble_lp_clk(&self) -> Option { + self.ble_lp_clk + } /// Returns the current configuration of the RTC_FAST_CLK clock tree node pub fn rtc_fast_clk(&self) -> Option { self.rtc_fast_clk @@ -2374,6 +2645,30 @@ macro_rules! define_clock_tree_types { pub fn i2c1_function_clock(&self) -> Option { self.i2c_function_clock[I2cInstance::I2c1 as usize] } + /// Returns the current configuration of the I2S0_TX_CLK clock tree node + pub fn i2s0_tx_clk(&self) -> Option { + self.i2s_tx_clk[I2sInstance::I2s0 as usize] + } + /// Returns the current configuration of the I2S0_RX_CLK clock tree node + pub fn i2s0_rx_clk(&self) -> Option { + self.i2s_rx_clk[I2sInstance::I2s0 as usize] + } + /// Returns the current configuration of the I2S0_MCLK_OUT clock tree node + pub fn i2s0_mclk_out(&self) -> Option { + self.i2s_mclk_out[I2sInstance::I2s0 as usize] + } + /// Returns the current configuration of the I2S1_TX_CLK clock tree node + pub fn i2s1_tx_clk(&self) -> Option { + self.i2s_tx_clk[I2sInstance::I2s1 as usize] + } + /// Returns the current configuration of the I2S1_RX_CLK clock tree node + pub fn i2s1_rx_clk(&self) -> Option { + self.i2s_rx_clk[I2sInstance::I2s1 as usize] + } + /// Returns the current configuration of the I2S1_MCLK_OUT clock tree node + pub fn i2s1_mclk_out(&self) -> Option { + self.i2s_mclk_out[I2sInstance::I2s1 as usize] + } /// Returns the current configuration of the LCD_CAM_LCD_CLOCK clock tree node pub fn lcd_cam_lcd_clock(&self) -> Option { self.lcd_cam_lcd_clock[LcdCamInstance::LcdCam as usize] @@ -2439,10 +2734,14 @@ macro_rules! define_clock_tree_types { cpu_clk: None, rc_fast_clk_div_n: None, rtc_slow_clk: None, + ble_lp_clk: None, rtc_fast_clk: None, low_power_clk: None, timg_calibration_clock: None, i2c_function_clock: [None; 2], + i2s_tx_clk: [None; 2], + i2s_rx_clk: [None; 2], + i2s_mclk_out: [None; 2], lcd_cam_lcd_clock: [None; 1], lcd_cam_cam_clock: [None; 1], rmt_sclk: [None; 1], @@ -2452,6 +2751,7 @@ macro_rules! define_clock_tree_types { uart_baud_rate_generator: [None; 3], pll_clk_refcount: 0, rc_fast_clk_refcount: 0, + #[cfg(use_xtal32k)] xtal32k_clk_refcount: 0, rc_slow_clk_refcount: 0, rc_fast_div_clk_refcount: 0, @@ -2459,12 +2759,17 @@ macro_rules! define_clock_tree_types { crypto_pwm_clk_refcount: 0, pll_d2_refcount: 0, pll_160m_refcount: 0, + rtc_slow_clk_refcount: 0, + ble_lp_clk_refcount: 0, rtc_fast_clk_refcount: 0, low_power_clk_refcount: 0, uart_mem_clk_refcount: 0, timg_calibration_clock_refcount: 0, sdm_function_clock_refcount: [0; 1], i2c_function_clock_refcount: [0; 2], + i2s_tx_clk_refcount: [0; 2], + i2s_rx_clk_refcount: [0; 2], + i2s_mclk_out_refcount: [0; 2], lcd_cam_lcd_clock_refcount: [0; 1], lcd_cam_cam_clock_refcount: [0; 1], mcpwm_function_clock_refcount: [0; 2], @@ -2491,6 +2796,8 @@ macro_rules! define_clock_tree_types { ::core::sync::atomic::AtomicU32::new(0); static RTC_SLOW_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); + static BLE_LP_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(0); static RTC_FAST_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); static LOW_POWER_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = @@ -2499,6 +2806,12 @@ macro_rules! define_clock_tree_types { ::core::sync::atomic::AtomicU32::new(0); static I2C_FUNCTION_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 2] = [const { ::core::sync::atomic::AtomicU32::new(0) }; 2]; + static I2S_TX_CLK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 2] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 2]; + static I2S_RX_CLK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 2] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 2]; + static I2S_MCLK_OUT_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 2] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 2]; static LCD_CAM_LCD_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; static LCD_CAM_CAM_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = @@ -2517,6 +2830,164 @@ macro_rules! define_clock_tree_types { [const { ::core::sync::atomic::AtomicU32::new(0) }; 3]; static UART_BAUD_RATE_GENERATOR_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 3] = [const { ::core::sync::atomic::AtomicU32::new(0) }; 3]; + /// The clock sources of the device. + /// + /// A clock source is a node of the clock tree that other nodes derive their output + /// from. Ask a node which source it runs on with its `..._root_source` function. + #[derive(Debug, enumset::EnumSetType)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum ClockSource { + /// `XTAL_CLK`. + XtalClk, + /// `RC_FAST_CLK`. + RcFastClk, + #[cfg(use_xtal32k)] + /// `XTAL32K_CLK`. + Xtal32kClk, + /// `RC_SLOW_CLK`. + RcSlowClk, + } + /// Returns the clock source that `XTAL_CLK` currently runs on. + pub fn xtal_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::XtalClk) + } + /// Returns the clock source that `PLL_CLK` currently runs on. + pub fn pll_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `RC_FAST_CLK` currently runs on. + pub fn rc_fast_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::RcFastClk) + } + #[cfg(use_xtal32k)] + /// Returns the clock source that `XTAL32K_CLK` currently runs on. + pub fn xtal32k_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::Xtal32kClk) + } + /// Returns the clock source that `RC_SLOW_CLK` currently runs on. + pub fn rc_slow_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::RcSlowClk) + } + /// Returns the clock source that `RC_FAST_DIV_CLK` currently runs on. + pub fn rc_fast_div_clk_root_source(clocks: &mut ClockTree) -> Option { + rc_fast_clk_root_source(clocks) + } + /// Returns the clock source that `SYSTEM_PRE_DIV_IN` currently runs on. + pub fn system_pre_div_in_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.system_pre_div_in?; + match config { + SystemPreDivInConfig::Xtal => xtal_clk_root_source(clocks), + SystemPreDivInConfig::RcFast => rc_fast_clk_root_source(clocks), + } + } + /// Returns the clock source that `SYSTEM_PRE_DIV` currently runs on. + pub fn system_pre_div_root_source(clocks: &mut ClockTree) -> Option { + system_pre_div_in_root_source(clocks) + } + /// Returns the clock source that `CPU_PLL_DIV_OUT` currently runs on. + pub fn cpu_pll_div_out_root_source(clocks: &mut ClockTree) -> Option { + pll_clk_root_source(clocks) + } + /// Returns the clock source that `CPU_CLK` currently runs on. + pub fn cpu_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.cpu_clk?; + match config { + CpuClkConfig::Xtal => system_pre_div_root_source(clocks), + CpuClkConfig::RcFast => system_pre_div_root_source(clocks), + CpuClkConfig::Pll => cpu_pll_div_out_root_source(clocks), + } + } + /// Returns the clock source that `PLL_D2` currently runs on. + pub fn pll_d2_root_source(clocks: &mut ClockTree) -> Option { + pll_clk_root_source(clocks) + } + /// Returns the clock source that `PLL_160M` currently runs on. + pub fn pll_160m_root_source(clocks: &mut ClockTree) -> Option { + cpu_clk_root_source(clocks) + } + /// Returns the clock source that `APB_80M` currently runs on. + pub fn apb_80m_root_source(clocks: &mut ClockTree) -> Option { + cpu_clk_root_source(clocks) + } + /// Returns the clock source that `RC_FAST_CLK_DIV_N` currently runs on. + pub fn rc_fast_clk_div_n_root_source(clocks: &mut ClockTree) -> Option { + rc_fast_clk_root_source(clocks) + } + /// Returns the clock source that `XTAL_DIV_CLK` currently runs on. + pub fn xtal_div_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `RTC_SLOW_CLK` currently runs on. + pub fn rtc_slow_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.rtc_slow_clk?; + match config { + #[cfg(use_xtal32k)] + RtcSlowClkConfig::Xtal32k => xtal32k_clk_root_source(clocks), + RtcSlowClkConfig::RcSlow => rc_slow_clk_root_source(clocks), + RtcSlowClkConfig::RcFast => rc_fast_div_clk_root_source(clocks), + } + } + /// Returns the clock source that `BLE_LP_XTAL_CLK` currently runs on. + pub fn ble_lp_xtal_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `BLE_LP_CLK` currently runs on. + pub fn ble_lp_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.ble_lp_clk?; + match config { + BleLpClkConfig::Xtal => ble_lp_xtal_clk_root_source(clocks), + BleLpClkConfig::RtcSlow => rtc_slow_clk_root_source(clocks), + } + } + /// Returns the clock source that `RTC_FAST_CLK` currently runs on. + pub fn rtc_fast_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.rtc_fast_clk?; + match config { + RtcFastClkConfig::Xtal => xtal_div_clk_root_source(clocks), + RtcFastClkConfig::Rc => rc_fast_clk_div_n_root_source(clocks), + } + } + /// Returns the clock source that `LOW_POWER_CLK` currently runs on. + pub fn low_power_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.low_power_clk?; + match config { + LowPowerClkConfig::Xtal => xtal_clk_root_source(clocks), + LowPowerClkConfig::RcFast => rc_fast_clk_root_source(clocks), + #[cfg(use_xtal32k)] + LowPowerClkConfig::Xtal32k => xtal32k_clk_root_source(clocks), + LowPowerClkConfig::RtcSlow => rtc_slow_clk_root_source(clocks), + } + } + /// Returns the clock source that `UART_MEM_CLK` currently runs on. + pub fn uart_mem_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `TIMG_CALIBRATION_CLOCK` currently runs on. + pub fn timg_calibration_clock_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.timg_calibration_clock?; + match config { + TimgCalibrationClockConfig::RcSlowClk => rc_slow_clk_root_source(clocks), + TimgCalibrationClockConfig::RcFastDivClk => rc_fast_div_clk_root_source(clocks), + #[cfg(use_xtal32k)] + TimgCalibrationClockConfig::Xtal32kClk => xtal32k_clk_root_source(clocks), + } + } + /// Returns the clock source that `APB_CLK` currently runs on. + pub fn apb_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.apb_clk?; + match config { + ApbClkConfig::Pll => apb_80m_root_source(clocks), + ApbClkConfig::Cpu => cpu_clk_root_source(clocks), + } + } + /// Returns the clock source that `CRYPTO_PWM_CLK` currently runs on. + pub fn crypto_pwm_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.crypto_pwm_clk?; + match config { + CryptoPwmClkConfig::Pll => pll_160m_root_source(clocks), + CryptoPwmClkConfig::Cpu => cpu_clk_root_source(clocks), + } + } pub fn configure_xtal_clk(clocks: &mut ClockTree, config: XtalClkConfig) { let old_config = clocks.xtal_clk.replace(config); refresh_xtal_clk_downstream(clocks); @@ -2527,8 +2998,7 @@ macro_rules! define_clock_tree_types { } fn request_xtal_clk(_clocks: &mut ClockTree) {} fn release_xtal_clk(_clocks: &mut ClockTree) {} - #[allow(unused_variables)] - pub fn xtal_clk_config_frequency(clocks: &mut ClockTree, config: XtalClkConfig) -> u32 { + pub fn xtal_clk_config_frequency(config: XtalClkConfig) -> u32 { config.value() } pub fn xtal_clk_frequency() -> u32 { @@ -2563,8 +3033,7 @@ macro_rules! define_clock_tree_types { release_xtal_clk(clocks); } } - #[allow(unused_variables)] - pub fn pll_clk_config_frequency(clocks: &mut ClockTree, config: PllClkConfig) -> u32 { + pub fn pll_clk_config_frequency(config: PllClkConfig) -> u32 { config.value() } pub fn pll_clk_frequency() -> u32 { @@ -2587,9 +3056,31 @@ macro_rules! define_clock_tree_types { enable_rc_fast_clk_impl(clocks, false); } } - pub fn rc_fast_clk_frequency() -> u32 { + static RC_FAST_CLK_FREQUENCY: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(rc_fast_clk_nominal_frequency()); + pub const fn rc_fast_clk_nominal_frequency() -> u32 { 17500000 } + pub fn rc_fast_clk_frequency() -> u32 { + RC_FAST_CLK_FREQUENCY.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn set_rc_fast_clk_frequency(clocks: &mut ClockTree, frequency: u32) { + if !(8750000..=26250000).contains(&frequency) { + warn!( + "Ignoring out-of-range RC_FAST_CLK frequency: {} Hz", + frequency + ); + return; + } + debug!( + "Updating RC_FAST_CLK frequency to {} Hz (nominal {} Hz)", + frequency, + rc_fast_clk_nominal_frequency() + ); + RC_FAST_CLK_FREQUENCY.store(frequency, ::core::sync::atomic::Ordering::Release); + refresh_rc_fast_clk_downstream(clocks); + } + #[cfg(use_xtal32k)] pub fn request_xtal32k_clk(clocks: &mut ClockTree) { trace!("Requesting XTAL32K_CLK"); if increment_reference_count(&mut clocks.xtal32k_clk_refcount) { @@ -2597,6 +3088,7 @@ macro_rules! define_clock_tree_types { enable_xtal32k_clk_impl(clocks, true); } } + #[cfg(use_xtal32k)] pub fn release_xtal32k_clk(clocks: &mut ClockTree) { trace!("Releasing XTAL32K_CLK"); if decrement_reference_count(&mut clocks.xtal32k_clk_refcount) { @@ -2604,6 +3096,7 @@ macro_rules! define_clock_tree_types { enable_xtal32k_clk_impl(clocks, false); } } + #[cfg(use_xtal32k)] pub fn xtal32k_clk_frequency() -> u32 { 32768 } @@ -2621,9 +3114,30 @@ macro_rules! define_clock_tree_types { enable_rc_slow_clk_impl(clocks, false); } } - pub fn rc_slow_clk_frequency() -> u32 { + static RC_SLOW_CLK_FREQUENCY: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(rc_slow_clk_nominal_frequency()); + pub const fn rc_slow_clk_nominal_frequency() -> u32 { 136000 } + pub fn rc_slow_clk_frequency() -> u32 { + RC_SLOW_CLK_FREQUENCY.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn set_rc_slow_clk_frequency(clocks: &mut ClockTree, frequency: u32) { + if !(68000..=204000).contains(&frequency) { + warn!( + "Ignoring out-of-range RC_SLOW_CLK frequency: {} Hz", + frequency + ); + return; + } + debug!( + "Updating RC_SLOW_CLK frequency to {} Hz (nominal {} Hz)", + frequency, + rc_slow_clk_nominal_frequency() + ); + RC_SLOW_CLK_FREQUENCY.store(frequency, ::core::sync::atomic::Ordering::Release); + refresh_rc_slow_clk_downstream(clocks); + } pub fn request_rc_fast_div_clk(clocks: &mut ClockTree) { trace!("Requesting RC_FAST_DIV_CLK"); if increment_reference_count(&mut clocks.rc_fast_div_clk_refcount) { @@ -2668,7 +3182,6 @@ macro_rules! define_clock_tree_types { clocks.system_pre_div_in } pub fn request_system_pre_div_in(clocks: &mut ClockTree) { - trace!("Requesting SYSTEM_PRE_DIV_IN"); trace!("Enabling SYSTEM_PRE_DIV_IN"); match unwrap!(clocks.system_pre_div_in) { SystemPreDivInConfig::Xtal => request_xtal_clk(clocks), @@ -2677,7 +3190,6 @@ macro_rules! define_clock_tree_types { enable_system_pre_div_in_impl(clocks, true); } pub fn release_system_pre_div_in(clocks: &mut ClockTree) { - trace!("Releasing SYSTEM_PRE_DIV_IN"); trace!("Disabling SYSTEM_PRE_DIV_IN"); enable_system_pre_div_in_impl(clocks, false); match unwrap!(clocks.system_pre_div_in) { @@ -2685,11 +3197,7 @@ macro_rules! define_clock_tree_types { SystemPreDivInConfig::RcFast => release_rc_fast_clk(clocks), } } - #[allow(unused_variables)] - pub fn system_pre_div_in_config_frequency( - clocks: &mut ClockTree, - config: SystemPreDivInConfig, - ) -> u32 { + pub fn system_pre_div_in_config_frequency(config: SystemPreDivInConfig) -> u32 { match config { SystemPreDivInConfig::Xtal => xtal_clk_frequency(), SystemPreDivInConfig::RcFast => rc_fast_clk_frequency(), @@ -2699,10 +3207,7 @@ macro_rules! define_clock_tree_types { SYSTEM_PRE_DIV_IN_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn system_pre_div_in_source_frequency(source: SystemPreDivInConfig) -> u32 { - match source { - SystemPreDivInConfig::Xtal => xtal_clk_frequency(), - SystemPreDivInConfig::RcFast => rc_fast_clk_frequency(), - } + system_pre_div_in_config_frequency(source) } pub fn configure_system_pre_div(clocks: &mut ClockTree, config: SystemPreDivConfig) { let old_config = clocks.system_pre_div.replace(config); @@ -2713,22 +3218,16 @@ macro_rules! define_clock_tree_types { clocks.system_pre_div } pub fn request_system_pre_div(clocks: &mut ClockTree) { - trace!("Requesting SYSTEM_PRE_DIV"); trace!("Enabling SYSTEM_PRE_DIV"); request_system_pre_div_in(clocks); enable_system_pre_div_impl(clocks, true); } pub fn release_system_pre_div(clocks: &mut ClockTree) { - trace!("Releasing SYSTEM_PRE_DIV"); trace!("Disabling SYSTEM_PRE_DIV"); enable_system_pre_div_impl(clocks, false); release_system_pre_div_in(clocks); } - #[allow(unused_variables)] - pub fn system_pre_div_config_frequency( - clocks: &mut ClockTree, - config: SystemPreDivConfig, - ) -> u32 { + pub fn system_pre_div_config_frequency(config: SystemPreDivConfig) -> u32 { (system_pre_div_in_frequency() / (config.divisor() + 1)) } pub fn system_pre_div_frequency() -> u32 { @@ -2749,22 +3248,16 @@ macro_rules! define_clock_tree_types { clocks.cpu_pll_div_out } pub fn request_cpu_pll_div_out(clocks: &mut ClockTree) { - trace!("Requesting CPU_PLL_DIV_OUT"); trace!("Enabling CPU_PLL_DIV_OUT"); request_pll_clk(clocks); enable_cpu_pll_div_out_impl(clocks, true); } pub fn release_cpu_pll_div_out(clocks: &mut ClockTree) { - trace!("Releasing CPU_PLL_DIV_OUT"); trace!("Disabling CPU_PLL_DIV_OUT"); enable_cpu_pll_div_out_impl(clocks, false); release_pll_clk(clocks); } - #[allow(unused_variables)] - pub fn cpu_pll_div_out_config_frequency( - clocks: &mut ClockTree, - config: CpuPllDivOutConfig, - ) -> u32 { + pub fn cpu_pll_div_out_config_frequency(config: CpuPllDivOutConfig) -> u32 { config.value() } pub fn cpu_pll_div_out_frequency() -> u32 { @@ -2776,20 +3269,19 @@ macro_rules! define_clock_tree_types { pub fn configure_apb_clk(clocks: &mut ClockTree, new_selector: ApbClkConfig) { let old_selector = clocks.apb_clk.replace(new_selector); refresh_apb_clk_downstream(clocks); - if clocks.apb_clk_refcount > 0 { + let active = clocks.apb_clk_refcount > 0; + if active { match new_selector { ApbClkConfig::Pll => request_apb_80m(clocks), ApbClkConfig::Cpu => request_cpu_clk(clocks), } - configure_apb_clk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - ApbClkConfig::Pll => release_apb_80m(clocks), - ApbClkConfig::Cpu => release_cpu_clk(clocks), - } + } + configure_apb_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + ApbClkConfig::Pll => release_apb_80m(clocks), + ApbClkConfig::Cpu => release_cpu_clk(clocks), } - } else { - configure_apb_clk_impl(clocks, old_selector, new_selector); } } pub fn apb_clk_config(clocks: &mut ClockTree) -> Option { @@ -2817,8 +3309,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn apb_clk_config_frequency(clocks: &mut ClockTree, config: ApbClkConfig) -> u32 { + pub fn apb_clk_config_frequency(config: ApbClkConfig) -> u32 { match config { ApbClkConfig::Pll => apb_80m_frequency(), ApbClkConfig::Cpu => cpu_clk_frequency(), @@ -2828,28 +3319,24 @@ macro_rules! define_clock_tree_types { APB_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn apb_clk_source_frequency(source: ApbClkConfig) -> u32 { - match source { - ApbClkConfig::Pll => apb_80m_frequency(), - ApbClkConfig::Cpu => cpu_clk_frequency(), - } + apb_clk_config_frequency(source) } pub fn configure_crypto_pwm_clk(clocks: &mut ClockTree, new_selector: CryptoPwmClkConfig) { let old_selector = clocks.crypto_pwm_clk.replace(new_selector); refresh_crypto_pwm_clk_downstream(clocks); - if clocks.crypto_pwm_clk_refcount > 0 { + let active = clocks.crypto_pwm_clk_refcount > 0; + if active { match new_selector { CryptoPwmClkConfig::Pll => request_pll_160m(clocks), CryptoPwmClkConfig::Cpu => request_cpu_clk(clocks), } - configure_crypto_pwm_clk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - CryptoPwmClkConfig::Pll => release_pll_160m(clocks), - CryptoPwmClkConfig::Cpu => release_cpu_clk(clocks), - } + } + configure_crypto_pwm_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + CryptoPwmClkConfig::Pll => release_pll_160m(clocks), + CryptoPwmClkConfig::Cpu => release_cpu_clk(clocks), } - } else { - configure_crypto_pwm_clk_impl(clocks, old_selector, new_selector); } } pub fn crypto_pwm_clk_config(clocks: &mut ClockTree) -> Option { @@ -2877,11 +3364,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn crypto_pwm_clk_config_frequency( - clocks: &mut ClockTree, - config: CryptoPwmClkConfig, - ) -> u32 { + pub fn crypto_pwm_clk_config_frequency(config: CryptoPwmClkConfig) -> u32 { match config { CryptoPwmClkConfig::Pll => pll_160m_frequency(), CryptoPwmClkConfig::Cpu => cpu_clk_frequency(), @@ -2891,10 +3374,7 @@ macro_rules! define_clock_tree_types { CRYPTO_PWM_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn crypto_pwm_clk_source_frequency(source: CryptoPwmClkConfig) -> u32 { - match source { - CryptoPwmClkConfig::Pll => pll_160m_frequency(), - CryptoPwmClkConfig::Cpu => cpu_clk_frequency(), - } + crypto_pwm_clk_config_frequency(source) } pub fn configure_cpu_clk(clocks: &mut ClockTree, new_selector: CpuClkConfig) { let old_selector = clocks.cpu_clk.replace(new_selector); @@ -2934,8 +3414,7 @@ macro_rules! define_clock_tree_types { } fn request_cpu_clk(_clocks: &mut ClockTree) {} fn release_cpu_clk(_clocks: &mut ClockTree) {} - #[allow(unused_variables)] - pub fn cpu_clk_config_frequency(clocks: &mut ClockTree, config: CpuClkConfig) -> u32 { + pub fn cpu_clk_config_frequency(config: CpuClkConfig) -> u32 { match config { CpuClkConfig::Xtal => system_pre_div_frequency(), CpuClkConfig::RcFast => system_pre_div_frequency(), @@ -2990,13 +3469,11 @@ macro_rules! define_clock_tree_types { cpu_clk_frequency() } pub fn request_apb_80m(clocks: &mut ClockTree) { - trace!("Requesting APB_80M"); trace!("Enabling APB_80M"); request_cpu_clk(clocks); enable_apb_80m_impl(clocks, true); } pub fn release_apb_80m(clocks: &mut ClockTree) { - trace!("Releasing APB_80M"); trace!("Disabling APB_80M"); enable_apb_80m_impl(clocks, false); release_cpu_clk(clocks); @@ -3016,22 +3493,16 @@ macro_rules! define_clock_tree_types { clocks.rc_fast_clk_div_n } pub fn request_rc_fast_clk_div_n(clocks: &mut ClockTree) { - trace!("Requesting RC_FAST_CLK_DIV_N"); trace!("Enabling RC_FAST_CLK_DIV_N"); request_rc_fast_clk(clocks); enable_rc_fast_clk_div_n_impl(clocks, true); } pub fn release_rc_fast_clk_div_n(clocks: &mut ClockTree) { - trace!("Releasing RC_FAST_CLK_DIV_N"); trace!("Disabling RC_FAST_CLK_DIV_N"); enable_rc_fast_clk_div_n_impl(clocks, false); release_rc_fast_clk(clocks); } - #[allow(unused_variables)] - pub fn rc_fast_clk_div_n_config_frequency( - clocks: &mut ClockTree, - config: RcFastClkDivNConfig, - ) -> u32 { + pub fn rc_fast_clk_div_n_config_frequency(config: RcFastClkDivNConfig) -> u32 { (rc_fast_clk_frequency() / (config.divisor() + 1)) } pub fn rc_fast_clk_div_n_frequency() -> u32 { @@ -3041,13 +3512,11 @@ macro_rules! define_clock_tree_types { rc_fast_clk_frequency() } pub fn request_xtal_div_clk(clocks: &mut ClockTree) { - trace!("Requesting XTAL_DIV_CLK"); trace!("Enabling XTAL_DIV_CLK"); request_xtal_clk(clocks); enable_xtal_div_clk_impl(clocks, true); } pub fn release_xtal_div_clk(clocks: &mut ClockTree) { - trace!("Releasing XTAL_DIV_CLK"); trace!("Disabling XTAL_DIV_CLK"); enable_xtal_div_clk_impl(clocks, false); release_xtal_clk(clocks); @@ -3061,14 +3530,19 @@ macro_rules! define_clock_tree_types { pub fn configure_rtc_slow_clk(clocks: &mut ClockTree, new_selector: RtcSlowClkConfig) { let old_selector = clocks.rtc_slow_clk.replace(new_selector); refresh_rtc_slow_clk_downstream(clocks); - match new_selector { - RtcSlowClkConfig::Xtal32k => request_xtal32k_clk(clocks), - RtcSlowClkConfig::RcSlow => request_rc_slow_clk(clocks), - RtcSlowClkConfig::RcFast => request_rc_fast_div_clk(clocks), + let active = clocks.rtc_slow_clk_refcount > 0; + if active { + match new_selector { + #[cfg(use_xtal32k)] + RtcSlowClkConfig::Xtal32k => request_xtal32k_clk(clocks), + RtcSlowClkConfig::RcSlow => request_rc_slow_clk(clocks), + RtcSlowClkConfig::RcFast => request_rc_fast_div_clk(clocks), + } } configure_rtc_slow_clk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { + if active && let Some(old_selector) = old_selector { match old_selector { + #[cfg(use_xtal32k)] RtcSlowClkConfig::Xtal32k => release_xtal32k_clk(clocks), RtcSlowClkConfig::RcSlow => release_rc_slow_clk(clocks), RtcSlowClkConfig::RcFast => release_rc_fast_div_clk(clocks), @@ -3080,30 +3554,33 @@ macro_rules! define_clock_tree_types { } pub fn request_rtc_slow_clk(clocks: &mut ClockTree) { trace!("Requesting RTC_SLOW_CLK"); - trace!("Enabling RTC_SLOW_CLK"); - match unwrap!(clocks.rtc_slow_clk) { - RtcSlowClkConfig::Xtal32k => request_xtal32k_clk(clocks), - RtcSlowClkConfig::RcSlow => request_rc_slow_clk(clocks), - RtcSlowClkConfig::RcFast => request_rc_fast_div_clk(clocks), + if increment_reference_count(&mut clocks.rtc_slow_clk_refcount) { + trace!("Enabling RTC_SLOW_CLK"); + match unwrap!(clocks.rtc_slow_clk) { + #[cfg(use_xtal32k)] + RtcSlowClkConfig::Xtal32k => request_xtal32k_clk(clocks), + RtcSlowClkConfig::RcSlow => request_rc_slow_clk(clocks), + RtcSlowClkConfig::RcFast => request_rc_fast_div_clk(clocks), + } + enable_rtc_slow_clk_impl(clocks, true); } - enable_rtc_slow_clk_impl(clocks, true); } pub fn release_rtc_slow_clk(clocks: &mut ClockTree) { trace!("Releasing RTC_SLOW_CLK"); - trace!("Disabling RTC_SLOW_CLK"); - enable_rtc_slow_clk_impl(clocks, false); - match unwrap!(clocks.rtc_slow_clk) { - RtcSlowClkConfig::Xtal32k => release_xtal32k_clk(clocks), - RtcSlowClkConfig::RcSlow => release_rc_slow_clk(clocks), - RtcSlowClkConfig::RcFast => release_rc_fast_div_clk(clocks), + if decrement_reference_count(&mut clocks.rtc_slow_clk_refcount) { + trace!("Disabling RTC_SLOW_CLK"); + enable_rtc_slow_clk_impl(clocks, false); + match unwrap!(clocks.rtc_slow_clk) { + #[cfg(use_xtal32k)] + RtcSlowClkConfig::Xtal32k => release_xtal32k_clk(clocks), + RtcSlowClkConfig::RcSlow => release_rc_slow_clk(clocks), + RtcSlowClkConfig::RcFast => release_rc_fast_div_clk(clocks), + } } } - #[allow(unused_variables)] - pub fn rtc_slow_clk_config_frequency( - clocks: &mut ClockTree, - config: RtcSlowClkConfig, - ) -> u32 { + pub fn rtc_slow_clk_config_frequency(config: RtcSlowClkConfig) -> u32 { match config { + #[cfg(use_xtal32k)] RtcSlowClkConfig::Xtal32k => xtal32k_clk_frequency(), RtcSlowClkConfig::RcSlow => rc_slow_clk_frequency(), RtcSlowClkConfig::RcFast => rc_fast_div_clk_frequency(), @@ -3113,29 +3590,95 @@ macro_rules! define_clock_tree_types { RTC_SLOW_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn rtc_slow_clk_source_frequency(source: RtcSlowClkConfig) -> u32 { - match source { - RtcSlowClkConfig::Xtal32k => xtal32k_clk_frequency(), - RtcSlowClkConfig::RcSlow => rc_slow_clk_frequency(), - RtcSlowClkConfig::RcFast => rc_fast_div_clk_frequency(), + rtc_slow_clk_config_frequency(source) + } + pub fn request_ble_lp_xtal_clk(clocks: &mut ClockTree) { + trace!("Enabling BLE_LP_XTAL_CLK"); + request_xtal_clk(clocks); + enable_ble_lp_xtal_clk_impl(clocks, true); + } + pub fn release_ble_lp_xtal_clk(clocks: &mut ClockTree) { + trace!("Disabling BLE_LP_XTAL_CLK"); + enable_ble_lp_xtal_clk_impl(clocks, false); + release_xtal_clk(clocks); + } + pub fn ble_lp_xtal_clk_frequency() -> u32 { + 1000000 + } + pub fn ble_lp_xtal_clk_source_frequency() -> u32 { + xtal_clk_frequency() + } + pub fn configure_ble_lp_clk(clocks: &mut ClockTree, new_selector: BleLpClkConfig) { + let old_selector = clocks.ble_lp_clk.replace(new_selector); + refresh_ble_lp_clk_downstream(clocks); + let active = clocks.ble_lp_clk_refcount > 0; + if active { + match new_selector { + BleLpClkConfig::Xtal => request_ble_lp_xtal_clk(clocks), + BleLpClkConfig::RtcSlow => request_rtc_slow_clk(clocks), + } + } + configure_ble_lp_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + BleLpClkConfig::Xtal => release_ble_lp_xtal_clk(clocks), + BleLpClkConfig::RtcSlow => release_rtc_slow_clk(clocks), + } + } + } + pub fn ble_lp_clk_config(clocks: &mut ClockTree) -> Option { + clocks.ble_lp_clk + } + pub fn request_ble_lp_clk(clocks: &mut ClockTree) { + trace!("Requesting BLE_LP_CLK"); + if increment_reference_count(&mut clocks.ble_lp_clk_refcount) { + trace!("Enabling BLE_LP_CLK"); + match unwrap!(clocks.ble_lp_clk) { + BleLpClkConfig::Xtal => request_ble_lp_xtal_clk(clocks), + BleLpClkConfig::RtcSlow => request_rtc_slow_clk(clocks), + } + enable_ble_lp_clk_impl(clocks, true); } } + pub fn release_ble_lp_clk(clocks: &mut ClockTree) { + trace!("Releasing BLE_LP_CLK"); + if decrement_reference_count(&mut clocks.ble_lp_clk_refcount) { + trace!("Disabling BLE_LP_CLK"); + enable_ble_lp_clk_impl(clocks, false); + match unwrap!(clocks.ble_lp_clk) { + BleLpClkConfig::Xtal => release_ble_lp_xtal_clk(clocks), + BleLpClkConfig::RtcSlow => release_rtc_slow_clk(clocks), + } + } + } + pub fn ble_lp_clk_config_frequency(config: BleLpClkConfig) -> u32 { + match config { + BleLpClkConfig::Xtal => ble_lp_xtal_clk_frequency(), + BleLpClkConfig::RtcSlow => rtc_slow_clk_frequency(), + } + } + pub fn ble_lp_clk_frequency() -> u32 { + BLE_LP_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn ble_lp_clk_source_frequency(source: BleLpClkConfig) -> u32 { + ble_lp_clk_config_frequency(source) + } pub fn configure_rtc_fast_clk(clocks: &mut ClockTree, new_selector: RtcFastClkConfig) { let old_selector = clocks.rtc_fast_clk.replace(new_selector); refresh_rtc_fast_clk_downstream(clocks); - if clocks.rtc_fast_clk_refcount > 0 { + let active = clocks.rtc_fast_clk_refcount > 0; + if active { match new_selector { RtcFastClkConfig::Xtal => request_xtal_div_clk(clocks), RtcFastClkConfig::Rc => request_rc_fast_clk_div_n(clocks), } - configure_rtc_fast_clk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - RtcFastClkConfig::Xtal => release_xtal_div_clk(clocks), - RtcFastClkConfig::Rc => release_rc_fast_clk_div_n(clocks), - } + } + configure_rtc_fast_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + RtcFastClkConfig::Xtal => release_xtal_div_clk(clocks), + RtcFastClkConfig::Rc => release_rc_fast_clk_div_n(clocks), } - } else { - configure_rtc_fast_clk_impl(clocks, old_selector, new_selector); } } pub fn rtc_fast_clk_config(clocks: &mut ClockTree) -> Option { @@ -3163,11 +3706,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn rtc_fast_clk_config_frequency( - clocks: &mut ClockTree, - config: RtcFastClkConfig, - ) -> u32 { + pub fn rtc_fast_clk_config_frequency(config: RtcFastClkConfig) -> u32 { match config { RtcFastClkConfig::Xtal => xtal_div_clk_frequency(), RtcFastClkConfig::Rc => rc_fast_clk_div_n_frequency(), @@ -3177,32 +3716,30 @@ macro_rules! define_clock_tree_types { RTC_FAST_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn rtc_fast_clk_source_frequency(source: RtcFastClkConfig) -> u32 { - match source { - RtcFastClkConfig::Xtal => xtal_div_clk_frequency(), - RtcFastClkConfig::Rc => rc_fast_clk_div_n_frequency(), - } + rtc_fast_clk_config_frequency(source) } pub fn configure_low_power_clk(clocks: &mut ClockTree, new_selector: LowPowerClkConfig) { let old_selector = clocks.low_power_clk.replace(new_selector); refresh_low_power_clk_downstream(clocks); - if clocks.low_power_clk_refcount > 0 { + let active = clocks.low_power_clk_refcount > 0; + if active { match new_selector { LowPowerClkConfig::Xtal => request_xtal_clk(clocks), LowPowerClkConfig::RcFast => request_rc_fast_clk(clocks), + #[cfg(use_xtal32k)] LowPowerClkConfig::Xtal32k => request_xtal32k_clk(clocks), LowPowerClkConfig::RtcSlow => request_rtc_slow_clk(clocks), } - configure_low_power_clk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - LowPowerClkConfig::Xtal => release_xtal_clk(clocks), - LowPowerClkConfig::RcFast => release_rc_fast_clk(clocks), - LowPowerClkConfig::Xtal32k => release_xtal32k_clk(clocks), - LowPowerClkConfig::RtcSlow => release_rtc_slow_clk(clocks), - } + } + configure_low_power_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + LowPowerClkConfig::Xtal => release_xtal_clk(clocks), + LowPowerClkConfig::RcFast => release_rc_fast_clk(clocks), + #[cfg(use_xtal32k)] + LowPowerClkConfig::Xtal32k => release_xtal32k_clk(clocks), + LowPowerClkConfig::RtcSlow => release_rtc_slow_clk(clocks), } - } else { - configure_low_power_clk_impl(clocks, old_selector, new_selector); } } pub fn low_power_clk_config(clocks: &mut ClockTree) -> Option { @@ -3215,6 +3752,7 @@ macro_rules! define_clock_tree_types { match unwrap!(clocks.low_power_clk) { LowPowerClkConfig::Xtal => request_xtal_clk(clocks), LowPowerClkConfig::RcFast => request_rc_fast_clk(clocks), + #[cfg(use_xtal32k)] LowPowerClkConfig::Xtal32k => request_xtal32k_clk(clocks), LowPowerClkConfig::RtcSlow => request_rtc_slow_clk(clocks), } @@ -3229,19 +3767,17 @@ macro_rules! define_clock_tree_types { match unwrap!(clocks.low_power_clk) { LowPowerClkConfig::Xtal => release_xtal_clk(clocks), LowPowerClkConfig::RcFast => release_rc_fast_clk(clocks), + #[cfg(use_xtal32k)] LowPowerClkConfig::Xtal32k => release_xtal32k_clk(clocks), LowPowerClkConfig::RtcSlow => release_rtc_slow_clk(clocks), } } } - #[allow(unused_variables)] - pub fn low_power_clk_config_frequency( - clocks: &mut ClockTree, - config: LowPowerClkConfig, - ) -> u32 { + pub fn low_power_clk_config_frequency(config: LowPowerClkConfig) -> u32 { match config { LowPowerClkConfig::Xtal => xtal_clk_frequency(), LowPowerClkConfig::RcFast => rc_fast_clk_frequency(), + #[cfg(use_xtal32k)] LowPowerClkConfig::Xtal32k => xtal32k_clk_frequency(), LowPowerClkConfig::RtcSlow => rtc_slow_clk_frequency(), } @@ -3250,12 +3786,7 @@ macro_rules! define_clock_tree_types { LOW_POWER_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn low_power_clk_source_frequency(source: LowPowerClkConfig) -> u32 { - match source { - LowPowerClkConfig::Xtal => xtal_clk_frequency(), - LowPowerClkConfig::RcFast => rc_fast_clk_frequency(), - LowPowerClkConfig::Xtal32k => xtal32k_clk_frequency(), - LowPowerClkConfig::RtcSlow => rtc_slow_clk_frequency(), - } + low_power_clk_config_frequency(source) } pub fn request_uart_mem_clk(clocks: &mut ClockTree) { trace!("Requesting UART_MEM_CLK"); @@ -3287,22 +3818,23 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.timg_calibration_clock.replace(new_selector); refresh_timg_calibration_clock_downstream(clocks); - if clocks.timg_calibration_clock_refcount > 0 { + let active = clocks.timg_calibration_clock_refcount > 0; + if active { match new_selector { TimgCalibrationClockConfig::RcSlowClk => request_rc_slow_clk(clocks), TimgCalibrationClockConfig::RcFastDivClk => request_rc_fast_div_clk(clocks), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => request_xtal32k_clk(clocks), } - configure_timg_calibration_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - TimgCalibrationClockConfig::RcSlowClk => release_rc_slow_clk(clocks), - TimgCalibrationClockConfig::RcFastDivClk => release_rc_fast_div_clk(clocks), - TimgCalibrationClockConfig::Xtal32kClk => release_xtal32k_clk(clocks), - } + } + configure_timg_calibration_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + TimgCalibrationClockConfig::RcSlowClk => release_rc_slow_clk(clocks), + TimgCalibrationClockConfig::RcFastDivClk => release_rc_fast_div_clk(clocks), + #[cfg(use_xtal32k)] + TimgCalibrationClockConfig::Xtal32kClk => release_xtal32k_clk(clocks), } - } else { - configure_timg_calibration_clock_impl(clocks, old_selector, new_selector); } } pub fn timg_calibration_clock_config( @@ -3318,6 +3850,7 @@ macro_rules! define_clock_tree_types { match unwrap!(clocks.timg_calibration_clock) { TimgCalibrationClockConfig::RcSlowClk => request_rc_slow_clk(clocks), TimgCalibrationClockConfig::RcFastDivClk => request_rc_fast_div_clk(clocks), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => request_xtal32k_clk(clocks), } enable_timg_calibration_clock_impl(clocks, true); @@ -3332,18 +3865,16 @@ macro_rules! define_clock_tree_types { match unwrap!(clocks.timg_calibration_clock) { TimgCalibrationClockConfig::RcSlowClk => release_rc_slow_clk(clocks), TimgCalibrationClockConfig::RcFastDivClk => release_rc_fast_div_clk(clocks), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => release_xtal32k_clk(clocks), } } } - #[allow(unused_variables)] - pub fn timg_calibration_clock_config_frequency( - clocks: &mut ClockTree, - config: TimgCalibrationClockConfig, - ) -> u32 { + pub fn timg_calibration_clock_config_frequency(config: TimgCalibrationClockConfig) -> u32 { match config { TimgCalibrationClockConfig::RcSlowClk => rc_slow_clk_frequency(), TimgCalibrationClockConfig::RcFastDivClk => rc_fast_div_clk_frequency(), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => xtal32k_clk_frequency(), } } @@ -3351,11 +3882,7 @@ macro_rules! define_clock_tree_types { TIMG_CALIBRATION_CLOCK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn timg_calibration_clock_source_frequency(source: TimgCalibrationClockConfig) -> u32 { - match source { - TimgCalibrationClockConfig::RcSlowClk => rc_slow_clk_frequency(), - TimgCalibrationClockConfig::RcFastDivClk => rc_fast_div_clk_frequency(), - TimgCalibrationClockConfig::Xtal32kClk => xtal32k_clk_frequency(), - } + timg_calibration_clock_config_frequency(source) } impl SdmInstance { pub fn request_function_clock(self, clocks: &mut ClockTree) { @@ -3391,20 +3918,19 @@ macro_rules! define_clock_tree_types { ) { let old_config = clocks.i2c_function_clock[self as usize].replace(config); refresh_i2c_function_clock_downstream(clocks, self); - if clocks.i2c_function_clock_refcount[self as usize] > 0 { + let active = clocks.i2c_function_clock_refcount[self as usize] > 0; + if active { match config.sclk { I2cFunctionClockSclk::Xtal => request_xtal_clk(clocks), I2cFunctionClockSclk::RcFast => request_rc_fast_clk(clocks), } - self.configure_function_clock_impl(clocks, old_config, config); - if let Some(old_config) = old_config { - match old_config.sclk { - I2cFunctionClockSclk::Xtal => release_xtal_clk(clocks), - I2cFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), - } + } + self.configure_function_clock_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + I2cFunctionClockSclk::Xtal => release_xtal_clk(clocks), + I2cFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_config, config); } } pub fn function_clock_config( @@ -3439,11 +3965,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: I2cFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: I2cFunctionClockConfig) -> u32 { (match config.sclk { I2cFunctionClockSclk::Xtal => xtal_clk_frequency(), I2cFunctionClockSclk::RcFast => rc_fast_clk_frequency(), @@ -3460,26 +3982,221 @@ macro_rules! define_clock_tree_types { } } } + impl I2sInstance { + pub fn configure_tx_clk(self, clocks: &mut ClockTree, config: I2sClkConfig) { + let old_config = clocks.i2s_tx_clk[self as usize].replace(config); + refresh_i2s_tx_clk_downstream(clocks, self); + let active = clocks.i2s_tx_clk_refcount[self as usize] > 0; + if active { + match config.sclk { + I2sClkSclk::Xtal => request_xtal_clk(clocks), + I2sClkSclk::PllD2 => request_pll_d2(clocks), + I2sClkSclk::Pll160m => request_pll_160m(clocks), + } + } + self.configure_tx_clk_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + I2sClkSclk::Xtal => release_xtal_clk(clocks), + I2sClkSclk::PllD2 => release_pll_d2(clocks), + I2sClkSclk::Pll160m => release_pll_160m(clocks), + } + } + } + pub fn tx_clk_config(self, clocks: &mut ClockTree) -> Option { + clocks.i2s_tx_clk[self as usize] + } + pub fn request_tx_clk(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::TX_CLK", self); + if increment_reference_count(&mut clocks.i2s_tx_clk_refcount[self as usize]) { + trace!("Enabling {:?}::TX_CLK", self); + crate::rtc_cntl::WakeLock::acquire(); + match unwrap!(clocks.i2s_tx_clk[self as usize]).sclk { + I2sClkSclk::Xtal => request_xtal_clk(clocks), + I2sClkSclk::PllD2 => request_pll_d2(clocks), + I2sClkSclk::Pll160m => request_pll_160m(clocks), + } + self.enable_tx_clk_impl(clocks, true); + } + } + pub fn release_tx_clk(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::TX_CLK", self); + if decrement_reference_count(&mut clocks.i2s_tx_clk_refcount[self as usize]) { + trace!("Disabling {:?}::TX_CLK", self); + crate::rtc_cntl::WakeLock::release(); + self.enable_tx_clk_impl(clocks, false); + match unwrap!(clocks.i2s_tx_clk[self as usize]).sclk { + I2sClkSclk::Xtal => release_xtal_clk(clocks), + I2sClkSclk::PllD2 => release_pll_d2(clocks), + I2sClkSclk::Pll160m => release_pll_160m(clocks), + } + } + } + pub fn tx_clk_config_frequency(config: I2sClkConfig) -> u32 { + (((match config.sclk { + I2sClkSclk::Xtal => xtal_clk_frequency(), + I2sClkSclk::PllD2 => pll_d2_frequency(), + I2sClkSclk::Pll160m => pll_160m_frequency(), + } as u64) + * (config.div_a() as u64)) + / (((config.div_num() * config.div_a()) + config.div_b()) as u64)) + as u32 + } + pub fn tx_clk_frequency(self) -> u32 { + I2S_TX_CLK_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) + } + pub fn tx_clk_source_frequency(sclk: I2sClkSclk) -> u32 { + match sclk { + I2sClkSclk::Xtal => xtal_clk_frequency(), + I2sClkSclk::PllD2 => pll_d2_frequency(), + I2sClkSclk::Pll160m => pll_160m_frequency(), + } + } + pub fn configure_rx_clk(self, clocks: &mut ClockTree, config: I2sClkConfig) { + let old_config = clocks.i2s_rx_clk[self as usize].replace(config); + refresh_i2s_rx_clk_downstream(clocks, self); + let active = clocks.i2s_rx_clk_refcount[self as usize] > 0; + if active { + match config.sclk { + I2sClkSclk::Xtal => request_xtal_clk(clocks), + I2sClkSclk::PllD2 => request_pll_d2(clocks), + I2sClkSclk::Pll160m => request_pll_160m(clocks), + } + } + self.configure_rx_clk_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + I2sClkSclk::Xtal => release_xtal_clk(clocks), + I2sClkSclk::PllD2 => release_pll_d2(clocks), + I2sClkSclk::Pll160m => release_pll_160m(clocks), + } + } + } + pub fn rx_clk_config(self, clocks: &mut ClockTree) -> Option { + clocks.i2s_rx_clk[self as usize] + } + pub fn request_rx_clk(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::RX_CLK", self); + if increment_reference_count(&mut clocks.i2s_rx_clk_refcount[self as usize]) { + trace!("Enabling {:?}::RX_CLK", self); + crate::rtc_cntl::WakeLock::acquire(); + match unwrap!(clocks.i2s_rx_clk[self as usize]).sclk { + I2sClkSclk::Xtal => request_xtal_clk(clocks), + I2sClkSclk::PllD2 => request_pll_d2(clocks), + I2sClkSclk::Pll160m => request_pll_160m(clocks), + } + self.enable_rx_clk_impl(clocks, true); + } + } + pub fn release_rx_clk(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::RX_CLK", self); + if decrement_reference_count(&mut clocks.i2s_rx_clk_refcount[self as usize]) { + trace!("Disabling {:?}::RX_CLK", self); + crate::rtc_cntl::WakeLock::release(); + self.enable_rx_clk_impl(clocks, false); + match unwrap!(clocks.i2s_rx_clk[self as usize]).sclk { + I2sClkSclk::Xtal => release_xtal_clk(clocks), + I2sClkSclk::PllD2 => release_pll_d2(clocks), + I2sClkSclk::Pll160m => release_pll_160m(clocks), + } + } + } + pub fn rx_clk_config_frequency(config: I2sClkConfig) -> u32 { + (((match config.sclk { + I2sClkSclk::Xtal => xtal_clk_frequency(), + I2sClkSclk::PllD2 => pll_d2_frequency(), + I2sClkSclk::Pll160m => pll_160m_frequency(), + } as u64) + * (config.div_a() as u64)) + / (((config.div_num() * config.div_a()) + config.div_b()) as u64)) + as u32 + } + pub fn rx_clk_frequency(self) -> u32 { + I2S_RX_CLK_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) + } + pub fn rx_clk_source_frequency(sclk: I2sClkSclk) -> u32 { + match sclk { + I2sClkSclk::Xtal => xtal_clk_frequency(), + I2sClkSclk::PllD2 => pll_d2_frequency(), + I2sClkSclk::Pll160m => pll_160m_frequency(), + } + } + pub fn configure_mclk_out( + self, + clocks: &mut ClockTree, + new_selector: I2sMclkOutConfig, + ) { + let old_selector = clocks.i2s_mclk_out[self as usize].replace(new_selector); + refresh_i2s_mclk_out_downstream(clocks, self); + let active = clocks.i2s_mclk_out_refcount[self as usize] > 0; + if active { + match new_selector { + I2sMclkOutConfig::Tx => self.request_tx_clk(clocks), + I2sMclkOutConfig::Rx => self.request_rx_clk(clocks), + } + } + self.configure_mclk_out_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + I2sMclkOutConfig::Tx => self.release_tx_clk(clocks), + I2sMclkOutConfig::Rx => self.release_rx_clk(clocks), + } + } + } + pub fn mclk_out_config(self, clocks: &mut ClockTree) -> Option { + clocks.i2s_mclk_out[self as usize] + } + pub fn request_mclk_out(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::MCLK_OUT", self); + if increment_reference_count(&mut clocks.i2s_mclk_out_refcount[self as usize]) { + trace!("Enabling {:?}::MCLK_OUT", self); + match unwrap!(clocks.i2s_mclk_out[self as usize]) { + I2sMclkOutConfig::Tx => self.request_tx_clk(clocks), + I2sMclkOutConfig::Rx => self.request_rx_clk(clocks), + } + self.enable_mclk_out_impl(clocks, true); + } + } + pub fn release_mclk_out(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::MCLK_OUT", self); + if decrement_reference_count(&mut clocks.i2s_mclk_out_refcount[self as usize]) { + trace!("Disabling {:?}::MCLK_OUT", self); + self.enable_mclk_out_impl(clocks, false); + match unwrap!(clocks.i2s_mclk_out[self as usize]) { + I2sMclkOutConfig::Tx => self.release_tx_clk(clocks), + I2sMclkOutConfig::Rx => self.release_rx_clk(clocks), + } + } + } + pub fn mclk_out_config_frequency(self, config: I2sMclkOutConfig) -> u32 { + match config { + I2sMclkOutConfig::Tx => self.tx_clk_frequency(), + I2sMclkOutConfig::Rx => self.rx_clk_frequency(), + } + } + pub fn mclk_out_frequency(self) -> u32 { + I2S_MCLK_OUT_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) + } + } impl LcdCamInstance { pub fn configure_lcd_clock(self, clocks: &mut ClockTree, config: LcdCamLcdClockConfig) { let old_config = clocks.lcd_cam_lcd_clock[self as usize].replace(config); refresh_lcd_cam_lcd_clock_downstream(clocks, self); - if clocks.lcd_cam_lcd_clock_refcount[self as usize] > 0 { + let active = clocks.lcd_cam_lcd_clock_refcount[self as usize] > 0; + if active { match config.sclk { LcdCamLcdClockSclk::XtalClk => request_xtal_clk(clocks), LcdCamLcdClockSclk::PllD2 => request_pll_d2(clocks), LcdCamLcdClockSclk::Pll160m => request_pll_160m(clocks), } - self.configure_lcd_clock_impl(clocks, old_config, config); - if let Some(old_config) = old_config { - match old_config.sclk { - LcdCamLcdClockSclk::XtalClk => release_xtal_clk(clocks), - LcdCamLcdClockSclk::PllD2 => release_pll_d2(clocks), - LcdCamLcdClockSclk::Pll160m => release_pll_160m(clocks), - } + } + self.configure_lcd_clock_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + LcdCamLcdClockSclk::XtalClk => release_xtal_clk(clocks), + LcdCamLcdClockSclk::PllD2 => release_pll_d2(clocks), + LcdCamLcdClockSclk::Pll160m => release_pll_160m(clocks), } - } else { - self.configure_lcd_clock_impl(clocks, old_config, config); } } pub fn lcd_clock_config(self, clocks: &mut ClockTree) -> Option { @@ -3513,11 +4230,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn lcd_clock_config_frequency( - clocks: &mut ClockTree, - config: LcdCamLcdClockConfig, - ) -> u32 { + pub fn lcd_clock_config_frequency(config: LcdCamLcdClockConfig) -> u32 { (((match config.sclk { LcdCamLcdClockSclk::XtalClk => xtal_clk_frequency(), LcdCamLcdClockSclk::PllD2 => pll_d2_frequency(), @@ -3541,22 +4254,21 @@ macro_rules! define_clock_tree_types { pub fn configure_cam_clock(self, clocks: &mut ClockTree, config: LcdCamCamClockConfig) { let old_config = clocks.lcd_cam_cam_clock[self as usize].replace(config); refresh_lcd_cam_cam_clock_downstream(clocks, self); - if clocks.lcd_cam_cam_clock_refcount[self as usize] > 0 { + let active = clocks.lcd_cam_cam_clock_refcount[self as usize] > 0; + if active { match config.sclk { LcdCamCamClockSclk::XtalClk => request_xtal_clk(clocks), LcdCamCamClockSclk::PllD2 => request_pll_d2(clocks), LcdCamCamClockSclk::Pll160m => request_pll_160m(clocks), } - self.configure_cam_clock_impl(clocks, old_config, config); - if let Some(old_config) = old_config { - match old_config.sclk { - LcdCamCamClockSclk::XtalClk => release_xtal_clk(clocks), - LcdCamCamClockSclk::PllD2 => release_pll_d2(clocks), - LcdCamCamClockSclk::Pll160m => release_pll_160m(clocks), - } + } + self.configure_cam_clock_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + LcdCamCamClockSclk::XtalClk => release_xtal_clk(clocks), + LcdCamCamClockSclk::PllD2 => release_pll_d2(clocks), + LcdCamCamClockSclk::Pll160m => release_pll_160m(clocks), } - } else { - self.configure_cam_clock_impl(clocks, old_config, config); } } pub fn cam_clock_config(self, clocks: &mut ClockTree) -> Option { @@ -3590,11 +4302,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn cam_clock_config_frequency( - clocks: &mut ClockTree, - config: LcdCamCamClockConfig, - ) -> u32 { + pub fn cam_clock_config_frequency(config: LcdCamCamClockConfig) -> u32 { (((match config.sclk { LcdCamCamClockSclk::XtalClk => xtal_clk_frequency(), LcdCamCamClockSclk::PllD2 => pll_d2_frequency(), @@ -3652,22 +4360,21 @@ macro_rules! define_clock_tree_types { pub fn configure_sclk(self, clocks: &mut ClockTree, new_selector: RmtSclkConfig) { let old_selector = clocks.rmt_sclk[self as usize].replace(new_selector); refresh_rmt_sclk_downstream(clocks, self); - if clocks.rmt_sclk_refcount[self as usize] > 0 { + let active = clocks.rmt_sclk_refcount[self as usize] > 0; + if active { match new_selector { RmtSclkConfig::ApbClk => request_apb_clk(clocks), RmtSclkConfig::RcFastClk => request_rc_fast_clk(clocks), RmtSclkConfig::XtalClk => request_xtal_clk(clocks), } - self.configure_sclk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - RmtSclkConfig::ApbClk => release_apb_clk(clocks), - RmtSclkConfig::RcFastClk => release_rc_fast_clk(clocks), - RmtSclkConfig::XtalClk => release_xtal_clk(clocks), - } + } + self.configure_sclk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + RmtSclkConfig::ApbClk => release_apb_clk(clocks), + RmtSclkConfig::RcFastClk => release_rc_fast_clk(clocks), + RmtSclkConfig::XtalClk => release_xtal_clk(clocks), } - } else { - self.configure_sclk_impl(clocks, old_selector, new_selector); } } pub fn sclk_config(self, clocks: &mut ClockTree) -> Option { @@ -3699,8 +4406,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn sclk_config_frequency(clocks: &mut ClockTree, config: RmtSclkConfig) -> u32 { + pub fn sclk_config_frequency(config: RmtSclkConfig) -> u32 { match config { RmtSclkConfig::ApbClk => apb_clk_frequency(), RmtSclkConfig::RcFastClk => rc_fast_clk_frequency(), @@ -3711,11 +4417,7 @@ macro_rules! define_clock_tree_types { RMT_SCLK_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) } pub fn sclk_source_frequency(source: RmtSclkConfig) -> u32 { - match source { - RmtSclkConfig::ApbClk => apb_clk_frequency(), - RmtSclkConfig::RcFastClk => rc_fast_clk_frequency(), - RmtSclkConfig::XtalClk => xtal_clk_frequency(), - } + Self::sclk_config_frequency(source) } } impl SpiInstance { @@ -3726,20 +4428,19 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.spi_function_clock[self as usize].replace(new_selector); refresh_spi_function_clock_downstream(clocks, self); - if clocks.spi_function_clock_refcount[self as usize] > 0 { + let active = clocks.spi_function_clock_refcount[self as usize] > 0; + if active { match new_selector { SpiFunctionClockConfig::Xtal => request_xtal_clk(clocks), SpiFunctionClockConfig::Apb => request_apb_clk(clocks), } - self.configure_function_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - SpiFunctionClockConfig::Xtal => release_xtal_clk(clocks), - SpiFunctionClockConfig::Apb => release_apb_clk(clocks), - } + } + self.configure_function_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + SpiFunctionClockConfig::Xtal => release_xtal_clk(clocks), + SpiFunctionClockConfig::Apb => release_apb_clk(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_selector, new_selector); } } pub fn function_clock_config( @@ -3774,11 +4475,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: SpiFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: SpiFunctionClockConfig) -> u32 { match config { SpiFunctionClockConfig::Xtal => xtal_clk_frequency(), SpiFunctionClockConfig::Apb => apb_clk_frequency(), @@ -3789,10 +4486,7 @@ macro_rules! define_clock_tree_types { .load(::core::sync::atomic::Ordering::Acquire) } pub fn function_clock_source_frequency(source: SpiFunctionClockConfig) -> u32 { - match source { - SpiFunctionClockConfig::Xtal => xtal_clk_frequency(), - SpiFunctionClockConfig::Apb => apb_clk_frequency(), - } + Self::function_clock_config_frequency(source) } } impl TimgInstance { @@ -3803,20 +4497,19 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.timg_function_clock[self as usize].replace(new_selector); refresh_timg_function_clock_downstream(clocks, self); - if clocks.timg_function_clock_refcount[self as usize] > 0 { + let active = clocks.timg_function_clock_refcount[self as usize] > 0; + if active { match new_selector { TimgFunctionClockConfig::XtalClk => request_xtal_clk(clocks), TimgFunctionClockConfig::ApbClk => request_apb_clk(clocks), } - self.configure_function_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - TimgFunctionClockConfig::XtalClk => release_xtal_clk(clocks), - TimgFunctionClockConfig::ApbClk => release_apb_clk(clocks), - } + } + self.configure_function_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + TimgFunctionClockConfig::XtalClk => release_xtal_clk(clocks), + TimgFunctionClockConfig::ApbClk => release_apb_clk(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_selector, new_selector); } } pub fn function_clock_config( @@ -3851,11 +4544,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: TimgFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: TimgFunctionClockConfig) -> u32 { match config { TimgFunctionClockConfig::XtalClk => xtal_clk_frequency(), TimgFunctionClockConfig::ApbClk => apb_clk_frequency(), @@ -3866,10 +4555,7 @@ macro_rules! define_clock_tree_types { .load(::core::sync::atomic::Ordering::Acquire) } pub fn function_clock_source_frequency(source: TimgFunctionClockConfig) -> u32 { - match source { - TimgFunctionClockConfig::XtalClk => xtal_clk_frequency(), - TimgFunctionClockConfig::ApbClk => apb_clk_frequency(), - } + Self::function_clock_config_frequency(source) } } impl UartInstance { @@ -3880,22 +4566,21 @@ macro_rules! define_clock_tree_types { ) { let old_config = clocks.uart_function_clock[self as usize].replace(config); refresh_uart_function_clock_downstream(clocks, self); - if clocks.uart_function_clock_refcount[self as usize] > 0 { + let active = clocks.uart_function_clock_refcount[self as usize] > 0; + if active { match config.sclk { UartFunctionClockSclk::Apb => request_apb_clk(clocks), UartFunctionClockSclk::RcFast => request_rc_fast_clk(clocks), UartFunctionClockSclk::Xtal => request_xtal_clk(clocks), } - self.configure_function_clock_impl(clocks, old_config, config); - if let Some(old_config) = old_config { - match old_config.sclk { - UartFunctionClockSclk::Apb => release_apb_clk(clocks), - UartFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), - UartFunctionClockSclk::Xtal => release_xtal_clk(clocks), - } + } + self.configure_function_clock_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + UartFunctionClockSclk::Apb => release_apb_clk(clocks), + UartFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), + UartFunctionClockSclk::Xtal => release_xtal_clk(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_config, config); } } pub fn function_clock_config( @@ -3932,11 +4617,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: UartFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: UartFunctionClockConfig) -> u32 { (match config.sclk { UartFunctionClockSclk::Apb => apb_clk_frequency(), UartFunctionClockSclk::RcFast => rc_fast_clk_frequency(), @@ -3989,10 +4670,8 @@ macro_rules! define_clock_tree_types { self.release_function_clock(clocks); } } - #[allow(unused_variables)] pub fn baud_rate_generator_config_frequency( self, - clocks: &mut ClockTree, config: UartBaudRateGeneratorConfig, ) -> u32 { ((self.function_clock_frequency() * 16) @@ -4050,6 +4729,8 @@ macro_rules! define_clock_tree_types { pub rc_fast_clk_div_n: Option, /// `RTC_SLOW_CLK` configuration. pub rtc_slow_clk: Option, + /// `BLE_LP_CLK` configuration. + pub ble_lp_clk: Option, /// `RTC_FAST_CLK` configuration. pub rtc_fast_clk: Option, /// `LOW_POWER_CLK` configuration. @@ -4080,6 +4761,9 @@ macro_rules! define_clock_tree_types { if let Some(config) = self.rtc_slow_clk { configure_rtc_slow_clk(clocks, config); } + if let Some(config) = self.ble_lp_clk { + configure_ble_lp_clk(clocks, config); + } if let Some(config) = self.rtc_fast_clk { configure_rtc_fast_clk(clocks, config); } @@ -4104,17 +4788,22 @@ macro_rules! define_clock_tree_types { fn refresh_xtal_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.xtal_clk { XTAL_CLK_FREQ_CACHE.store( - xtal_clk_config_frequency(clocks, config), + xtal_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } refresh_pll_clk_downstream(clocks); refresh_system_pre_div_in_downstream(clocks); + refresh_ble_lp_clk_downstream(clocks); refresh_rtc_fast_clk_downstream(clocks); refresh_low_power_clk_downstream(clocks); for child_instance in [I2cInstance::I2c0, I2cInstance::I2c1] { refresh_i2c_function_clock_downstream(clocks, child_instance); } + for child_instance in [I2sInstance::I2s0, I2sInstance::I2s1] { + refresh_i2s_tx_clk_downstream(clocks, child_instance); + refresh_i2s_rx_clk_downstream(clocks, child_instance); + } for child_instance in [LcdCamInstance::LcdCam] { refresh_lcd_cam_lcd_clock_downstream(clocks, child_instance); refresh_lcd_cam_cam_clock_downstream(clocks, child_instance); @@ -4139,20 +4828,48 @@ macro_rules! define_clock_tree_types { fn refresh_pll_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.pll_clk { PLL_CLK_FREQ_CACHE.store( - pll_clk_config_frequency(clocks, config), + pll_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } refresh_cpu_pll_div_out_downstream(clocks); + for child_instance in [I2sInstance::I2s0, I2sInstance::I2s1] { + refresh_i2s_tx_clk_downstream(clocks, child_instance); + refresh_i2s_rx_clk_downstream(clocks, child_instance); + } for child_instance in [LcdCamInstance::LcdCam] { refresh_lcd_cam_lcd_clock_downstream(clocks, child_instance); refresh_lcd_cam_cam_clock_downstream(clocks, child_instance); } } + fn refresh_rc_fast_clk_downstream(clocks: &mut ClockTree) { + refresh_system_pre_div_in_downstream(clocks); + refresh_rc_fast_clk_div_n_downstream(clocks); + refresh_rtc_slow_clk_downstream(clocks); + refresh_low_power_clk_downstream(clocks); + refresh_timg_calibration_clock_downstream(clocks); + for child_instance in [I2cInstance::I2c0, I2cInstance::I2c1] { + refresh_i2c_function_clock_downstream(clocks, child_instance); + } + for child_instance in [RmtInstance::Rmt] { + refresh_rmt_sclk_downstream(clocks, child_instance); + } + for child_instance in [ + UartInstance::Uart0, + UartInstance::Uart1, + UartInstance::Uart2, + ] { + refresh_uart_function_clock_downstream(clocks, child_instance); + } + } + fn refresh_rc_slow_clk_downstream(clocks: &mut ClockTree) { + refresh_rtc_slow_clk_downstream(clocks); + refresh_timg_calibration_clock_downstream(clocks); + } fn refresh_system_pre_div_in_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.system_pre_div_in { SYSTEM_PRE_DIV_IN_FREQ_CACHE.store( - system_pre_div_in_config_frequency(clocks, config), + system_pre_div_in_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4161,7 +4878,7 @@ macro_rules! define_clock_tree_types { fn refresh_system_pre_div_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.system_pre_div { SYSTEM_PRE_DIV_FREQ_CACHE.store( - system_pre_div_config_frequency(clocks, config), + system_pre_div_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4170,7 +4887,7 @@ macro_rules! define_clock_tree_types { fn refresh_cpu_pll_div_out_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.cpu_pll_div_out { CPU_PLL_DIV_OUT_FREQ_CACHE.store( - cpu_pll_div_out_config_frequency(clocks, config), + cpu_pll_div_out_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4179,12 +4896,16 @@ macro_rules! define_clock_tree_types { fn refresh_cpu_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.cpu_clk { CPU_CLK_FREQ_CACHE.store( - cpu_clk_config_frequency(clocks, config), + cpu_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } refresh_apb_clk_downstream(clocks); refresh_crypto_pwm_clk_downstream(clocks); + for child_instance in [I2sInstance::I2s0, I2sInstance::I2s1] { + refresh_i2s_tx_clk_downstream(clocks, child_instance); + refresh_i2s_rx_clk_downstream(clocks, child_instance); + } for child_instance in [LcdCamInstance::LcdCam] { refresh_lcd_cam_lcd_clock_downstream(clocks, child_instance); refresh_lcd_cam_cam_clock_downstream(clocks, child_instance); @@ -4193,7 +4914,7 @@ macro_rules! define_clock_tree_types { fn refresh_rc_fast_clk_div_n_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.rc_fast_clk_div_n { RC_FAST_CLK_DIV_N_FREQ_CACHE.store( - rc_fast_clk_div_n_config_frequency(clocks, config), + rc_fast_clk_div_n_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4202,16 +4923,25 @@ macro_rules! define_clock_tree_types { fn refresh_rtc_slow_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.rtc_slow_clk { RTC_SLOW_CLK_FREQ_CACHE.store( - rtc_slow_clk_config_frequency(clocks, config), + rtc_slow_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } + refresh_ble_lp_clk_downstream(clocks); refresh_low_power_clk_downstream(clocks); } + fn refresh_ble_lp_clk_downstream(clocks: &mut ClockTree) { + if let Some(config) = clocks.ble_lp_clk { + BLE_LP_CLK_FREQ_CACHE.store( + ble_lp_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } fn refresh_rtc_fast_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.rtc_fast_clk { RTC_FAST_CLK_FREQ_CACHE.store( - rtc_fast_clk_config_frequency(clocks, config), + rtc_fast_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4219,7 +4949,7 @@ macro_rules! define_clock_tree_types { fn refresh_low_power_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.low_power_clk { LOW_POWER_CLK_FREQ_CACHE.store( - low_power_clk_config_frequency(clocks, config), + low_power_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4227,7 +4957,7 @@ macro_rules! define_clock_tree_types { fn refresh_timg_calibration_clock_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.timg_calibration_clock { TIMG_CALIBRATION_CLOCK_FREQ_CACHE.store( - timg_calibration_clock_config_frequency(clocks, config), + timg_calibration_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4235,7 +4965,33 @@ macro_rules! define_clock_tree_types { fn refresh_i2c_function_clock_downstream(clocks: &mut ClockTree, instance: I2cInstance) { if let Some(config) = clocks.i2c_function_clock[instance as usize] { I2C_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - I2cInstance::function_clock_config_frequency(clocks, config), + I2cInstance::function_clock_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + fn refresh_i2s_tx_clk_downstream(clocks: &mut ClockTree, instance: I2sInstance) { + if let Some(config) = clocks.i2s_tx_clk[instance as usize] { + I2S_TX_CLK_FREQ_CACHE[instance as usize].store( + I2sInstance::tx_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + refresh_i2s_mclk_out_downstream(clocks, instance); + } + fn refresh_i2s_rx_clk_downstream(clocks: &mut ClockTree, instance: I2sInstance) { + if let Some(config) = clocks.i2s_rx_clk[instance as usize] { + I2S_RX_CLK_FREQ_CACHE[instance as usize].store( + I2sInstance::rx_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + refresh_i2s_mclk_out_downstream(clocks, instance); + } + fn refresh_i2s_mclk_out_downstream(clocks: &mut ClockTree, instance: I2sInstance) { + if let Some(config) = clocks.i2s_mclk_out[instance as usize] { + I2S_MCLK_OUT_FREQ_CACHE[instance as usize].store( + instance.mclk_out_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4243,7 +4999,7 @@ macro_rules! define_clock_tree_types { fn refresh_lcd_cam_lcd_clock_downstream(clocks: &mut ClockTree, instance: LcdCamInstance) { if let Some(config) = clocks.lcd_cam_lcd_clock[instance as usize] { LCD_CAM_LCD_CLOCK_FREQ_CACHE[instance as usize].store( - LcdCamInstance::lcd_clock_config_frequency(clocks, config), + LcdCamInstance::lcd_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4251,7 +5007,7 @@ macro_rules! define_clock_tree_types { fn refresh_lcd_cam_cam_clock_downstream(clocks: &mut ClockTree, instance: LcdCamInstance) { if let Some(config) = clocks.lcd_cam_cam_clock[instance as usize] { LCD_CAM_CAM_CLOCK_FREQ_CACHE[instance as usize].store( - LcdCamInstance::cam_clock_config_frequency(clocks, config), + LcdCamInstance::cam_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4259,7 +5015,7 @@ macro_rules! define_clock_tree_types { fn refresh_apb_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.apb_clk { APB_CLK_FREQ_CACHE.store( - apb_clk_config_frequency(clocks, config), + apb_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4283,7 +5039,7 @@ macro_rules! define_clock_tree_types { fn refresh_crypto_pwm_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.crypto_pwm_clk { CRYPTO_PWM_CLK_FREQ_CACHE.store( - crypto_pwm_clk_config_frequency(clocks, config), + crypto_pwm_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4291,7 +5047,7 @@ macro_rules! define_clock_tree_types { fn refresh_rmt_sclk_downstream(clocks: &mut ClockTree, instance: RmtInstance) { if let Some(config) = clocks.rmt_sclk[instance as usize] { RMT_SCLK_FREQ_CACHE[instance as usize].store( - RmtInstance::sclk_config_frequency(clocks, config), + RmtInstance::sclk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4299,7 +5055,7 @@ macro_rules! define_clock_tree_types { fn refresh_spi_function_clock_downstream(clocks: &mut ClockTree, instance: SpiInstance) { if let Some(config) = clocks.spi_function_clock[instance as usize] { SPI_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - SpiInstance::function_clock_config_frequency(clocks, config), + SpiInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4307,7 +5063,7 @@ macro_rules! define_clock_tree_types { fn refresh_timg_function_clock_downstream(clocks: &mut ClockTree, instance: TimgInstance) { if let Some(config) = clocks.timg_function_clock[instance as usize] { TIMG_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - TimgInstance::function_clock_config_frequency(clocks, config), + TimgInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4315,7 +5071,7 @@ macro_rules! define_clock_tree_types { fn refresh_uart_function_clock_downstream(clocks: &mut ClockTree, instance: UartInstance) { if let Some(config) = clocks.uart_function_clock[instance as usize] { UART_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - UartInstance::function_clock_config_frequency(clocks, config), + UartInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -4327,7 +5083,7 @@ macro_rules! define_clock_tree_types { ) { if let Some(config) = clocks.uart_baud_rate_generator[instance as usize] { UART_BAUD_RATE_GENERATOR_FREQ_CACHE[instance as usize].store( - instance.baud_rate_generator_config_frequency(clocks, config), + instance.baud_rate_generator_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -5014,6 +5770,57 @@ macro_rules! for_each_spi_slave { (SPI3, Spi3, SPI3_CLK, SPI3_D, SPI3_Q, SPI3_CS0))); }; } +/// This macro can be used to generate code for each PCNT unit. +/// +/// For an explanation on the general syntax, as well as usage of individual/repeated +/// matchers, refer to [the crate-level documentation][crate#for_each-macros]. +/// +/// This macro has four options for its "Individual matcher" case: +/// +/// - `names`: `($instance:ident)` +/// - `all`: `($peri:ident, $variant:ident, $sys:ident, $regs:ident, $unit:literal, +/// $interrupt:ident, $sig_ch0:ident, $sig_ch1:ident, $ctrl_ch0:ident, $ctrl_ch1:ident)` +/// - `interrupt`: `($interrupt:ident)` (repeated: one ident per unique IRQ) +/// - `regs`: `($regs:ident)` (repeated: one ident per register block) +/// +/// Macro fragments: +/// +/// - `$peri`: unit singleton name (`PCNT0_UNIT0`, `PCNT1_UNIT0`, …) +/// - `$variant`: `AnyPcntUnit` enum variant (`Pcnt0Unit0`, `Pcnt1Unit0`, …) +/// - `$sys`: `esp_hal::system::Peripheral` variant for clocks +/// - `$regs`: register-block singleton (`PCNT`, `PCNT1`) +/// - `$unit`: hardware unit index within that register block +/// - `$interrupt`: shared peripheral interrupt +/// - `$sig_ch0`, `$sig_ch1`, `$ctrl_ch0`, `$ctrl_ch1`: GPIO matrix input signals +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! for_each_pcnt_unit { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _for_each_inner_pcnt_unit { $(($pattern) => $code;)* ($other : tt) + => {} } _for_each_inner_pcnt_unit!((PCNT0_UNIT0)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT2)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT3)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT0, Pcnt0Unit0, Pcnt, PCNT, 0, PCNT, + PCNT0_SIG_CH0, PCNT0_SIG_CH1, PCNT0_CTRL_CH0, PCNT0_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT1, Pcnt0Unit1, Pcnt, PCNT, 1, PCNT, + PCNT1_SIG_CH0, PCNT1_SIG_CH1, PCNT1_CTRL_CH0, PCNT1_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT2, Pcnt0Unit2, Pcnt, PCNT, 2, PCNT, + PCNT2_SIG_CH0, PCNT2_SIG_CH1, PCNT2_CTRL_CH0, PCNT2_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT3, Pcnt0Unit3, Pcnt, PCNT, 3, PCNT, + PCNT3_SIG_CH0, PCNT3_SIG_CH1, PCNT3_CTRL_CH0, PCNT3_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT)); _for_each_inner_pcnt_unit!((PCNT)); + _for_each_inner_pcnt_unit!((names(PCNT0_UNIT0), (PCNT0_UNIT1), (PCNT0_UNIT2), + (PCNT0_UNIT3))); _for_each_inner_pcnt_unit!((all(PCNT0_UNIT0, Pcnt0Unit0, Pcnt, + PCNT, 0, PCNT, PCNT0_SIG_CH0, PCNT0_SIG_CH1, PCNT0_CTRL_CH0, PCNT0_CTRL_CH1), + (PCNT0_UNIT1, Pcnt0Unit1, Pcnt, PCNT, 1, PCNT, PCNT1_SIG_CH0, PCNT1_SIG_CH1, + PCNT1_CTRL_CH0, PCNT1_CTRL_CH1), (PCNT0_UNIT2, Pcnt0Unit2, Pcnt, PCNT, 2, PCNT, + PCNT2_SIG_CH0, PCNT2_SIG_CH1, PCNT2_CTRL_CH0, PCNT2_CTRL_CH1), (PCNT0_UNIT3, + Pcnt0Unit3, Pcnt, PCNT, 3, PCNT, PCNT3_SIG_CH0, PCNT3_SIG_CH1, PCNT3_CTRL_CH0, + PCNT3_CTRL_CH1))); _for_each_inner_pcnt_unit!((interrupt(PCNT))); + _for_each_inner_pcnt_unit!((regs(PCNT))); + }; +} #[macro_export] #[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] macro_rules! for_each_peripheral { @@ -5245,6 +6052,14 @@ macro_rules! for_each_peripheral { DMA_CH4 <= virtual(DMA_IN_CH4 : { bind_dma_in_interrupt, enable_dma_in_interrupt, disable_dma_in_interrupt }, DMA_OUT_CH4 : { bind_dma_out_interrupt, enable_dma_out_interrupt, disable_dma_out_interrupt }) (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT0_UNIT0 peripheral singleton"] PCNT0_UNIT0 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT0_UNIT1 peripheral singleton"] PCNT0_UNIT1 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT0_UNIT2 peripheral singleton"] PCNT0_UNIT2 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT0_UNIT3 peripheral singleton"] PCNT0_UNIT3 <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "SDM_CH0 peripheral singleton"] SDM_CH0 <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "SDM_CH1 peripheral singleton"] SDM_CH1 <= virtual() (unstable))); @@ -5305,22 +6120,23 @@ macro_rules! for_each_peripheral { MCPWM0 <= MCPWM0() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "MCPWM1 peripheral singleton"] MCPWM1 <= MCPWM1() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "PCNT peripheral singleton"] - PCNT <= PCNT() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "PERI_BACKUP peripheral singleton"] PERI_BACKUP <= PERI_BACKUP() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "RMT peripheral singleton"] RMT - <= RMT() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "RNG peripheral singleton"] RNG <= RNG() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "RSA peripheral singleton"] RSA - <= RSA(RSA : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt - }) (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "RTC_CNTL peripheral singleton"] RTC_CNTL <= RTC_CNTL() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "LP_I2C0 peripheral singleton"] - LP_I2C0 <= RTC_I2C() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc - = "RTC_IO peripheral singleton"] RTC_IO <= RTC_IO() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "SDHOST peripheral singleton"] - SDHOST <= SDHOST() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "SENS peripheral singleton"] SENS <= SENS() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = + PCNT <= PCNT(PCNT : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt }) (unstable))); _for_each_inner_peripheral!((@ peri_type + #[doc = "PERI_BACKUP peripheral singleton"] PERI_BACKUP <= PERI_BACKUP() + (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "RMT peripheral singleton"] RMT <= RMT() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "RNG peripheral singleton"] RNG + <= RNG() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "RSA peripheral singleton"] RSA <= RSA(RSA : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }) (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "RTC_CNTL peripheral singleton"] + RTC_CNTL <= RTC_CNTL() (unstable))); _for_each_inner_peripheral!((@ peri_type + #[doc = "LP_I2C0 peripheral singleton"] LP_I2C0 <= RTC_I2C() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "RTC_IO peripheral singleton"] + RTC_IO <= RTC_IO() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "SDHOST peripheral singleton"] SDHOST <= SDHOST() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "SENS peripheral singleton"] + SENS <= SENS() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "SENSITIVE peripheral singleton"] SENSITIVE <= SENSITIVE() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "SHA peripheral singleton"] SHA <= SHA(SHA : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt @@ -5377,6 +6193,8 @@ macro_rules! for_each_peripheral { WIFI <= virtual(WIFI_MAC : { bind_mac_interrupt, enable_mac_interrupt, disable_mac_interrupt }, WIFI_PWR : { bind_pwr_interrupt, enable_pwr_interrupt, disable_pwr_interrupt }))); _for_each_inner_peripheral!((@ peri_type #[doc = + "IPC peripheral singleton"] IPC <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "FROM_CPU_INTR0 peripheral singleton"] FROM_CPU_INTR0 <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "FROM_CPU_INTR1 peripheral singleton"] FROM_CPU_INTR1 <= virtual() (unstable))); @@ -5413,6 +6231,10 @@ macro_rules! for_each_peripheral { _for_each_inner_peripheral!((DMA_CH2(unstable))); _for_each_inner_peripheral!((DMA_CH3(unstable))); _for_each_inner_peripheral!((DMA_CH4(unstable))); + _for_each_inner_peripheral!((PCNT0_UNIT0(unstable))); + _for_each_inner_peripheral!((PCNT0_UNIT1(unstable))); + _for_each_inner_peripheral!((PCNT0_UNIT2(unstable))); + _for_each_inner_peripheral!((PCNT0_UNIT3(unstable))); _for_each_inner_peripheral!((SDM_CH0(unstable))); _for_each_inner_peripheral!((SDM_CH1(unstable))); _for_each_inner_peripheral!((SDM_CH2(unstable))); @@ -5480,8 +6302,7 @@ macro_rules! for_each_peripheral { _for_each_inner_peripheral!((PSRAM(unstable))); _for_each_inner_peripheral!((ULP_RISCV_CORE(unstable))); _for_each_inner_peripheral!((WIFI)); - _for_each_inner_peripheral!((FROM_CPU_INTR0(unstable))); - _for_each_inner_peripheral!((FROM_CPU_INTR1(unstable))); + _for_each_inner_peripheral!((IPC(unstable))); _for_each_inner_peripheral!((FROM_CPU_INTR2(unstable))); _for_each_inner_peripheral!((FROM_CPU_INTR3(unstable))); _for_each_inner_peripheral!((SPI2, Spi2, 0, AhbGdmaChannel)); @@ -5689,38 +6510,44 @@ macro_rules! for_each_peripheral { bind_dma_in_interrupt, enable_dma_in_interrupt, disable_dma_in_interrupt }, DMA_OUT_CH4 : { bind_dma_out_interrupt, enable_dma_out_interrupt, disable_dma_out_interrupt }) (unstable)), (@ peri_type #[doc = - "SDM_CH0 peripheral singleton"] SDM_CH0 <= virtual() (unstable)), (@ peri_type - #[doc = "SDM_CH1 peripheral singleton"] SDM_CH1 <= virtual() (unstable)), (@ - peri_type #[doc = "SDM_CH2 peripheral singleton"] SDM_CH2 <= virtual() - (unstable)), (@ peri_type #[doc = "SDM_CH3 peripheral singleton"] SDM_CH3 <= - virtual() (unstable)), (@ peri_type #[doc = "SDM_CH4 peripheral singleton"] - SDM_CH4 <= virtual() (unstable)), (@ peri_type #[doc = - "SDM_CH5 peripheral singleton"] SDM_CH5 <= virtual() (unstable)), (@ peri_type - #[doc = "SDM_CH6 peripheral singleton"] SDM_CH6 <= virtual() (unstable)), (@ - peri_type #[doc = "SDM_CH7 peripheral singleton"] SDM_CH7 <= virtual() - (unstable)), (@ peri_type #[doc = "AES peripheral singleton"] AES <= AES(AES : { - bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) - (unstable)), (@ peri_type #[doc = "APB_CTRL peripheral singleton"] APB_CTRL <= - APB_CTRL() (unstable)), (@ peri_type #[doc = "APB_SARADC peripheral singleton"] - APB_SARADC <= APB_SARADC() (unstable)), (@ peri_type #[doc = - "ASSIST_DEBUG peripheral singleton"] ASSIST_DEBUG <= ASSIST_DEBUG() (unstable)), - (@ peri_type #[doc = "DMA peripheral singleton"] DMA <= DMA() (unstable)), (@ - peri_type #[doc = "DS peripheral singleton"] DS <= DS() (unstable)), (@ peri_type - #[doc = "EFUSE peripheral singleton"] EFUSE <= EFUSE() (unstable)), (@ peri_type - #[doc = "EXTMEM peripheral singleton"] EXTMEM <= EXTMEM() (unstable)), (@ - peri_type #[doc = "MMU_TABLE peripheral singleton"] MMU_TABLE <= MMU_TABLE() - (unstable)), (@ peri_type #[doc = "GPIO peripheral singleton"] GPIO <= GPIO() - (unstable)), (@ peri_type #[doc = "GPIO_SD peripheral singleton"] GPIO_SD <= - GPIO_SD() (unstable)), (@ peri_type #[doc = "HMAC peripheral singleton"] HMAC <= - HMAC() (unstable)), (@ peri_type #[doc = "I2C_ANA_MST peripheral singleton"] - I2C_ANA_MST <= I2C_ANA_MST() (unstable)), (@ peri_type #[doc = - "I2C0 peripheral singleton"] I2C0 <= I2C0(I2C_EXT0 : { bind_peri_interrupt, - enable_peri_interrupt, disable_peri_interrupt })), (@ peri_type #[doc = - "I2C1 peripheral singleton"] I2C1 <= I2C1(I2C_EXT1 : { bind_peri_interrupt, - enable_peri_interrupt, disable_peri_interrupt })), (@ peri_type #[doc = - "I2S0 peripheral singleton"] I2S0 <= I2S0(I2S0 : { bind_peri_interrupt, + "PCNT0_UNIT0 peripheral singleton"] PCNT0_UNIT0 <= virtual() (unstable)), (@ + peri_type #[doc = "PCNT0_UNIT1 peripheral singleton"] PCNT0_UNIT1 <= virtual() + (unstable)), (@ peri_type #[doc = "PCNT0_UNIT2 peripheral singleton"] PCNT0_UNIT2 + <= virtual() (unstable)), (@ peri_type #[doc = + "PCNT0_UNIT3 peripheral singleton"] PCNT0_UNIT3 <= virtual() (unstable)), (@ + peri_type #[doc = "SDM_CH0 peripheral singleton"] SDM_CH0 <= virtual() + (unstable)), (@ peri_type #[doc = "SDM_CH1 peripheral singleton"] SDM_CH1 <= + virtual() (unstable)), (@ peri_type #[doc = "SDM_CH2 peripheral singleton"] + SDM_CH2 <= virtual() (unstable)), (@ peri_type #[doc = + "SDM_CH3 peripheral singleton"] SDM_CH3 <= virtual() (unstable)), (@ peri_type + #[doc = "SDM_CH4 peripheral singleton"] SDM_CH4 <= virtual() (unstable)), (@ + peri_type #[doc = "SDM_CH5 peripheral singleton"] SDM_CH5 <= virtual() + (unstable)), (@ peri_type #[doc = "SDM_CH6 peripheral singleton"] SDM_CH6 <= + virtual() (unstable)), (@ peri_type #[doc = "SDM_CH7 peripheral singleton"] + SDM_CH7 <= virtual() (unstable)), (@ peri_type #[doc = + "AES peripheral singleton"] AES <= AES(AES : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc - = "I2S1 peripheral singleton"] I2S1 <= I2S1(I2S1 : { bind_peri_interrupt, + = "APB_CTRL peripheral singleton"] APB_CTRL <= APB_CTRL() (unstable)), (@ + peri_type #[doc = "APB_SARADC peripheral singleton"] APB_SARADC <= APB_SARADC() + (unstable)), (@ peri_type #[doc = "ASSIST_DEBUG peripheral singleton"] + ASSIST_DEBUG <= ASSIST_DEBUG() (unstable)), (@ peri_type #[doc = + "DMA peripheral singleton"] DMA <= DMA() (unstable)), (@ peri_type #[doc = + "DS peripheral singleton"] DS <= DS() (unstable)), (@ peri_type #[doc = + "EFUSE peripheral singleton"] EFUSE <= EFUSE() (unstable)), (@ peri_type #[doc = + "EXTMEM peripheral singleton"] EXTMEM <= EXTMEM() (unstable)), (@ peri_type #[doc + = "MMU_TABLE peripheral singleton"] MMU_TABLE <= MMU_TABLE() (unstable)), (@ + peri_type #[doc = "GPIO peripheral singleton"] GPIO <= GPIO() (unstable)), (@ + peri_type #[doc = "GPIO_SD peripheral singleton"] GPIO_SD <= GPIO_SD() + (unstable)), (@ peri_type #[doc = "HMAC peripheral singleton"] HMAC <= HMAC() + (unstable)), (@ peri_type #[doc = "I2C_ANA_MST peripheral singleton"] I2C_ANA_MST + <= I2C_ANA_MST() (unstable)), (@ peri_type #[doc = "I2C0 peripheral singleton"] + I2C0 <= I2C0(I2C_EXT0 : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt })), (@ peri_type #[doc = "I2C1 peripheral singleton"] + I2C1 <= I2C1(I2C_EXT1 : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt })), (@ peri_type #[doc = "I2S0 peripheral singleton"] + I2S0 <= I2S0(I2S0 : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt }) (unstable)), (@ peri_type #[doc = + "I2S1 peripheral singleton"] I2S1 <= I2S1(I2S1 : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc = "INTERRUPT_CORE0 peripheral singleton"] INTERRUPT_CORE0 <= INTERRUPT_CORE0() (unstable)), (@ peri_type #[doc = "INTERRUPT_CORE1 peripheral singleton"] @@ -5732,7 +6559,8 @@ macro_rules! for_each_peripheral { #[doc = "RTC_TIMER peripheral singleton"] RTC_TIMER <= RTC_CNTL() (unstable)), (@ peri_type #[doc = "MCPWM0 peripheral singleton"] MCPWM0 <= MCPWM0() (unstable)), (@ peri_type #[doc = "MCPWM1 peripheral singleton"] MCPWM1 <= MCPWM1() - (unstable)), (@ peri_type #[doc = "PCNT peripheral singleton"] PCNT <= PCNT() + (unstable)), (@ peri_type #[doc = "PCNT peripheral singleton"] PCNT <= PCNT(PCNT + : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc = "PERI_BACKUP peripheral singleton"] PERI_BACKUP <= PERI_BACKUP() (unstable)), (@ peri_type #[doc = "RMT peripheral singleton"] RMT <= RMT() (unstable)), (@ peri_type #[doc = "RNG peripheral singleton"] RNG <= @@ -5788,6 +6616,7 @@ macro_rules! for_each_peripheral { "WIFI peripheral singleton"] WIFI <= virtual(WIFI_MAC : { bind_mac_interrupt, enable_mac_interrupt, disable_mac_interrupt }, WIFI_PWR : { bind_pwr_interrupt, enable_pwr_interrupt, disable_pwr_interrupt })), (@ peri_type #[doc = + "IPC peripheral singleton"] IPC <= virtual() (unstable)), (@ peri_type #[doc = "FROM_CPU_INTR0 peripheral singleton"] FROM_CPU_INTR0 <= virtual() (unstable)), (@ peri_type #[doc = "FROM_CPU_INTR1 peripheral singleton"] FROM_CPU_INTR1 <= virtual() (unstable)), (@ peri_type #[doc = @@ -5801,10 +6630,11 @@ macro_rules! for_each_peripheral { (GPIO33), (GPIO34), (GPIO35), (GPIO36), (GPIO37), (GPIO38), (GPIO39), (GPIO40), (GPIO41), (GPIO42), (GPIO43), (GPIO44), (GPIO45), (GPIO46), (GPIO47), (GPIO48), (DMA_CH0(unstable)), (DMA_CH1(unstable)), (DMA_CH2(unstable)), - (DMA_CH3(unstable)), (DMA_CH4(unstable)), (SDM_CH0(unstable)), - (SDM_CH1(unstable)), (SDM_CH2(unstable)), (SDM_CH3(unstable)), - (SDM_CH4(unstable)), (SDM_CH5(unstable)), (SDM_CH6(unstable)), - (SDM_CH7(unstable)), (AES(unstable)), (APB_CTRL(unstable)), + (DMA_CH3(unstable)), (DMA_CH4(unstable)), (PCNT0_UNIT0(unstable)), + (PCNT0_UNIT1(unstable)), (PCNT0_UNIT2(unstable)), (PCNT0_UNIT3(unstable)), + (SDM_CH0(unstable)), (SDM_CH1(unstable)), (SDM_CH2(unstable)), + (SDM_CH3(unstable)), (SDM_CH4(unstable)), (SDM_CH5(unstable)), + (SDM_CH6(unstable)), (SDM_CH7(unstable)), (AES(unstable)), (APB_CTRL(unstable)), (APB_SARADC(unstable)), (ASSIST_DEBUG(unstable)), (DMA(unstable)), (DS(unstable)), (EXTMEM(unstable)), (GPIO(unstable)), (GPIO_SD(unstable)), (HMAC(unstable)), (I2C_ANA_MST(unstable)), (I2C0), (I2C1), (I2S0(unstable)), @@ -5820,13 +6650,13 @@ macro_rules! for_each_peripheral { (USB_DEVICE(unstable)), (WCL(unstable)), (XTS_AES(unstable)), (ADC1(unstable)), (ADC2(unstable)), (BT(unstable)), (CPU_CTRL(unstable)), (FLASH(unstable)), (GPIO_DEDICATED(unstable)), (PSRAM(unstable)), (ULP_RISCV_CORE(unstable)), - (WIFI), (FROM_CPU_INTR0(unstable)), (FROM_CPU_INTR1(unstable)), - (FROM_CPU_INTR2(unstable)), (FROM_CPU_INTR3(unstable)))); - _for_each_inner_peripheral!((dma_eligible(SPI2, Spi2, 0, AhbGdmaChannel), (SPI3, - Spi3, 1, AhbGdmaChannel), (UHCI0, Uhci0, 2, AhbGdmaChannel), (I2S0, I2s0, 3, - AhbGdmaChannel), (I2S1, I2s1, 4, AhbGdmaChannel), (LCD_CAM, LcdCam, 5, - AhbGdmaChannel), (AES, Aes, 6, AhbGdmaChannel), (SHA, Sha, 7, AhbGdmaChannel), - (APB_SARADC, ApbSaradc, 8, AhbGdmaChannel), (RMT, Rmt, 9, AhbGdmaChannel))); + (WIFI), (IPC(unstable)), (FROM_CPU_INTR2(unstable)), + (FROM_CPU_INTR3(unstable)))); _for_each_inner_peripheral!((dma_eligible(SPI2, + Spi2, 0, AhbGdmaChannel), (SPI3, Spi3, 1, AhbGdmaChannel), (UHCI0, Uhci0, 2, + AhbGdmaChannel), (I2S0, I2s0, 3, AhbGdmaChannel), (I2S1, I2s1, 4, + AhbGdmaChannel), (LCD_CAM, LcdCam, 5, AhbGdmaChannel), (AES, Aes, 6, + AhbGdmaChannel), (SHA, Sha, 7, AhbGdmaChannel), (APB_SARADC, ApbSaradc, 8, + AhbGdmaChannel), (RMT, Rmt, 9, AhbGdmaChannel))); }; } /// This macro can be used to generate code for each `GPIOn` instance. diff --git a/esp-metadata-generated/src/_generated_esp32s31.rs b/esp-metadata-generated/src/_generated_esp32s31.rs index 99f7554cf6d..ce885343317 100644 --- a/esp-metadata-generated/src/_generated_esp32s31.rs +++ b/esp-metadata-generated/src/_generated_esp32s31.rs @@ -88,6 +88,9 @@ macro_rules! property { ("gpio.func_in_sel_offset", str) => { stringify!(0) }; + ("gpio.need_soft_isolate_during_pd") => { + true + }; ("gpio.has_bank_1") => { true }; @@ -115,6 +118,12 @@ macro_rules! property { ("dedicated_gpio.channel_count", str) => { stringify!(8) }; + ("lp_io.version") => { + "esp32s31" + }; + ("lp_io.has_gpio_matrix") => { + true + }; ("uart.ram_size") => { 128 }; @@ -226,6 +235,45 @@ macro_rules! property { ("spi_master.dma_can_access_flash") => { false }; + ("i2s.version") => { + 3 + }; + ("i2s.version", str) => { + stringify!(3) + }; + ("i2s.mclk_divider_bit_width") => { + 8 + }; + ("i2s.mclk_divider_bit_width", str) => { + stringify!(8) + }; + ("i2s.max_ws_width") => { + 512 + }; + ("i2s.max_ws_width", str) => { + stringify!(512) + }; + ("i2s.clock_configured_by_pcr") => { + false + }; + ("i2s.clock_configured_by_hp_sys_clkrst") => { + true + }; + ("i2s.supports_pdm_rx_hp_filter") => { + true + }; + ("i2s.supports_pdm_tx") => { + true + }; + ("i2s.supports_pdm_rx") => { + true + }; + ("i2s.supports_pcm2pdm") => { + true + }; + ("i2s.supports_pdm2pcm") => { + true + }; ("rmt.ram_start") => { 540366848 }; @@ -286,6 +334,84 @@ macro_rules! property { ("usb_otg_hs.fifo_depth_words", str) => { stringify!(896) }; + ("bt.controller") => { + "btdm2" + }; + ("wifi.has_wifi6") => { + true + }; + ("wifi.mac_version") => { + 3 + }; + ("wifi.mac_version", str) => { + stringify!(3) + }; + ("wifi.has_5g") => { + false + }; + ("wifi.csi_supported") => { + true + }; + ("wifi.has_nan") => { + true + }; + ("wifi.has_ftm") => { + true + }; + ("ethernet.mii_via_gpio_matrix") => { + true + }; + ("ethernet.rx_store_and_forward") => { + false + }; + ("ethernet.rx_checksum_offload") => { + true + }; + ("ethernet.tx_checksum_offload") => { + false + }; + ("ethernet.dma_burst_len") => { + 16 + }; + ("ethernet.dma_burst_len", str) => { + stringify!(16) + }; + ("ethernet.has_rgmii") => { + true + }; + ("phy.combo_module") => { + false + }; + ("rgb_display.output_lines") => { + 24 + }; + ("rgb_display.output_lines", str) => { + stringify!(24) + }; + ("adc.line_calibration") => { + false + }; + ("adc.curve_calibration") => { + false + }; + ("adc.basic_calibration") => { + false + }; + ("adc.calibration_v1_scheme_supported") => { + false + }; + ("adc.channel_compensation") => { + false + }; + ("adc.pcr_clock") => { + false + }; + ("adc.pcr_sar_clk_div") => { + false + }; + ("adc.sar_power_override") => { + false + }; ("sdm.channel_count") => { 8 }; @@ -293,11 +419,14 @@ macro_rules! property { stringify!(8) }; ("timergroup.timg_has_timer1") => { - false + true }; ("timergroup.timg_has_divcnt_rst") => { true }; + ("timergroup.wdt_has_conf_update") => { + true + }; ("timergroup.rc_fast_calibration_divider_min_rev") => { 0 }; @@ -335,7 +464,7 @@ macro_rules! property { stringify!(16) }; ("rng.trng_supported") => { - false + true }; ("rng.is_lp_sys") => { false @@ -358,6 +487,30 @@ macro_rules! property { ("rsa.memory_size_bytes", str) => { stringify!(512) }; + ("sleep.light_sleep") => { + true + }; + ("sleep.deep_sleep") => { + true + }; + ("sleep.rejectable_mask") => { + 46150029 + }; + ("sleep.ext1_version") => { + 3 + }; + ("sleep.ext1_version", str) => { + stringify!(3) + }; + ("sleep.pin_wakeup_version") => { + 3 + }; + ("sleep.pin_wakeup_version", str) => { + stringify!(3) + }; + ("sleep.deep_sleep_needs_gpio_isolation") => { + false + }; ("dma.mem2mem_requires_peripheral") => { false }; @@ -424,6 +577,9 @@ macro_rules! property { ("soc.cpu_has_csr_pc") => { false }; + ("soc.cpu_has_zcmp_workaround") => { + true + }; ("soc.multi_core_enabled") => { true }; @@ -445,6 +601,12 @@ macro_rules! property { ("soc.cpu_mcause_mask", str) => { stringify!(63) }; + ("soc.cpu_pmp_granularity") => { + 128 + }; + ("soc.cpu_pmp_granularity", str) => { + stringify!(128) + }; ("clock_tree.cpu_root_clk") => { [crate ::soc::clocks::CpuRootClkConfig::Xtal, crate ::soc::clocks::CpuRootClkConfig::Cpll, crate @@ -454,7 +616,10 @@ macro_rules! property { ("clock_tree.cpu_clk.divisor") => { (0, 255) }; - ("clock_tree.ahb_clk.divisor") => { + ("clock_tree.mem_clk.divisor") => { + (0, 1) + }; + ("clock_tree.sys_clk.divisor") => { (0, 255) }; ("clock_tree.apb_clk.divisor") => { @@ -465,9 +630,18 @@ macro_rules! property { ::soc::clocks::LpFastClkConfig::Xtal] }; ("clock_tree.lp_slow_clk") => { - [crate ::soc::clocks::LpSlowClkConfig::RcSlow, crate + [crate ::soc::clocks::LpSlowClkConfig::RcSlow, #[cfg(use_xtal32k)] crate ::soc::clocks::LpSlowClkConfig::Xtal32k] }; + ("clock_tree.ble_lp_clk") => { + [crate ::soc::clocks::BleLpClkConfig::Xtal, #[cfg(use_xtal32k)] crate + ::soc::clocks::BleLpClkConfig::Xtal32k] + }; + ("clock_tree.crypto_clk") => { + [crate ::soc::clocks::CryptoClkConfig::Xtal, crate + ::soc::clocks::CryptoClkConfig::RcFast, crate + ::soc::clocks::CryptoClkConfig::PllF240m] + }; ("clock_tree.iomux_function_clock.source") => { [crate ::soc::clocks::IomuxFunctionClockSource::XtalClk, crate ::soc::clocks::IomuxFunctionClockSource::PllF80m] @@ -477,8 +651,8 @@ macro_rules! property { }; ("clock_tree.timg_calibration_clock") => { [crate ::soc::clocks::TimgCalibrationClockConfig::RcSlowClk, crate - ::soc::clocks::TimgCalibrationClockConfig::RcFastDivClk, crate - ::soc::clocks::TimgCalibrationClockConfig::Xtal32kClk] + ::soc::clocks::TimgCalibrationClockConfig::RcFastDivClk, #[cfg(use_xtal32k)] + crate ::soc::clocks::TimgCalibrationClockConfig::Xtal32kClk] }; ("clock_tree.psram.function_clock") => { [crate ::soc::clocks::PsramFunctionClockConfig::Xtal, crate @@ -521,11 +695,65 @@ macro_rules! property { ("clock_tree.i2c.function_clock.div_num") => { (0, 255) }; + ("clock_tree.i2s.tx_clk.sclk") => { + [crate ::soc::clocks::I2sClkSclk::Xtal] + }; + ("clock_tree.i2s.tx_clk.div_num") => { + (1, 256) + }; + ("clock_tree.i2s.tx_clk.div_a") => { + (1, 511) + }; + ("clock_tree.i2s.tx_clk.div_b") => { + (0, 511) + }; + ("clock_tree.i2s.rx_clk.sclk") => { + [crate ::soc::clocks::I2sClkSclk::Xtal] + }; + ("clock_tree.i2s.rx_clk.div_num") => { + (1, 256) + }; + ("clock_tree.i2s.rx_clk.div_a") => { + (1, 511) + }; + ("clock_tree.i2s.rx_clk.div_b") => { + (0, 511) + }; + ("clock_tree.i2s.mclk_out") => { + [crate ::soc::clocks::I2sMclkOutConfig::Tx, crate + ::soc::clocks::I2sMclkOutConfig::Rx] + }; ("clock_tree.rmt.sclk") => { [crate ::soc::clocks::RmtSclkConfig::PllF80m, crate ::soc::clocks::RmtSclkConfig::RcFastClk, crate ::soc::clocks::RmtSclkConfig::XtalClk] }; + ("clock_tree.lcd_cam.lcd_clock.sclk") => { + [crate ::soc::clocks::LcdCamLcdClockSclk::XtalClk, crate + ::soc::clocks::LcdCamLcdClockSclk::PllF160m] + }; + ("clock_tree.lcd_cam.lcd_clock.div_num") => { + (1, 256) + }; + ("clock_tree.lcd_cam.lcd_clock.div_a") => { + (1, 255) + }; + ("clock_tree.lcd_cam.lcd_clock.div_b") => { + (0, 255) + }; + ("clock_tree.lcd_cam.cam_clock.sclk") => { + [crate ::soc::clocks::LcdCamCamClockSclk::XtalClk, crate + ::soc::clocks::LcdCamCamClockSclk::PllF160m] + }; + ("clock_tree.lcd_cam.cam_clock.div_num") => { + (1, 256) + }; + ("clock_tree.lcd_cam.cam_clock.div_a") => { + (1, 255) + }; + ("clock_tree.lcd_cam.cam_clock.div_b") => { + (0, 255) + }; } #[macro_export] #[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] @@ -560,6 +788,45 @@ macro_rules! for_each_dedicated_gpio { 5, CPU_GPIO_13), (1, 6, CPU_GPIO_14), (1, 7, CPU_GPIO_15))); }; } +/// Defines the `LpInputSignal` and `LpOutputSignal` enums. +/// +/// This macro is intended to be called in esp-hal only. +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! define_lp_io_signals { + () => { + #[allow(non_camel_case_types, clippy::upper_case_acronyms)] + #[derive(Debug, PartialEq, Copy, Clone)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + #[doc(hidden)] + pub enum LpInputSignal { + LP_I2C_SCL = 0, + LP_I2C_SDA = 1, + LP_UART_RXD = 2, + LP_UART_CTSN = 3, + LP_UART_DSRN = 4, + LP_SPI_CK = 5, + LP_SPI_CS = 6, + LP_SPI_D = 7, + LP_SPI_Q = 8, + } + #[allow(non_camel_case_types, clippy::upper_case_acronyms)] + #[derive(Debug, PartialEq, Copy, Clone)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + #[doc(hidden)] + pub enum LpOutputSignal { + LP_I2C_SCL = 0, + LP_I2C_SDA = 1, + LP_UART_TXD = 2, + LP_UART_RTSN = 3, + LP_UART_DTRN = 4, + LP_SPI_CK = 5, + LP_SPI_CS = 6, + LP_SPI_D = 7, + LP_SPI_Q = 8, + } + }; +} /// This macro can be used to generate code for each channel of the RMT peripheral. /// /// For an explanation on the general syntax, as well as usage of individual/repeated @@ -703,8 +970,9 @@ macro_rules! for_each_ecc_curve { macro_rules! _for_each_inner_ecc_curve { $(($pattern) => $code;)* ($other : tt) => {} } _for_each_inner_ecc_curve!((0, P192, 192)); _for_each_inner_ecc_curve!((1, P256, 256)); _for_each_inner_ecc_curve!((2, P384, - 384)); _for_each_inner_ecc_curve!((all(0, P192, 192), (1, P256, 256), (2, P384, - 384))); + 384)); _for_each_inner_ecc_curve!((3, Sm2, 256)); + _for_each_inner_ecc_curve!((all(0, P192, 192), (1, P256, 256), (2, P384, 384), + (3, Sm2, 256))); }; } #[macro_export] @@ -950,14 +1218,34 @@ macro_rules! for_each_sha_algorithm { _for_each_inner_sha_algorithm!((Sha512_224, "SHA-512/224"(sizes : 128, 28, 16) (insecure_against :), 5)); _for_each_inner_sha_algorithm!((Sha512_256, "SHA-512/256"(sizes : 128, 32, 16) (insecure_against :), 6)); - _for_each_inner_sha_algorithm!((algos(Sha1, "SHA-1"(sizes : 64, 20, 8) - (insecure_against : "collision", "length extension"), 0), (Sha224, - "SHA-224"(sizes : 64, 28, 8) (insecure_against : "length extension"), 1), - (Sha256, "SHA-256"(sizes : 64, 32, 8) (insecure_against : "length extension"), - 2), (Sha384, "SHA-384"(sizes : 128, 48, 16) (insecure_against :), 3), (Sha512, - "SHA-512"(sizes : 128, 64, 16) (insecure_against : "length extension"), 4), - (Sha512_224, "SHA-512/224"(sizes : 128, 28, 16) (insecure_against :), 5), - (Sha512_256, "SHA-512/256"(sizes : 128, 32, 16) (insecure_against :), 6))); + _for_each_inner_sha_algorithm!((Sm3, "SM3"(sizes : 64, 32, 8) (insecure_against : + "length extension"), 14)); _for_each_inner_sha_algorithm!((algos(Sha1, + "SHA-1"(sizes : 64, 20, 8) (insecure_against : "collision", "length extension"), + 0), (Sha224, "SHA-224"(sizes : 64, 28, 8) (insecure_against : + "length extension"), 1), (Sha256, "SHA-256"(sizes : 64, 32, 8) (insecure_against + : "length extension"), 2), (Sha384, "SHA-384"(sizes : 128, 48, 16) + (insecure_against :), 3), (Sha512, "SHA-512"(sizes : 128, 64, 16) + (insecure_against : "length extension"), 4), (Sha512_224, "SHA-512/224"(sizes : + 128, 28, 16) (insecure_against :), 5), (Sha512_256, "SHA-512/256"(sizes : 128, + 32, 16) (insecure_against :), 6), (Sm3, "SM3"(sizes : 64, 32, 8) + (insecure_against : "length extension"), 14))); + }; +} +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! for_each_wakeup_source { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _for_each_inner_wakeup_source { $(($pattern) => $code;)* ($other : + tt) => {} } _for_each_inner_wakeup_source!((LpCore, 0)); + _for_each_inner_wakeup_source!((Gpio, 2)); _for_each_inner_wakeup_source!((Usb, + 3)); _for_each_inner_wakeup_source!((Uart1, 7)); + _for_each_inner_wakeup_source!((Uart0, 8)); _for_each_inner_wakeup_source!((Ext1, + 12)); _for_each_inner_wakeup_source!((Timer, 13)); + _for_each_inner_wakeup_source!((Wifi, 22)); + _for_each_inner_wakeup_source!((WifiBeacon, 23)); + _for_each_inner_wakeup_source!((Bt, 25)); + _for_each_inner_wakeup_source!((all(LpCore, 0), (Gpio, 2), (Usb, 3), (Uart1, 7), + (Uart0, 8), (Ext1, 12), (Timer, 13), (Wifi, 22), (WifiBeacon, 23), (Bt, 25))); }; } #[macro_export] @@ -986,41 +1274,43 @@ macro_rules! for_each_dma_channel { _for_each_inner_dma_channel!(("AHB_GDMA", any_channel = AhbGdmaChannel)); _for_each_inner_dma_channel!(("AXI_GDMA", any_channel = AxiGdmaChannel)); _for_each_inner_dma_channel!(("AHB_GDMA", DMA_CH0, 0, interrupt_in = - AHB_PDMA_IN_CH0, interrupt_out = AHB_PDMA_OUT_CH0, compatible = [UHCI0])); - _for_each_inner_dma_channel!(("AHB_GDMA", DMA_CH1, 1, interrupt_in = - AHB_PDMA_IN_CH1, interrupt_out = AHB_PDMA_OUT_CH1, compatible = [UHCI0])); - _for_each_inner_dma_channel!(("AHB_GDMA", DMA_CH2, 2, interrupt_in = - AHB_PDMA_IN_CH2, interrupt_out = AHB_PDMA_OUT_CH2, compatible = [UHCI0])); - _for_each_inner_dma_channel!(("AHB_GDMA", DMA_CH3, 3, interrupt_in = - AHB_PDMA_IN_CH3, interrupt_out = AHB_PDMA_OUT_CH3, compatible = [UHCI0])); - _for_each_inner_dma_channel!(("AHB_GDMA", DMA_CH4, 4, interrupt_in = - AHB_PDMA_IN_CH4, interrupt_out = AHB_PDMA_OUT_CH4, compatible = [UHCI0])); - _for_each_inner_dma_channel!(("AXI_GDMA", DMA_AXI_CH0, 0, interrupt_in = - AXI_PDMA_IN_CH0, interrupt_out = AXI_PDMA_OUT_CH0, compatible = [SPI2, SPI3, AES, - SHA])); _for_each_inner_dma_channel!(("AXI_GDMA", DMA_AXI_CH1, 1, interrupt_in = - AXI_PDMA_IN_CH1, interrupt_out = AXI_PDMA_OUT_CH1, compatible = [SPI2, SPI3, AES, - SHA])); _for_each_inner_dma_channel!(("AXI_GDMA", DMA_AXI_CH2, 2, interrupt_in = - AXI_PDMA_IN_CH2, interrupt_out = AXI_PDMA_OUT_CH2, compatible = [SPI2, SPI3, AES, - SHA])); _for_each_inner_dma_channel!((names("AHB_GDMA", DMA_CH0), ("AHB_GDMA", - DMA_CH1), ("AHB_GDMA", DMA_CH2), ("AHB_GDMA", DMA_CH3), ("AHB_GDMA", DMA_CH4), - ("AXI_GDMA", DMA_AXI_CH0), ("AXI_GDMA", DMA_AXI_CH1), ("AXI_GDMA", - DMA_AXI_CH2))); _for_each_inner_dma_channel!((separate_any_type("AHB_GDMA", - any_channel = AhbGdmaChannel), ("AXI_GDMA", any_channel = AxiGdmaChannel))); + AHB_PDMA_IN_CH0, interrupt_out = AHB_PDMA_OUT_CH0, compatible = [UHCI0, I2S0, + I2S1])); _for_each_inner_dma_channel!(("AHB_GDMA", DMA_CH1, 1, interrupt_in = + AHB_PDMA_IN_CH1, interrupt_out = AHB_PDMA_OUT_CH1, compatible = [UHCI0, I2S0, + I2S1])); _for_each_inner_dma_channel!(("AHB_GDMA", DMA_CH2, 2, interrupt_in = + AHB_PDMA_IN_CH2, interrupt_out = AHB_PDMA_OUT_CH2, compatible = [UHCI0, I2S0, + I2S1])); _for_each_inner_dma_channel!(("AHB_GDMA", DMA_CH3, 3, interrupt_in = + AHB_PDMA_IN_CH3, interrupt_out = AHB_PDMA_OUT_CH3, compatible = [UHCI0, I2S0, + I2S1])); _for_each_inner_dma_channel!(("AHB_GDMA", DMA_CH4, 4, interrupt_in = + AHB_PDMA_IN_CH4, interrupt_out = AHB_PDMA_OUT_CH4, compatible = [UHCI0, I2S0, + I2S1])); _for_each_inner_dma_channel!(("AXI_GDMA", DMA_AXI_CH0, 0, interrupt_in = + AXI_PDMA_IN_CH0, interrupt_out = AXI_PDMA_OUT_CH0, compatible = [LCD_CAM, SPI2, + SPI3, AES, SHA])); _for_each_inner_dma_channel!(("AXI_GDMA", DMA_AXI_CH1, 1, + interrupt_in = AXI_PDMA_IN_CH1, interrupt_out = AXI_PDMA_OUT_CH1, compatible = + [LCD_CAM, SPI2, SPI3, AES, SHA])); _for_each_inner_dma_channel!(("AXI_GDMA", + DMA_AXI_CH2, 2, interrupt_in = AXI_PDMA_IN_CH2, interrupt_out = AXI_PDMA_OUT_CH2, + compatible = [LCD_CAM, SPI2, SPI3, AES, SHA])); + _for_each_inner_dma_channel!((names("AHB_GDMA", DMA_CH0), ("AHB_GDMA", DMA_CH1), + ("AHB_GDMA", DMA_CH2), ("AHB_GDMA", DMA_CH3), ("AHB_GDMA", DMA_CH4), ("AXI_GDMA", + DMA_AXI_CH0), ("AXI_GDMA", DMA_AXI_CH1), ("AXI_GDMA", DMA_AXI_CH2))); + _for_each_inner_dma_channel!((separate_any_type("AHB_GDMA", any_channel = + AhbGdmaChannel), ("AXI_GDMA", any_channel = AxiGdmaChannel))); _for_each_inner_dma_channel!((shared)); _for_each_inner_dma_channel!((split("AHB_GDMA", DMA_CH0, 0, interrupt_in = - AHB_PDMA_IN_CH0, interrupt_out = AHB_PDMA_OUT_CH0, compatible = [UHCI0]), - ("AHB_GDMA", DMA_CH1, 1, interrupt_in = AHB_PDMA_IN_CH1, interrupt_out = - AHB_PDMA_OUT_CH1, compatible = [UHCI0]), ("AHB_GDMA", DMA_CH2, 2, interrupt_in = - AHB_PDMA_IN_CH2, interrupt_out = AHB_PDMA_OUT_CH2, compatible = [UHCI0]), - ("AHB_GDMA", DMA_CH3, 3, interrupt_in = AHB_PDMA_IN_CH3, interrupt_out = - AHB_PDMA_OUT_CH3, compatible = [UHCI0]), ("AHB_GDMA", DMA_CH4, 4, interrupt_in = - AHB_PDMA_IN_CH4, interrupt_out = AHB_PDMA_OUT_CH4, compatible = [UHCI0]), - ("AXI_GDMA", DMA_AXI_CH0, 0, interrupt_in = AXI_PDMA_IN_CH0, interrupt_out = - AXI_PDMA_OUT_CH0, compatible = [SPI2, SPI3, AES, SHA]), ("AXI_GDMA", DMA_AXI_CH1, - 1, interrupt_in = AXI_PDMA_IN_CH1, interrupt_out = AXI_PDMA_OUT_CH1, compatible = - [SPI2, SPI3, AES, SHA]), ("AXI_GDMA", DMA_AXI_CH2, 2, interrupt_in = - AXI_PDMA_IN_CH2, interrupt_out = AXI_PDMA_OUT_CH2, compatible = [SPI2, SPI3, AES, - SHA]))); _for_each_inner_dma_channel!((no_own_interrupt)); + AHB_PDMA_IN_CH0, interrupt_out = AHB_PDMA_OUT_CH0, compatible = [UHCI0, I2S0, + I2S1]), ("AHB_GDMA", DMA_CH1, 1, interrupt_in = AHB_PDMA_IN_CH1, interrupt_out = + AHB_PDMA_OUT_CH1, compatible = [UHCI0, I2S0, I2S1]), ("AHB_GDMA", DMA_CH2, 2, + interrupt_in = AHB_PDMA_IN_CH2, interrupt_out = AHB_PDMA_OUT_CH2, compatible = + [UHCI0, I2S0, I2S1]), ("AHB_GDMA", DMA_CH3, 3, interrupt_in = AHB_PDMA_IN_CH3, + interrupt_out = AHB_PDMA_OUT_CH3, compatible = [UHCI0, I2S0, I2S1]), ("AHB_GDMA", + DMA_CH4, 4, interrupt_in = AHB_PDMA_IN_CH4, interrupt_out = AHB_PDMA_OUT_CH4, + compatible = [UHCI0, I2S0, I2S1]), ("AXI_GDMA", DMA_AXI_CH0, 0, interrupt_in = + AXI_PDMA_IN_CH0, interrupt_out = AXI_PDMA_OUT_CH0, compatible = [LCD_CAM, SPI2, + SPI3, AES, SHA]), ("AXI_GDMA", DMA_AXI_CH1, 1, interrupt_in = AXI_PDMA_IN_CH1, + interrupt_out = AXI_PDMA_OUT_CH1, compatible = [LCD_CAM, SPI2, SPI3, AES, SHA]), + ("AXI_GDMA", DMA_AXI_CH2, 2, interrupt_in = AXI_PDMA_IN_CH2, interrupt_out = + AXI_PDMA_OUT_CH2, compatible = [LCD_CAM, SPI2, SPI3, AES, SHA]))); + _for_each_inner_dma_channel!((no_own_interrupt)); }; } #[macro_export] @@ -1029,39 +1319,63 @@ macro_rules! for_each_dma_channel_peri_pair { ($($pattern:tt => $code:tt;)*) => { macro_rules! _for_each_inner_dma_channel_peri_pair { $(($pattern) => $code;)* ($other : tt) => {} } _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", - DMA_CH0, UHCI0)); _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH1, - UHCI0)); _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH2, UHCI0)); + DMA_CH0, UHCI0)); _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH0, + I2S0)); _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH0, I2S1)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH1, UHCI0)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH1, I2S0)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH1, I2S1)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH2, UHCI0)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH2, I2S0)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH2, I2S1)); _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH3, UHCI0)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH3, I2S0)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH3, I2S1)); _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH4, UHCI0)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH4, I2S0)); + _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", DMA_CH4, I2S1)); + _for_each_inner_dma_channel_peri_pair!(("AXI_GDMA", DMA_AXI_CH0, LCD_CAM)); _for_each_inner_dma_channel_peri_pair!(("AXI_GDMA", DMA_AXI_CH0, SPI2)); _for_each_inner_dma_channel_peri_pair!(("AXI_GDMA", DMA_AXI_CH0, SPI3)); _for_each_inner_dma_channel_peri_pair!(("AXI_GDMA", DMA_AXI_CH0, AES)); _for_each_inner_dma_channel_peri_pair!(("AXI_GDMA", DMA_AXI_CH0, SHA)); + _for_each_inner_dma_channel_peri_pair!(("AXI_GDMA", DMA_AXI_CH1, LCD_CAM)); _for_each_inner_dma_channel_peri_pair!(("AXI_GDMA", DMA_AXI_CH1, SPI2)); _for_each_inner_dma_channel_peri_pair!(("AXI_GDMA", DMA_AXI_CH1, SPI3)); _for_each_inner_dma_channel_peri_pair!(("AXI_GDMA", DMA_AXI_CH1, AES)); _for_each_inner_dma_channel_peri_pair!(("AXI_GDMA", DMA_AXI_CH1, SHA)); + _for_each_inner_dma_channel_peri_pair!(("AXI_GDMA", DMA_AXI_CH2, LCD_CAM)); _for_each_inner_dma_channel_peri_pair!(("AXI_GDMA", DMA_AXI_CH2, SPI2)); _for_each_inner_dma_channel_peri_pair!(("AXI_GDMA", DMA_AXI_CH2, SPI3)); _for_each_inner_dma_channel_peri_pair!(("AXI_GDMA", DMA_AXI_CH2, AES)); _for_each_inner_dma_channel_peri_pair!(("AXI_GDMA", DMA_AXI_CH2, SHA)); _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", any_channel = AhbGdmaChannel, - UHCI0)); _for_each_inner_dma_channel_peri_pair!(("AXI_GDMA", any_channel = + UHCI0)); _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", any_channel = + AhbGdmaChannel, I2S0)); _for_each_inner_dma_channel_peri_pair!(("AHB_GDMA", + any_channel = AhbGdmaChannel, I2S1)); + _for_each_inner_dma_channel_peri_pair!(("AXI_GDMA", any_channel = AxiGdmaChannel, + LCD_CAM)); _for_each_inner_dma_channel_peri_pair!(("AXI_GDMA", any_channel = AxiGdmaChannel, SPI2)); _for_each_inner_dma_channel_peri_pair!(("AXI_GDMA", any_channel = AxiGdmaChannel, SPI3)); _for_each_inner_dma_channel_peri_pair!(("AXI_GDMA", any_channel = AxiGdmaChannel, AES)); _for_each_inner_dma_channel_peri_pair!(("AXI_GDMA", any_channel = AxiGdmaChannel, SHA)); _for_each_inner_dma_channel_peri_pair!((channels("AHB_GDMA", DMA_CH0, UHCI0), - ("AHB_GDMA", DMA_CH1, UHCI0), ("AHB_GDMA", DMA_CH2, UHCI0), ("AHB_GDMA", DMA_CH3, - UHCI0), ("AHB_GDMA", DMA_CH4, UHCI0), ("AXI_GDMA", DMA_AXI_CH0, SPI2), - ("AXI_GDMA", DMA_AXI_CH0, SPI3), ("AXI_GDMA", DMA_AXI_CH0, AES), ("AXI_GDMA", - DMA_AXI_CH0, SHA), ("AXI_GDMA", DMA_AXI_CH1, SPI2), ("AXI_GDMA", DMA_AXI_CH1, - SPI3), ("AXI_GDMA", DMA_AXI_CH1, AES), ("AXI_GDMA", DMA_AXI_CH1, SHA), + ("AHB_GDMA", DMA_CH0, I2S0), ("AHB_GDMA", DMA_CH0, I2S1), ("AHB_GDMA", DMA_CH1, + UHCI0), ("AHB_GDMA", DMA_CH1, I2S0), ("AHB_GDMA", DMA_CH1, I2S1), ("AHB_GDMA", + DMA_CH2, UHCI0), ("AHB_GDMA", DMA_CH2, I2S0), ("AHB_GDMA", DMA_CH2, I2S1), + ("AHB_GDMA", DMA_CH3, UHCI0), ("AHB_GDMA", DMA_CH3, I2S0), ("AHB_GDMA", DMA_CH3, + I2S1), ("AHB_GDMA", DMA_CH4, UHCI0), ("AHB_GDMA", DMA_CH4, I2S0), ("AHB_GDMA", + DMA_CH4, I2S1), ("AXI_GDMA", DMA_AXI_CH0, LCD_CAM), ("AXI_GDMA", DMA_AXI_CH0, + SPI2), ("AXI_GDMA", DMA_AXI_CH0, SPI3), ("AXI_GDMA", DMA_AXI_CH0, AES), + ("AXI_GDMA", DMA_AXI_CH0, SHA), ("AXI_GDMA", DMA_AXI_CH1, LCD_CAM), ("AXI_GDMA", + DMA_AXI_CH1, SPI2), ("AXI_GDMA", DMA_AXI_CH1, SPI3), ("AXI_GDMA", DMA_AXI_CH1, + AES), ("AXI_GDMA", DMA_AXI_CH1, SHA), ("AXI_GDMA", DMA_AXI_CH2, LCD_CAM), ("AXI_GDMA", DMA_AXI_CH2, SPI2), ("AXI_GDMA", DMA_AXI_CH2, SPI3), ("AXI_GDMA", DMA_AXI_CH2, AES), ("AXI_GDMA", DMA_AXI_CH2, SHA))); _for_each_inner_dma_channel_peri_pair!((any_channels("AHB_GDMA", any_channel = - AhbGdmaChannel, UHCI0), ("AXI_GDMA", any_channel = AxiGdmaChannel, SPI2), + AhbGdmaChannel, UHCI0), ("AHB_GDMA", any_channel = AhbGdmaChannel, I2S0), + ("AHB_GDMA", any_channel = AhbGdmaChannel, I2S1), ("AXI_GDMA", any_channel = + AxiGdmaChannel, LCD_CAM), ("AXI_GDMA", any_channel = AxiGdmaChannel, SPI2), ("AXI_GDMA", any_channel = AxiGdmaChannel, SPI3), ("AXI_GDMA", any_channel = AxiGdmaChannel, AES), ("AXI_GDMA", any_channel = AxiGdmaChannel, SHA))); }; @@ -1100,6 +1414,22 @@ macro_rules! with_aes_dma_engine { } #[macro_export] #[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! with_i2s_dma_engine { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _with_inner_i2s_dma_engine { $(($pattern) => $code;)* ($other : tt) + => {} } _with_inner_i2s_dma_engine!(("AHB_GDMA", AhbGdmaChannel)); + }; +} +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! with_lcd_cam_dma_engine { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _with_inner_lcd_cam_dma_engine { $(($pattern) => $code;)* ($other : + tt) => {} } _with_inner_lcd_cam_dma_engine!(("AXI_GDMA", AxiGdmaChannel)); + }; +} +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] macro_rules! with_spi_master_dma_engine { ($($pattern:tt => $code:tt;)*) => { macro_rules! _with_inner_spi_master_dma_engine { $(($pattern) => $code;)* ($other @@ -1257,6 +1587,7 @@ macro_rules! for_each_classified_interrupt { ([reserved 5] 6), ([reserved 6] 7), ([reserved 7] 8), ([reserved 8] 9), ([reserved 9] 10), ([reserved 10] 11), ([reserved 11] 12), ([reserved 12] 13), ([reserved 13] 14), ([reserved 14] 15))); + _for_each_inner_classified_interrupt!((context_switch)); }; } #[macro_export] @@ -1315,6 +1646,14 @@ macro_rules! for_each_sw_interrupt { /// todo!() /// } /// +/// fn configure_mpll_clk_impl( +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: MpllClkConfig, +/// ) { +/// todo!() +/// } +/// /// // RC_FAST_CLK /// /// fn enable_rc_fast_clk_impl(_clocks: &mut ClockTree, _en: bool) { @@ -1323,6 +1662,7 @@ macro_rules! for_each_sw_interrupt { /// /// // XTAL32K_CLK /// +/// #[cfg(use_xtal32k)] /// fn enable_xtal32k_clk_impl(_clocks: &mut ClockTree, _en: bool) { /// todo!() /// } @@ -1363,6 +1703,12 @@ macro_rules! for_each_sw_interrupt { /// todo!() /// } /// +/// // BBPLL_D3_CLOCK +/// +/// fn enable_bbpll_d3_clock_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// /// // PLL_F25M /// /// fn enable_pll_f25m_impl(_clocks: &mut ClockTree, _en: bool) { @@ -1409,16 +1755,30 @@ macro_rules! for_each_sw_interrupt { /// todo!() /// } /// -/// // AHB_CLK +/// // MEM_CLK +/// +/// fn enable_mem_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_mem_clk_impl( +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: MemClkConfig, +/// ) { +/// todo!() +/// } +/// +/// // SYS_CLK /// -/// fn enable_ahb_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// fn enable_sys_clk_impl(_clocks: &mut ClockTree, _en: bool) { /// todo!() /// } /// -/// fn configure_ahb_clk_impl( +/// fn configure_sys_clk_impl( /// _clocks: &mut ClockTree, -/// _old_config: Option, -/// _new_config: AhbClkConfig, +/// _old_config: Option, +/// _new_config: SysClkConfig, /// ) { /// todo!() /// } @@ -1461,6 +1821,40 @@ macro_rules! for_each_sw_interrupt { /// todo!() /// } /// +/// // BLE_LP_XTAL_CLK +/// +/// fn enable_ble_lp_xtal_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// // BLE_LP_CLK +/// +/// fn enable_ble_lp_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_ble_lp_clk_impl( +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: BleLpClkConfig, +/// ) { +/// todo!() +/// } +/// +/// // CRYPTO_CLK +/// +/// fn enable_crypto_clk_impl(_clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_crypto_clk_impl( +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: CryptoClkConfig, +/// ) { +/// todo!() +/// } +/// /// // IOMUX_FUNCTION_CLOCK /// /// fn configure_iomux_function_clock_impl( @@ -1508,6 +1902,83 @@ macro_rules! for_each_sw_interrupt { /// todo!() /// } /// } +/// impl I2sInstance { +/// // I2S_TX_CLK +/// +/// fn enable_tx_clk_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_tx_clk_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: I2sClkConfig, +/// ) { +/// todo!() +/// } +/// +/// // I2S_RX_CLK +/// +/// fn enable_rx_clk_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_rx_clk_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: I2sClkConfig, +/// ) { +/// todo!() +/// } +/// +/// // I2S_MCLK_OUT +/// +/// fn enable_mclk_out_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_mclk_out_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: I2sMclkOutConfig, +/// ) { +/// todo!() +/// } +/// } +/// impl LcdCamInstance { +/// // LCD_CAM_LCD_CLOCK +/// +/// fn enable_lcd_clock_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_lcd_clock_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: LcdCamLcdClockConfig, +/// ) { +/// todo!() +/// } +/// +/// // LCD_CAM_CAM_CLOCK +/// +/// fn enable_cam_clock_impl(self, _clocks: &mut ClockTree, _en: bool) { +/// todo!() +/// } +/// +/// fn configure_cam_clock_impl( +/// self, +/// _clocks: &mut ClockTree, +/// _old_config: Option, +/// _new_config: LcdCamCamClockConfig, +/// ) { +/// todo!() +/// } +/// } /// impl RmtInstance { /// // RMT_SCLK /// @@ -1640,12 +2111,23 @@ macro_rules! define_clock_tree_types { } #[derive(Clone, Copy, PartialEq, Eq, Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] - pub enum RmtInstance { - Rmt = 0, + pub enum I2sInstance { + I2s0 = 0, + I2s1 = 1, } #[derive(Clone, Copy, PartialEq, Eq, Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] - pub enum SpiInstance { + pub enum LcdCamInstance { + LcdCam = 0, + } + #[derive(Clone, Copy, PartialEq, Eq, Debug)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum RmtInstance { + Rmt = 0, + } + #[derive(Clone, Copy, PartialEq, Eq, Debug)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum SpiInstance { Spi2 = 0, Spi3 = 1, } @@ -1668,6 +2150,23 @@ macro_rules! define_clock_tree_types { pub enum PsramInstance { Psram = 0, } + /// Selects the output frequency of `MPLL_CLK`. Depends on `XTAL_CLK`. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum MpllClkConfig { + /// 400 MHz + _400, + /// 500 MHz + _500, + } + impl MpllClkConfig { + pub fn value(&self) -> u32 { + match self { + MpllClkConfig::_400 => 400000000, + MpllClkConfig::_500 => 500000000, + } + } + } /// The list of clock signals that the `CPU_ROOT_CLK` multiplexer can output. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] @@ -1703,20 +2202,46 @@ macro_rules! define_clock_tree_types { ); Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } - /// Configures the `AHB_CLK` clock node. + /// Configures the `MEM_CLK` clock node. /// /// The output is calculated as `OUTPUT = CPU_CLK / (divisor + 1)`. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] - pub struct AhbClkConfig { + pub struct MemClkConfig { divisor: u32, } - impl AhbClkConfig { - /// Creates a new configuration for the AHB_CLK clock node. + impl MemClkConfig { + /// Creates a new configuration for the MEM_CLK clock node. + /// + /// ## Panics + /// + /// Panics if the divisor value is outside the + /// valid range (0 ..= 1). + pub const fn new(divisor: u32) -> Self { + ::core::assert!( + divisor <= 1, + "`MEM_CLK` divisor must be between 0 and 1 (inclusive)." + ); + Self { divisor } + } + pub fn divisor(self) -> u32 { + self.divisor as u32 + } + } + /// Configures the `SYS_CLK` clock node. + /// + /// The output is calculated as `OUTPUT = CPU_CLK / (divisor + 1)`. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub struct SysClkConfig { + divisor: u32, + } + impl SysClkConfig { + /// Creates a new configuration for the SYS_CLK clock node. /// /// ## Panics /// @@ -1725,17 +2250,17 @@ macro_rules! define_clock_tree_types { pub const fn new(divisor: u32) -> Self { ::core::assert!( divisor <= 255, - "`AHB_CLK` divisor must be between 0 and 255 (inclusive)." + "`SYS_CLK` divisor must be between 0 and 255 (inclusive)." ); Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } /// Configures the `APB_CLK` clock node. /// - /// The output is calculated as `OUTPUT = AHB_CLK / (divisor + 1)`. + /// The output is calculated as `OUTPUT = SYS_CLK / (divisor + 1)`. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub struct ApbClkConfig { @@ -1755,7 +2280,7 @@ macro_rules! define_clock_tree_types { ); Self { divisor } } - pub(crate) fn divisor(self) -> u32 { + pub fn divisor(self) -> u32 { self.divisor as u32 } } @@ -1774,9 +2299,31 @@ macro_rules! define_clock_tree_types { pub enum LpSlowClkConfig { /// Selects `RC_SLOW_CLK`. RcSlow, + #[cfg(use_xtal32k)] + /// Selects `XTAL32K_CLK`. + Xtal32k, + } + /// The list of clock signals that the `BLE_LP_CLK` multiplexer can output. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum BleLpClkConfig { + /// Selects `BLE_LP_XTAL_CLK`. + Xtal, + #[cfg(use_xtal32k)] /// Selects `XTAL32K_CLK`. Xtal32k, } + /// The list of clock signals that the `CRYPTO_CLK` multiplexer can output. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum CryptoClkConfig { + /// Selects `XTAL_CLK`. + Xtal, + /// Selects `RC_FAST_CLK`. + RcFast, + /// Selects `PLL_F240M`. + PllF240m, + } #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum IomuxFunctionClockSource { @@ -1809,10 +2356,10 @@ macro_rules! define_clock_tree_types { ); Self { source, div_num } } - pub(crate) fn source(self) -> IomuxFunctionClockSource { + pub fn source(self) -> IomuxFunctionClockSource { self.source } - pub(crate) fn div_num(self) -> u32 { + pub fn div_num(self) -> u32 { self.div_num as u32 } } @@ -1824,6 +2371,7 @@ macro_rules! define_clock_tree_types { RcSlowClk, /// Selects `RC_FAST_CLK`. RcFastDivClk, + #[cfg(use_xtal32k)] /// Selects `XTAL32K_CLK`. Xtal32kClk, } @@ -1859,12 +2407,228 @@ macro_rules! define_clock_tree_types { ); Self { sclk, div_num } } - pub(crate) fn sclk(self) -> I2cFunctionClockSclk { + pub fn sclk(self) -> I2cFunctionClockSclk { + self.sclk + } + pub fn div_num(self) -> u32 { + self.div_num as u32 + } + } + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum I2sClkSclk { + #[default] + /// Selects `XTAL_CLK`. + Xtal, + } + /// Configures the `I2S0_TX_CLK` clock node. + /// + /// The output is calculated as `OUTPUT = (sclk * div_a) / (div_num * div_a + div_b)`. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub struct I2sClkConfig { + sclk: I2sClkSclk, + div_num: u32, + div_a: u32, + div_b: u32, + } + impl I2sClkConfig { + /// Creates a new configuration for the TX_CLK clock node. + /// + /// ## Panics + /// + /// Panics if the div_num value is outside the + /// valid range (1 ..= 256). + /// + /// Panics if the div_a value is outside the + /// valid range (1 ..= 511). + /// + /// Panics if the div_b value is outside the + /// valid range (0 ..= 511). + pub const fn new(sclk: I2sClkSclk, div_num: u32, div_a: u32, div_b: u32) -> Self { + ::core::assert!( + div_num >= 1 && div_num <= 256, + "`I2S0_TX_CLK` div_num must be between 1 and 256 (inclusive)." + ); + ::core::assert!( + div_a >= 1 && div_a <= 511, + "`I2S0_TX_CLK` div_a must be between 1 and 511 (inclusive)." + ); + ::core::assert!( + div_b <= 511, + "`I2S0_TX_CLK` div_b must be between 0 and 511 (inclusive)." + ); + Self { + sclk, + div_num, + div_a, + div_b, + } + } + pub fn sclk(self) -> I2sClkSclk { + self.sclk + } + pub fn div_num(self) -> u32 { + self.div_num as u32 + } + pub fn div_a(self) -> u32 { + self.div_a as u32 + } + pub fn div_b(self) -> u32 { + self.div_b as u32 + } + } + /// The list of clock signals that the `I2S0_MCLK_OUT` multiplexer can output. + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum I2sMclkOutConfig { + /// Selects `TX_CLK`. + Tx, + #[default] + /// Selects `RX_CLK`. + Rx, + } + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum LcdCamLcdClockSclk { + #[default] + /// Selects `XTAL_CLK`. + XtalClk, + /// Selects `PLL_F160M`. + PllF160m, + } + /// Configures the `LCD_CAM_LCD_CLOCK` clock node. + /// + /// The output is calculated as `OUTPUT = (sclk * div_a) / (div_num * div_a + div_b)`. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub struct LcdCamLcdClockConfig { + sclk: LcdCamLcdClockSclk, + div_num: u32, + div_a: u32, + div_b: u32, + } + impl LcdCamLcdClockConfig { + /// Creates a new configuration for the LCD_CLOCK clock node. + /// + /// ## Panics + /// + /// Panics if the div_num value is outside the + /// valid range (1 ..= 256). + /// + /// Panics if the div_a value is outside the + /// valid range (1 ..= 255). + /// + /// Panics if the div_b value is outside the + /// valid range (0 ..= 255). + pub const fn new( + sclk: LcdCamLcdClockSclk, + div_num: u32, + div_a: u32, + div_b: u32, + ) -> Self { + ::core::assert!( + div_num >= 1 && div_num <= 256, + "`LCD_CAM_LCD_CLOCK` div_num must be between 1 and 256 (inclusive)." + ); + ::core::assert!( + div_a >= 1 && div_a <= 255, + "`LCD_CAM_LCD_CLOCK` div_a must be between 1 and 255 (inclusive)." + ); + ::core::assert!( + div_b <= 255, + "`LCD_CAM_LCD_CLOCK` div_b must be between 0 and 255 (inclusive)." + ); + Self { + sclk, + div_num, + div_a, + div_b, + } + } + pub fn sclk(self) -> LcdCamLcdClockSclk { self.sclk } - pub(crate) fn div_num(self) -> u32 { + pub fn div_num(self) -> u32 { self.div_num as u32 } + pub fn div_a(self) -> u32 { + self.div_a as u32 + } + pub fn div_b(self) -> u32 { + self.div_b as u32 + } + } + #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum LcdCamCamClockSclk { + #[default] + /// Selects `XTAL_CLK`. + XtalClk, + /// Selects `PLL_F160M`. + PllF160m, + } + /// Configures the `LCD_CAM_CAM_CLOCK` clock node. + /// + /// The output is calculated as `OUTPUT = (sclk * div_a) / (div_num * div_a + div_b)`. + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub struct LcdCamCamClockConfig { + sclk: LcdCamCamClockSclk, + div_num: u32, + div_a: u32, + div_b: u32, + } + impl LcdCamCamClockConfig { + /// Creates a new configuration for the CAM_CLOCK clock node. + /// + /// ## Panics + /// + /// Panics if the div_num value is outside the + /// valid range (1 ..= 256). + /// + /// Panics if the div_a value is outside the + /// valid range (1 ..= 255). + /// + /// Panics if the div_b value is outside the + /// valid range (0 ..= 255). + pub const fn new( + sclk: LcdCamCamClockSclk, + div_num: u32, + div_a: u32, + div_b: u32, + ) -> Self { + ::core::assert!( + div_num >= 1 && div_num <= 256, + "`LCD_CAM_CAM_CLOCK` div_num must be between 1 and 256 (inclusive)." + ); + ::core::assert!( + div_a >= 1 && div_a <= 255, + "`LCD_CAM_CAM_CLOCK` div_a must be between 1 and 255 (inclusive)." + ); + ::core::assert!( + div_b <= 255, + "`LCD_CAM_CAM_CLOCK` div_b must be between 0 and 255 (inclusive)." + ); + Self { + sclk, + div_num, + div_a, + div_b, + } + } + pub fn sclk(self) -> LcdCamCamClockSclk { + self.sclk + } + pub fn div_num(self) -> u32 { + self.div_num as u32 + } + pub fn div_a(self) -> u32 { + self.div_a as u32 + } + pub fn div_b(self) -> u32 { + self.div_b as u32 + } } /// The list of clock signals that the `RMT_SCLK` multiplexer can output. #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] @@ -1882,9 +2646,9 @@ macro_rules! define_clock_tree_types { #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub enum SpiFunctionClockConfig { - /// Selects `BBPLL_CLK`. - Bbpll, #[default] + /// Selects `BBPLL_D3_CLOCK`. + Bbpll, /// Selects `XTAL_CLK`. Xtal, /// Selects `RC_FAST_CLK`. @@ -1948,10 +2712,10 @@ macro_rules! define_clock_tree_types { ); Self { sclk, div_num } } - pub(crate) fn sclk(self) -> UartFunctionClockSclk { + pub fn sclk(self) -> UartFunctionClockSclk { self.sclk } - pub(crate) fn div_num(self) -> u32 { + pub fn div_num(self) -> u32 { self.div_num as u32 } } @@ -1989,10 +2753,10 @@ macro_rules! define_clock_tree_types { integral, } } - pub(crate) fn fractional(self) -> u32 { + pub fn fractional(self) -> u32 { self.fractional as u32 } - pub(crate) fn integral(self) -> u32 { + pub fn integral(self) -> u32 { self.integral as u32 } } @@ -2010,15 +2774,24 @@ macro_rules! define_clock_tree_types { } /// Represents the device's clock tree. pub struct ClockTree { + mpll_clk: Option, cpu_root_clk: Option, cpu_clk: Option, - ahb_clk: Option, + mem_clk: Option, + sys_clk: Option, apb_clk: Option, lp_fast_clk: Option, lp_slow_clk: Option, + ble_lp_clk: Option, + crypto_clk: Option, iomux_function_clock: Option, timg_calibration_clock: Option, i2c_function_clock: [Option; 2], + i2s_tx_clk: [Option; 2], + i2s_rx_clk: [Option; 2], + i2s_mclk_out: [Option; 2], + lcd_cam_lcd_clock: [Option; 1], + lcd_cam_cam_clock: [Option; 1], rmt_sclk: [Option; 1], spi_function_clock: [Option; 2], timg_function_clock: [Option; 2], @@ -2030,20 +2803,32 @@ macro_rules! define_clock_tree_types { cpll_clk_refcount: u32, mpll_clk_refcount: u32, rc_fast_clk_refcount: u32, + #[cfg(use_xtal32k)] xtal32k_clk_refcount: u32, rc_slow_clk_refcount: u32, pll_f20m_refcount: u32, pll_f80m_refcount: u32, pll_f120m_refcount: u32, pll_f160m_refcount: u32, + pll_f240m_refcount: u32, + bbpll_d3_clock_refcount: u32, pll_f25m_refcount: u32, pll_f50m_refcount: u32, xtal_d2_clk_refcount: u32, + cpu_clk_refcount: u32, + mem_clk_refcount: u32, lp_fast_clk_refcount: u32, lp_slow_clk_refcount: u32, + ble_lp_clk_refcount: u32, + crypto_clk_refcount: u32, timg_calibration_clock_refcount: u32, sdm_function_clock_refcount: [u32; 1], i2c_function_clock_refcount: [u32; 2], + i2s_tx_clk_refcount: [u32; 2], + i2s_rx_clk_refcount: [u32; 2], + i2s_mclk_out_refcount: [u32; 2], + lcd_cam_lcd_clock_refcount: [u32; 1], + lcd_cam_cam_clock_refcount: [u32; 1], rmt_sclk_refcount: [u32; 1], spi_function_clock_refcount: [u32; 2], timg_function_clock_refcount: [u32; 2], @@ -2058,6 +2843,10 @@ macro_rules! define_clock_tree_types { pub fn with(f: impl FnOnce(&mut ClockTree) -> R) -> R { CLOCK_TREE.with(f) } + /// Returns the current configuration of the MPLL_CLK clock tree node + pub fn mpll_clk(&self) -> Option { + self.mpll_clk + } /// Returns the current configuration of the CPU_ROOT_CLK clock tree node pub fn cpu_root_clk(&self) -> Option { self.cpu_root_clk @@ -2066,9 +2855,13 @@ macro_rules! define_clock_tree_types { pub fn cpu_clk(&self) -> Option { self.cpu_clk } - /// Returns the current configuration of the AHB_CLK clock tree node - pub fn ahb_clk(&self) -> Option { - self.ahb_clk + /// Returns the current configuration of the MEM_CLK clock tree node + pub fn mem_clk(&self) -> Option { + self.mem_clk + } + /// Returns the current configuration of the SYS_CLK clock tree node + pub fn sys_clk(&self) -> Option { + self.sys_clk } /// Returns the current configuration of the APB_CLK clock tree node pub fn apb_clk(&self) -> Option { @@ -2082,6 +2875,14 @@ macro_rules! define_clock_tree_types { pub fn lp_slow_clk(&self) -> Option { self.lp_slow_clk } + /// Returns the current configuration of the BLE_LP_CLK clock tree node + pub fn ble_lp_clk(&self) -> Option { + self.ble_lp_clk + } + /// Returns the current configuration of the CRYPTO_CLK clock tree node + pub fn crypto_clk(&self) -> Option { + self.crypto_clk + } /// Returns the current configuration of the IOMUX_FUNCTION_CLOCK clock tree node pub fn iomux_function_clock(&self) -> Option { self.iomux_function_clock @@ -2098,6 +2899,38 @@ macro_rules! define_clock_tree_types { pub fn i2c1_function_clock(&self) -> Option { self.i2c_function_clock[I2cInstance::I2c1 as usize] } + /// Returns the current configuration of the I2S0_TX_CLK clock tree node + pub fn i2s0_tx_clk(&self) -> Option { + self.i2s_tx_clk[I2sInstance::I2s0 as usize] + } + /// Returns the current configuration of the I2S0_RX_CLK clock tree node + pub fn i2s0_rx_clk(&self) -> Option { + self.i2s_rx_clk[I2sInstance::I2s0 as usize] + } + /// Returns the current configuration of the I2S0_MCLK_OUT clock tree node + pub fn i2s0_mclk_out(&self) -> Option { + self.i2s_mclk_out[I2sInstance::I2s0 as usize] + } + /// Returns the current configuration of the I2S1_TX_CLK clock tree node + pub fn i2s1_tx_clk(&self) -> Option { + self.i2s_tx_clk[I2sInstance::I2s1 as usize] + } + /// Returns the current configuration of the I2S1_RX_CLK clock tree node + pub fn i2s1_rx_clk(&self) -> Option { + self.i2s_rx_clk[I2sInstance::I2s1 as usize] + } + /// Returns the current configuration of the I2S1_MCLK_OUT clock tree node + pub fn i2s1_mclk_out(&self) -> Option { + self.i2s_mclk_out[I2sInstance::I2s1 as usize] + } + /// Returns the current configuration of the LCD_CAM_LCD_CLOCK clock tree node + pub fn lcd_cam_lcd_clock(&self) -> Option { + self.lcd_cam_lcd_clock[LcdCamInstance::LcdCam as usize] + } + /// Returns the current configuration of the LCD_CAM_CAM_CLOCK clock tree node + pub fn lcd_cam_cam_clock(&self) -> Option { + self.lcd_cam_cam_clock[LcdCamInstance::LcdCam as usize] + } /// Returns the current configuration of the RMT_SCLK clock tree node pub fn rmt_sclk(&self) -> Option { self.rmt_sclk[RmtInstance::Rmt as usize] @@ -2165,15 +2998,24 @@ macro_rules! define_clock_tree_types { } static CLOCK_TREE: ::esp_sync::NonReentrantMutex = ::esp_sync::NonReentrantMutex::new(ClockTree { + mpll_clk: None, cpu_root_clk: None, cpu_clk: None, - ahb_clk: None, + mem_clk: None, + sys_clk: None, apb_clk: None, lp_fast_clk: None, lp_slow_clk: None, + ble_lp_clk: None, + crypto_clk: None, iomux_function_clock: None, timg_calibration_clock: None, i2c_function_clock: [None; 2], + i2s_tx_clk: [None; 2], + i2s_rx_clk: [None; 2], + i2s_mclk_out: [None; 2], + lcd_cam_lcd_clock: [None; 1], + lcd_cam_cam_clock: [None; 1], rmt_sclk: [None; 1], spi_function_clock: [None; 2], timg_function_clock: [None; 2], @@ -2185,20 +3027,32 @@ macro_rules! define_clock_tree_types { cpll_clk_refcount: 0, mpll_clk_refcount: 0, rc_fast_clk_refcount: 0, + #[cfg(use_xtal32k)] xtal32k_clk_refcount: 0, rc_slow_clk_refcount: 0, pll_f20m_refcount: 0, pll_f80m_refcount: 0, pll_f120m_refcount: 0, pll_f160m_refcount: 0, + pll_f240m_refcount: 0, + bbpll_d3_clock_refcount: 0, pll_f25m_refcount: 0, pll_f50m_refcount: 0, xtal_d2_clk_refcount: 0, + cpu_clk_refcount: 0, + mem_clk_refcount: 0, lp_fast_clk_refcount: 0, lp_slow_clk_refcount: 0, + ble_lp_clk_refcount: 0, + crypto_clk_refcount: 0, timg_calibration_clock_refcount: 0, sdm_function_clock_refcount: [0; 1], i2c_function_clock_refcount: [0; 2], + i2s_tx_clk_refcount: [0; 2], + i2s_rx_clk_refcount: [0; 2], + i2s_mclk_out_refcount: [0; 2], + lcd_cam_lcd_clock_refcount: [0; 1], + lcd_cam_cam_clock_refcount: [0; 1], rmt_sclk_refcount: [0; 1], spi_function_clock_refcount: [0; 2], timg_function_clock_refcount: [0; 2], @@ -2208,11 +3062,15 @@ macro_rules! define_clock_tree_types { uart_mem_clock_refcount: [0; 4], psram_function_clock_refcount: [0; 1], }); + static MPLL_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(0); static CPU_ROOT_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); static CPU_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); - static AHB_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = + static MEM_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(0); + static SYS_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); static APB_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); @@ -2220,12 +3078,26 @@ macro_rules! define_clock_tree_types { ::core::sync::atomic::AtomicU32::new(0); static LP_SLOW_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); + static BLE_LP_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(0); + static CRYPTO_CLK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(0); static IOMUX_FUNCTION_CLOCK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); static TIMG_CALIBRATION_CLOCK_FREQ_CACHE: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); static I2C_FUNCTION_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 2] = [const { ::core::sync::atomic::AtomicU32::new(0) }; 2]; + static I2S_TX_CLK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 2] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 2]; + static I2S_RX_CLK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 2] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 2]; + static I2S_MCLK_OUT_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 2] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 2]; + static LCD_CAM_LCD_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; + static LCD_CAM_CAM_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = + [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; static RMT_SCLK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; static SPI_FUNCTION_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 2] = @@ -2240,6 +3112,171 @@ macro_rules! define_clock_tree_types { [const { ::core::sync::atomic::AtomicU32::new(0) }; 4]; static PSRAM_FUNCTION_CLOCK_FREQ_CACHE: [::core::sync::atomic::AtomicU32; 1] = [const { ::core::sync::atomic::AtomicU32::new(0) }; 1]; + /// The clock sources of the device. + /// + /// A clock source is a node of the clock tree that other nodes derive their output + /// from. Ask a node which source it runs on with its `..._root_source` function. + #[derive(Debug, enumset::EnumSetType)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum ClockSource { + /// `XTAL_CLK`. + XtalClk, + /// `RC_FAST_CLK`. + RcFastClk, + #[cfg(use_xtal32k)] + /// `XTAL32K_CLK`. + Xtal32kClk, + /// `RC_SLOW_CLK`. + RcSlowClk, + } + /// Returns the clock source that `XTAL_CLK` currently runs on. + pub fn xtal_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::XtalClk) + } + /// Returns the clock source that `BBPLL_CLK` currently runs on. + pub fn bbpll_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `CPLL_CLK` currently runs on. + pub fn cpll_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `MPLL_CLK` currently runs on. + pub fn mpll_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `RC_FAST_CLK` currently runs on. + pub fn rc_fast_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::RcFastClk) + } + #[cfg(use_xtal32k)] + /// Returns the clock source that `XTAL32K_CLK` currently runs on. + pub fn xtal32k_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::Xtal32kClk) + } + /// Returns the clock source that `RC_SLOW_CLK` currently runs on. + pub fn rc_slow_clk_root_source(_clocks: &mut ClockTree) -> Option { + Some(ClockSource::RcSlowClk) + } + /// Returns the clock source that `PLL_F20M` currently runs on. + pub fn pll_f20m_root_source(clocks: &mut ClockTree) -> Option { + bbpll_clk_root_source(clocks) + } + /// Returns the clock source that `PLL_F80M` currently runs on. + pub fn pll_f80m_root_source(clocks: &mut ClockTree) -> Option { + bbpll_clk_root_source(clocks) + } + /// Returns the clock source that `PLL_F120M` currently runs on. + pub fn pll_f120m_root_source(clocks: &mut ClockTree) -> Option { + bbpll_clk_root_source(clocks) + } + /// Returns the clock source that `PLL_F160M` currently runs on. + pub fn pll_f160m_root_source(clocks: &mut ClockTree) -> Option { + bbpll_clk_root_source(clocks) + } + /// Returns the clock source that `PLL_F240M` currently runs on. + pub fn pll_f240m_root_source(clocks: &mut ClockTree) -> Option { + bbpll_clk_root_source(clocks) + } + /// Returns the clock source that `BBPLL_D3_CLOCK` currently runs on. + pub fn bbpll_d3_clock_root_source(clocks: &mut ClockTree) -> Option { + bbpll_clk_root_source(clocks) + } + /// Returns the clock source that `PLL_F25M` currently runs on. + pub fn pll_f25m_root_source(clocks: &mut ClockTree) -> Option { + mpll_clk_root_source(clocks) + } + /// Returns the clock source that `PLL_F50M` currently runs on. + pub fn pll_f50m_root_source(clocks: &mut ClockTree) -> Option { + mpll_clk_root_source(clocks) + } + /// Returns the clock source that `XTAL_D2_CLK` currently runs on. + pub fn xtal_d2_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `CPU_ROOT_CLK` currently runs on. + pub fn cpu_root_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.cpu_root_clk?; + match config { + CpuRootClkConfig::Xtal => xtal_clk_root_source(clocks), + CpuRootClkConfig::Cpll => cpll_clk_root_source(clocks), + CpuRootClkConfig::RcFast => rc_fast_clk_root_source(clocks), + CpuRootClkConfig::PllF240m => pll_f240m_root_source(clocks), + } + } + /// Returns the clock source that `CPU_CLK` currently runs on. + pub fn cpu_clk_root_source(clocks: &mut ClockTree) -> Option { + cpu_root_clk_root_source(clocks) + } + /// Returns the clock source that `MEM_CLK` currently runs on. + pub fn mem_clk_root_source(clocks: &mut ClockTree) -> Option { + cpu_clk_root_source(clocks) + } + /// Returns the clock source that `SYS_CLK` currently runs on. + pub fn sys_clk_root_source(clocks: &mut ClockTree) -> Option { + cpu_clk_root_source(clocks) + } + /// Returns the clock source that `APB_CLK` currently runs on. + pub fn apb_clk_root_source(clocks: &mut ClockTree) -> Option { + sys_clk_root_source(clocks) + } + /// Returns the clock source that `LP_FAST_CLK` currently runs on. + pub fn lp_fast_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.lp_fast_clk?; + match config { + LpFastClkConfig::RcFast => rc_fast_clk_root_source(clocks), + LpFastClkConfig::Xtal => xtal_clk_root_source(clocks), + } + } + /// Returns the clock source that `LP_SLOW_CLK` currently runs on. + pub fn lp_slow_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.lp_slow_clk?; + match config { + LpSlowClkConfig::RcSlow => rc_slow_clk_root_source(clocks), + #[cfg(use_xtal32k)] + LpSlowClkConfig::Xtal32k => xtal32k_clk_root_source(clocks), + } + } + /// Returns the clock source that `BLE_LP_XTAL_CLK` currently runs on. + pub fn ble_lp_xtal_clk_root_source(clocks: &mut ClockTree) -> Option { + xtal_clk_root_source(clocks) + } + /// Returns the clock source that `BLE_LP_CLK` currently runs on. + pub fn ble_lp_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.ble_lp_clk?; + match config { + BleLpClkConfig::Xtal => ble_lp_xtal_clk_root_source(clocks), + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => xtal32k_clk_root_source(clocks), + } + } + /// Returns the clock source that `CRYPTO_CLK` currently runs on. + pub fn crypto_clk_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.crypto_clk?; + match config { + CryptoClkConfig::Xtal => xtal_clk_root_source(clocks), + CryptoClkConfig::RcFast => rc_fast_clk_root_source(clocks), + CryptoClkConfig::PllF240m => pll_f240m_root_source(clocks), + } + } + /// Returns the clock source that `IOMUX_FUNCTION_CLOCK` currently runs on. + pub fn iomux_function_clock_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.iomux_function_clock?; + match config.source() { + IomuxFunctionClockSource::XtalClk => xtal_clk_root_source(clocks), + IomuxFunctionClockSource::PllF80m => pll_f80m_root_source(clocks), + } + } + /// Returns the clock source that `TIMG_CALIBRATION_CLOCK` currently runs on. + pub fn timg_calibration_clock_root_source(clocks: &mut ClockTree) -> Option { + let config = clocks.timg_calibration_clock?; + match config { + TimgCalibrationClockConfig::RcSlowClk => rc_slow_clk_root_source(clocks), + TimgCalibrationClockConfig::RcFastDivClk => rc_fast_clk_root_source(clocks), + #[cfg(use_xtal32k)] + TimgCalibrationClockConfig::Xtal32kClk => xtal32k_clk_root_source(clocks), + } + } fn request_xtal_clk(_clocks: &mut ClockTree) {} fn release_xtal_clk(_clocks: &mut ClockTree) {} pub fn xtal_clk_frequency() -> u32 { @@ -2289,6 +3326,14 @@ macro_rules! define_clock_tree_types { pub fn cpll_clk_source_frequency() -> u32 { xtal_clk_frequency() } + pub fn configure_mpll_clk(clocks: &mut ClockTree, config: MpllClkConfig) { + let old_config = clocks.mpll_clk.replace(config); + refresh_mpll_clk_downstream(clocks); + configure_mpll_clk_impl(clocks, old_config, config); + } + pub fn mpll_clk_config(clocks: &mut ClockTree) -> Option { + clocks.mpll_clk + } pub fn request_mpll_clk(clocks: &mut ClockTree) { trace!("Requesting MPLL_CLK"); if increment_reference_count(&mut clocks.mpll_clk_refcount) { @@ -2305,8 +3350,11 @@ macro_rules! define_clock_tree_types { release_xtal_clk(clocks); } } + pub fn mpll_clk_config_frequency(config: MpllClkConfig) -> u32 { + config.value() + } pub fn mpll_clk_frequency() -> u32 { - (500 * 1000000) + MPLL_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn mpll_clk_source_frequency() -> u32 { xtal_clk_frequency() @@ -2325,9 +3373,31 @@ macro_rules! define_clock_tree_types { enable_rc_fast_clk_impl(clocks, false); } } - pub fn rc_fast_clk_frequency() -> u32 { + static RC_FAST_CLK_FREQUENCY: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(rc_fast_clk_nominal_frequency()); + pub const fn rc_fast_clk_nominal_frequency() -> u32 { 17500000 } + pub fn rc_fast_clk_frequency() -> u32 { + RC_FAST_CLK_FREQUENCY.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn set_rc_fast_clk_frequency(clocks: &mut ClockTree, frequency: u32) { + if !(8750000..=26250000).contains(&frequency) { + warn!( + "Ignoring out-of-range RC_FAST_CLK frequency: {} Hz", + frequency + ); + return; + } + debug!( + "Updating RC_FAST_CLK frequency to {} Hz (nominal {} Hz)", + frequency, + rc_fast_clk_nominal_frequency() + ); + RC_FAST_CLK_FREQUENCY.store(frequency, ::core::sync::atomic::Ordering::Release); + refresh_rc_fast_clk_downstream(clocks); + } + #[cfg(use_xtal32k)] pub fn request_xtal32k_clk(clocks: &mut ClockTree) { trace!("Requesting XTAL32K_CLK"); if increment_reference_count(&mut clocks.xtal32k_clk_refcount) { @@ -2335,6 +3405,7 @@ macro_rules! define_clock_tree_types { enable_xtal32k_clk_impl(clocks, true); } } + #[cfg(use_xtal32k)] pub fn release_xtal32k_clk(clocks: &mut ClockTree) { trace!("Releasing XTAL32K_CLK"); if decrement_reference_count(&mut clocks.xtal32k_clk_refcount) { @@ -2342,6 +3413,7 @@ macro_rules! define_clock_tree_types { enable_xtal32k_clk_impl(clocks, false); } } + #[cfg(use_xtal32k)] pub fn xtal32k_clk_frequency() -> u32 { 32768 } @@ -2359,9 +3431,30 @@ macro_rules! define_clock_tree_types { enable_rc_slow_clk_impl(clocks, false); } } - pub fn rc_slow_clk_frequency() -> u32 { + static RC_SLOW_CLK_FREQUENCY: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(rc_slow_clk_nominal_frequency()); + pub const fn rc_slow_clk_nominal_frequency() -> u32 { 136000 } + pub fn rc_slow_clk_frequency() -> u32 { + RC_SLOW_CLK_FREQUENCY.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn set_rc_slow_clk_frequency(clocks: &mut ClockTree, frequency: u32) { + if !(68000..=204000).contains(&frequency) { + warn!( + "Ignoring out-of-range RC_SLOW_CLK frequency: {} Hz", + frequency + ); + return; + } + debug!( + "Updating RC_SLOW_CLK frequency to {} Hz (nominal {} Hz)", + frequency, + rc_slow_clk_nominal_frequency() + ); + RC_SLOW_CLK_FREQUENCY.store(frequency, ::core::sync::atomic::Ordering::Release); + refresh_rc_slow_clk_downstream(clocks); + } pub fn request_pll_f20m(clocks: &mut ClockTree) { trace!("Requesting PLL_F20M"); if increment_reference_count(&mut clocks.pll_f20m_refcount) { @@ -2452,15 +3545,19 @@ macro_rules! define_clock_tree_types { } pub fn request_pll_f240m(clocks: &mut ClockTree) { trace!("Requesting PLL_F240M"); - trace!("Enabling PLL_F240M"); - request_bbpll_clk(clocks); - enable_pll_f240m_impl(clocks, true); + if increment_reference_count(&mut clocks.pll_f240m_refcount) { + trace!("Enabling PLL_F240M"); + request_bbpll_clk(clocks); + enable_pll_f240m_impl(clocks, true); + } } pub fn release_pll_f240m(clocks: &mut ClockTree) { trace!("Releasing PLL_F240M"); - trace!("Disabling PLL_F240M"); - enable_pll_f240m_impl(clocks, false); - release_bbpll_clk(clocks); + if decrement_reference_count(&mut clocks.pll_f240m_refcount) { + trace!("Disabling PLL_F240M"); + enable_pll_f240m_impl(clocks, false); + release_bbpll_clk(clocks); + } } pub fn pll_f240m_frequency() -> u32 { (bbpll_clk_frequency() / 2) @@ -2468,6 +3565,28 @@ macro_rules! define_clock_tree_types { pub fn pll_f240m_source_frequency() -> u32 { bbpll_clk_frequency() } + pub fn request_bbpll_d3_clock(clocks: &mut ClockTree) { + trace!("Requesting BBPLL_D3_CLOCK"); + if increment_reference_count(&mut clocks.bbpll_d3_clock_refcount) { + trace!("Enabling BBPLL_D3_CLOCK"); + request_bbpll_clk(clocks); + enable_bbpll_d3_clock_impl(clocks, true); + } + } + pub fn release_bbpll_d3_clock(clocks: &mut ClockTree) { + trace!("Releasing BBPLL_D3_CLOCK"); + if decrement_reference_count(&mut clocks.bbpll_d3_clock_refcount) { + trace!("Disabling BBPLL_D3_CLOCK"); + enable_bbpll_d3_clock_impl(clocks, false); + release_bbpll_clk(clocks); + } + } + pub fn bbpll_d3_clock_frequency() -> u32 { + (bbpll_clk_frequency() / 3) + } + pub fn bbpll_d3_clock_source_frequency() -> u32 { + bbpll_clk_frequency() + } pub fn request_pll_f25m(clocks: &mut ClockTree) { trace!("Requesting PLL_F25M"); if increment_reference_count(&mut clocks.pll_f25m_refcount) { @@ -2485,7 +3604,7 @@ macro_rules! define_clock_tree_types { } } pub fn pll_f25m_frequency() -> u32 { - (mpll_clk_frequency() / 20) + 25000000 } pub fn pll_f25m_source_frequency() -> u32 { mpll_clk_frequency() @@ -2507,7 +3626,7 @@ macro_rules! define_clock_tree_types { } } pub fn pll_f50m_frequency() -> u32 { - (mpll_clk_frequency() / 10) + 50000000 } pub fn pll_f50m_source_frequency() -> u32 { mpll_clk_frequency() @@ -2557,7 +3676,6 @@ macro_rules! define_clock_tree_types { clocks.cpu_root_clk } pub fn request_cpu_root_clk(clocks: &mut ClockTree) { - trace!("Requesting CPU_ROOT_CLK"); trace!("Enabling CPU_ROOT_CLK"); match unwrap!(clocks.cpu_root_clk) { CpuRootClkConfig::Xtal => request_xtal_clk(clocks), @@ -2568,7 +3686,6 @@ macro_rules! define_clock_tree_types { enable_cpu_root_clk_impl(clocks, true); } pub fn release_cpu_root_clk(clocks: &mut ClockTree) { - trace!("Releasing CPU_ROOT_CLK"); trace!("Disabling CPU_ROOT_CLK"); enable_cpu_root_clk_impl(clocks, false); match unwrap!(clocks.cpu_root_clk) { @@ -2578,11 +3695,7 @@ macro_rules! define_clock_tree_types { CpuRootClkConfig::PllF240m => release_pll_f240m(clocks), } } - #[allow(unused_variables)] - pub fn cpu_root_clk_config_frequency( - clocks: &mut ClockTree, - config: CpuRootClkConfig, - ) -> u32 { + pub fn cpu_root_clk_config_frequency(config: CpuRootClkConfig) -> u32 { match config { CpuRootClkConfig::Xtal => xtal_clk_frequency(), CpuRootClkConfig::Cpll => cpll_clk_frequency(), @@ -2594,12 +3707,7 @@ macro_rules! define_clock_tree_types { CPU_ROOT_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn cpu_root_clk_source_frequency(source: CpuRootClkConfig) -> u32 { - match source { - CpuRootClkConfig::Xtal => xtal_clk_frequency(), - CpuRootClkConfig::Cpll => cpll_clk_frequency(), - CpuRootClkConfig::RcFast => rc_fast_clk_frequency(), - CpuRootClkConfig::PllF240m => pll_f240m_frequency(), - } + cpu_root_clk_config_frequency(source) } pub fn configure_cpu_clk(clocks: &mut ClockTree, config: CpuClkConfig) { let old_config = clocks.cpu_clk.replace(config); @@ -2611,18 +3719,21 @@ macro_rules! define_clock_tree_types { } pub fn request_cpu_clk(clocks: &mut ClockTree) { trace!("Requesting CPU_CLK"); - trace!("Enabling CPU_CLK"); - request_cpu_root_clk(clocks); - enable_cpu_clk_impl(clocks, true); + if increment_reference_count(&mut clocks.cpu_clk_refcount) { + trace!("Enabling CPU_CLK"); + request_cpu_root_clk(clocks); + enable_cpu_clk_impl(clocks, true); + } } pub fn release_cpu_clk(clocks: &mut ClockTree) { trace!("Releasing CPU_CLK"); - trace!("Disabling CPU_CLK"); - enable_cpu_clk_impl(clocks, false); - release_cpu_root_clk(clocks); + if decrement_reference_count(&mut clocks.cpu_clk_refcount) { + trace!("Disabling CPU_CLK"); + enable_cpu_clk_impl(clocks, false); + release_cpu_root_clk(clocks); + } } - #[allow(unused_variables)] - pub fn cpu_clk_config_frequency(clocks: &mut ClockTree, config: CpuClkConfig) -> u32 { + pub fn cpu_clk_config_frequency(config: CpuClkConfig) -> u32 { (cpu_root_clk_frequency() / (config.divisor() + 1)) } pub fn cpu_clk_frequency() -> u32 { @@ -2631,34 +3742,64 @@ macro_rules! define_clock_tree_types { pub fn cpu_clk_source_frequency() -> u32 { cpu_root_clk_frequency() } - pub fn configure_ahb_clk(clocks: &mut ClockTree, config: AhbClkConfig) { - let old_config = clocks.ahb_clk.replace(config); - refresh_ahb_clk_downstream(clocks); - configure_ahb_clk_impl(clocks, old_config, config); + pub fn configure_mem_clk(clocks: &mut ClockTree, config: MemClkConfig) { + let old_config = clocks.mem_clk.replace(config); + refresh_mem_clk_downstream(clocks); + configure_mem_clk_impl(clocks, old_config, config); + } + pub fn mem_clk_config(clocks: &mut ClockTree) -> Option { + clocks.mem_clk + } + pub fn request_mem_clk(clocks: &mut ClockTree) { + trace!("Requesting MEM_CLK"); + if increment_reference_count(&mut clocks.mem_clk_refcount) { + trace!("Enabling MEM_CLK"); + request_cpu_clk(clocks); + enable_mem_clk_impl(clocks, true); + } + } + pub fn release_mem_clk(clocks: &mut ClockTree) { + trace!("Releasing MEM_CLK"); + if decrement_reference_count(&mut clocks.mem_clk_refcount) { + trace!("Disabling MEM_CLK"); + enable_mem_clk_impl(clocks, false); + release_cpu_clk(clocks); + } + } + pub fn mem_clk_config_frequency(config: MemClkConfig) -> u32 { + (cpu_clk_frequency() / (config.divisor() + 1)) + } + pub fn mem_clk_frequency() -> u32 { + MEM_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn mem_clk_source_frequency() -> u32 { + cpu_clk_frequency() + } + pub fn configure_sys_clk(clocks: &mut ClockTree, config: SysClkConfig) { + let old_config = clocks.sys_clk.replace(config); + refresh_sys_clk_downstream(clocks); + configure_sys_clk_impl(clocks, old_config, config); } - pub fn ahb_clk_config(clocks: &mut ClockTree) -> Option { - clocks.ahb_clk + pub fn sys_clk_config(clocks: &mut ClockTree) -> Option { + clocks.sys_clk } - pub fn request_ahb_clk(clocks: &mut ClockTree) { - trace!("Requesting AHB_CLK"); - trace!("Enabling AHB_CLK"); + pub fn request_sys_clk(clocks: &mut ClockTree) { + trace!("Enabling SYS_CLK"); request_cpu_clk(clocks); - enable_ahb_clk_impl(clocks, true); + enable_sys_clk_impl(clocks, true); } - pub fn release_ahb_clk(clocks: &mut ClockTree) { - trace!("Releasing AHB_CLK"); - trace!("Disabling AHB_CLK"); - enable_ahb_clk_impl(clocks, false); + pub fn release_sys_clk(clocks: &mut ClockTree) { + trace!("Disabling SYS_CLK"); + enable_sys_clk_impl(clocks, false); release_cpu_clk(clocks); } - #[allow(unused_variables)] - pub fn ahb_clk_config_frequency(clocks: &mut ClockTree, config: AhbClkConfig) -> u32 { + pub fn sys_clk_config_frequency(config: SysClkConfig) -> u32 { (cpu_clk_frequency() / (config.divisor() + 1)) } - pub fn ahb_clk_frequency() -> u32 { - AHB_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) + pub fn sys_clk_frequency() -> u32 { + SYS_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } - pub fn ahb_clk_source_frequency() -> u32 { + pub fn sys_clk_source_frequency() -> u32 { cpu_clk_frequency() } pub fn configure_apb_clk(clocks: &mut ClockTree, config: ApbClkConfig) { @@ -2671,33 +3812,31 @@ macro_rules! define_clock_tree_types { } fn request_apb_clk(_clocks: &mut ClockTree) {} fn release_apb_clk(_clocks: &mut ClockTree) {} - #[allow(unused_variables)] - pub fn apb_clk_config_frequency(clocks: &mut ClockTree, config: ApbClkConfig) -> u32 { - (ahb_clk_frequency() / (config.divisor() + 1)) + pub fn apb_clk_config_frequency(config: ApbClkConfig) -> u32 { + (sys_clk_frequency() / (config.divisor() + 1)) } pub fn apb_clk_frequency() -> u32 { APB_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn apb_clk_source_frequency() -> u32 { - ahb_clk_frequency() + sys_clk_frequency() } pub fn configure_lp_fast_clk(clocks: &mut ClockTree, new_selector: LpFastClkConfig) { let old_selector = clocks.lp_fast_clk.replace(new_selector); refresh_lp_fast_clk_downstream(clocks); - if clocks.lp_fast_clk_refcount > 0 { + let active = clocks.lp_fast_clk_refcount > 0; + if active { match new_selector { LpFastClkConfig::RcFast => request_rc_fast_clk(clocks), LpFastClkConfig::Xtal => request_xtal_clk(clocks), } - configure_lp_fast_clk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - LpFastClkConfig::RcFast => release_rc_fast_clk(clocks), - LpFastClkConfig::Xtal => release_xtal_clk(clocks), - } + } + configure_lp_fast_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + LpFastClkConfig::RcFast => release_rc_fast_clk(clocks), + LpFastClkConfig::Xtal => release_xtal_clk(clocks), } - } else { - configure_lp_fast_clk_impl(clocks, old_selector, new_selector); } } pub fn lp_fast_clk_config(clocks: &mut ClockTree) -> Option { @@ -2725,11 +3864,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn lp_fast_clk_config_frequency( - clocks: &mut ClockTree, - config: LpFastClkConfig, - ) -> u32 { + pub fn lp_fast_clk_config_frequency(config: LpFastClkConfig) -> u32 { match config { LpFastClkConfig::RcFast => rc_fast_clk_frequency(), LpFastClkConfig::Xtal => xtal_clk_frequency(), @@ -2739,28 +3874,26 @@ macro_rules! define_clock_tree_types { LP_FAST_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn lp_fast_clk_source_frequency(source: LpFastClkConfig) -> u32 { - match source { - LpFastClkConfig::RcFast => rc_fast_clk_frequency(), - LpFastClkConfig::Xtal => xtal_clk_frequency(), - } + lp_fast_clk_config_frequency(source) } pub fn configure_lp_slow_clk(clocks: &mut ClockTree, new_selector: LpSlowClkConfig) { let old_selector = clocks.lp_slow_clk.replace(new_selector); refresh_lp_slow_clk_downstream(clocks); - if clocks.lp_slow_clk_refcount > 0 { + let active = clocks.lp_slow_clk_refcount > 0; + if active { match new_selector { LpSlowClkConfig::RcSlow => request_rc_slow_clk(clocks), + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => request_xtal32k_clk(clocks), } - configure_lp_slow_clk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - LpSlowClkConfig::RcSlow => release_rc_slow_clk(clocks), - LpSlowClkConfig::Xtal32k => release_xtal32k_clk(clocks), - } + } + configure_lp_slow_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + LpSlowClkConfig::RcSlow => release_rc_slow_clk(clocks), + #[cfg(use_xtal32k)] + LpSlowClkConfig::Xtal32k => release_xtal32k_clk(clocks), } - } else { - configure_lp_slow_clk_impl(clocks, old_selector, new_selector); } } pub fn lp_slow_clk_config(clocks: &mut ClockTree) -> Option { @@ -2772,6 +3905,7 @@ macro_rules! define_clock_tree_types { trace!("Enabling LP_SLOW_CLK"); match unwrap!(clocks.lp_slow_clk) { LpSlowClkConfig::RcSlow => request_rc_slow_clk(clocks), + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => request_xtal32k_clk(clocks), } enable_lp_slow_clk_impl(clocks, true); @@ -2784,17 +3918,15 @@ macro_rules! define_clock_tree_types { enable_lp_slow_clk_impl(clocks, false); match unwrap!(clocks.lp_slow_clk) { LpSlowClkConfig::RcSlow => release_rc_slow_clk(clocks), + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => release_xtal32k_clk(clocks), } } } - #[allow(unused_variables)] - pub fn lp_slow_clk_config_frequency( - clocks: &mut ClockTree, - config: LpSlowClkConfig, - ) -> u32 { + pub fn lp_slow_clk_config_frequency(config: LpSlowClkConfig) -> u32 { match config { LpSlowClkConfig::RcSlow => rc_slow_clk_frequency(), + #[cfg(use_xtal32k)] LpSlowClkConfig::Xtal32k => xtal32k_clk_frequency(), } } @@ -2802,11 +3934,144 @@ macro_rules! define_clock_tree_types { LP_SLOW_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn lp_slow_clk_source_frequency(source: LpSlowClkConfig) -> u32 { - match source { - LpSlowClkConfig::RcSlow => rc_slow_clk_frequency(), - LpSlowClkConfig::Xtal32k => xtal32k_clk_frequency(), + lp_slow_clk_config_frequency(source) + } + pub fn request_ble_lp_xtal_clk(clocks: &mut ClockTree) { + trace!("Enabling BLE_LP_XTAL_CLK"); + request_xtal_clk(clocks); + enable_ble_lp_xtal_clk_impl(clocks, true); + } + pub fn release_ble_lp_xtal_clk(clocks: &mut ClockTree) { + trace!("Disabling BLE_LP_XTAL_CLK"); + enable_ble_lp_xtal_clk_impl(clocks, false); + release_xtal_clk(clocks); + } + pub fn ble_lp_xtal_clk_frequency() -> u32 { + 100000 + } + pub fn ble_lp_xtal_clk_source_frequency() -> u32 { + xtal_clk_frequency() + } + pub fn configure_ble_lp_clk(clocks: &mut ClockTree, new_selector: BleLpClkConfig) { + let old_selector = clocks.ble_lp_clk.replace(new_selector); + refresh_ble_lp_clk_downstream(clocks); + let active = clocks.ble_lp_clk_refcount > 0; + if active { + match new_selector { + BleLpClkConfig::Xtal => request_ble_lp_xtal_clk(clocks), + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => request_xtal32k_clk(clocks), + } + } + configure_ble_lp_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + BleLpClkConfig::Xtal => release_ble_lp_xtal_clk(clocks), + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => release_xtal32k_clk(clocks), + } + } + } + pub fn ble_lp_clk_config(clocks: &mut ClockTree) -> Option { + clocks.ble_lp_clk + } + pub fn request_ble_lp_clk(clocks: &mut ClockTree) { + trace!("Requesting BLE_LP_CLK"); + if increment_reference_count(&mut clocks.ble_lp_clk_refcount) { + trace!("Enabling BLE_LP_CLK"); + match unwrap!(clocks.ble_lp_clk) { + BleLpClkConfig::Xtal => request_ble_lp_xtal_clk(clocks), + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => request_xtal32k_clk(clocks), + } + enable_ble_lp_clk_impl(clocks, true); + } + } + pub fn release_ble_lp_clk(clocks: &mut ClockTree) { + trace!("Releasing BLE_LP_CLK"); + if decrement_reference_count(&mut clocks.ble_lp_clk_refcount) { + trace!("Disabling BLE_LP_CLK"); + enable_ble_lp_clk_impl(clocks, false); + match unwrap!(clocks.ble_lp_clk) { + BleLpClkConfig::Xtal => release_ble_lp_xtal_clk(clocks), + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => release_xtal32k_clk(clocks), + } } } + pub fn ble_lp_clk_config_frequency(config: BleLpClkConfig) -> u32 { + match config { + BleLpClkConfig::Xtal => ble_lp_xtal_clk_frequency(), + #[cfg(use_xtal32k)] + BleLpClkConfig::Xtal32k => xtal32k_clk_frequency(), + } + } + pub fn ble_lp_clk_frequency() -> u32 { + BLE_LP_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn ble_lp_clk_source_frequency(source: BleLpClkConfig) -> u32 { + ble_lp_clk_config_frequency(source) + } + pub fn configure_crypto_clk(clocks: &mut ClockTree, new_selector: CryptoClkConfig) { + let old_selector = clocks.crypto_clk.replace(new_selector); + refresh_crypto_clk_downstream(clocks); + let active = clocks.crypto_clk_refcount > 0; + if active { + match new_selector { + CryptoClkConfig::Xtal => request_xtal_clk(clocks), + CryptoClkConfig::RcFast => request_rc_fast_clk(clocks), + CryptoClkConfig::PllF240m => request_pll_f240m(clocks), + } + } + configure_crypto_clk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + CryptoClkConfig::Xtal => release_xtal_clk(clocks), + CryptoClkConfig::RcFast => release_rc_fast_clk(clocks), + CryptoClkConfig::PllF240m => release_pll_f240m(clocks), + } + } + } + pub fn crypto_clk_config(clocks: &mut ClockTree) -> Option { + clocks.crypto_clk + } + pub fn request_crypto_clk(clocks: &mut ClockTree) { + trace!("Requesting CRYPTO_CLK"); + if increment_reference_count(&mut clocks.crypto_clk_refcount) { + trace!("Enabling CRYPTO_CLK"); + match unwrap!(clocks.crypto_clk) { + CryptoClkConfig::Xtal => request_xtal_clk(clocks), + CryptoClkConfig::RcFast => request_rc_fast_clk(clocks), + CryptoClkConfig::PllF240m => request_pll_f240m(clocks), + } + enable_crypto_clk_impl(clocks, true); + } + } + pub fn release_crypto_clk(clocks: &mut ClockTree) { + trace!("Releasing CRYPTO_CLK"); + if decrement_reference_count(&mut clocks.crypto_clk_refcount) { + trace!("Disabling CRYPTO_CLK"); + enable_crypto_clk_impl(clocks, false); + match unwrap!(clocks.crypto_clk) { + CryptoClkConfig::Xtal => release_xtal_clk(clocks), + CryptoClkConfig::RcFast => release_rc_fast_clk(clocks), + CryptoClkConfig::PllF240m => release_pll_f240m(clocks), + } + } + } + pub fn crypto_clk_config_frequency(config: CryptoClkConfig) -> u32 { + match config { + CryptoClkConfig::Xtal => xtal_clk_frequency(), + CryptoClkConfig::RcFast => rc_fast_clk_frequency(), + CryptoClkConfig::PllF240m => pll_f240m_frequency(), + } + } + pub fn crypto_clk_frequency() -> u32 { + CRYPTO_CLK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) + } + pub fn crypto_clk_source_frequency(source: CryptoClkConfig) -> u32 { + crypto_clk_config_frequency(source) + } pub fn configure_iomux_function_clock( clocks: &mut ClockTree, config: IomuxFunctionClockConfig, @@ -2832,11 +4097,7 @@ macro_rules! define_clock_tree_types { } fn request_iomux_function_clock(_clocks: &mut ClockTree) {} fn release_iomux_function_clock(_clocks: &mut ClockTree) {} - #[allow(unused_variables)] - pub fn iomux_function_clock_config_frequency( - clocks: &mut ClockTree, - config: IomuxFunctionClockConfig, - ) -> u32 { + pub fn iomux_function_clock_config_frequency(config: IomuxFunctionClockConfig) -> u32 { (match config.source { IomuxFunctionClockSource::XtalClk => xtal_clk_frequency(), IomuxFunctionClockSource::PllF80m => pll_f80m_frequency(), @@ -2857,22 +4118,23 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.timg_calibration_clock.replace(new_selector); refresh_timg_calibration_clock_downstream(clocks); - if clocks.timg_calibration_clock_refcount > 0 { + let active = clocks.timg_calibration_clock_refcount > 0; + if active { match new_selector { TimgCalibrationClockConfig::RcSlowClk => request_rc_slow_clk(clocks), TimgCalibrationClockConfig::RcFastDivClk => request_rc_fast_clk(clocks), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => request_xtal32k_clk(clocks), } - configure_timg_calibration_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - TimgCalibrationClockConfig::RcSlowClk => release_rc_slow_clk(clocks), - TimgCalibrationClockConfig::RcFastDivClk => release_rc_fast_clk(clocks), - TimgCalibrationClockConfig::Xtal32kClk => release_xtal32k_clk(clocks), - } + } + configure_timg_calibration_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + TimgCalibrationClockConfig::RcSlowClk => release_rc_slow_clk(clocks), + TimgCalibrationClockConfig::RcFastDivClk => release_rc_fast_clk(clocks), + #[cfg(use_xtal32k)] + TimgCalibrationClockConfig::Xtal32kClk => release_xtal32k_clk(clocks), } - } else { - configure_timg_calibration_clock_impl(clocks, old_selector, new_selector); } } pub fn timg_calibration_clock_config( @@ -2888,6 +4150,7 @@ macro_rules! define_clock_tree_types { match unwrap!(clocks.timg_calibration_clock) { TimgCalibrationClockConfig::RcSlowClk => request_rc_slow_clk(clocks), TimgCalibrationClockConfig::RcFastDivClk => request_rc_fast_clk(clocks), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => request_xtal32k_clk(clocks), } enable_timg_calibration_clock_impl(clocks, true); @@ -2902,18 +4165,16 @@ macro_rules! define_clock_tree_types { match unwrap!(clocks.timg_calibration_clock) { TimgCalibrationClockConfig::RcSlowClk => release_rc_slow_clk(clocks), TimgCalibrationClockConfig::RcFastDivClk => release_rc_fast_clk(clocks), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => release_xtal32k_clk(clocks), } } } - #[allow(unused_variables)] - pub fn timg_calibration_clock_config_frequency( - clocks: &mut ClockTree, - config: TimgCalibrationClockConfig, - ) -> u32 { + pub fn timg_calibration_clock_config_frequency(config: TimgCalibrationClockConfig) -> u32 { match config { TimgCalibrationClockConfig::RcSlowClk => rc_slow_clk_frequency(), TimgCalibrationClockConfig::RcFastDivClk => rc_fast_clk_frequency(), + #[cfg(use_xtal32k)] TimgCalibrationClockConfig::Xtal32kClk => xtal32k_clk_frequency(), } } @@ -2921,11 +4182,7 @@ macro_rules! define_clock_tree_types { TIMG_CALIBRATION_CLOCK_FREQ_CACHE.load(::core::sync::atomic::Ordering::Acquire) } pub fn timg_calibration_clock_source_frequency(source: TimgCalibrationClockConfig) -> u32 { - match source { - TimgCalibrationClockConfig::RcSlowClk => rc_slow_clk_frequency(), - TimgCalibrationClockConfig::RcFastDivClk => rc_fast_clk_frequency(), - TimgCalibrationClockConfig::Xtal32kClk => xtal32k_clk_frequency(), - } + timg_calibration_clock_config_frequency(source) } impl SdmInstance { pub fn request_function_clock(self, clocks: &mut ClockTree) { @@ -2961,20 +4218,19 @@ macro_rules! define_clock_tree_types { ) { let old_config = clocks.i2c_function_clock[self as usize].replace(config); refresh_i2c_function_clock_downstream(clocks, self); - if clocks.i2c_function_clock_refcount[self as usize] > 0 { + let active = clocks.i2c_function_clock_refcount[self as usize] > 0; + if active { match config.sclk { I2cFunctionClockSclk::Xtal => request_xtal_clk(clocks), I2cFunctionClockSclk::RcFast => request_rc_fast_clk(clocks), } - self.configure_function_clock_impl(clocks, old_config, config); - if let Some(old_config) = old_config { - match old_config.sclk { - I2cFunctionClockSclk::Xtal => release_xtal_clk(clocks), - I2cFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), - } + } + self.configure_function_clock_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + I2cFunctionClockSclk::Xtal => release_xtal_clk(clocks), + I2cFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_config, config); } } pub fn function_clock_config( @@ -2992,39 +4248,313 @@ macro_rules! define_clock_tree_types { I2cFunctionClockSclk::Xtal => request_xtal_clk(clocks), I2cFunctionClockSclk::RcFast => request_rc_fast_clk(clocks), } - self.enable_function_clock_impl(clocks, true); + self.enable_function_clock_impl(clocks, true); + } + } + pub fn release_function_clock(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::FUNCTION_CLOCK", self); + if decrement_reference_count(&mut clocks.i2c_function_clock_refcount[self as usize]) + { + trace!("Disabling {:?}::FUNCTION_CLOCK", self); + self.enable_function_clock_impl(clocks, false); + match unwrap!(clocks.i2c_function_clock[self as usize]).sclk { + I2cFunctionClockSclk::Xtal => release_xtal_clk(clocks), + I2cFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), + } + } + } + pub fn function_clock_config_frequency(config: I2cFunctionClockConfig) -> u32 { + (match config.sclk { + I2cFunctionClockSclk::Xtal => xtal_clk_frequency(), + I2cFunctionClockSclk::RcFast => rc_fast_clk_frequency(), + } / (config.div_num() + 1)) + } + pub fn function_clock_frequency(self) -> u32 { + I2C_FUNCTION_CLOCK_FREQ_CACHE[self as usize] + .load(::core::sync::atomic::Ordering::Acquire) + } + pub fn function_clock_source_frequency(sclk: I2cFunctionClockSclk) -> u32 { + match sclk { + I2cFunctionClockSclk::Xtal => xtal_clk_frequency(), + I2cFunctionClockSclk::RcFast => rc_fast_clk_frequency(), + } + } + } + impl I2sInstance { + pub fn configure_tx_clk(self, clocks: &mut ClockTree, config: I2sClkConfig) { + let old_config = clocks.i2s_tx_clk[self as usize].replace(config); + refresh_i2s_tx_clk_downstream(clocks, self); + self.configure_tx_clk_impl(clocks, old_config, config); + } + pub fn tx_clk_config(self, clocks: &mut ClockTree) -> Option { + clocks.i2s_tx_clk[self as usize] + } + pub fn request_tx_clk(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::TX_CLK", self); + if increment_reference_count(&mut clocks.i2s_tx_clk_refcount[self as usize]) { + trace!("Enabling {:?}::TX_CLK", self); + crate::rtc_cntl::WakeLock::acquire(); + match unwrap!(clocks.i2s_tx_clk[self as usize]).sclk { + I2sClkSclk::Xtal => request_xtal_clk(clocks), + } + self.enable_tx_clk_impl(clocks, true); + } + } + pub fn release_tx_clk(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::TX_CLK", self); + if decrement_reference_count(&mut clocks.i2s_tx_clk_refcount[self as usize]) { + trace!("Disabling {:?}::TX_CLK", self); + crate::rtc_cntl::WakeLock::release(); + self.enable_tx_clk_impl(clocks, false); + match unwrap!(clocks.i2s_tx_clk[self as usize]).sclk { + I2sClkSclk::Xtal => release_xtal_clk(clocks), + } + } + } + pub fn tx_clk_config_frequency(config: I2sClkConfig) -> u32 { + (((xtal_clk_frequency() as u64) * (config.div_a() as u64)) + / (((config.div_num() * config.div_a()) + config.div_b()) as u64)) + as u32 + } + pub fn tx_clk_frequency(self) -> u32 { + I2S_TX_CLK_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) + } + pub fn tx_clk_source_frequency(sclk: I2sClkSclk) -> u32 { + match sclk { + I2sClkSclk::Xtal => xtal_clk_frequency(), + } + } + pub fn configure_rx_clk(self, clocks: &mut ClockTree, config: I2sClkConfig) { + let old_config = clocks.i2s_rx_clk[self as usize].replace(config); + refresh_i2s_rx_clk_downstream(clocks, self); + self.configure_rx_clk_impl(clocks, old_config, config); + } + pub fn rx_clk_config(self, clocks: &mut ClockTree) -> Option { + clocks.i2s_rx_clk[self as usize] + } + pub fn request_rx_clk(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::RX_CLK", self); + if increment_reference_count(&mut clocks.i2s_rx_clk_refcount[self as usize]) { + trace!("Enabling {:?}::RX_CLK", self); + crate::rtc_cntl::WakeLock::acquire(); + match unwrap!(clocks.i2s_rx_clk[self as usize]).sclk { + I2sClkSclk::Xtal => request_xtal_clk(clocks), + } + self.enable_rx_clk_impl(clocks, true); + } + } + pub fn release_rx_clk(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::RX_CLK", self); + if decrement_reference_count(&mut clocks.i2s_rx_clk_refcount[self as usize]) { + trace!("Disabling {:?}::RX_CLK", self); + crate::rtc_cntl::WakeLock::release(); + self.enable_rx_clk_impl(clocks, false); + match unwrap!(clocks.i2s_rx_clk[self as usize]).sclk { + I2sClkSclk::Xtal => release_xtal_clk(clocks), + } + } + } + pub fn rx_clk_config_frequency(config: I2sClkConfig) -> u32 { + (((xtal_clk_frequency() as u64) * (config.div_a() as u64)) + / (((config.div_num() * config.div_a()) + config.div_b()) as u64)) + as u32 + } + pub fn rx_clk_frequency(self) -> u32 { + I2S_RX_CLK_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) + } + pub fn rx_clk_source_frequency(sclk: I2sClkSclk) -> u32 { + match sclk { + I2sClkSclk::Xtal => xtal_clk_frequency(), + } + } + pub fn configure_mclk_out( + self, + clocks: &mut ClockTree, + new_selector: I2sMclkOutConfig, + ) { + let old_selector = clocks.i2s_mclk_out[self as usize].replace(new_selector); + refresh_i2s_mclk_out_downstream(clocks, self); + let active = clocks.i2s_mclk_out_refcount[self as usize] > 0; + if active { + match new_selector { + I2sMclkOutConfig::Tx => self.request_tx_clk(clocks), + I2sMclkOutConfig::Rx => self.request_rx_clk(clocks), + } + } + self.configure_mclk_out_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + I2sMclkOutConfig::Tx => self.release_tx_clk(clocks), + I2sMclkOutConfig::Rx => self.release_rx_clk(clocks), + } + } + } + pub fn mclk_out_config(self, clocks: &mut ClockTree) -> Option { + clocks.i2s_mclk_out[self as usize] + } + pub fn request_mclk_out(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::MCLK_OUT", self); + if increment_reference_count(&mut clocks.i2s_mclk_out_refcount[self as usize]) { + trace!("Enabling {:?}::MCLK_OUT", self); + match unwrap!(clocks.i2s_mclk_out[self as usize]) { + I2sMclkOutConfig::Tx => self.request_tx_clk(clocks), + I2sMclkOutConfig::Rx => self.request_rx_clk(clocks), + } + self.enable_mclk_out_impl(clocks, true); + } + } + pub fn release_mclk_out(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::MCLK_OUT", self); + if decrement_reference_count(&mut clocks.i2s_mclk_out_refcount[self as usize]) { + trace!("Disabling {:?}::MCLK_OUT", self); + self.enable_mclk_out_impl(clocks, false); + match unwrap!(clocks.i2s_mclk_out[self as usize]) { + I2sMclkOutConfig::Tx => self.release_tx_clk(clocks), + I2sMclkOutConfig::Rx => self.release_rx_clk(clocks), + } + } + } + pub fn mclk_out_config_frequency(self, config: I2sMclkOutConfig) -> u32 { + match config { + I2sMclkOutConfig::Tx => self.tx_clk_frequency(), + I2sMclkOutConfig::Rx => self.rx_clk_frequency(), + } + } + pub fn mclk_out_frequency(self) -> u32 { + I2S_MCLK_OUT_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) + } + } + impl LcdCamInstance { + pub fn configure_lcd_clock(self, clocks: &mut ClockTree, config: LcdCamLcdClockConfig) { + let old_config = clocks.lcd_cam_lcd_clock[self as usize].replace(config); + refresh_lcd_cam_lcd_clock_downstream(clocks, self); + let active = clocks.lcd_cam_lcd_clock_refcount[self as usize] > 0; + if active { + match config.sclk { + LcdCamLcdClockSclk::XtalClk => request_xtal_clk(clocks), + LcdCamLcdClockSclk::PllF160m => request_pll_f160m(clocks), + } + } + self.configure_lcd_clock_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + LcdCamLcdClockSclk::XtalClk => release_xtal_clk(clocks), + LcdCamLcdClockSclk::PllF160m => release_pll_f160m(clocks), + } + } + } + pub fn lcd_clock_config(self, clocks: &mut ClockTree) -> Option { + clocks.lcd_cam_lcd_clock[self as usize] + } + pub fn request_lcd_clock(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::LCD_CLOCK", self); + if increment_reference_count(&mut clocks.lcd_cam_lcd_clock_refcount[self as usize]) + { + trace!("Enabling {:?}::LCD_CLOCK", self); + crate::rtc_cntl::WakeLock::acquire(); + match unwrap!(clocks.lcd_cam_lcd_clock[self as usize]).sclk { + LcdCamLcdClockSclk::XtalClk => request_xtal_clk(clocks), + LcdCamLcdClockSclk::PllF160m => request_pll_f160m(clocks), + } + self.enable_lcd_clock_impl(clocks, true); + } + } + pub fn release_lcd_clock(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::LCD_CLOCK", self); + if decrement_reference_count(&mut clocks.lcd_cam_lcd_clock_refcount[self as usize]) + { + trace!("Disabling {:?}::LCD_CLOCK", self); + crate::rtc_cntl::WakeLock::release(); + self.enable_lcd_clock_impl(clocks, false); + match unwrap!(clocks.lcd_cam_lcd_clock[self as usize]).sclk { + LcdCamLcdClockSclk::XtalClk => release_xtal_clk(clocks), + LcdCamLcdClockSclk::PllF160m => release_pll_f160m(clocks), + } + } + } + pub fn lcd_clock_config_frequency(config: LcdCamLcdClockConfig) -> u32 { + (((match config.sclk { + LcdCamLcdClockSclk::XtalClk => xtal_clk_frequency(), + LcdCamLcdClockSclk::PllF160m => pll_f160m_frequency(), + } as u64) + * (config.div_a() as u64)) + / (((config.div_num() * config.div_a()) + config.div_b()) as u64)) + as u32 + } + pub fn lcd_clock_frequency(self) -> u32 { + LCD_CAM_LCD_CLOCK_FREQ_CACHE[self as usize] + .load(::core::sync::atomic::Ordering::Acquire) + } + pub fn lcd_clock_source_frequency(sclk: LcdCamLcdClockSclk) -> u32 { + match sclk { + LcdCamLcdClockSclk::XtalClk => xtal_clk_frequency(), + LcdCamLcdClockSclk::PllF160m => pll_f160m_frequency(), + } + } + pub fn configure_cam_clock(self, clocks: &mut ClockTree, config: LcdCamCamClockConfig) { + let old_config = clocks.lcd_cam_cam_clock[self as usize].replace(config); + refresh_lcd_cam_cam_clock_downstream(clocks, self); + let active = clocks.lcd_cam_cam_clock_refcount[self as usize] > 0; + if active { + match config.sclk { + LcdCamCamClockSclk::XtalClk => request_xtal_clk(clocks), + LcdCamCamClockSclk::PllF160m => request_pll_f160m(clocks), + } + } + self.configure_cam_clock_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + LcdCamCamClockSclk::XtalClk => release_xtal_clk(clocks), + LcdCamCamClockSclk::PllF160m => release_pll_f160m(clocks), + } } } - pub fn release_function_clock(self, clocks: &mut ClockTree) { - trace!("Releasing {:?}::FUNCTION_CLOCK", self); - if decrement_reference_count(&mut clocks.i2c_function_clock_refcount[self as usize]) + pub fn cam_clock_config(self, clocks: &mut ClockTree) -> Option { + clocks.lcd_cam_cam_clock[self as usize] + } + pub fn request_cam_clock(self, clocks: &mut ClockTree) { + trace!("Requesting {:?}::CAM_CLOCK", self); + if increment_reference_count(&mut clocks.lcd_cam_cam_clock_refcount[self as usize]) { - trace!("Disabling {:?}::FUNCTION_CLOCK", self); - self.enable_function_clock_impl(clocks, false); - match unwrap!(clocks.i2c_function_clock[self as usize]).sclk { - I2cFunctionClockSclk::Xtal => release_xtal_clk(clocks), - I2cFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), + trace!("Enabling {:?}::CAM_CLOCK", self); + crate::rtc_cntl::WakeLock::acquire(); + match unwrap!(clocks.lcd_cam_cam_clock[self as usize]).sclk { + LcdCamCamClockSclk::XtalClk => request_xtal_clk(clocks), + LcdCamCamClockSclk::PllF160m => request_pll_f160m(clocks), } + self.enable_cam_clock_impl(clocks, true); } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: I2cFunctionClockConfig, - ) -> u32 { - (match config.sclk { - I2cFunctionClockSclk::Xtal => xtal_clk_frequency(), - I2cFunctionClockSclk::RcFast => rc_fast_clk_frequency(), - } / (config.div_num() + 1)) + pub fn release_cam_clock(self, clocks: &mut ClockTree) { + trace!("Releasing {:?}::CAM_CLOCK", self); + if decrement_reference_count(&mut clocks.lcd_cam_cam_clock_refcount[self as usize]) + { + trace!("Disabling {:?}::CAM_CLOCK", self); + crate::rtc_cntl::WakeLock::release(); + self.enable_cam_clock_impl(clocks, false); + match unwrap!(clocks.lcd_cam_cam_clock[self as usize]).sclk { + LcdCamCamClockSclk::XtalClk => release_xtal_clk(clocks), + LcdCamCamClockSclk::PllF160m => release_pll_f160m(clocks), + } + } } - pub fn function_clock_frequency(self) -> u32 { - I2C_FUNCTION_CLOCK_FREQ_CACHE[self as usize] + pub fn cam_clock_config_frequency(config: LcdCamCamClockConfig) -> u32 { + (((match config.sclk { + LcdCamCamClockSclk::XtalClk => xtal_clk_frequency(), + LcdCamCamClockSclk::PllF160m => pll_f160m_frequency(), + } as u64) + * (config.div_a() as u64)) + / (((config.div_num() * config.div_a()) + config.div_b()) as u64)) + as u32 + } + pub fn cam_clock_frequency(self) -> u32 { + LCD_CAM_CAM_CLOCK_FREQ_CACHE[self as usize] .load(::core::sync::atomic::Ordering::Acquire) } - pub fn function_clock_source_frequency(sclk: I2cFunctionClockSclk) -> u32 { + pub fn cam_clock_source_frequency(sclk: LcdCamCamClockSclk) -> u32 { match sclk { - I2cFunctionClockSclk::Xtal => xtal_clk_frequency(), - I2cFunctionClockSclk::RcFast => rc_fast_clk_frequency(), + LcdCamCamClockSclk::XtalClk => xtal_clk_frequency(), + LcdCamCamClockSclk::PllF160m => pll_f160m_frequency(), } } } @@ -3032,22 +4562,21 @@ macro_rules! define_clock_tree_types { pub fn configure_sclk(self, clocks: &mut ClockTree, new_selector: RmtSclkConfig) { let old_selector = clocks.rmt_sclk[self as usize].replace(new_selector); refresh_rmt_sclk_downstream(clocks, self); - if clocks.rmt_sclk_refcount[self as usize] > 0 { + let active = clocks.rmt_sclk_refcount[self as usize] > 0; + if active { match new_selector { RmtSclkConfig::PllF80m => request_pll_f80m(clocks), RmtSclkConfig::RcFastClk => request_rc_fast_clk(clocks), RmtSclkConfig::XtalClk => request_xtal_clk(clocks), } - self.configure_sclk_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - RmtSclkConfig::PllF80m => release_pll_f80m(clocks), - RmtSclkConfig::RcFastClk => release_rc_fast_clk(clocks), - RmtSclkConfig::XtalClk => release_xtal_clk(clocks), - } + } + self.configure_sclk_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + RmtSclkConfig::PllF80m => release_pll_f80m(clocks), + RmtSclkConfig::RcFastClk => release_rc_fast_clk(clocks), + RmtSclkConfig::XtalClk => release_xtal_clk(clocks), } - } else { - self.configure_sclk_impl(clocks, old_selector, new_selector); } } pub fn sclk_config(self, clocks: &mut ClockTree) -> Option { @@ -3079,8 +4608,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn sclk_config_frequency(clocks: &mut ClockTree, config: RmtSclkConfig) -> u32 { + pub fn sclk_config_frequency(config: RmtSclkConfig) -> u32 { match config { RmtSclkConfig::PllF80m => pll_f80m_frequency(), RmtSclkConfig::RcFastClk => rc_fast_clk_frequency(), @@ -3091,11 +4619,7 @@ macro_rules! define_clock_tree_types { RMT_SCLK_FREQ_CACHE[self as usize].load(::core::sync::atomic::Ordering::Acquire) } pub fn sclk_source_frequency(source: RmtSclkConfig) -> u32 { - match source { - RmtSclkConfig::PllF80m => pll_f80m_frequency(), - RmtSclkConfig::RcFastClk => rc_fast_clk_frequency(), - RmtSclkConfig::XtalClk => xtal_clk_frequency(), - } + Self::sclk_config_frequency(source) } } impl SpiInstance { @@ -3106,22 +4630,21 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.spi_function_clock[self as usize].replace(new_selector); refresh_spi_function_clock_downstream(clocks, self); - if clocks.spi_function_clock_refcount[self as usize] > 0 { + let active = clocks.spi_function_clock_refcount[self as usize] > 0; + if active { match new_selector { - SpiFunctionClockConfig::Bbpll => request_bbpll_clk(clocks), + SpiFunctionClockConfig::Bbpll => request_bbpll_d3_clock(clocks), SpiFunctionClockConfig::Xtal => request_xtal_clk(clocks), SpiFunctionClockConfig::RcFast => request_rc_fast_clk(clocks), } - self.configure_function_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - SpiFunctionClockConfig::Bbpll => release_bbpll_clk(clocks), - SpiFunctionClockConfig::Xtal => release_xtal_clk(clocks), - SpiFunctionClockConfig::RcFast => release_rc_fast_clk(clocks), - } + } + self.configure_function_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + SpiFunctionClockConfig::Bbpll => release_bbpll_d3_clock(clocks), + SpiFunctionClockConfig::Xtal => release_xtal_clk(clocks), + SpiFunctionClockConfig::RcFast => release_rc_fast_clk(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_selector, new_selector); } } pub fn function_clock_config( @@ -3136,7 +4659,7 @@ macro_rules! define_clock_tree_types { { trace!("Enabling {:?}::FUNCTION_CLOCK", self); match unwrap!(clocks.spi_function_clock[self as usize]) { - SpiFunctionClockConfig::Bbpll => request_bbpll_clk(clocks), + SpiFunctionClockConfig::Bbpll => request_bbpll_d3_clock(clocks), SpiFunctionClockConfig::Xtal => request_xtal_clk(clocks), SpiFunctionClockConfig::RcFast => request_rc_fast_clk(clocks), } @@ -3150,19 +4673,15 @@ macro_rules! define_clock_tree_types { trace!("Disabling {:?}::FUNCTION_CLOCK", self); self.enable_function_clock_impl(clocks, false); match unwrap!(clocks.spi_function_clock[self as usize]) { - SpiFunctionClockConfig::Bbpll => release_bbpll_clk(clocks), + SpiFunctionClockConfig::Bbpll => release_bbpll_d3_clock(clocks), SpiFunctionClockConfig::Xtal => release_xtal_clk(clocks), SpiFunctionClockConfig::RcFast => release_rc_fast_clk(clocks), } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: SpiFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: SpiFunctionClockConfig) -> u32 { match config { - SpiFunctionClockConfig::Bbpll => bbpll_clk_frequency(), + SpiFunctionClockConfig::Bbpll => bbpll_d3_clock_frequency(), SpiFunctionClockConfig::Xtal => xtal_clk_frequency(), SpiFunctionClockConfig::RcFast => rc_fast_clk_frequency(), } @@ -3172,11 +4691,7 @@ macro_rules! define_clock_tree_types { .load(::core::sync::atomic::Ordering::Acquire) } pub fn function_clock_source_frequency(source: SpiFunctionClockConfig) -> u32 { - match source { - SpiFunctionClockConfig::Bbpll => bbpll_clk_frequency(), - SpiFunctionClockConfig::Xtal => xtal_clk_frequency(), - SpiFunctionClockConfig::RcFast => rc_fast_clk_frequency(), - } + Self::function_clock_config_frequency(source) } } impl TimgInstance { @@ -3187,22 +4702,21 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.timg_function_clock[self as usize].replace(new_selector); refresh_timg_function_clock_downstream(clocks, self); - if clocks.timg_function_clock_refcount[self as usize] > 0 { + let active = clocks.timg_function_clock_refcount[self as usize] > 0; + if active { match new_selector { TimgFunctionClockConfig::PllF80m => request_pll_f80m(clocks), TimgFunctionClockConfig::RcFastClk => request_rc_fast_clk(clocks), TimgFunctionClockConfig::XtalClk => request_xtal_clk(clocks), } - self.configure_function_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - TimgFunctionClockConfig::PllF80m => release_pll_f80m(clocks), - TimgFunctionClockConfig::RcFastClk => release_rc_fast_clk(clocks), - TimgFunctionClockConfig::XtalClk => release_xtal_clk(clocks), - } + } + self.configure_function_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + TimgFunctionClockConfig::PllF80m => release_pll_f80m(clocks), + TimgFunctionClockConfig::RcFastClk => release_rc_fast_clk(clocks), + TimgFunctionClockConfig::XtalClk => release_xtal_clk(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_selector, new_selector); } } pub fn function_clock_config( @@ -3239,11 +4753,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: TimgFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: TimgFunctionClockConfig) -> u32 { match config { TimgFunctionClockConfig::PllF80m => pll_f80m_frequency(), TimgFunctionClockConfig::RcFastClk => rc_fast_clk_frequency(), @@ -3255,11 +4765,7 @@ macro_rules! define_clock_tree_types { .load(::core::sync::atomic::Ordering::Acquire) } pub fn function_clock_source_frequency(source: TimgFunctionClockConfig) -> u32 { - match source { - TimgFunctionClockConfig::PllF80m => pll_f80m_frequency(), - TimgFunctionClockConfig::RcFastClk => rc_fast_clk_frequency(), - TimgFunctionClockConfig::XtalClk => xtal_clk_frequency(), - } + Self::function_clock_config_frequency(source) } pub fn configure_wdt_clock( self, @@ -3268,22 +4774,21 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.timg_wdt_clock[self as usize].replace(new_selector); refresh_timg_wdt_clock_downstream(clocks, self); - if clocks.timg_wdt_clock_refcount[self as usize] > 0 { + let active = clocks.timg_wdt_clock_refcount[self as usize] > 0; + if active { match new_selector { TimgWdtClockConfig::XtalClk => request_xtal_clk(clocks), TimgWdtClockConfig::PllF80m => request_pll_f80m(clocks), TimgWdtClockConfig::RcFastClk => request_rc_fast_clk(clocks), } - self.configure_wdt_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - TimgWdtClockConfig::XtalClk => release_xtal_clk(clocks), - TimgWdtClockConfig::PllF80m => release_pll_f80m(clocks), - TimgWdtClockConfig::RcFastClk => release_rc_fast_clk(clocks), - } + } + self.configure_wdt_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + TimgWdtClockConfig::XtalClk => release_xtal_clk(clocks), + TimgWdtClockConfig::PllF80m => release_pll_f80m(clocks), + TimgWdtClockConfig::RcFastClk => release_rc_fast_clk(clocks), } - } else { - self.configure_wdt_clock_impl(clocks, old_selector, new_selector); } } pub fn wdt_clock_config(self, clocks: &mut ClockTree) -> Option { @@ -3313,11 +4818,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn wdt_clock_config_frequency( - clocks: &mut ClockTree, - config: TimgWdtClockConfig, - ) -> u32 { + pub fn wdt_clock_config_frequency(config: TimgWdtClockConfig) -> u32 { match config { TimgWdtClockConfig::XtalClk => xtal_clk_frequency(), TimgWdtClockConfig::PllF80m => pll_f80m_frequency(), @@ -3329,11 +4830,7 @@ macro_rules! define_clock_tree_types { .load(::core::sync::atomic::Ordering::Acquire) } pub fn wdt_clock_source_frequency(source: TimgWdtClockConfig) -> u32 { - match source { - TimgWdtClockConfig::XtalClk => xtal_clk_frequency(), - TimgWdtClockConfig::PllF80m => pll_f80m_frequency(), - TimgWdtClockConfig::RcFastClk => rc_fast_clk_frequency(), - } + Self::wdt_clock_config_frequency(source) } } impl UartInstance { @@ -3344,22 +4841,21 @@ macro_rules! define_clock_tree_types { ) { let old_config = clocks.uart_function_clock[self as usize].replace(config); refresh_uart_function_clock_downstream(clocks, self); - if clocks.uart_function_clock_refcount[self as usize] > 0 { + let active = clocks.uart_function_clock_refcount[self as usize] > 0; + if active { match config.sclk { UartFunctionClockSclk::PllF80m => request_pll_f80m(clocks), UartFunctionClockSclk::Xtal => request_xtal_clk(clocks), UartFunctionClockSclk::RcFast => request_rc_fast_clk(clocks), } - self.configure_function_clock_impl(clocks, old_config, config); - if let Some(old_config) = old_config { - match old_config.sclk { - UartFunctionClockSclk::PllF80m => release_pll_f80m(clocks), - UartFunctionClockSclk::Xtal => release_xtal_clk(clocks), - UartFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), - } + } + self.configure_function_clock_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + match old_config.sclk { + UartFunctionClockSclk::PllF80m => release_pll_f80m(clocks), + UartFunctionClockSclk::Xtal => release_xtal_clk(clocks), + UartFunctionClockSclk::RcFast => release_rc_fast_clk(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_config, config); } } pub fn function_clock_config( @@ -3396,11 +4892,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: UartFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: UartFunctionClockConfig) -> u32 { (match config.sclk { UartFunctionClockSclk::PllF80m => pll_f80m_frequency(), UartFunctionClockSclk::Xtal => xtal_clk_frequency(), @@ -3453,10 +4945,8 @@ macro_rules! define_clock_tree_types { self.release_function_clock(clocks); } } - #[allow(unused_variables)] pub fn baud_rate_generator_config_frequency( self, - clocks: &mut ClockTree, config: UartBaudRateGeneratorConfig, ) -> u32 { ((self.function_clock_frequency() * 16) @@ -3497,22 +4987,21 @@ macro_rules! define_clock_tree_types { ) { let old_selector = clocks.psram_function_clock[self as usize].replace(new_selector); refresh_psram_function_clock_downstream(clocks, self); - if clocks.psram_function_clock_refcount[self as usize] > 0 { + let active = clocks.psram_function_clock_refcount[self as usize] > 0; + if active { match new_selector { PsramFunctionClockConfig::Xtal => request_xtal_clk(clocks), PsramFunctionClockConfig::Mpll => request_mpll_clk(clocks), PsramFunctionClockConfig::Cpll => request_cpll_clk(clocks), } - self.configure_function_clock_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - match old_selector { - PsramFunctionClockConfig::Xtal => release_xtal_clk(clocks), - PsramFunctionClockConfig::Mpll => release_mpll_clk(clocks), - PsramFunctionClockConfig::Cpll => release_cpll_clk(clocks), - } + } + self.configure_function_clock_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + match old_selector { + PsramFunctionClockConfig::Xtal => release_xtal_clk(clocks), + PsramFunctionClockConfig::Mpll => release_mpll_clk(clocks), + PsramFunctionClockConfig::Cpll => release_cpll_clk(clocks), } - } else { - self.configure_function_clock_impl(clocks, old_selector, new_selector); } } pub fn function_clock_config( @@ -3549,11 +5038,7 @@ macro_rules! define_clock_tree_types { } } } - #[allow(unused_variables)] - pub fn function_clock_config_frequency( - clocks: &mut ClockTree, - config: PsramFunctionClockConfig, - ) -> u32 { + pub fn function_clock_config_frequency(config: PsramFunctionClockConfig) -> u32 { match config { PsramFunctionClockConfig::Xtal => xtal_clk_frequency(), PsramFunctionClockConfig::Mpll => mpll_clk_frequency(), @@ -3565,11 +5050,7 @@ macro_rules! define_clock_tree_types { .load(::core::sync::atomic::Ordering::Acquire) } pub fn function_clock_source_frequency(source: PsramFunctionClockConfig) -> u32 { - match source { - PsramFunctionClockConfig::Xtal => xtal_clk_frequency(), - PsramFunctionClockConfig::Mpll => mpll_clk_frequency(), - PsramFunctionClockConfig::Cpll => cpll_clk_frequency(), - } + Self::function_clock_config_frequency(source) } } /// Clock tree configuration. @@ -3583,18 +5064,26 @@ macro_rules! define_clock_tree_types { #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[instability::unstable] pub struct ClockConfig { + /// `MPLL_CLK` configuration. + pub mpll_clk: Option, /// `CPU_ROOT_CLK` configuration. pub cpu_root_clk: Option, /// `CPU_CLK` configuration. pub cpu_clk: Option, - /// `AHB_CLK` configuration. - pub ahb_clk: Option, + /// `MEM_CLK` configuration. + pub mem_clk: Option, + /// `SYS_CLK` configuration. + pub sys_clk: Option, /// `APB_CLK` configuration. pub apb_clk: Option, /// `LP_FAST_CLK` configuration. pub lp_fast_clk: Option, /// `LP_SLOW_CLK` configuration. pub lp_slow_clk: Option, + /// `BLE_LP_CLK` configuration. + pub ble_lp_clk: Option, + /// `CRYPTO_CLK` configuration. + pub crypto_clk: Option, /// `IOMUX_FUNCTION_CLOCK` configuration. pub iomux_function_clock: Option, /// `TIMG_CALIBRATION_CLOCK` configuration. @@ -3602,14 +5091,20 @@ macro_rules! define_clock_tree_types { } impl ClockConfig { fn apply(&self, clocks: &mut ClockTree) { + if let Some(config) = self.mpll_clk { + configure_mpll_clk(clocks, config); + } if let Some(config) = self.cpu_root_clk { configure_cpu_root_clk(clocks, config); } if let Some(config) = self.cpu_clk { configure_cpu_clk(clocks, config); } - if let Some(config) = self.ahb_clk { - configure_ahb_clk(clocks, config); + if let Some(config) = self.mem_clk { + configure_mem_clk(clocks, config); + } + if let Some(config) = self.sys_clk { + configure_sys_clk(clocks, config); } if let Some(config) = self.apb_clk { configure_apb_clk(clocks, config); @@ -3620,6 +5115,12 @@ macro_rules! define_clock_tree_types { if let Some(config) = self.lp_slow_clk { configure_lp_slow_clk(clocks, config); } + if let Some(config) = self.ble_lp_clk { + configure_ble_lp_clk(clocks, config); + } + if let Some(config) = self.crypto_clk { + configure_crypto_clk(clocks, config); + } if let Some(config) = self.iomux_function_clock { configure_iomux_function_clock(clocks, config); } @@ -3638,10 +5139,52 @@ macro_rules! define_clock_tree_types { let last = *refcount == 0; last } + fn refresh_mpll_clk_downstream(clocks: &mut ClockTree) { + if let Some(config) = clocks.mpll_clk { + MPLL_CLK_FREQ_CACHE.store( + mpll_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + for child_instance in [PsramInstance::Psram] { + refresh_psram_function_clock_downstream(clocks, child_instance); + } + } + fn refresh_rc_fast_clk_downstream(clocks: &mut ClockTree) { + refresh_cpu_root_clk_downstream(clocks); + refresh_lp_fast_clk_downstream(clocks); + refresh_crypto_clk_downstream(clocks); + refresh_timg_calibration_clock_downstream(clocks); + for child_instance in [I2cInstance::I2c0, I2cInstance::I2c1] { + refresh_i2c_function_clock_downstream(clocks, child_instance); + } + for child_instance in [RmtInstance::Rmt] { + refresh_rmt_sclk_downstream(clocks, child_instance); + } + for child_instance in [SpiInstance::Spi2, SpiInstance::Spi3] { + refresh_spi_function_clock_downstream(clocks, child_instance); + } + for child_instance in [TimgInstance::Timg0, TimgInstance::Timg1] { + refresh_timg_function_clock_downstream(clocks, child_instance); + refresh_timg_wdt_clock_downstream(clocks, child_instance); + } + for child_instance in [ + UartInstance::Uart0, + UartInstance::Uart1, + UartInstance::Uart2, + UartInstance::Uart3, + ] { + refresh_uart_function_clock_downstream(clocks, child_instance); + } + } + fn refresh_rc_slow_clk_downstream(clocks: &mut ClockTree) { + refresh_lp_slow_clk_downstream(clocks); + refresh_timg_calibration_clock_downstream(clocks); + } fn refresh_cpu_root_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.cpu_root_clk { CPU_ROOT_CLK_FREQ_CACHE.store( - cpu_root_clk_config_frequency(clocks, config), + cpu_root_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3650,16 +5193,25 @@ macro_rules! define_clock_tree_types { fn refresh_cpu_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.cpu_clk { CPU_CLK_FREQ_CACHE.store( - cpu_clk_config_frequency(clocks, config), + cpu_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + refresh_mem_clk_downstream(clocks); + refresh_sys_clk_downstream(clocks); + } + fn refresh_mem_clk_downstream(clocks: &mut ClockTree) { + if let Some(config) = clocks.mem_clk { + MEM_CLK_FREQ_CACHE.store( + mem_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } - refresh_ahb_clk_downstream(clocks); } - fn refresh_ahb_clk_downstream(clocks: &mut ClockTree) { - if let Some(config) = clocks.ahb_clk { - AHB_CLK_FREQ_CACHE.store( - ahb_clk_config_frequency(clocks, config), + fn refresh_sys_clk_downstream(clocks: &mut ClockTree) { + if let Some(config) = clocks.sys_clk { + SYS_CLK_FREQ_CACHE.store( + sys_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3668,7 +5220,7 @@ macro_rules! define_clock_tree_types { fn refresh_apb_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.apb_clk { APB_CLK_FREQ_CACHE.store( - apb_clk_config_frequency(clocks, config), + apb_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3676,7 +5228,7 @@ macro_rules! define_clock_tree_types { fn refresh_lp_fast_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.lp_fast_clk { LP_FAST_CLK_FREQ_CACHE.store( - lp_fast_clk_config_frequency(clocks, config), + lp_fast_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3684,7 +5236,23 @@ macro_rules! define_clock_tree_types { fn refresh_lp_slow_clk_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.lp_slow_clk { LP_SLOW_CLK_FREQ_CACHE.store( - lp_slow_clk_config_frequency(clocks, config), + lp_slow_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + fn refresh_ble_lp_clk_downstream(clocks: &mut ClockTree) { + if let Some(config) = clocks.ble_lp_clk { + BLE_LP_CLK_FREQ_CACHE.store( + ble_lp_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + fn refresh_crypto_clk_downstream(clocks: &mut ClockTree) { + if let Some(config) = clocks.crypto_clk { + CRYPTO_CLK_FREQ_CACHE.store( + crypto_clk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3692,7 +5260,7 @@ macro_rules! define_clock_tree_types { fn refresh_iomux_function_clock_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.iomux_function_clock { IOMUX_FUNCTION_CLOCK_FREQ_CACHE.store( - iomux_function_clock_config_frequency(clocks, config), + iomux_function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3700,7 +5268,7 @@ macro_rules! define_clock_tree_types { fn refresh_timg_calibration_clock_downstream(clocks: &mut ClockTree) { if let Some(config) = clocks.timg_calibration_clock { TIMG_CALIBRATION_CLOCK_FREQ_CACHE.store( - timg_calibration_clock_config_frequency(clocks, config), + timg_calibration_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3708,7 +5276,49 @@ macro_rules! define_clock_tree_types { fn refresh_i2c_function_clock_downstream(clocks: &mut ClockTree, instance: I2cInstance) { if let Some(config) = clocks.i2c_function_clock[instance as usize] { I2C_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - I2cInstance::function_clock_config_frequency(clocks, config), + I2cInstance::function_clock_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + fn refresh_i2s_tx_clk_downstream(clocks: &mut ClockTree, instance: I2sInstance) { + if let Some(config) = clocks.i2s_tx_clk[instance as usize] { + I2S_TX_CLK_FREQ_CACHE[instance as usize].store( + I2sInstance::tx_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + refresh_i2s_mclk_out_downstream(clocks, instance); + } + fn refresh_i2s_rx_clk_downstream(clocks: &mut ClockTree, instance: I2sInstance) { + if let Some(config) = clocks.i2s_rx_clk[instance as usize] { + I2S_RX_CLK_FREQ_CACHE[instance as usize].store( + I2sInstance::rx_clk_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + refresh_i2s_mclk_out_downstream(clocks, instance); + } + fn refresh_i2s_mclk_out_downstream(clocks: &mut ClockTree, instance: I2sInstance) { + if let Some(config) = clocks.i2s_mclk_out[instance as usize] { + I2S_MCLK_OUT_FREQ_CACHE[instance as usize].store( + instance.mclk_out_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + fn refresh_lcd_cam_lcd_clock_downstream(clocks: &mut ClockTree, instance: LcdCamInstance) { + if let Some(config) = clocks.lcd_cam_lcd_clock[instance as usize] { + LCD_CAM_LCD_CLOCK_FREQ_CACHE[instance as usize].store( + LcdCamInstance::lcd_clock_config_frequency(config), + ::core::sync::atomic::Ordering::Release, + ); + } + } + fn refresh_lcd_cam_cam_clock_downstream(clocks: &mut ClockTree, instance: LcdCamInstance) { + if let Some(config) = clocks.lcd_cam_cam_clock[instance as usize] { + LCD_CAM_CAM_CLOCK_FREQ_CACHE[instance as usize].store( + LcdCamInstance::cam_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3716,7 +5326,7 @@ macro_rules! define_clock_tree_types { fn refresh_rmt_sclk_downstream(clocks: &mut ClockTree, instance: RmtInstance) { if let Some(config) = clocks.rmt_sclk[instance as usize] { RMT_SCLK_FREQ_CACHE[instance as usize].store( - RmtInstance::sclk_config_frequency(clocks, config), + RmtInstance::sclk_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3724,7 +5334,7 @@ macro_rules! define_clock_tree_types { fn refresh_spi_function_clock_downstream(clocks: &mut ClockTree, instance: SpiInstance) { if let Some(config) = clocks.spi_function_clock[instance as usize] { SPI_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - SpiInstance::function_clock_config_frequency(clocks, config), + SpiInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3732,7 +5342,7 @@ macro_rules! define_clock_tree_types { fn refresh_timg_function_clock_downstream(clocks: &mut ClockTree, instance: TimgInstance) { if let Some(config) = clocks.timg_function_clock[instance as usize] { TIMG_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - TimgInstance::function_clock_config_frequency(clocks, config), + TimgInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3740,7 +5350,7 @@ macro_rules! define_clock_tree_types { fn refresh_timg_wdt_clock_downstream(clocks: &mut ClockTree, instance: TimgInstance) { if let Some(config) = clocks.timg_wdt_clock[instance as usize] { TIMG_WDT_CLOCK_FREQ_CACHE[instance as usize].store( - TimgInstance::wdt_clock_config_frequency(clocks, config), + TimgInstance::wdt_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3748,7 +5358,7 @@ macro_rules! define_clock_tree_types { fn refresh_uart_function_clock_downstream(clocks: &mut ClockTree, instance: UartInstance) { if let Some(config) = clocks.uart_function_clock[instance as usize] { UART_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - UartInstance::function_clock_config_frequency(clocks, config), + UartInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3760,7 +5370,7 @@ macro_rules! define_clock_tree_types { ) { if let Some(config) = clocks.uart_baud_rate_generator[instance as usize] { UART_BAUD_RATE_GENERATOR_FREQ_CACHE[instance as usize].store( - instance.baud_rate_generator_config_frequency(clocks, config), + instance.baud_rate_generator_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3771,7 +5381,7 @@ macro_rules! define_clock_tree_types { ) { if let Some(config) = clocks.psram_function_clock[instance as usize] { PSRAM_FUNCTION_CLOCK_FREQ_CACHE[instance as usize].store( - PsramInstance::function_clock_config_frequency(clocks, config), + PsramInstance::function_clock_config_frequency(config), ::core::sync::atomic::Ordering::Release, ); } @@ -3800,12 +5410,24 @@ macro_rules! implement_peripheral_clocks { AxiGdma, /// ECC peripheral clock signal Ecc, + /// EMAC peripheral clock signal + Emac, /// GPIO_SD peripheral clock signal GpioSd, /// I2C0 peripheral clock signal I2c0, /// I2C1 peripheral clock signal I2c1, + /// I2S0 peripheral clock signal + I2s0, + /// I2S1 peripheral clock signal + I2s1, + /// LCD_CAM peripheral clock signal + LcdCam, + /// PCNT peripheral clock signal + Pcnt, + /// PCNT1 peripheral clock signal + Pcnt1, /// RMT peripheral clock signal Rmt, /// RSA peripheral clock signal @@ -3840,8 +5462,13 @@ macro_rules! implement_peripheral_clocks { UsbHs, } impl Peripheral { - const KEEP_ENABLED: &[Peripheral] = - &[Self::Systimer, Self::Timg0, Self::Uart0, Self::UsbDevice]; + const KEEP_ENABLED: &[Peripheral] = &[ + Self::ApbSarAdc, + Self::Systimer, + Self::Timg0, + Self::Uart0, + Self::UsbDevice, + ]; const COUNT: usize = Self::ALL.len(); const ALL: &[Self] = &[ Self::Aes, @@ -3849,9 +5476,15 @@ macro_rules! implement_peripheral_clocks { Self::ApbSarAdc, Self::AxiGdma, Self::Ecc, + Self::Emac, Self::GpioSd, Self::I2c0, Self::I2c1, + Self::I2s0, + Self::I2s1, + Self::LcdCam, + Self::Pcnt, + Self::Pcnt1, Self::Rmt, Self::Rsa, Self::SdioHost, @@ -3897,6 +5530,11 @@ macro_rules! implement_peripheral_clocks { .crypto_ctrl0() .modify(|_, w| w.crypto_ecc_clk_en().bit(enable)); } + Peripheral::Emac => { + crate::peripherals::HP_SYS_CLKRST::regs() + .emac_ctrl0() + .modify(|_, w| w.sys_clk_en().bit(enable)); + } Peripheral::GpioSd => { crate::peripherals::GPIO_SD::regs() .clock_gate() @@ -3912,6 +5550,37 @@ macro_rules! implement_peripheral_clocks { .i2c_ctrl0(1) .modify(|_, w| w.apb_clk_en().bit(enable).clk_en().bit(enable)); } + Peripheral::I2s0 => { + crate::peripherals::HP_SYS_CLKRST::regs() + .i2s0_ctrl0() + .modify(|_, w| w.apb_clk_en().bit(enable)); + crate::peripherals::HP_ALIVE_SYS::regs() + .hp_pad_i2s0_ctrl() + .modify(|_, w| w.hp_pad_i2s0_mclk_en().bit(enable)); + } + Peripheral::I2s1 => { + crate::peripherals::HP_SYS_CLKRST::regs() + .i2s1_ctrl0() + .modify(|_, w| w.apb_clk_en().bit(enable)); + crate::peripherals::HP_ALIVE_SYS::regs() + .hp_pad_i2s1_ctrl() + .modify(|_, w| w.hp_pad_i2s1_mclk_en().bit(enable)); + } + Peripheral::LcdCam => { + crate::peripherals::HP_SYS_CLKRST::regs() + .lcdcam_ctrl0() + .modify(|_, w| w.sys_clk_en().bit(enable).apb_clk_en().bit(enable)); + } + Peripheral::Pcnt => { + crate::peripherals::HP_SYS_CLKRST::regs() + .pcnt_ctrl0() + .modify(|_, w| w.pcnt0_apb_clk_en().bit(enable)); + } + Peripheral::Pcnt1 => { + crate::peripherals::HP_SYS_CLKRST::regs() + .pcnt_ctrl0() + .modify(|_, w| w.pcnt1_apb_clk_en().bit(enable)); + } Peripheral::Rmt => { crate::peripherals::HP_SYS_CLKRST::regs() .rmt_ctrl0() @@ -4024,6 +5693,9 @@ macro_rules! implement_peripheral_clocks { .crypto_ctrl0() .modify(|_, w| w.crypto_ecc_rst_en().bit(reset)); } + Peripheral::Emac => { + let _ = reset; + } Peripheral::GpioSd => { let _ = reset; } @@ -4037,6 +5709,31 @@ macro_rules! implement_peripheral_clocks { .i2c_ctrl0(1) .modify(|_, w| w.rst_en().bit(reset)); } + Peripheral::I2s0 => { + crate::peripherals::HP_SYS_CLKRST::regs() + .i2s0_ctrl0() + .modify(|_, w| w.apb_rst_en().bit(reset)); + } + Peripheral::I2s1 => { + crate::peripherals::HP_SYS_CLKRST::regs() + .i2s1_ctrl0() + .modify(|_, w| w.apb_rst_en().bit(reset)); + } + Peripheral::LcdCam => { + crate::peripherals::HP_SYS_CLKRST::regs() + .lcdcam_ctrl0() + .modify(|_, w| w.apb_rst_en().bit(reset).rst_en().bit(reset)); + } + Peripheral::Pcnt => { + crate::peripherals::HP_SYS_CLKRST::regs() + .pcnt_ctrl0() + .modify(|_, w| w.pcnt0_rst_en().bit(reset)); + } + Peripheral::Pcnt1 => { + crate::peripherals::HP_SYS_CLKRST::regs() + .pcnt_ctrl0() + .modify(|_, w| w.pcnt1_rst_en().bit(reset)); + } Peripheral::Rmt => { crate::peripherals::HP_SYS_CLKRST::regs() .rmt_ctrl0() @@ -4130,16 +5827,16 @@ macro_rules! implement_peripheral_clocks { #[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] macro_rules! memory_range { ("DRAM") => { - 0x2F000000..0x2F07AFC0 + 0x2F000000..0x2F080000 }; (size as str, "DRAM") => { - "503744" + "524288" }; ("DRAM2_UNINIT") => { - 0x2F07AFC0..0x2F07CFB0 + 0x2F06CFB0..0x2F07CFB0 }; (size as str, "DRAM2_UNINIT") => { - "8176" + "65536" }; ("IROM") => { 0x40000000..0x50000000 @@ -4212,7 +5909,16 @@ macro_rules! for_each_i2c_master { macro_rules! for_each_i2s { ($($pattern:tt => $code:tt;)*) => { macro_rules! _for_each_inner_i2s { $(($pattern) => $code;)* ($other : tt) => {} } - _for_each_inner_i2s!((names)); _for_each_inner_i2s!((all)); + _for_each_inner_i2s!((I2S0)); _for_each_inner_i2s!((I2S1)); + _for_each_inner_i2s!((I2S0, I2s0, I2S0_MCLK, I2S0O_BCK, I2S0O_WS, I2S0I_BCK, + I2S0I_WS, [I2S0O_SD, I2S0O_SD1], [I2S0I_SD, I2S0I_SD1, I2S0I_SD2, I2S0I_SD3], + true, true, true, true)); _for_each_inner_i2s!((I2S1, I2s1, I2S1_MCLK, I2S1O_BCK, + I2S1O_WS, I2S1I_BCK, I2S1I_WS, [I2S1O_SD], [I2S1I_SD], true, true, false, + false)); _for_each_inner_i2s!((names(I2S0), (I2S1))); + _for_each_inner_i2s!((all(I2S0, I2s0, I2S0_MCLK, I2S0O_BCK, I2S0O_WS, I2S0I_BCK, + I2S0I_WS, [I2S0O_SD, I2S0O_SD1], [I2S0I_SD, I2S0I_SD1, I2S0I_SD2, I2S0I_SD3], + true, true, true, true), (I2S1, I2s1, I2S1_MCLK, I2S1O_BCK, I2S1O_WS, I2S1I_BCK, + I2S1I_WS, [I2S1O_SD], [I2S1I_SD], true, true, false, false))); }; } /// This macro can be used to generate code for each peripheral instance of the UART driver. @@ -4241,13 +5947,13 @@ macro_rules! for_each_uart { } _for_each_inner_uart!((0, UART0, Uart0, U0RXD, U0TXD, U0CTS, U0RTS, wakeup_source = true)); _for_each_inner_uart!((1, UART1, Uart1, U1RXD, U1TXD, U1CTS, U1RTS, wakeup_source = true)); _for_each_inner_uart!((2, UART2, Uart2, - U2RXD, U2TXD, U2CTS, U2RTS, wakeup_source = true)); _for_each_inner_uart!((3, - UART3, Uart3, U3RXD, U3TXD, U3CTS, U3RTS, wakeup_source = true)); + U2RXD, U2TXD, U2CTS, U2RTS, wakeup_source = false)); _for_each_inner_uart!((3, + UART3, Uart3, U3RXD, U3TXD, U3CTS, U3RTS, wakeup_source = false)); _for_each_inner_uart!((all(0, UART0, Uart0, U0RXD, U0TXD, U0CTS, U0RTS, wakeup_source = true), (1, UART1, Uart1, U1RXD, U1TXD, U1CTS, U1RTS, wakeup_source = true), (2, UART2, Uart2, U2RXD, U2TXD, U2CTS, U2RTS, - wakeup_source = true), (3, UART3, Uart3, U3RXD, U3TXD, U3CTS, U3RTS, - wakeup_source = true))); + wakeup_source = false), (3, UART3, Uart3, U3RXD, U3TXD, U3CTS, U3RTS, + wakeup_source = false))); }; } /// This macro can be used to generate code for each peripheral instance of the SPI master driver. @@ -4317,6 +6023,102 @@ macro_rules! for_each_spi_slave { (SPI3, Spi3, SPI3_CK, SPI3_D, SPI3_Q, SPI3_CS))); }; } +/// This macro can be used to generate code for each PCNT unit. +/// +/// For an explanation on the general syntax, as well as usage of individual/repeated +/// matchers, refer to [the crate-level documentation][crate#for_each-macros]. +/// +/// This macro has four options for its "Individual matcher" case: +/// +/// - `names`: `($instance:ident)` +/// - `all`: `($peri:ident, $variant:ident, $sys:ident, $regs:ident, $unit:literal, +/// $interrupt:ident, $sig_ch0:ident, $sig_ch1:ident, $ctrl_ch0:ident, $ctrl_ch1:ident)` +/// - `interrupt`: `($interrupt:ident)` (repeated: one ident per unique IRQ) +/// - `regs`: `($regs:ident)` (repeated: one ident per register block) +/// +/// Macro fragments: +/// +/// - `$peri`: unit singleton name (`PCNT0_UNIT0`, `PCNT1_UNIT0`, …) +/// - `$variant`: `AnyPcntUnit` enum variant (`Pcnt0Unit0`, `Pcnt1Unit0`, …) +/// - `$sys`: `esp_hal::system::Peripheral` variant for clocks +/// - `$regs`: register-block singleton (`PCNT`, `PCNT1`) +/// - `$unit`: hardware unit index within that register block +/// - `$interrupt`: shared peripheral interrupt +/// - `$sig_ch0`, `$sig_ch1`, `$ctrl_ch0`, `$ctrl_ch1`: GPIO matrix input signals +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! for_each_pcnt_unit { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _for_each_inner_pcnt_unit { $(($pattern) => $code;)* ($other : tt) + => {} } _for_each_inner_pcnt_unit!((PCNT0_UNIT0)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT2)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT3)); + _for_each_inner_pcnt_unit!((PCNT1_UNIT0)); + _for_each_inner_pcnt_unit!((PCNT1_UNIT1)); + _for_each_inner_pcnt_unit!((PCNT1_UNIT2)); + _for_each_inner_pcnt_unit!((PCNT1_UNIT3)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT0, Pcnt0Unit0, Pcnt, PCNT, 0, PCNT0, + PCNT0_SIG_CH0, PCNT0_SIG_CH1, PCNT0_CTRL_CH0, PCNT0_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT1, Pcnt0Unit1, Pcnt, PCNT, 1, PCNT0, + PCNT1_SIG_CH0, PCNT1_SIG_CH1, PCNT1_CTRL_CH0, PCNT1_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT2, Pcnt0Unit2, Pcnt, PCNT, 2, PCNT0, + PCNT2_SIG_CH0, PCNT2_SIG_CH1, PCNT2_CTRL_CH0, PCNT2_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT0_UNIT3, Pcnt0Unit3, Pcnt, PCNT, 3, PCNT0, + PCNT3_SIG_CH0, PCNT3_SIG_CH1, PCNT3_CTRL_CH0, PCNT3_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT1_UNIT0, Pcnt1Unit0, Pcnt1, PCNT1, 0, PCNT1, + PCNT1_U0_SIG_CH0, PCNT1_U0_SIG_CH1, PCNT1_U0_CTRL_CH0, PCNT1_U0_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT1_UNIT1, Pcnt1Unit1, Pcnt1, PCNT1, 1, PCNT1, + PCNT1_U1_SIG_CH0, PCNT1_U1_SIG_CH1, PCNT1_U1_CTRL_CH0, PCNT1_U1_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT1_UNIT2, Pcnt1Unit2, Pcnt1, PCNT1, 2, PCNT1, + PCNT1_U2_SIG_CH0, PCNT1_U2_SIG_CH1, PCNT1_U2_CTRL_CH0, PCNT1_U2_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT1_UNIT3, Pcnt1Unit3, Pcnt1, PCNT1, 3, PCNT1, + PCNT1_U3_SIG_CH0, PCNT1_U3_SIG_CH1, PCNT1_U3_CTRL_CH0, PCNT1_U3_CTRL_CH1)); + _for_each_inner_pcnt_unit!((PCNT0)); _for_each_inner_pcnt_unit!((PCNT1)); + _for_each_inner_pcnt_unit!((PCNT)); _for_each_inner_pcnt_unit!((PCNT1)); + _for_each_inner_pcnt_unit!((names(PCNT0_UNIT0), (PCNT0_UNIT1), (PCNT0_UNIT2), + (PCNT0_UNIT3), (PCNT1_UNIT0), (PCNT1_UNIT1), (PCNT1_UNIT2), (PCNT1_UNIT3))); + _for_each_inner_pcnt_unit!((all(PCNT0_UNIT0, Pcnt0Unit0, Pcnt, PCNT, 0, PCNT0, + PCNT0_SIG_CH0, PCNT0_SIG_CH1, PCNT0_CTRL_CH0, PCNT0_CTRL_CH1), (PCNT0_UNIT1, + Pcnt0Unit1, Pcnt, PCNT, 1, PCNT0, PCNT1_SIG_CH0, PCNT1_SIG_CH1, PCNT1_CTRL_CH0, + PCNT1_CTRL_CH1), (PCNT0_UNIT2, Pcnt0Unit2, Pcnt, PCNT, 2, PCNT0, PCNT2_SIG_CH0, + PCNT2_SIG_CH1, PCNT2_CTRL_CH0, PCNT2_CTRL_CH1), (PCNT0_UNIT3, Pcnt0Unit3, Pcnt, + PCNT, 3, PCNT0, PCNT3_SIG_CH0, PCNT3_SIG_CH1, PCNT3_CTRL_CH0, PCNT3_CTRL_CH1), + (PCNT1_UNIT0, Pcnt1Unit0, Pcnt1, PCNT1, 0, PCNT1, PCNT1_U0_SIG_CH0, + PCNT1_U0_SIG_CH1, PCNT1_U0_CTRL_CH0, PCNT1_U0_CTRL_CH1), (PCNT1_UNIT1, + Pcnt1Unit1, Pcnt1, PCNT1, 1, PCNT1, PCNT1_U1_SIG_CH0, PCNT1_U1_SIG_CH1, + PCNT1_U1_CTRL_CH0, PCNT1_U1_CTRL_CH1), (PCNT1_UNIT2, Pcnt1Unit2, Pcnt1, PCNT1, 2, + PCNT1, PCNT1_U2_SIG_CH0, PCNT1_U2_SIG_CH1, PCNT1_U2_CTRL_CH0, PCNT1_U2_CTRL_CH1), + (PCNT1_UNIT3, Pcnt1Unit3, Pcnt1, PCNT1, 3, PCNT1, PCNT1_U3_SIG_CH0, + PCNT1_U3_SIG_CH1, PCNT1_U3_CTRL_CH0, PCNT1_U3_CTRL_CH1))); + _for_each_inner_pcnt_unit!((interrupt(PCNT0), (PCNT1))); + _for_each_inner_pcnt_unit!((regs(PCNT), (PCNT1))); + }; +} +/// This macro can be used to generate code for each peripheral instance of the CAN FD driver. +/// +/// For an explanation on the general syntax, as well as usage of individual/repeated +/// matchers, refer to [the crate-level documentation][crate#for_each-macros]. +/// +/// This macro has one option for its "Individual matcher" case: +/// +/// Syntax: `($instance:ident, $sys:ident, $rx:ident, $tx:ident)` +/// +/// Macro fragments: +/// +/// - `$instance`: the name of the CAN FD instance +/// - `$sys`: the name of the instance as it is in the `esp_hal::system::Peripheral` enum. +/// - `$rx`, `$tx`: signal names. +/// +/// Example data: `(TWAI0, Twai0, TWAI0_RX, TWAI0_TX)` +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! for_each_canfd { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _for_each_inner_canfd { $(($pattern) => $code;)* ($other : tt) => {} + } _for_each_inner_canfd!((all)); + }; +} #[macro_export] #[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] macro_rules! for_each_peripheral { @@ -4563,6 +6365,22 @@ macro_rules! for_each_peripheral { virtual(AXI_PDMA_IN_CH2 : { bind_dma_in_interrupt, enable_dma_in_interrupt, disable_dma_in_interrupt }, AXI_PDMA_OUT_CH2 : { bind_dma_out_interrupt, enable_dma_out_interrupt, disable_dma_out_interrupt }) (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT0_UNIT0 peripheral singleton"] PCNT0_UNIT0 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT0_UNIT1 peripheral singleton"] PCNT0_UNIT1 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT0_UNIT2 peripheral singleton"] PCNT0_UNIT2 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT0_UNIT3 peripheral singleton"] PCNT0_UNIT3 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT1_UNIT0 peripheral singleton"] PCNT1_UNIT0 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT1_UNIT1 peripheral singleton"] PCNT1_UNIT1 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT1_UNIT2 peripheral singleton"] PCNT1_UNIT2 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "PCNT1_UNIT3 peripheral singleton"] PCNT1_UNIT3 <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "SDM_CH0 peripheral singleton"] SDM_CH0 <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "SDM_CH1 peripheral singleton"] SDM_CH1 <= virtual() (unstable))); @@ -4584,10 +6402,19 @@ macro_rules! for_each_peripheral { _for_each_inner_peripheral!((@ peri_type #[doc = "CACHE peripheral singleton"] CACHE <= CACHE() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "CLIC peripheral singleton"] CLIC <= CLIC() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = "CNNT_SYS peripheral singleton"] - CNNT_SYS <= CNNT_SYS() (unstable))); _for_each_inner_peripheral!((@ peri_type - #[doc = "CNNT_IO_MUX peripheral singleton"] CNNT_IO_MUX <= CNNT_IO_MUX() + _for_each_inner_peripheral!((@ peri_type #[doc = "CLINT peripheral singleton"] + CLINT <= CLINT() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "CLINT_OTHER_CORE peripheral singleton"] CLINT_OTHER_CORE <= CLINT_OTHER_CORE() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "CNNT_SYS peripheral singleton"] CNNT_SYS <= CNNT_SYS() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "CNNT_IO_MUX peripheral singleton"] CNNT_IO_MUX <= CNNT_IO_MUX() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "ETH peripheral singleton"] ETH + <= virtual(SBD : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt }) (unstable))); _for_each_inner_peripheral!((@ peri_type + #[doc = "EMAC_DMA peripheral singleton"] EMAC_DMA <= GMAC_DMA() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "EMAC_MAC peripheral singleton"] + EMAC_MAC <= GMAC() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "ECC peripheral singleton"] ECC <= ECC() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "EFUSE peripheral singleton"] EFUSE <= EFUSE() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = @@ -4608,13 +6435,23 @@ macro_rules! for_each_peripheral { _for_each_inner_peripheral!((@ peri_type #[doc = "I2C1 peripheral singleton"] I2C1 <= I2C1(I2C1 : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }))); _for_each_inner_peripheral!((@ peri_type #[doc = + "I2S0 peripheral singleton"] I2S0 <= I2S0(I2S0 : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }) (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "I2S1 peripheral singleton"] + I2S1 <= I2S1(I2S1 : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt }) (unstable))); _for_each_inner_peripheral!((@ peri_type + #[doc = "IEEE802154 peripheral singleton"] IEEE802154 <= IEEE802154(MODEM_ZB_MAC + : { bind_mac_interrupt, enable_mac_interrupt, disable_mac_interrupt }) + (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "INTERRUPT_CORE0 peripheral singleton"] INTERRUPT_CORE0 <= INTERRUPT_CORE0() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "INTERRUPT_CORE1 peripheral singleton"] INTERRUPT_CORE1 <= INTERRUPT_CORE1() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "IO_MUX peripheral singleton"] IO_MUX <= IO_MUX() (unstable))); - _for_each_inner_peripheral!((@ peri_type #[doc = - "IOMUX_MSPI_PIN peripheral singleton"] IOMUX_MSPI_PIN <= IOMUX_MSPI_PIN() + _for_each_inner_peripheral!((@ peri_type #[doc = "LCD_CAM peripheral singleton"] + LCD_CAM <= LCD_CAM(LCD_CAM : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt }) (unstable))); _for_each_inner_peripheral!((@ peri_type + #[doc = "IOMUX_MSPI_PIN peripheral singleton"] IOMUX_MSPI_PIN <= IOMUX_MSPI_PIN() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "LP_AON_CLK_RST peripheral singleton"] LP_AON_CLK_RST <= LP_AON_CLKRST() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = @@ -4637,12 +6474,17 @@ macro_rules! for_each_peripheral { "MODEM_SYSCON peripheral singleton"] MODEM_SYSCON <= MODEM_SYSCON() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "PAU peripheral singleton"] PAU <= PAU() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "PMU peripheral singleton"] PMU <= PMU() (unstable))); + "PCNT peripheral singleton"] PCNT <= PCNT(PCNT0 : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }) (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "PCNT1 peripheral singleton"] + PCNT1 <= PCNT1(PCNT1 : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt }) (unstable))); _for_each_inner_peripheral!((@ peri_type + #[doc = "PMU peripheral singleton"] PMU <= PMU() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "RTC_TIMER peripheral singleton"] RTC_TIMER <= LP_TIMER() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "RNG peripheral singleton"] RNG <= TRNG() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = - "RMT peripheral singleton"] RMT <= virtual(RMT : { bind_peri_interrupt, + "RMT peripheral singleton"] RMT <= RMT(RMT : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "RSA peripheral singleton"] RSA <= RSA(RSA : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt @@ -4692,14 +6534,26 @@ macro_rules! for_each_peripheral { "ADC1 peripheral singleton"] ADC1 <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "ADC2 peripheral singleton"] ADC2 <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + "BT peripheral singleton"] BT <= virtual(MODEM_BT_BB : { bind_bb_interrupt, + enable_bb_interrupt, disable_bb_interrupt }, MODEM_LP_TIMER : { + bind_lp_timer_interrupt, enable_lp_timer_interrupt, disable_lp_timer_interrupt }, + MODEM_BT_MAC : { bind_mac_interrupt, enable_mac_interrupt, disable_mac_interrupt + }) (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "FLASH peripheral singleton"] FLASH <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "PSRAM peripheral singleton"] PSRAM <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "GPIO_DEDICATED peripheral singleton"] GPIO_DEDICATED <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "WIFI peripheral singleton"] + WIFI <= virtual(MODEM_WIFI_BB : { bind_bb_interrupt, enable_bb_interrupt, + disable_bb_interrupt }, MODEM_WIFI_MAC : { bind_mac_interrupt, + enable_mac_interrupt, disable_mac_interrupt }, MODEM_WIFI_PWR : { + bind_pwr_interrupt, enable_pwr_interrupt, disable_pwr_interrupt }))); _for_each_inner_peripheral!((@ peri_type #[doc = "CPU_CTRL peripheral singleton"] CPU_CTRL <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type - #[doc = "FROM_CPU_INTR0 peripheral singleton"] FROM_CPU_INTR0 <= virtual() - (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = + #[doc = "IPC peripheral singleton"] IPC <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = + "FROM_CPU_INTR0 peripheral singleton"] FROM_CPU_INTR0 <= virtual() (unstable))); + _for_each_inner_peripheral!((@ peri_type #[doc = "FROM_CPU_INTR1 peripheral singleton"] FROM_CPU_INTR1 <= virtual() (unstable))); _for_each_inner_peripheral!((@ peri_type #[doc = "FROM_CPU_INTR2 peripheral singleton"] FROM_CPU_INTR2 <= virtual() (unstable))); @@ -4744,6 +6598,14 @@ macro_rules! for_each_peripheral { _for_each_inner_peripheral!((DMA_AXI_CH0(unstable))); _for_each_inner_peripheral!((DMA_AXI_CH1(unstable))); _for_each_inner_peripheral!((DMA_AXI_CH2(unstable))); + _for_each_inner_peripheral!((PCNT0_UNIT0(unstable))); + _for_each_inner_peripheral!((PCNT0_UNIT1(unstable))); + _for_each_inner_peripheral!((PCNT0_UNIT2(unstable))); + _for_each_inner_peripheral!((PCNT0_UNIT3(unstable))); + _for_each_inner_peripheral!((PCNT1_UNIT0(unstable))); + _for_each_inner_peripheral!((PCNT1_UNIT1(unstable))); + _for_each_inner_peripheral!((PCNT1_UNIT2(unstable))); + _for_each_inner_peripheral!((PCNT1_UNIT3(unstable))); _for_each_inner_peripheral!((SDM_CH0(unstable))); _for_each_inner_peripheral!((SDM_CH1(unstable))); _for_each_inner_peripheral!((SDM_CH2(unstable))); @@ -4757,6 +6619,9 @@ macro_rules! for_each_peripheral { _for_each_inner_peripheral!((ASSIST_DEBUG(unstable))); _for_each_inner_peripheral!((CACHE(unstable))); _for_each_inner_peripheral!((CLIC(unstable))); + _for_each_inner_peripheral!((CLINT(unstable))); + _for_each_inner_peripheral!((CLINT_OTHER_CORE(unstable))); + _for_each_inner_peripheral!((ETH(unstable))); _for_each_inner_peripheral!((ECC(unstable))); _for_each_inner_peripheral!((GPIO(unstable))); _for_each_inner_peripheral!((GPIO_SD(unstable))); @@ -4766,9 +6631,13 @@ macro_rules! for_each_peripheral { _for_each_inner_peripheral!((HP_ALIVE_SYS(unstable))); _for_each_inner_peripheral!((HP_SYS_CLKRST(unstable))); _for_each_inner_peripheral!((I2C0)); _for_each_inner_peripheral!((I2C1)); + _for_each_inner_peripheral!((I2S0(unstable))); + _for_each_inner_peripheral!((I2S1(unstable))); + _for_each_inner_peripheral!((IEEE802154(unstable))); _for_each_inner_peripheral!((INTERRUPT_CORE0(unstable))); _for_each_inner_peripheral!((INTERRUPT_CORE1(unstable))); _for_each_inner_peripheral!((IO_MUX(unstable))); + _for_each_inner_peripheral!((LCD_CAM(unstable))); _for_each_inner_peripheral!((LP_AON_CLK_RST(unstable))); _for_each_inner_peripheral!((LP_APM(unstable))); _for_each_inner_peripheral!((LP_GPIO(unstable))); @@ -4782,6 +6651,8 @@ macro_rules! for_each_peripheral { _for_each_inner_peripheral!((MODEM_LPCON(unstable))); _for_each_inner_peripheral!((MODEM_SYSCON(unstable))); _for_each_inner_peripheral!((PAU(unstable))); + _for_each_inner_peripheral!((PCNT(unstable))); + _for_each_inner_peripheral!((PCNT1(unstable))); _for_each_inner_peripheral!((PMU(unstable))); _for_each_inner_peripheral!((RTC_TIMER(unstable))); _for_each_inner_peripheral!((RNG(unstable))); @@ -4806,18 +6677,24 @@ macro_rules! for_each_peripheral { _for_each_inner_peripheral!((USB_HS(unstable))); _for_each_inner_peripheral!((ADC1(unstable))); _for_each_inner_peripheral!((ADC2(unstable))); + _for_each_inner_peripheral!((BT(unstable))); _for_each_inner_peripheral!((FLASH(unstable))); _for_each_inner_peripheral!((PSRAM(unstable))); _for_each_inner_peripheral!((GPIO_DEDICATED(unstable))); + _for_each_inner_peripheral!((WIFI)); _for_each_inner_peripheral!((CPU_CTRL(unstable))); + _for_each_inner_peripheral!((IPC(unstable))); _for_each_inner_peripheral!((FROM_CPU_INTR0(unstable))); _for_each_inner_peripheral!((FROM_CPU_INTR1(unstable))); _for_each_inner_peripheral!((FROM_CPU_INTR2(unstable))); _for_each_inner_peripheral!((FROM_CPU_INTR3(unstable))); _for_each_inner_peripheral!((UHCI0, Uhci0, 0, AhbGdmaChannel)); + _for_each_inner_peripheral!((LCD_CAM, LcdCam, 0, AxiGdmaChannel)); + _for_each_inner_peripheral!((I2S0, I2s0, 1, AhbGdmaChannel)); _for_each_inner_peripheral!((SPI2, Spi2, 1, AxiGdmaChannel)); _for_each_inner_peripheral!((SPI3, Spi3, 2, AxiGdmaChannel)); _for_each_inner_peripheral!((AES, Aes, 4, AxiGdmaChannel)); + _for_each_inner_peripheral!((I2S1, I2s1, 5, AhbGdmaChannel)); _for_each_inner_peripheral!((SHA, Sha, 5, AxiGdmaChannel)); _for_each_inner_peripheral!((all(@ peri_type #[doc = "GPIO0 peripheral singleton"] GPIO0 <= virtual()), (@ peri_type #[doc = @@ -5019,24 +6896,42 @@ macro_rules! for_each_peripheral { bind_dma_in_interrupt, enable_dma_in_interrupt, disable_dma_in_interrupt }, AXI_PDMA_OUT_CH2 : { bind_dma_out_interrupt, enable_dma_out_interrupt, disable_dma_out_interrupt }) (unstable)), (@ peri_type #[doc = - "SDM_CH0 peripheral singleton"] SDM_CH0 <= virtual() (unstable)), (@ peri_type - #[doc = "SDM_CH1 peripheral singleton"] SDM_CH1 <= virtual() (unstable)), (@ - peri_type #[doc = "SDM_CH2 peripheral singleton"] SDM_CH2 <= virtual() - (unstable)), (@ peri_type #[doc = "SDM_CH3 peripheral singleton"] SDM_CH3 <= - virtual() (unstable)), (@ peri_type #[doc = "SDM_CH4 peripheral singleton"] - SDM_CH4 <= virtual() (unstable)), (@ peri_type #[doc = - "SDM_CH5 peripheral singleton"] SDM_CH5 <= virtual() (unstable)), (@ peri_type - #[doc = "SDM_CH6 peripheral singleton"] SDM_CH6 <= virtual() (unstable)), (@ - peri_type #[doc = "SDM_CH7 peripheral singleton"] SDM_CH7 <= virtual() - (unstable)), (@ peri_type #[doc = "AES peripheral singleton"] AES <= AES(AES : { - bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) - (unstable)), (@ peri_type #[doc = "APB_SARADC peripheral singleton"] APB_SARADC - <= ADC() (unstable)), (@ peri_type #[doc = "ASSIST_DEBUG peripheral singleton"] - ASSIST_DEBUG <= ASSIST_DEBUG() (unstable)), (@ peri_type #[doc = - "CACHE peripheral singleton"] CACHE <= CACHE() (unstable)), (@ peri_type #[doc = - "CLIC peripheral singleton"] CLIC <= CLIC() (unstable)), (@ peri_type #[doc = - "CNNT_SYS peripheral singleton"] CNNT_SYS <= CNNT_SYS() (unstable)), (@ peri_type - #[doc = "CNNT_IO_MUX peripheral singleton"] CNNT_IO_MUX <= CNNT_IO_MUX() + "PCNT0_UNIT0 peripheral singleton"] PCNT0_UNIT0 <= virtual() (unstable)), (@ + peri_type #[doc = "PCNT0_UNIT1 peripheral singleton"] PCNT0_UNIT1 <= virtual() + (unstable)), (@ peri_type #[doc = "PCNT0_UNIT2 peripheral singleton"] PCNT0_UNIT2 + <= virtual() (unstable)), (@ peri_type #[doc = + "PCNT0_UNIT3 peripheral singleton"] PCNT0_UNIT3 <= virtual() (unstable)), (@ + peri_type #[doc = "PCNT1_UNIT0 peripheral singleton"] PCNT1_UNIT0 <= virtual() + (unstable)), (@ peri_type #[doc = "PCNT1_UNIT1 peripheral singleton"] PCNT1_UNIT1 + <= virtual() (unstable)), (@ peri_type #[doc = + "PCNT1_UNIT2 peripheral singleton"] PCNT1_UNIT2 <= virtual() (unstable)), (@ + peri_type #[doc = "PCNT1_UNIT3 peripheral singleton"] PCNT1_UNIT3 <= virtual() + (unstable)), (@ peri_type #[doc = "SDM_CH0 peripheral singleton"] SDM_CH0 <= + virtual() (unstable)), (@ peri_type #[doc = "SDM_CH1 peripheral singleton"] + SDM_CH1 <= virtual() (unstable)), (@ peri_type #[doc = + "SDM_CH2 peripheral singleton"] SDM_CH2 <= virtual() (unstable)), (@ peri_type + #[doc = "SDM_CH3 peripheral singleton"] SDM_CH3 <= virtual() (unstable)), (@ + peri_type #[doc = "SDM_CH4 peripheral singleton"] SDM_CH4 <= virtual() + (unstable)), (@ peri_type #[doc = "SDM_CH5 peripheral singleton"] SDM_CH5 <= + virtual() (unstable)), (@ peri_type #[doc = "SDM_CH6 peripheral singleton"] + SDM_CH6 <= virtual() (unstable)), (@ peri_type #[doc = + "SDM_CH7 peripheral singleton"] SDM_CH7 <= virtual() (unstable)), (@ peri_type + #[doc = "AES peripheral singleton"] AES <= AES(AES : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc + = "APB_SARADC peripheral singleton"] APB_SARADC <= ADC() (unstable)), (@ + peri_type #[doc = "ASSIST_DEBUG peripheral singleton"] ASSIST_DEBUG <= + ASSIST_DEBUG() (unstable)), (@ peri_type #[doc = "CACHE peripheral singleton"] + CACHE <= CACHE() (unstable)), (@ peri_type #[doc = "CLIC peripheral singleton"] + CLIC <= CLIC() (unstable)), (@ peri_type #[doc = "CLINT peripheral singleton"] + CLINT <= CLINT() (unstable)), (@ peri_type #[doc = + "CLINT_OTHER_CORE peripheral singleton"] CLINT_OTHER_CORE <= CLINT_OTHER_CORE() + (unstable)), (@ peri_type #[doc = "CNNT_SYS peripheral singleton"] CNNT_SYS <= + CNNT_SYS() (unstable)), (@ peri_type #[doc = "CNNT_IO_MUX peripheral singleton"] + CNNT_IO_MUX <= CNNT_IO_MUX() (unstable)), (@ peri_type #[doc = + "ETH peripheral singleton"] ETH <= virtual(SBD : { bind_peri_interrupt, + enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc + = "EMAC_DMA peripheral singleton"] EMAC_DMA <= GMAC_DMA() (unstable)), (@ + peri_type #[doc = "EMAC_MAC peripheral singleton"] EMAC_MAC <= GMAC() (unstable)), (@ peri_type #[doc = "ECC peripheral singleton"] ECC <= ECC() (unstable)), (@ peri_type #[doc = "EFUSE peripheral singleton"] EFUSE <= EFUSE() (unstable)), (@ peri_type #[doc = "GPIO peripheral singleton"] GPIO <= GPIO() @@ -5052,11 +6947,20 @@ macro_rules! for_each_peripheral { : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt })), (@ peri_type #[doc = "I2C1 peripheral singleton"] I2C1 <= I2C1(I2C1 : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt })), (@ - peri_type #[doc = "INTERRUPT_CORE0 peripheral singleton"] INTERRUPT_CORE0 <= - INTERRUPT_CORE0() (unstable)), (@ peri_type #[doc = - "INTERRUPT_CORE1 peripheral singleton"] INTERRUPT_CORE1 <= INTERRUPT_CORE1() - (unstable)), (@ peri_type #[doc = "IO_MUX peripheral singleton"] IO_MUX <= - IO_MUX() (unstable)), (@ peri_type #[doc = "IOMUX_MSPI_PIN peripheral singleton"] + peri_type #[doc = "I2S0 peripheral singleton"] I2S0 <= I2S0(I2S0 : { + bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) + (unstable)), (@ peri_type #[doc = "I2S1 peripheral singleton"] I2S1 <= I2S1(I2S1 + : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) + (unstable)), (@ peri_type #[doc = "IEEE802154 peripheral singleton"] IEEE802154 + <= IEEE802154(MODEM_ZB_MAC : { bind_mac_interrupt, enable_mac_interrupt, + disable_mac_interrupt }) (unstable)), (@ peri_type #[doc = + "INTERRUPT_CORE0 peripheral singleton"] INTERRUPT_CORE0 <= INTERRUPT_CORE0() + (unstable)), (@ peri_type #[doc = "INTERRUPT_CORE1 peripheral singleton"] + INTERRUPT_CORE1 <= INTERRUPT_CORE1() (unstable)), (@ peri_type #[doc = + "IO_MUX peripheral singleton"] IO_MUX <= IO_MUX() (unstable)), (@ peri_type #[doc + = "LCD_CAM peripheral singleton"] LCD_CAM <= LCD_CAM(LCD_CAM : { + bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) + (unstable)), (@ peri_type #[doc = "IOMUX_MSPI_PIN peripheral singleton"] IOMUX_MSPI_PIN <= IOMUX_MSPI_PIN() (unstable)), (@ peri_type #[doc = "LP_AON_CLK_RST peripheral singleton"] LP_AON_CLK_RST <= LP_AON_CLKRST() (unstable)), (@ peri_type #[doc = "LP_APM peripheral singleton"] LP_APM <= @@ -5074,11 +6978,16 @@ macro_rules! for_each_peripheral { MODEM_LPCON() (unstable)), (@ peri_type #[doc = "MODEM_SYSCON peripheral singleton"] MODEM_SYSCON <= MODEM_SYSCON() (unstable)), (@ peri_type #[doc = "PAU peripheral singleton"] PAU <= PAU() (unstable)), (@ - peri_type #[doc = "PMU peripheral singleton"] PMU <= PMU() (unstable)), (@ - peri_type #[doc = "RTC_TIMER peripheral singleton"] RTC_TIMER <= LP_TIMER() - (unstable)), (@ peri_type #[doc = "RNG peripheral singleton"] RNG <= TRNG() - (unstable)), (@ peri_type #[doc = "RMT peripheral singleton"] RMT <= virtual(RMT - : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) + peri_type #[doc = "PCNT peripheral singleton"] PCNT <= PCNT(PCNT0 : { + bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) + (unstable)), (@ peri_type #[doc = "PCNT1 peripheral singleton"] PCNT1 <= + PCNT1(PCNT1 : { bind_peri_interrupt, enable_peri_interrupt, + disable_peri_interrupt }) (unstable)), (@ peri_type #[doc = + "PMU peripheral singleton"] PMU <= PMU() (unstable)), (@ peri_type #[doc = + "RTC_TIMER peripheral singleton"] RTC_TIMER <= LP_TIMER() (unstable)), (@ + peri_type #[doc = "RNG peripheral singleton"] RNG <= TRNG() (unstable)), (@ + peri_type #[doc = "RMT peripheral singleton"] RMT <= RMT(RMT : { + bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc = "RSA peripheral singleton"] RSA <= RSA(RSA : { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc = "SPI0 peripheral singleton"] SPI0 <= SPI0() @@ -5115,17 +7024,28 @@ macro_rules! for_each_peripheral { bind_peri_interrupt, enable_peri_interrupt, disable_peri_interrupt }) (unstable)), (@ peri_type #[doc = "ADC1 peripheral singleton"] ADC1 <= virtual() (unstable)), (@ peri_type #[doc = "ADC2 peripheral singleton"] ADC2 <= virtual() - (unstable)), (@ peri_type #[doc = "FLASH peripheral singleton"] FLASH <= - virtual() (unstable)), (@ peri_type #[doc = "PSRAM peripheral singleton"] PSRAM - <= virtual() (unstable)), (@ peri_type #[doc = + (unstable)), (@ peri_type #[doc = "BT peripheral singleton"] BT <= + virtual(MODEM_BT_BB : { bind_bb_interrupt, enable_bb_interrupt, + disable_bb_interrupt }, MODEM_LP_TIMER : { bind_lp_timer_interrupt, + enable_lp_timer_interrupt, disable_lp_timer_interrupt }, MODEM_BT_MAC : { + bind_mac_interrupt, enable_mac_interrupt, disable_mac_interrupt }) (unstable)), + (@ peri_type #[doc = "FLASH peripheral singleton"] FLASH <= virtual() + (unstable)), (@ peri_type #[doc = "PSRAM peripheral singleton"] PSRAM <= + virtual() (unstable)), (@ peri_type #[doc = "GPIO_DEDICATED peripheral singleton"] GPIO_DEDICATED <= virtual() (unstable)), - (@ peri_type #[doc = "CPU_CTRL peripheral singleton"] CPU_CTRL <= virtual() - (unstable)), (@ peri_type #[doc = "FROM_CPU_INTR0 peripheral singleton"] - FROM_CPU_INTR0 <= virtual() (unstable)), (@ peri_type #[doc = - "FROM_CPU_INTR1 peripheral singleton"] FROM_CPU_INTR1 <= virtual() (unstable)), - (@ peri_type #[doc = "FROM_CPU_INTR2 peripheral singleton"] FROM_CPU_INTR2 <= + (@ peri_type #[doc = "WIFI peripheral singleton"] WIFI <= virtual(MODEM_WIFI_BB : + { bind_bb_interrupt, enable_bb_interrupt, disable_bb_interrupt }, MODEM_WIFI_MAC + : { bind_mac_interrupt, enable_mac_interrupt, disable_mac_interrupt }, + MODEM_WIFI_PWR : { bind_pwr_interrupt, enable_pwr_interrupt, + disable_pwr_interrupt })), (@ peri_type #[doc = "CPU_CTRL peripheral singleton"] + CPU_CTRL <= virtual() (unstable)), (@ peri_type #[doc = + "IPC peripheral singleton"] IPC <= virtual() (unstable)), (@ peri_type #[doc = + "FROM_CPU_INTR0 peripheral singleton"] FROM_CPU_INTR0 <= virtual() (unstable)), + (@ peri_type #[doc = "FROM_CPU_INTR1 peripheral singleton"] FROM_CPU_INTR1 <= virtual() (unstable)), (@ peri_type #[doc = - "FROM_CPU_INTR3 peripheral singleton"] FROM_CPU_INTR3 <= virtual() (unstable)))); + "FROM_CPU_INTR2 peripheral singleton"] FROM_CPU_INTR2 <= virtual() (unstable)), + (@ peri_type #[doc = "FROM_CPU_INTR3 peripheral singleton"] FROM_CPU_INTR3 <= + virtual() (unstable)))); _for_each_inner_peripheral!((singletons(#[cfg(not(use_xtal32k))] GPIO0), (#[cfg(not(use_xtal32k))] GPIO1), (GPIO2), (GPIO3), (GPIO4), (GPIO5), (GPIO6), (GPIO7), (GPIO8), (GPIO9), (GPIO10), (GPIO11), (GPIO12), (GPIO13), (GPIO14), @@ -5137,30 +7057,38 @@ macro_rules! for_each_peripheral { (GPIO57), (GPIO58), (GPIO59), (GPIO60), (GPIO61), (DMA_CH0(unstable)), (DMA_CH1(unstable)), (DMA_CH2(unstable)), (DMA_CH3(unstable)), (DMA_CH4(unstable)), (DMA_AXI_CH0(unstable)), (DMA_AXI_CH1(unstable)), - (DMA_AXI_CH2(unstable)), (SDM_CH0(unstable)), (SDM_CH1(unstable)), - (SDM_CH2(unstable)), (SDM_CH3(unstable)), (SDM_CH4(unstable)), - (SDM_CH5(unstable)), (SDM_CH6(unstable)), (SDM_CH7(unstable)), (AES(unstable)), + (DMA_AXI_CH2(unstable)), (PCNT0_UNIT0(unstable)), (PCNT0_UNIT1(unstable)), + (PCNT0_UNIT2(unstable)), (PCNT0_UNIT3(unstable)), (PCNT1_UNIT0(unstable)), + (PCNT1_UNIT1(unstable)), (PCNT1_UNIT2(unstable)), (PCNT1_UNIT3(unstable)), + (SDM_CH0(unstable)), (SDM_CH1(unstable)), (SDM_CH2(unstable)), + (SDM_CH3(unstable)), (SDM_CH4(unstable)), (SDM_CH5(unstable)), + (SDM_CH6(unstable)), (SDM_CH7(unstable)), (AES(unstable)), (APB_SARADC(unstable)), (ASSIST_DEBUG(unstable)), (CACHE(unstable)), - (CLIC(unstable)), (ECC(unstable)), (GPIO(unstable)), (GPIO_SD(unstable)), + (CLIC(unstable)), (CLINT(unstable)), (CLINT_OTHER_CORE(unstable)), + (ETH(unstable)), (ECC(unstable)), (GPIO(unstable)), (GPIO_SD(unstable)), (HP_APM(unstable)), (HP_MEM_APM(unstable)), (HP_SYS(unstable)), (HP_ALIVE_SYS(unstable)), (HP_SYS_CLKRST(unstable)), (I2C0), (I2C1), + (I2S0(unstable)), (I2S1(unstable)), (IEEE802154(unstable)), (INTERRUPT_CORE0(unstable)), (INTERRUPT_CORE1(unstable)), (IO_MUX(unstable)), - (LP_AON_CLK_RST(unstable)), (LP_APM(unstable)), (LP_GPIO(unstable)), - (LP_IO_MUX(unstable)), (LP_PERI(unstable)), (LP_SYS(unstable)), - (LP_TEE(unstable)), (LP_WDT(unstable)), (LPWR(unstable)), + (LCD_CAM(unstable)), (LP_AON_CLK_RST(unstable)), (LP_APM(unstable)), + (LP_GPIO(unstable)), (LP_IO_MUX(unstable)), (LP_PERI(unstable)), + (LP_SYS(unstable)), (LP_TEE(unstable)), (LP_WDT(unstable)), (LPWR(unstable)), (MEM_MONITOR(unstable)), (MODEM_LPCON(unstable)), (MODEM_SYSCON(unstable)), - (PAU(unstable)), (PMU(unstable)), (RTC_TIMER(unstable)), (RNG(unstable)), - (RMT(unstable)), (RSA(unstable)), (SPI0(unstable)), (SPI1(unstable)), (SPI2), - (SPI3), (AXI_GDMA(unstable)), (DMA(unstable)), (SHA(unstable)), - (SYSTEM(unstable)), (SYSTIMER(unstable)), (SDHOST(unstable)), (TEE(unstable)), - (TIMG0(unstable)), (TIMG1(unstable)), (UART0), (UART1), (UART2), (UART3), - (UHCI0(unstable)), (USB_DEVICE(unstable)), (USB_HS(unstable)), (ADC1(unstable)), - (ADC2(unstable)), (FLASH(unstable)), (PSRAM(unstable)), - (GPIO_DEDICATED(unstable)), (CPU_CTRL(unstable)), (FROM_CPU_INTR0(unstable)), + (PAU(unstable)), (PCNT(unstable)), (PCNT1(unstable)), (PMU(unstable)), + (RTC_TIMER(unstable)), (RNG(unstable)), (RMT(unstable)), (RSA(unstable)), + (SPI0(unstable)), (SPI1(unstable)), (SPI2), (SPI3), (AXI_GDMA(unstable)), + (DMA(unstable)), (SHA(unstable)), (SYSTEM(unstable)), (SYSTIMER(unstable)), + (SDHOST(unstable)), (TEE(unstable)), (TIMG0(unstable)), (TIMG1(unstable)), + (UART0), (UART1), (UART2), (UART3), (UHCI0(unstable)), (USB_DEVICE(unstable)), + (USB_HS(unstable)), (ADC1(unstable)), (ADC2(unstable)), (BT(unstable)), + (FLASH(unstable)), (PSRAM(unstable)), (GPIO_DEDICATED(unstable)), (WIFI), + (CPU_CTRL(unstable)), (IPC(unstable)), (FROM_CPU_INTR0(unstable)), (FROM_CPU_INTR1(unstable)), (FROM_CPU_INTR2(unstable)), (FROM_CPU_INTR3(unstable)))); _for_each_inner_peripheral!((dma_eligible(UHCI0, - Uhci0, 0, AhbGdmaChannel), (SPI2, Spi2, 1, AxiGdmaChannel), (SPI3, Spi3, 2, - AxiGdmaChannel), (AES, Aes, 4, AxiGdmaChannel), (SHA, Sha, 5, AxiGdmaChannel))); + Uhci0, 0, AhbGdmaChannel), (LCD_CAM, LcdCam, 0, AxiGdmaChannel), (I2S0, I2s0, 1, + AhbGdmaChannel), (SPI2, Spi2, 1, AxiGdmaChannel), (SPI3, Spi3, 2, + AxiGdmaChannel), (AES, Aes, 4, AxiGdmaChannel), (I2S1, I2s1, 5, AhbGdmaChannel), + (SHA, Sha, 5, AxiGdmaChannel))); }; } /// This macro can be used to generate code for each `GPIOn` instance. @@ -5196,187 +7124,158 @@ macro_rules! for_each_gpio { macro_rules! _for_each_inner_gpio { $(($pattern) => $code;)* ($other : tt) => {} } _for_each_inner_gpio!((0, GPIO0() () ([Input] [Output]))); _for_each_inner_gpio!((1, GPIO1() () ([Input] [Output]))); - _for_each_inner_gpio!((2, GPIO2(_3 => LCD_DATA19) (_3 => LCD_DATA19) ([Input] - [Output]))); _for_each_inner_gpio!((3, GPIO3(_3 => LCD_DATA20) (_3 => LCD_DATA20) - ([Input] [Output]))); _for_each_inner_gpio!((4, GPIO4(_3 => LCD_DATA21) (_3 => - LCD_DATA21) ([Input] [Output]))); _for_each_inner_gpio!((5, GPIO5(_3 => - LCD_DATA22) (_3 => LCD_DATA22) ([Input] [Output]))); _for_each_inner_gpio!((6, - GPIO6() () ([Input] [Output]))); _for_each_inner_gpio!((7, GPIO7(_3 => - LCD_DATA23) (_3 => LCD_DATA23) ([Input] [Output]))); _for_each_inner_gpio!((8, - GPIO8(_2 => GMAC_PHY_TXD0 _3 => LCD_DATA0) (_2 => GMAC_PHY_TXD0 _3 => LCD_DATA0) - ([Input] [Output]))); _for_each_inner_gpio!((9, GPIO9(_0 => FSPIHD _2 => - GMAC_PHY_TXD1 _3 => LCD_DATA1 _4 => DBG_PSRAM_CK) (_0 => FSPIHD _2 => - GMAC_PHY_TXD1 _3 => LCD_DATA1 _4 => DBG_PSRAM_CK) ([Input] [Output]))); - _for_each_inner_gpio!((10, GPIO10(_0 => FSPICS0 _2 => GMAC_PHY_TXD2 _3 => - LCD_DATA2 _4 => DBG_PSRAM_CS) (_0 => FSPICS0 _2 => GMAC_PHY_TXD2 _3 => LCD_DATA2 - _4 => DBG_PSRAM_CS) ([Input] [Output]))); _for_each_inner_gpio!((11, GPIO11(_0 => - FSPID _2 => GMAC_PHY_TXD3 _3 => LCD_DATA3 _4 => DBG_PSRAM_D) (_0 => FSPID _2 => - GMAC_PHY_TXD3 _3 => LCD_DATA3 _4 => DBG_PSRAM_D) ([Input] [Output]))); - _for_each_inner_gpio!((12, GPIO12(_0 => FSPICLK _2 => GMAC_PHY_TXEN _3 => - LCD_DATA4 _4 => DBG_PSRAM_Q) (_0 => FSPICLK _2 => GMAC_PHY_TXEN _3 => LCD_DATA4 - _4 => DBG_PSRAM_Q) ([Input] [Output]))); _for_each_inner_gpio!((13, GPIO13(_0 => - FSPIQ _2 => GMAC_RMII_CLK _3 => LCD_DATA5 _4 => DBG_PSRAM_WP) (_0 => FSPIQ _2 => - GMAC_RMII_CLK _3 => LCD_DATA5 _4 => DBG_PSRAM_WP) ([Input] [Output]))); - _for_each_inner_gpio!((14, GPIO14(_0 => FSPIWP _2 => GMAC_RX_CLK _3 => LCD_DATA6 - _4 => DBG_PSRAM_HOLD) (_0 => FSPIWP _2 => GMAC_RX_CLK _3 => LCD_DATA6 _4 => - DBG_PSRAM_HOLD) ([Input] [Output]))); _for_each_inner_gpio!((15, GPIO15(_0 => - FSPIIO4 _2 => GMAC_PHY_RXDV _3 => LCD_DATA7 _4 => DBG_PSRAM_DQ4) (_0 => FSPIIO4 - _2 => GMAC_PHY_RXDV _3 => LCD_DATA7 _4 => DBG_PSRAM_DQ4) ([Input] [Output]))); - _for_each_inner_gpio!((16, GPIO16(_0 => FSPIIO5 _2 => GMAC_PHY_RXD3 _3 => - LCD_DATA8 _4 => DBG_PSRAM_DQ5) (_0 => FSPIIO5 _2 => GMAC_PHY_RXD3 _3 => LCD_DATA8 - _4 => DBG_PSRAM_DQ5) ([Input] [Output]))); _for_each_inner_gpio!((17, GPIO17(_0 - => FSPIIO6 _2 => GMAC_PHY_RXD2 _3 => LCD_DATA9 _4 => DBG_PSRAM_DQ6) (_0 => - FSPIIO6 _2 => GMAC_PHY_RXD2 _3 => LCD_DATA9 _4 => DBG_PSRAM_DQ6) ([Input] - [Output]))); _for_each_inner_gpio!((18, GPIO18(_0 => FSPIIO7 _2 => GMAC_PHY_RXD1 - _3 => LCD_DATA10 _4 => DBG_PSRAM_DQ7) (_0 => FSPIIO7 _2 => GMAC_PHY_RXD1 _3 => - LCD_DATA10 _4 => DBG_PSRAM_DQ7) ([Input] [Output]))); _for_each_inner_gpio!((19, - GPIO19(_2 => GMAC_PHY_RXD0 _3 => LCD_DATA11 _4 => DBG_PSRAM_DQS_0) (_0 => FSPIDQS - _2 => GMAC_PHY_RXD0 _3 => LCD_DATA11 _4 => DBG_PSRAM_DQS_0) ([Input] [Output]))); - _for_each_inner_gpio!((20, GPIO20(_0 => SD1_DATA0 _2 => FSPICLK _4 => - DBG_FLASH_CK) (_0 => SD1_DATA0 _2 => FSPICLK _4 => DBG_FLASH_CK) ([Input] - [Output]))); _for_each_inner_gpio!((21, GPIO21(_0 => SD1_DATA1 _2 => FSPID _4 => - DBG_FLASH_D) (_0 => SD1_DATA1 _2 => FSPID _4 => DBG_FLASH_D) ([Input] - [Output]))); _for_each_inner_gpio!((22, GPIO22(_0 => SD1_DATA2 _2 => FSPIQ _4 => + _for_each_inner_gpio!((2, GPIO2() (_3 => LCD_DATA_19) ([Input] [Output]))); + _for_each_inner_gpio!((3, GPIO3() (_3 => LCD_DATA_20) ([Input] [Output]))); + _for_each_inner_gpio!((4, GPIO4() (_3 => LCD_DATA_21) ([Input] [Output]))); + _for_each_inner_gpio!((5, GPIO5() (_3 => LCD_DATA_22) ([Input] [Output]))); + _for_each_inner_gpio!((6, GPIO6() () ([Input] [Output]))); + _for_each_inner_gpio!((7, GPIO7() (_3 => LCD_DATA_23) ([Input] [Output]))); + _for_each_inner_gpio!((8, GPIO8() (_2 => EMAC_TXD0 _3 => LCD_DATA_0) ([Input] + [Output]))); _for_each_inner_gpio!((9, GPIO9(_0 => FSPIHD _4 => DBG_PSRAM_CK) (_0 + => FSPIHD _2 => EMAC_TXD1 _3 => LCD_DATA_1 _4 => DBG_PSRAM_CK) ([Input] + [Output]))); _for_each_inner_gpio!((10, GPIO10(_0 => FSPICS0 _4 => DBG_PSRAM_CS) + (_0 => FSPICS0 _2 => EMAC_TXD2 _3 => LCD_DATA_2 _4 => DBG_PSRAM_CS) ([Input] + [Output]))); _for_each_inner_gpio!((11, GPIO11(_0 => FSPID _4 => DBG_PSRAM_D) (_0 + => FSPID _2 => EMAC_TXD3 _3 => LCD_DATA_3 _4 => DBG_PSRAM_D) ([Input] + [Output]))); _for_each_inner_gpio!((12, GPIO12(_0 => FSPICLK _4 => DBG_PSRAM_Q) + (_0 => FSPICLK _2 => EMAC_TXEN _3 => LCD_DATA_4 _4 => DBG_PSRAM_Q) ([Input] + [Output]))); _for_each_inner_gpio!((13, GPIO13(_0 => FSPIQ _2 => EMAC_RMII_CLK _4 + => DBG_PSRAM_WP) (_0 => FSPIQ _2 => EMAC_RMII_CLK _3 => LCD_DATA_5 _4 => + DBG_PSRAM_WP) ([Input] [Output]))); _for_each_inner_gpio!((14, GPIO14(_0 => + FSPIWP _2 => EMAC_RX_CLK _4 => DBG_PSRAM_HOLD) (_0 => FSPIWP _3 => LCD_DATA_6 _4 + => DBG_PSRAM_HOLD) ([Input] [Output]))); _for_each_inner_gpio!((15, GPIO15(_0 => + FSPIIO4 _2 => EMAC_RXDV _4 => DBG_PSRAM_DQ4) (_0 => FSPIIO4 _3 => LCD_DATA_7 _4 + => DBG_PSRAM_DQ4) ([Input] [Output]))); _for_each_inner_gpio!((16, GPIO16(_0 => + FSPIIO5 _2 => EMAC_RXD3 _4 => DBG_PSRAM_DQ5) (_0 => FSPIIO5 _3 => LCD_DATA_8 _4 + => DBG_PSRAM_DQ5) ([Input] [Output]))); _for_each_inner_gpio!((17, GPIO17(_0 => + FSPIIO6 _2 => EMAC_RXD2 _4 => DBG_PSRAM_DQ6) (_0 => FSPIIO6 _3 => LCD_DATA_9 _4 + => DBG_PSRAM_DQ6) ([Input] [Output]))); _for_each_inner_gpio!((18, GPIO18(_0 => + FSPIIO7 _2 => EMAC_RXD1 _4 => DBG_PSRAM_DQ7) (_0 => FSPIIO7 _3 => LCD_DATA_10 _4 + => DBG_PSRAM_DQ7) ([Input] [Output]))); _for_each_inner_gpio!((19, GPIO19(_2 => + EMAC_RXD0 _4 => DBG_PSRAM_DQS_0) (_0 => FSPIDQS _3 => LCD_DATA_11 _4 => + DBG_PSRAM_DQS_0) ([Input] [Output]))); _for_each_inner_gpio!((20, GPIO20(_0 => + SD1_DATA0 _2 => FSPICLK _4 => DBG_FLASH_CK) (_0 => SD1_DATA0 _2 => FSPICLK _4 => + DBG_FLASH_CK) ([Input] [Output]))); _for_each_inner_gpio!((21, GPIO21(_0 => + SD1_DATA1 _2 => FSPID _4 => DBG_FLASH_D) (_0 => SD1_DATA1 _2 => FSPID _4 => + DBG_FLASH_D) ([Input] [Output]))); _for_each_inner_gpio!((22, GPIO22(_0 => + SD1_DATA2 _2 => FSPIQ _4 => DBG_FLASH_CS) (_0 => SD1_DATA2 _2 => FSPIQ _4 => + DBG_FLASH_CS) ([Input] [Output]))); _for_each_inner_gpio!((23, GPIO23(_0 => + SD1_DATA3 _2 => FSPICS0 _4 => DBG_FLASH_Q) (_0 => SD1_DATA3 _2 => FSPICS0 _4 => + DBG_FLASH_Q) ([Input] [Output]))); _for_each_inner_gpio!((24, GPIO24(_0 => + SD1_CLK _2 => FSPIHD _4 => DBG_FLASH_WP) (_0 => SD1_CLK _2 => FSPIHD _4 => + DBG_FLASH_WP) ([Input] [Output]))); _for_each_inner_gpio!((25, GPIO25(_0 => + SD1_CMD _2 => FSPIWP _4 => DBG_FLASH_HOLD) (_0 => SD1_CMD _2 => FSPIWP _4 => + DBG_FLASH_HOLD) ([Input] [Output]))); _for_each_inner_gpio!((26, GPIO26(_0 => + SPICS0) (_0 => SPICS0) ([Input] [Output]))); _for_each_inner_gpio!((27, GPIO27(_0 + => SPIQ) (_0 => SPIQ) ([Input] [Output]))); _for_each_inner_gpio!((28, GPIO28(_0 + => SPIWP) (_0 => SPIWP) ([Input] [Output]))); _for_each_inner_gpio!((30, + GPIO30(_0 => SPIHD) (_0 => SPIHD) ([Input] [Output]))); + _for_each_inner_gpio!((31, GPIO31(_0 => SPICLK) (_0 => SPICLK) ([Input] + [Output]))); _for_each_inner_gpio!((32, GPIO32(_0 => SPID) (_0 => SPID) ([Input] + [Output]))); _for_each_inner_gpio!((33, GPIO33() (_3 => LCD_DATA_12) ([Input] + [Output]))); _for_each_inner_gpio!((34, GPIO34() (_3 => LCD_DATA_13) ([Input] + [Output]))); _for_each_inner_gpio!((35, GPIO35(_2 => REF_50M_CLK _4 => + SD2_CDATA0) (_2 => REF_50M_CLK _3 => LCD_DATA_14 _4 => SD2_CDATA0) ([Input] + [Output]))); _for_each_inner_gpio!((36, GPIO36(_2 => EMAC_RXDV _4 => SD2_CDATA1) + (_3 => LCD_DATA_15 _4 => SD2_CDATA1) ([Input] [Output]))); + _for_each_inner_gpio!((37, GPIO37(_4 => SD2_CDATA2) (_2 => EMAC_TXEN _3 => + LCD_DATA_16 _4 => SD2_CDATA2) ([Input] [Output]))); _for_each_inner_gpio!((38, + GPIO38(_2 => EMAC_RXD3 _4 => SD2_CDATA3) (_3 => LCD_DATA_17 _4 => SD2_CDATA3) + ([Input] [Output]))); _for_each_inner_gpio!((39, GPIO39(_2 => EMAC_RXD2 _4 => + SD2_CCLK) (_3 => LCD_DATA_18 _4 => SD2_CCLK) ([Input] [Output]))); + _for_each_inner_gpio!((40, GPIO40(_2 => EMAC_RXD1 _4 => SD2_CCMD) (_3 => LCD_PCLK + _4 => SD2_CCMD) ([Input] [Output]))); _for_each_inner_gpio!((42, GPIO42(_2 => + EMAC_RX_CLK) () ([Input] [Output]))); _for_each_inner_gpio!((43, GPIO43(_2 => + EMAC_RMII_CLK) (_2 => EMAC_RMII_CLK _3 => LCD_H_ENABLE) ([Input] [Output]))); + _for_each_inner_gpio!((44, GPIO44() (_2 => EMAC_TXD0 _3 => LCD_H_SYNC) ([Input] + [Output]))); _for_each_inner_gpio!((45, GPIO45() (_2 => EMAC_TXD1 _3 => + LCD_V_SYNC) ([Input] [Output]))); _for_each_inner_gpio!((46, GPIO46(_3 => + CAM_DATA_0) (_2 => EMAC_TXD2) ([Input] [Output]))); _for_each_inner_gpio!((47, + GPIO47(_3 => CAM_DATA_1) (_2 => EMAC_TXD3) ([Input] [Output]))); + _for_each_inner_gpio!((48, GPIO48(_3 => CAM_DATA_2) () ([Input] [Output]))); + _for_each_inner_gpio!((49, GPIO49(_3 => CAM_DATA_3) () ([Input] [Output]))); + _for_each_inner_gpio!((50, GPIO50(_3 => CAM_DATA_4) () ([Input] [Output]))); + _for_each_inner_gpio!((51, GPIO51(_3 => CAM_DATA_5) () ([Input] [Output]))); + _for_each_inner_gpio!((52, GPIO52(_2 => FSPICS0 _3 => CAM_DATA_6) (_2 => FSPICS0) + ([Input] [Output]))); _for_each_inner_gpio!((53, GPIO53(_2 => FSPICLK _3 => + CAM_DATA_7) (_2 => FSPICLK) ([Input] [Output]))); _for_each_inner_gpio!((54, + GPIO54(_0 => MTDO _2 => FSPID _3 => CAM_PCLK) (_0 => MTDO _2 => FSPID) ([Input] + [Output]))); _for_each_inner_gpio!((55, GPIO55(_0 => MTCK _2 => FSPIQ _3 => + CAM_XCLK) (_0 => MTCK _2 => FSPIQ _3 => CAM_XCLK) ([Input] [Output]))); + _for_each_inner_gpio!((56, GPIO56(_0 => MTDI _2 => FSPIHD _3 => CAM_V_SYNC) (_0 + => MTDI _2 => FSPIHD) ([Input] [Output]))); _for_each_inner_gpio!((57, GPIO57(_0 + => MTMS _2 => FSPIWP _3 => CAM_H_SYNC) (_0 => MTMS _2 => FSPIWP) ([Input] + [Output]))); _for_each_inner_gpio!((58, GPIO58() (_0 => U0TXD) ([Input] + [Output]))); _for_each_inner_gpio!((59, GPIO59(_0 => U0RXD) () ([Input] + [Output]))); _for_each_inner_gpio!((60, GPIO60() () ([Input] [Output]))); + _for_each_inner_gpio!((61, GPIO61() () ([Input] [Output]))); + _for_each_inner_gpio!((all(0, GPIO0() () ([Input] [Output])), (1, GPIO1() () + ([Input] [Output])), (2, GPIO2() (_3 => LCD_DATA_19) ([Input] [Output])), (3, + GPIO3() (_3 => LCD_DATA_20) ([Input] [Output])), (4, GPIO4() (_3 => LCD_DATA_21) + ([Input] [Output])), (5, GPIO5() (_3 => LCD_DATA_22) ([Input] [Output])), (6, + GPIO6() () ([Input] [Output])), (7, GPIO7() (_3 => LCD_DATA_23) ([Input] + [Output])), (8, GPIO8() (_2 => EMAC_TXD0 _3 => LCD_DATA_0) ([Input] [Output])), + (9, GPIO9(_0 => FSPIHD _4 => DBG_PSRAM_CK) (_0 => FSPIHD _2 => EMAC_TXD1 _3 => + LCD_DATA_1 _4 => DBG_PSRAM_CK) ([Input] [Output])), (10, GPIO10(_0 => FSPICS0 _4 + => DBG_PSRAM_CS) (_0 => FSPICS0 _2 => EMAC_TXD2 _3 => LCD_DATA_2 _4 => + DBG_PSRAM_CS) ([Input] [Output])), (11, GPIO11(_0 => FSPID _4 => DBG_PSRAM_D) (_0 + => FSPID _2 => EMAC_TXD3 _3 => LCD_DATA_3 _4 => DBG_PSRAM_D) ([Input] [Output])), + (12, GPIO12(_0 => FSPICLK _4 => DBG_PSRAM_Q) (_0 => FSPICLK _2 => EMAC_TXEN _3 => + LCD_DATA_4 _4 => DBG_PSRAM_Q) ([Input] [Output])), (13, GPIO13(_0 => FSPIQ _2 => + EMAC_RMII_CLK _4 => DBG_PSRAM_WP) (_0 => FSPIQ _2 => EMAC_RMII_CLK _3 => + LCD_DATA_5 _4 => DBG_PSRAM_WP) ([Input] [Output])), (14, GPIO14(_0 => FSPIWP _2 + => EMAC_RX_CLK _4 => DBG_PSRAM_HOLD) (_0 => FSPIWP _3 => LCD_DATA_6 _4 => + DBG_PSRAM_HOLD) ([Input] [Output])), (15, GPIO15(_0 => FSPIIO4 _2 => EMAC_RXDV _4 + => DBG_PSRAM_DQ4) (_0 => FSPIIO4 _3 => LCD_DATA_7 _4 => DBG_PSRAM_DQ4) ([Input] + [Output])), (16, GPIO16(_0 => FSPIIO5 _2 => EMAC_RXD3 _4 => DBG_PSRAM_DQ5) (_0 => + FSPIIO5 _3 => LCD_DATA_8 _4 => DBG_PSRAM_DQ5) ([Input] [Output])), (17, GPIO17(_0 + => FSPIIO6 _2 => EMAC_RXD2 _4 => DBG_PSRAM_DQ6) (_0 => FSPIIO6 _3 => LCD_DATA_9 + _4 => DBG_PSRAM_DQ6) ([Input] [Output])), (18, GPIO18(_0 => FSPIIO7 _2 => + EMAC_RXD1 _4 => DBG_PSRAM_DQ7) (_0 => FSPIIO7 _3 => LCD_DATA_10 _4 => + DBG_PSRAM_DQ7) ([Input] [Output])), (19, GPIO19(_2 => EMAC_RXD0 _4 => + DBG_PSRAM_DQS_0) (_0 => FSPIDQS _3 => LCD_DATA_11 _4 => DBG_PSRAM_DQS_0) ([Input] + [Output])), (20, GPIO20(_0 => SD1_DATA0 _2 => FSPICLK _4 => DBG_FLASH_CK) (_0 => + SD1_DATA0 _2 => FSPICLK _4 => DBG_FLASH_CK) ([Input] [Output])), (21, GPIO21(_0 + => SD1_DATA1 _2 => FSPID _4 => DBG_FLASH_D) (_0 => SD1_DATA1 _2 => FSPID _4 => + DBG_FLASH_D) ([Input] [Output])), (22, GPIO22(_0 => SD1_DATA2 _2 => FSPIQ _4 => DBG_FLASH_CS) (_0 => SD1_DATA2 _2 => FSPIQ _4 => DBG_FLASH_CS) ([Input] - [Output]))); _for_each_inner_gpio!((23, GPIO23(_0 => SD1_DATA3 _2 => FSPICS0 _4 - => DBG_FLASH_Q) (_0 => SD1_DATA3 _2 => FSPICS0 _4 => DBG_FLASH_Q) ([Input] - [Output]))); _for_each_inner_gpio!((24, GPIO24(_0 => SD1_CLK _2 => FSPIHD _4 => - DBG_FLASH_WP) (_0 => SD1_CLK _2 => FSPIHD _4 => DBG_FLASH_WP) ([Input] - [Output]))); _for_each_inner_gpio!((25, GPIO25(_0 => SD1_CMD _2 => FSPIWP _4 => + [Output])), (23, GPIO23(_0 => SD1_DATA3 _2 => FSPICS0 _4 => DBG_FLASH_Q) (_0 => + SD1_DATA3 _2 => FSPICS0 _4 => DBG_FLASH_Q) ([Input] [Output])), (24, GPIO24(_0 => + SD1_CLK _2 => FSPIHD _4 => DBG_FLASH_WP) (_0 => SD1_CLK _2 => FSPIHD _4 => + DBG_FLASH_WP) ([Input] [Output])), (25, GPIO25(_0 => SD1_CMD _2 => FSPIWP _4 => DBG_FLASH_HOLD) (_0 => SD1_CMD _2 => FSPIWP _4 => DBG_FLASH_HOLD) ([Input] - [Output]))); _for_each_inner_gpio!((26, GPIO26(_0 => SPICS0) (_0 => SPICS0) - ([Input] [Output]))); _for_each_inner_gpio!((27, GPIO27(_0 => SPIQ) (_0 => SPIQ) - ([Input] [Output]))); _for_each_inner_gpio!((28, GPIO28(_0 => SPIWP) (_0 => - SPIWP) ([Input] [Output]))); _for_each_inner_gpio!((30, GPIO30(_0 => SPIHD) (_0 - => SPIHD) ([Input] [Output]))); _for_each_inner_gpio!((31, GPIO31(_0 => SPICLK) - (_0 => SPICLK) ([Input] [Output]))); _for_each_inner_gpio!((32, GPIO32(_0 => - SPID) (_0 => SPID) ([Input] [Output]))); _for_each_inner_gpio!((33, GPIO33(_3 => - LCD_DATA12) (_3 => LCD_DATA12) ([Input] [Output]))); _for_each_inner_gpio!((34, - GPIO34(_3 => LCD_DATA13) (_3 => LCD_DATA13) ([Input] [Output]))); - _for_each_inner_gpio!((35, GPIO35(_2 => REF_GMAC_CLK _3 => LCD_DATA14 _4 => - SD2_CDATA0) (_2 => REF_GMAC_CLK _3 => LCD_DATA14 _4 => SD2_CDATA0) ([Input] - [Output]))); _for_each_inner_gpio!((36, GPIO36(_2 => GMAC_PHY_RXDV _3 => - LCD_DATA15 _4 => SD2_CDATA1) (_2 => GMAC_PHY_RXDV _3 => LCD_DATA15 _4 => - SD2_CDATA1) ([Input] [Output]))); _for_each_inner_gpio!((37, GPIO37(_2 => - GMAC_PHY_TXEN _3 => LCD_DATA16 _4 => SD2_CDATA2) (_2 => GMAC_PHY_TXEN _3 => - LCD_DATA16 _4 => SD2_CDATA2) ([Input] [Output]))); _for_each_inner_gpio!((38, - GPIO38(_2 => GMAC_PHY_RXD3 _3 => LCD_DATA17 _4 => SD2_CDATA3) (_2 => - GMAC_PHY_RXD3 _3 => LCD_DATA17 _4 => SD2_CDATA3) ([Input] [Output]))); - _for_each_inner_gpio!((39, GPIO39(_2 => GMAC_PHY_RXD2 _3 => LCD_DATA18 _4 => - SD2_CCLK) (_2 => GMAC_PHY_RXD2 _3 => LCD_DATA18 _4 => SD2_CCLK) ([Input] - [Output]))); _for_each_inner_gpio!((40, GPIO40(_2 => GMAC_PHY_RXD1 _3 => LCD_PCLK - _4 => SD2_CCMD) (_2 => GMAC_PHY_RXD1 _3 => LCD_PCLK _4 => SD2_CCMD) ([Input] - [Output]))); _for_each_inner_gpio!((42, GPIO42(_2 => GMAC_RX_CLK) (_2 => - GMAC_RX_CLK) ([Input] [Output]))); _for_each_inner_gpio!((43, GPIO43(_2 => - GMAC_RMII_CLK _3 => LCD_H_ENABLE) (_2 => GMAC_RMII_CLK _3 => LCD_H_ENABLE) - ([Input] [Output]))); _for_each_inner_gpio!((44, GPIO44(_2 => GMAC_PHY_TXD0 _3 => - LCD_H_SYNC) (_2 => GMAC_PHY_TXD0 _3 => LCD_H_SYNC) ([Input] [Output]))); - _for_each_inner_gpio!((45, GPIO45(_2 => GMAC_PHY_TXD1 _3 => LCD_V_SYNC) (_2 => - GMAC_PHY_TXD1 _3 => LCD_V_SYNC) ([Input] [Output]))); _for_each_inner_gpio!((46, - GPIO46(_2 => GMAC_PHY_TXD2 _3 => CAM_DATA0) (_2 => GMAC_PHY_TXD2 _3 => CAM_DATA0) - ([Input] [Output]))); _for_each_inner_gpio!((47, GPIO47(_2 => GMAC_PHY_TXD3 _3 => - CAM_DATA1) (_2 => GMAC_PHY_TXD3 _3 => CAM_DATA1) ([Input] [Output]))); - _for_each_inner_gpio!((48, GPIO48(_3 => CAM_DATA2) (_3 => CAM_DATA2) ([Input] - [Output]))); _for_each_inner_gpio!((49, GPIO49(_3 => CAM_DATA3) (_3 => CAM_DATA3) - ([Input] [Output]))); _for_each_inner_gpio!((50, GPIO50(_3 => CAM_DATA4) (_3 => - CAM_DATA4) ([Input] [Output]))); _for_each_inner_gpio!((51, GPIO51(_3 => - CAM_DATA5) (_3 => CAM_DATA5) ([Input] [Output]))); _for_each_inner_gpio!((52, - GPIO52(_2 => FSPICS0 _3 => CAM_DATA6) (_2 => FSPICS0 _3 => CAM_DATA6) ([Input] - [Output]))); _for_each_inner_gpio!((53, GPIO53(_2 => FSPICLK _3 => CAM_DATA7) (_2 - => FSPICLK _3 => CAM_DATA7) ([Input] [Output]))); _for_each_inner_gpio!((54, - GPIO54(_0 => MTDO _2 => FSPID _3 => CAM_PCLK) (_0 => MTDO _2 => FSPID _3 => - CAM_PCLK) ([Input] [Output]))); _for_each_inner_gpio!((55, GPIO55(_0 => MTCK _2 + [Output])), (26, GPIO26(_0 => SPICS0) (_0 => SPICS0) ([Input] [Output])), (27, + GPIO27(_0 => SPIQ) (_0 => SPIQ) ([Input] [Output])), (28, GPIO28(_0 => SPIWP) (_0 + => SPIWP) ([Input] [Output])), (30, GPIO30(_0 => SPIHD) (_0 => SPIHD) ([Input] + [Output])), (31, GPIO31(_0 => SPICLK) (_0 => SPICLK) ([Input] [Output])), (32, + GPIO32(_0 => SPID) (_0 => SPID) ([Input] [Output])), (33, GPIO33() (_3 => + LCD_DATA_12) ([Input] [Output])), (34, GPIO34() (_3 => LCD_DATA_13) ([Input] + [Output])), (35, GPIO35(_2 => REF_50M_CLK _4 => SD2_CDATA0) (_2 => REF_50M_CLK _3 + => LCD_DATA_14 _4 => SD2_CDATA0) ([Input] [Output])), (36, GPIO36(_2 => EMAC_RXDV + _4 => SD2_CDATA1) (_3 => LCD_DATA_15 _4 => SD2_CDATA1) ([Input] [Output])), (37, + GPIO37(_4 => SD2_CDATA2) (_2 => EMAC_TXEN _3 => LCD_DATA_16 _4 => SD2_CDATA2) + ([Input] [Output])), (38, GPIO38(_2 => EMAC_RXD3 _4 => SD2_CDATA3) (_3 => + LCD_DATA_17 _4 => SD2_CDATA3) ([Input] [Output])), (39, GPIO39(_2 => EMAC_RXD2 _4 + => SD2_CCLK) (_3 => LCD_DATA_18 _4 => SD2_CCLK) ([Input] [Output])), (40, + GPIO40(_2 => EMAC_RXD1 _4 => SD2_CCMD) (_3 => LCD_PCLK _4 => SD2_CCMD) ([Input] + [Output])), (42, GPIO42(_2 => EMAC_RX_CLK) () ([Input] [Output])), (43, GPIO43(_2 + => EMAC_RMII_CLK) (_2 => EMAC_RMII_CLK _3 => LCD_H_ENABLE) ([Input] [Output])), + (44, GPIO44() (_2 => EMAC_TXD0 _3 => LCD_H_SYNC) ([Input] [Output])), (45, + GPIO45() (_2 => EMAC_TXD1 _3 => LCD_V_SYNC) ([Input] [Output])), (46, GPIO46(_3 + => CAM_DATA_0) (_2 => EMAC_TXD2) ([Input] [Output])), (47, GPIO47(_3 => + CAM_DATA_1) (_2 => EMAC_TXD3) ([Input] [Output])), (48, GPIO48(_3 => CAM_DATA_2) + () ([Input] [Output])), (49, GPIO49(_3 => CAM_DATA_3) () ([Input] [Output])), + (50, GPIO50(_3 => CAM_DATA_4) () ([Input] [Output])), (51, GPIO51(_3 => + CAM_DATA_5) () ([Input] [Output])), (52, GPIO52(_2 => FSPICS0 _3 => CAM_DATA_6) + (_2 => FSPICS0) ([Input] [Output])), (53, GPIO53(_2 => FSPICLK _3 => CAM_DATA_7) + (_2 => FSPICLK) ([Input] [Output])), (54, GPIO54(_0 => MTDO _2 => FSPID _3 => + CAM_PCLK) (_0 => MTDO _2 => FSPID) ([Input] [Output])), (55, GPIO55(_0 => MTCK _2 => FSPIQ _3 => CAM_XCLK) (_0 => MTCK _2 => FSPIQ _3 => CAM_XCLK) ([Input] - [Output]))); _for_each_inner_gpio!((56, GPIO56(_0 => MTDI _2 => FSPIHD _3 => - CAM_V_SYNC) (_0 => MTDI _2 => FSPIHD _3 => CAM_V_SYNC) ([Input] [Output]))); - _for_each_inner_gpio!((57, GPIO57(_0 => MTMS _2 => FSPIWP _3 => CAM_H_SYNC) (_0 - => MTMS _2 => FSPIWP _3 => CAM_H_SYNC) ([Input] [Output]))); - _for_each_inner_gpio!((58, GPIO58() (_0 => U0TXD) ([Input] [Output]))); - _for_each_inner_gpio!((59, GPIO59(_0 => U0RXD) () ([Input] [Output]))); - _for_each_inner_gpio!((60, GPIO60() () ([Input] [Output]))); - _for_each_inner_gpio!((61, GPIO61() () ([Input] [Output]))); - _for_each_inner_gpio!((all(0, GPIO0() () ([Input] [Output])), (1, GPIO1() () - ([Input] [Output])), (2, GPIO2(_3 => LCD_DATA19) (_3 => LCD_DATA19) ([Input] - [Output])), (3, GPIO3(_3 => LCD_DATA20) (_3 => LCD_DATA20) ([Input] [Output])), - (4, GPIO4(_3 => LCD_DATA21) (_3 => LCD_DATA21) ([Input] [Output])), (5, GPIO5(_3 - => LCD_DATA22) (_3 => LCD_DATA22) ([Input] [Output])), (6, GPIO6() () ([Input] - [Output])), (7, GPIO7(_3 => LCD_DATA23) (_3 => LCD_DATA23) ([Input] [Output])), - (8, GPIO8(_2 => GMAC_PHY_TXD0 _3 => LCD_DATA0) (_2 => GMAC_PHY_TXD0 _3 => - LCD_DATA0) ([Input] [Output])), (9, GPIO9(_0 => FSPIHD _2 => GMAC_PHY_TXD1 _3 => - LCD_DATA1 _4 => DBG_PSRAM_CK) (_0 => FSPIHD _2 => GMAC_PHY_TXD1 _3 => LCD_DATA1 - _4 => DBG_PSRAM_CK) ([Input] [Output])), (10, GPIO10(_0 => FSPICS0 _2 => - GMAC_PHY_TXD2 _3 => LCD_DATA2 _4 => DBG_PSRAM_CS) (_0 => FSPICS0 _2 => - GMAC_PHY_TXD2 _3 => LCD_DATA2 _4 => DBG_PSRAM_CS) ([Input] [Output])), (11, - GPIO11(_0 => FSPID _2 => GMAC_PHY_TXD3 _3 => LCD_DATA3 _4 => DBG_PSRAM_D) (_0 => - FSPID _2 => GMAC_PHY_TXD3 _3 => LCD_DATA3 _4 => DBG_PSRAM_D) ([Input] [Output])), - (12, GPIO12(_0 => FSPICLK _2 => GMAC_PHY_TXEN _3 => LCD_DATA4 _4 => DBG_PSRAM_Q) - (_0 => FSPICLK _2 => GMAC_PHY_TXEN _3 => LCD_DATA4 _4 => DBG_PSRAM_Q) ([Input] - [Output])), (13, GPIO13(_0 => FSPIQ _2 => GMAC_RMII_CLK _3 => LCD_DATA5 _4 => - DBG_PSRAM_WP) (_0 => FSPIQ _2 => GMAC_RMII_CLK _3 => LCD_DATA5 _4 => - DBG_PSRAM_WP) ([Input] [Output])), (14, GPIO14(_0 => FSPIWP _2 => GMAC_RX_CLK _3 - => LCD_DATA6 _4 => DBG_PSRAM_HOLD) (_0 => FSPIWP _2 => GMAC_RX_CLK _3 => - LCD_DATA6 _4 => DBG_PSRAM_HOLD) ([Input] [Output])), (15, GPIO15(_0 => FSPIIO4 _2 - => GMAC_PHY_RXDV _3 => LCD_DATA7 _4 => DBG_PSRAM_DQ4) (_0 => FSPIIO4 _2 => - GMAC_PHY_RXDV _3 => LCD_DATA7 _4 => DBG_PSRAM_DQ4) ([Input] [Output])), (16, - GPIO16(_0 => FSPIIO5 _2 => GMAC_PHY_RXD3 _3 => LCD_DATA8 _4 => DBG_PSRAM_DQ5) (_0 - => FSPIIO5 _2 => GMAC_PHY_RXD3 _3 => LCD_DATA8 _4 => DBG_PSRAM_DQ5) ([Input] - [Output])), (17, GPIO17(_0 => FSPIIO6 _2 => GMAC_PHY_RXD2 _3 => LCD_DATA9 _4 => - DBG_PSRAM_DQ6) (_0 => FSPIIO6 _2 => GMAC_PHY_RXD2 _3 => LCD_DATA9 _4 => - DBG_PSRAM_DQ6) ([Input] [Output])), (18, GPIO18(_0 => FSPIIO7 _2 => GMAC_PHY_RXD1 - _3 => LCD_DATA10 _4 => DBG_PSRAM_DQ7) (_0 => FSPIIO7 _2 => GMAC_PHY_RXD1 _3 => - LCD_DATA10 _4 => DBG_PSRAM_DQ7) ([Input] [Output])), (19, GPIO19(_2 => - GMAC_PHY_RXD0 _3 => LCD_DATA11 _4 => DBG_PSRAM_DQS_0) (_0 => FSPIDQS _2 => - GMAC_PHY_RXD0 _3 => LCD_DATA11 _4 => DBG_PSRAM_DQS_0) ([Input] [Output])), (20, - GPIO20(_0 => SD1_DATA0 _2 => FSPICLK _4 => DBG_FLASH_CK) (_0 => SD1_DATA0 _2 => - FSPICLK _4 => DBG_FLASH_CK) ([Input] [Output])), (21, GPIO21(_0 => SD1_DATA1 _2 - => FSPID _4 => DBG_FLASH_D) (_0 => SD1_DATA1 _2 => FSPID _4 => DBG_FLASH_D) - ([Input] [Output])), (22, GPIO22(_0 => SD1_DATA2 _2 => FSPIQ _4 => DBG_FLASH_CS) - (_0 => SD1_DATA2 _2 => FSPIQ _4 => DBG_FLASH_CS) ([Input] [Output])), (23, - GPIO23(_0 => SD1_DATA3 _2 => FSPICS0 _4 => DBG_FLASH_Q) (_0 => SD1_DATA3 _2 => - FSPICS0 _4 => DBG_FLASH_Q) ([Input] [Output])), (24, GPIO24(_0 => SD1_CLK _2 => - FSPIHD _4 => DBG_FLASH_WP) (_0 => SD1_CLK _2 => FSPIHD _4 => DBG_FLASH_WP) - ([Input] [Output])), (25, GPIO25(_0 => SD1_CMD _2 => FSPIWP _4 => DBG_FLASH_HOLD) - (_0 => SD1_CMD _2 => FSPIWP _4 => DBG_FLASH_HOLD) ([Input] [Output])), (26, - GPIO26(_0 => SPICS0) (_0 => SPICS0) ([Input] [Output])), (27, GPIO27(_0 => SPIQ) - (_0 => SPIQ) ([Input] [Output])), (28, GPIO28(_0 => SPIWP) (_0 => SPIWP) ([Input] - [Output])), (30, GPIO30(_0 => SPIHD) (_0 => SPIHD) ([Input] [Output])), (31, - GPIO31(_0 => SPICLK) (_0 => SPICLK) ([Input] [Output])), (32, GPIO32(_0 => SPID) - (_0 => SPID) ([Input] [Output])), (33, GPIO33(_3 => LCD_DATA12) (_3 => - LCD_DATA12) ([Input] [Output])), (34, GPIO34(_3 => LCD_DATA13) (_3 => LCD_DATA13) - ([Input] [Output])), (35, GPIO35(_2 => REF_GMAC_CLK _3 => LCD_DATA14 _4 => - SD2_CDATA0) (_2 => REF_GMAC_CLK _3 => LCD_DATA14 _4 => SD2_CDATA0) ([Input] - [Output])), (36, GPIO36(_2 => GMAC_PHY_RXDV _3 => LCD_DATA15 _4 => SD2_CDATA1) - (_2 => GMAC_PHY_RXDV _3 => LCD_DATA15 _4 => SD2_CDATA1) ([Input] [Output])), (37, - GPIO37(_2 => GMAC_PHY_TXEN _3 => LCD_DATA16 _4 => SD2_CDATA2) (_2 => - GMAC_PHY_TXEN _3 => LCD_DATA16 _4 => SD2_CDATA2) ([Input] [Output])), (38, - GPIO38(_2 => GMAC_PHY_RXD3 _3 => LCD_DATA17 _4 => SD2_CDATA3) (_2 => - GMAC_PHY_RXD3 _3 => LCD_DATA17 _4 => SD2_CDATA3) ([Input] [Output])), (39, - GPIO39(_2 => GMAC_PHY_RXD2 _3 => LCD_DATA18 _4 => SD2_CCLK) (_2 => GMAC_PHY_RXD2 - _3 => LCD_DATA18 _4 => SD2_CCLK) ([Input] [Output])), (40, GPIO40(_2 => - GMAC_PHY_RXD1 _3 => LCD_PCLK _4 => SD2_CCMD) (_2 => GMAC_PHY_RXD1 _3 => LCD_PCLK - _4 => SD2_CCMD) ([Input] [Output])), (42, GPIO42(_2 => GMAC_RX_CLK) (_2 => - GMAC_RX_CLK) ([Input] [Output])), (43, GPIO43(_2 => GMAC_RMII_CLK _3 => - LCD_H_ENABLE) (_2 => GMAC_RMII_CLK _3 => LCD_H_ENABLE) ([Input] [Output])), (44, - GPIO44(_2 => GMAC_PHY_TXD0 _3 => LCD_H_SYNC) (_2 => GMAC_PHY_TXD0 _3 => - LCD_H_SYNC) ([Input] [Output])), (45, GPIO45(_2 => GMAC_PHY_TXD1 _3 => - LCD_V_SYNC) (_2 => GMAC_PHY_TXD1 _3 => LCD_V_SYNC) ([Input] [Output])), (46, - GPIO46(_2 => GMAC_PHY_TXD2 _3 => CAM_DATA0) (_2 => GMAC_PHY_TXD2 _3 => CAM_DATA0) - ([Input] [Output])), (47, GPIO47(_2 => GMAC_PHY_TXD3 _3 => CAM_DATA1) (_2 => - GMAC_PHY_TXD3 _3 => CAM_DATA1) ([Input] [Output])), (48, GPIO48(_3 => CAM_DATA2) - (_3 => CAM_DATA2) ([Input] [Output])), (49, GPIO49(_3 => CAM_DATA3) (_3 => - CAM_DATA3) ([Input] [Output])), (50, GPIO50(_3 => CAM_DATA4) (_3 => CAM_DATA4) - ([Input] [Output])), (51, GPIO51(_3 => CAM_DATA5) (_3 => CAM_DATA5) ([Input] - [Output])), (52, GPIO52(_2 => FSPICS0 _3 => CAM_DATA6) (_2 => FSPICS0 _3 => - CAM_DATA6) ([Input] [Output])), (53, GPIO53(_2 => FSPICLK _3 => CAM_DATA7) (_2 => - FSPICLK _3 => CAM_DATA7) ([Input] [Output])), (54, GPIO54(_0 => MTDO _2 => FSPID - _3 => CAM_PCLK) (_0 => MTDO _2 => FSPID _3 => CAM_PCLK) ([Input] [Output])), (55, - GPIO55(_0 => MTCK _2 => FSPIQ _3 => CAM_XCLK) (_0 => MTCK _2 => FSPIQ _3 => - CAM_XCLK) ([Input] [Output])), (56, GPIO56(_0 => MTDI _2 => FSPIHD _3 => - CAM_V_SYNC) (_0 => MTDI _2 => FSPIHD _3 => CAM_V_SYNC) ([Input] [Output])), (57, - GPIO57(_0 => MTMS _2 => FSPIWP _3 => CAM_H_SYNC) (_0 => MTMS _2 => FSPIWP _3 => - CAM_H_SYNC) ([Input] [Output])), (58, GPIO58() (_0 => U0TXD) ([Input] [Output])), - (59, GPIO59(_0 => U0RXD) () ([Input] [Output])), (60, GPIO60() () ([Input] - [Output])), (61, GPIO61() () ([Input] [Output])))); + [Output])), (56, GPIO56(_0 => MTDI _2 => FSPIHD _3 => CAM_V_SYNC) (_0 => MTDI _2 + => FSPIHD) ([Input] [Output])), (57, GPIO57(_0 => MTMS _2 => FSPIWP _3 => + CAM_H_SYNC) (_0 => MTMS _2 => FSPIWP) ([Input] [Output])), (58, GPIO58() (_0 => + U0TXD) ([Input] [Output])), (59, GPIO59(_0 => U0RXD) () ([Input] [Output])), (60, + GPIO60() () ([Input] [Output])), (61, GPIO61() () ([Input] [Output])))); }; } /// This macro can be used to generate code for each analog function of each GPIO. @@ -5505,30 +7404,30 @@ macro_rules! for_each_analog_function { macro_rules! for_each_lp_function { ($($pattern:tt => $code:tt;)*) => { macro_rules! _for_each_inner_lp_function { $(($pattern) => $code;)* ($other : tt) - => {} } _for_each_inner_lp_function!((LP_GPIO0, GPIO0, _0)); - _for_each_inner_lp_function!((LP_GPIO1, GPIO1, _0)); - _for_each_inner_lp_function!((LP_GPIO2, GPIO2, _0)); - _for_each_inner_lp_function!((LP_GPIO3, GPIO3, _0)); - _for_each_inner_lp_function!((LP_GPIO4, GPIO4, _0)); - _for_each_inner_lp_function!((LP_GPIO5, GPIO5, _0)); - _for_each_inner_lp_function!((LP_GPIO6, GPIO6, _0)); - _for_each_inner_lp_function!((LP_GPIO7, GPIO7, _0)); - _for_each_inner_lp_function!(((LP_GPIO0, LP_GPIOn, 0), GPIO0, _0, () ())); - _for_each_inner_lp_function!(((LP_GPIO1, LP_GPIOn, 1), GPIO1, _0, () ())); - _for_each_inner_lp_function!(((LP_GPIO2, LP_GPIOn, 2), GPIO2, _0, () ())); - _for_each_inner_lp_function!(((LP_GPIO3, LP_GPIOn, 3), GPIO3, _0, () ())); - _for_each_inner_lp_function!(((LP_GPIO4, LP_GPIOn, 4), GPIO4, _0, () ())); - _for_each_inner_lp_function!(((LP_GPIO5, LP_GPIOn, 5), GPIO5, _0, () ())); - _for_each_inner_lp_function!(((LP_GPIO6, LP_GPIOn, 6), GPIO6, _0, () ())); - _for_each_inner_lp_function!(((LP_GPIO7, LP_GPIOn, 7), GPIO7, _0, () ())); - _for_each_inner_lp_function!((all(LP_GPIO0, GPIO0, _0), (LP_GPIO1, GPIO1, _0), - (LP_GPIO2, GPIO2, _0), (LP_GPIO3, GPIO3, _0), (LP_GPIO4, GPIO4, _0), (LP_GPIO5, - GPIO5, _0), (LP_GPIO6, GPIO6, _0), (LP_GPIO7, GPIO7, _0))); - _for_each_inner_lp_function!((LP_GPIOn((LP_GPIO0, LP_GPIOn, 0), GPIO0, _0, () - ()), ((LP_GPIO1, LP_GPIOn, 1), GPIO1, _0, () ()), ((LP_GPIO2, LP_GPIOn, 2), - GPIO2, _0, () ()), ((LP_GPIO3, LP_GPIOn, 3), GPIO3, _0, () ()), ((LP_GPIO4, - LP_GPIOn, 4), GPIO4, _0, () ()), ((LP_GPIO5, LP_GPIOn, 5), GPIO5, _0, () ()), - ((LP_GPIO6, LP_GPIOn, 6), GPIO6, _0, () ()), ((LP_GPIO7, LP_GPIOn, 7), GPIO7, _0, + => {} } _for_each_inner_lp_function!((LP_GPIO0, GPIO0, _1)); + _for_each_inner_lp_function!((LP_GPIO1, GPIO1, _1)); + _for_each_inner_lp_function!((LP_GPIO2, GPIO2, _1)); + _for_each_inner_lp_function!((LP_GPIO3, GPIO3, _1)); + _for_each_inner_lp_function!((LP_GPIO4, GPIO4, _1)); + _for_each_inner_lp_function!((LP_GPIO5, GPIO5, _1)); + _for_each_inner_lp_function!((LP_GPIO6, GPIO6, _1)); + _for_each_inner_lp_function!((LP_GPIO7, GPIO7, _1)); + _for_each_inner_lp_function!(((LP_GPIO0, LP_GPIOn, 0), GPIO0, _1, () ())); + _for_each_inner_lp_function!(((LP_GPIO1, LP_GPIOn, 1), GPIO1, _1, () ())); + _for_each_inner_lp_function!(((LP_GPIO2, LP_GPIOn, 2), GPIO2, _1, () ())); + _for_each_inner_lp_function!(((LP_GPIO3, LP_GPIOn, 3), GPIO3, _1, () ())); + _for_each_inner_lp_function!(((LP_GPIO4, LP_GPIOn, 4), GPIO4, _1, () ())); + _for_each_inner_lp_function!(((LP_GPIO5, LP_GPIOn, 5), GPIO5, _1, () ())); + _for_each_inner_lp_function!(((LP_GPIO6, LP_GPIOn, 6), GPIO6, _1, () ())); + _for_each_inner_lp_function!(((LP_GPIO7, LP_GPIOn, 7), GPIO7, _1, () ())); + _for_each_inner_lp_function!((all(LP_GPIO0, GPIO0, _1), (LP_GPIO1, GPIO1, _1), + (LP_GPIO2, GPIO2, _1), (LP_GPIO3, GPIO3, _1), (LP_GPIO4, GPIO4, _1), (LP_GPIO5, + GPIO5, _1), (LP_GPIO6, GPIO6, _1), (LP_GPIO7, GPIO7, _1))); + _for_each_inner_lp_function!((LP_GPIOn((LP_GPIO0, LP_GPIOn, 0), GPIO0, _1, () + ()), ((LP_GPIO1, LP_GPIOn, 1), GPIO1, _1, () ()), ((LP_GPIO2, LP_GPIOn, 2), + GPIO2, _1, () ()), ((LP_GPIO3, LP_GPIOn, 3), GPIO3, _1, () ()), ((LP_GPIO4, + LP_GPIOn, 4), GPIO4, _1, () ()), ((LP_GPIO5, LP_GPIOn, 5), GPIO5, _1, () ()), + ((LP_GPIO6, LP_GPIOn, 6), GPIO6, _1, () ()), ((LP_GPIO7, LP_GPIOn, 7), GPIO7, _1, () ()))); }; } @@ -5567,56 +7466,56 @@ macro_rules! for_each_lp_function { macro_rules! for_each_iomux_function { ($($pattern:tt => $code:tt;)*) => { macro_rules! _for_each_inner_iomux_function { $(($pattern) => $code;)* ($other : - tt) => {} } _for_each_inner_iomux_function!((LCD_DATA19, GPIO2, _3)); - _for_each_inner_iomux_function!((LCD_DATA20, GPIO3, _3)); - _for_each_inner_iomux_function!((LCD_DATA21, GPIO4, _3)); - _for_each_inner_iomux_function!((LCD_DATA22, GPIO5, _3)); - _for_each_inner_iomux_function!((LCD_DATA23, GPIO7, _3)); - _for_each_inner_iomux_function!((GMAC_PHY_TXD0, GPIO8, _2)); - _for_each_inner_iomux_function!((LCD_DATA0, GPIO8, _3)); + tt) => {} } _for_each_inner_iomux_function!((LCD_DATA_19, GPIO2, _3)); + _for_each_inner_iomux_function!((LCD_DATA_20, GPIO3, _3)); + _for_each_inner_iomux_function!((LCD_DATA_21, GPIO4, _3)); + _for_each_inner_iomux_function!((LCD_DATA_22, GPIO5, _3)); + _for_each_inner_iomux_function!((LCD_DATA_23, GPIO7, _3)); + _for_each_inner_iomux_function!((EMAC_TXD0, GPIO8, _2)); + _for_each_inner_iomux_function!((LCD_DATA_0, GPIO8, _3)); _for_each_inner_iomux_function!((FSPIHD, GPIO9, _0)); - _for_each_inner_iomux_function!((GMAC_PHY_TXD1, GPIO9, _2)); - _for_each_inner_iomux_function!((LCD_DATA1, GPIO9, _3)); + _for_each_inner_iomux_function!((EMAC_TXD1, GPIO9, _2)); + _for_each_inner_iomux_function!((LCD_DATA_1, GPIO9, _3)); _for_each_inner_iomux_function!((DBG_PSRAM_CK, GPIO9, _4)); _for_each_inner_iomux_function!((FSPICS0, GPIO10, _0)); - _for_each_inner_iomux_function!((GMAC_PHY_TXD2, GPIO10, _2)); - _for_each_inner_iomux_function!((LCD_DATA2, GPIO10, _3)); + _for_each_inner_iomux_function!((EMAC_TXD2, GPIO10, _2)); + _for_each_inner_iomux_function!((LCD_DATA_2, GPIO10, _3)); _for_each_inner_iomux_function!((DBG_PSRAM_CS, GPIO10, _4)); _for_each_inner_iomux_function!((FSPID, GPIO11, _0)); - _for_each_inner_iomux_function!((GMAC_PHY_TXD3, GPIO11, _2)); - _for_each_inner_iomux_function!((LCD_DATA3, GPIO11, _3)); + _for_each_inner_iomux_function!((EMAC_TXD3, GPIO11, _2)); + _for_each_inner_iomux_function!((LCD_DATA_3, GPIO11, _3)); _for_each_inner_iomux_function!((DBG_PSRAM_D, GPIO11, _4)); _for_each_inner_iomux_function!((FSPICLK, GPIO12, _0)); - _for_each_inner_iomux_function!((GMAC_PHY_TXEN, GPIO12, _2)); - _for_each_inner_iomux_function!((LCD_DATA4, GPIO12, _3)); + _for_each_inner_iomux_function!((EMAC_TXEN, GPIO12, _2)); + _for_each_inner_iomux_function!((LCD_DATA_4, GPIO12, _3)); _for_each_inner_iomux_function!((DBG_PSRAM_Q, GPIO12, _4)); _for_each_inner_iomux_function!((FSPIQ, GPIO13, _0)); - _for_each_inner_iomux_function!((GMAC_RMII_CLK, GPIO13, _2)); - _for_each_inner_iomux_function!((LCD_DATA5, GPIO13, _3)); + _for_each_inner_iomux_function!((EMAC_RMII_CLK, GPIO13, _2)); + _for_each_inner_iomux_function!((LCD_DATA_5, GPIO13, _3)); _for_each_inner_iomux_function!((DBG_PSRAM_WP, GPIO13, _4)); _for_each_inner_iomux_function!((FSPIWP, GPIO14, _0)); - _for_each_inner_iomux_function!((GMAC_RX_CLK, GPIO14, _2)); - _for_each_inner_iomux_function!((LCD_DATA6, GPIO14, _3)); + _for_each_inner_iomux_function!((EMAC_RX_CLK, GPIO14, _2)); + _for_each_inner_iomux_function!((LCD_DATA_6, GPIO14, _3)); _for_each_inner_iomux_function!((DBG_PSRAM_HOLD, GPIO14, _4)); _for_each_inner_iomux_function!((FSPIIO4, GPIO15, _0)); - _for_each_inner_iomux_function!((GMAC_PHY_RXDV, GPIO15, _2)); - _for_each_inner_iomux_function!((LCD_DATA7, GPIO15, _3)); + _for_each_inner_iomux_function!((EMAC_RXDV, GPIO15, _2)); + _for_each_inner_iomux_function!((LCD_DATA_7, GPIO15, _3)); _for_each_inner_iomux_function!((DBG_PSRAM_DQ4, GPIO15, _4)); _for_each_inner_iomux_function!((FSPIIO5, GPIO16, _0)); - _for_each_inner_iomux_function!((GMAC_PHY_RXD3, GPIO16, _2)); - _for_each_inner_iomux_function!((LCD_DATA8, GPIO16, _3)); + _for_each_inner_iomux_function!((EMAC_RXD3, GPIO16, _2)); + _for_each_inner_iomux_function!((LCD_DATA_8, GPIO16, _3)); _for_each_inner_iomux_function!((DBG_PSRAM_DQ5, GPIO16, _4)); _for_each_inner_iomux_function!((FSPIIO6, GPIO17, _0)); - _for_each_inner_iomux_function!((GMAC_PHY_RXD2, GPIO17, _2)); - _for_each_inner_iomux_function!((LCD_DATA9, GPIO17, _3)); + _for_each_inner_iomux_function!((EMAC_RXD2, GPIO17, _2)); + _for_each_inner_iomux_function!((LCD_DATA_9, GPIO17, _3)); _for_each_inner_iomux_function!((DBG_PSRAM_DQ6, GPIO17, _4)); _for_each_inner_iomux_function!((FSPIIO7, GPIO18, _0)); - _for_each_inner_iomux_function!((GMAC_PHY_RXD1, GPIO18, _2)); - _for_each_inner_iomux_function!((LCD_DATA10, GPIO18, _3)); + _for_each_inner_iomux_function!((EMAC_RXD1, GPIO18, _2)); + _for_each_inner_iomux_function!((LCD_DATA_10, GPIO18, _3)); _for_each_inner_iomux_function!((DBG_PSRAM_DQ7, GPIO18, _4)); _for_each_inner_iomux_function!((FSPIDQS, GPIO19, _0)); - _for_each_inner_iomux_function!((GMAC_PHY_RXD0, GPIO19, _2)); - _for_each_inner_iomux_function!((LCD_DATA11, GPIO19, _3)); + _for_each_inner_iomux_function!((EMAC_RXD0, GPIO19, _2)); + _for_each_inner_iomux_function!((LCD_DATA_11, GPIO19, _3)); _for_each_inner_iomux_function!((DBG_PSRAM_DQS_0, GPIO19, _4)); _for_each_inner_iomux_function!((SD1_DATA0, GPIO20, _0)); _for_each_inner_iomux_function!((FSPICLK, GPIO20, _2)); @@ -5642,45 +7541,45 @@ macro_rules! for_each_iomux_function { _for_each_inner_iomux_function!((SPIHD, GPIO30, _0)); _for_each_inner_iomux_function!((SPICLK, GPIO31, _0)); _for_each_inner_iomux_function!((SPID, GPIO32, _0)); - _for_each_inner_iomux_function!((LCD_DATA12, GPIO33, _3)); - _for_each_inner_iomux_function!((LCD_DATA13, GPIO34, _3)); - _for_each_inner_iomux_function!((REF_GMAC_CLK, GPIO35, _2)); - _for_each_inner_iomux_function!((LCD_DATA14, GPIO35, _3)); + _for_each_inner_iomux_function!((LCD_DATA_12, GPIO33, _3)); + _for_each_inner_iomux_function!((LCD_DATA_13, GPIO34, _3)); + _for_each_inner_iomux_function!((REF_50M_CLK, GPIO35, _2)); + _for_each_inner_iomux_function!((LCD_DATA_14, GPIO35, _3)); _for_each_inner_iomux_function!((SD2_CDATA0, GPIO35, _4)); - _for_each_inner_iomux_function!((GMAC_PHY_RXDV, GPIO36, _2)); - _for_each_inner_iomux_function!((LCD_DATA15, GPIO36, _3)); + _for_each_inner_iomux_function!((EMAC_RXDV, GPIO36, _2)); + _for_each_inner_iomux_function!((LCD_DATA_15, GPIO36, _3)); _for_each_inner_iomux_function!((SD2_CDATA1, GPIO36, _4)); - _for_each_inner_iomux_function!((GMAC_PHY_TXEN, GPIO37, _2)); - _for_each_inner_iomux_function!((LCD_DATA16, GPIO37, _3)); + _for_each_inner_iomux_function!((EMAC_TXEN, GPIO37, _2)); + _for_each_inner_iomux_function!((LCD_DATA_16, GPIO37, _3)); _for_each_inner_iomux_function!((SD2_CDATA2, GPIO37, _4)); - _for_each_inner_iomux_function!((GMAC_PHY_RXD3, GPIO38, _2)); - _for_each_inner_iomux_function!((LCD_DATA17, GPIO38, _3)); + _for_each_inner_iomux_function!((EMAC_RXD3, GPIO38, _2)); + _for_each_inner_iomux_function!((LCD_DATA_17, GPIO38, _3)); _for_each_inner_iomux_function!((SD2_CDATA3, GPIO38, _4)); - _for_each_inner_iomux_function!((GMAC_PHY_RXD2, GPIO39, _2)); - _for_each_inner_iomux_function!((LCD_DATA18, GPIO39, _3)); + _for_each_inner_iomux_function!((EMAC_RXD2, GPIO39, _2)); + _for_each_inner_iomux_function!((LCD_DATA_18, GPIO39, _3)); _for_each_inner_iomux_function!((SD2_CCLK, GPIO39, _4)); - _for_each_inner_iomux_function!((GMAC_PHY_RXD1, GPIO40, _2)); + _for_each_inner_iomux_function!((EMAC_RXD1, GPIO40, _2)); _for_each_inner_iomux_function!((LCD_PCLK, GPIO40, _3)); _for_each_inner_iomux_function!((SD2_CCMD, GPIO40, _4)); - _for_each_inner_iomux_function!((GMAC_RX_CLK, GPIO42, _2)); - _for_each_inner_iomux_function!((GMAC_RMII_CLK, GPIO43, _2)); + _for_each_inner_iomux_function!((EMAC_RX_CLK, GPIO42, _2)); + _for_each_inner_iomux_function!((EMAC_RMII_CLK, GPIO43, _2)); _for_each_inner_iomux_function!((LCD_H_ENABLE, GPIO43, _3)); - _for_each_inner_iomux_function!((GMAC_PHY_TXD0, GPIO44, _2)); + _for_each_inner_iomux_function!((EMAC_TXD0, GPIO44, _2)); _for_each_inner_iomux_function!((LCD_H_SYNC, GPIO44, _3)); - _for_each_inner_iomux_function!((GMAC_PHY_TXD1, GPIO45, _2)); + _for_each_inner_iomux_function!((EMAC_TXD1, GPIO45, _2)); _for_each_inner_iomux_function!((LCD_V_SYNC, GPIO45, _3)); - _for_each_inner_iomux_function!((GMAC_PHY_TXD2, GPIO46, _2)); - _for_each_inner_iomux_function!((CAM_DATA0, GPIO46, _3)); - _for_each_inner_iomux_function!((GMAC_PHY_TXD3, GPIO47, _2)); - _for_each_inner_iomux_function!((CAM_DATA1, GPIO47, _3)); - _for_each_inner_iomux_function!((CAM_DATA2, GPIO48, _3)); - _for_each_inner_iomux_function!((CAM_DATA3, GPIO49, _3)); - _for_each_inner_iomux_function!((CAM_DATA4, GPIO50, _3)); - _for_each_inner_iomux_function!((CAM_DATA5, GPIO51, _3)); + _for_each_inner_iomux_function!((EMAC_TXD2, GPIO46, _2)); + _for_each_inner_iomux_function!((CAM_DATA_0, GPIO46, _3)); + _for_each_inner_iomux_function!((EMAC_TXD3, GPIO47, _2)); + _for_each_inner_iomux_function!((CAM_DATA_1, GPIO47, _3)); + _for_each_inner_iomux_function!((CAM_DATA_2, GPIO48, _3)); + _for_each_inner_iomux_function!((CAM_DATA_3, GPIO49, _3)); + _for_each_inner_iomux_function!((CAM_DATA_4, GPIO50, _3)); + _for_each_inner_iomux_function!((CAM_DATA_5, GPIO51, _3)); _for_each_inner_iomux_function!((FSPICS0, GPIO52, _2)); - _for_each_inner_iomux_function!((CAM_DATA6, GPIO52, _3)); + _for_each_inner_iomux_function!((CAM_DATA_6, GPIO52, _3)); _for_each_inner_iomux_function!((FSPICLK, GPIO53, _2)); - _for_each_inner_iomux_function!((CAM_DATA7, GPIO53, _3)); + _for_each_inner_iomux_function!((CAM_DATA_7, GPIO53, _3)); _for_each_inner_iomux_function!((MTDO, GPIO54, _0)); _for_each_inner_iomux_function!((FSPID, GPIO54, _2)); _for_each_inner_iomux_function!((CAM_PCLK, GPIO54, _3)); @@ -5695,38 +7594,38 @@ macro_rules! for_each_iomux_function { _for_each_inner_iomux_function!((CAM_H_SYNC, GPIO57, _3)); _for_each_inner_iomux_function!((U0TXD, GPIO58, _0)); _for_each_inner_iomux_function!((U0RXD, GPIO59, _0)); - _for_each_inner_iomux_function!(((LCD_DATA19, LCD_DATAn, 19), GPIO2, _3)); - _for_each_inner_iomux_function!(((LCD_DATA20, LCD_DATAn, 20), GPIO3, _3)); - _for_each_inner_iomux_function!(((LCD_DATA21, LCD_DATAn, 21), GPIO4, _3)); - _for_each_inner_iomux_function!(((LCD_DATA22, LCD_DATAn, 22), GPIO5, _3)); - _for_each_inner_iomux_function!(((LCD_DATA23, LCD_DATAn, 23), GPIO7, _3)); - _for_each_inner_iomux_function!(((LCD_DATA0, LCD_DATAn, 0), GPIO8, _3)); - _for_each_inner_iomux_function!(((LCD_DATA1, LCD_DATAn, 1), GPIO9, _3)); - _for_each_inner_iomux_function!(((LCD_DATA2, LCD_DATAn, 2), GPIO10, _3)); - _for_each_inner_iomux_function!(((LCD_DATA3, LCD_DATAn, 3), GPIO11, _3)); - _for_each_inner_iomux_function!(((LCD_DATA4, LCD_DATAn, 4), GPIO12, _3)); - _for_each_inner_iomux_function!(((LCD_DATA5, LCD_DATAn, 5), GPIO13, _3)); - _for_each_inner_iomux_function!(((LCD_DATA6, LCD_DATAn, 6), GPIO14, _3)); - _for_each_inner_iomux_function!(((LCD_DATA7, LCD_DATAn, 7), GPIO15, _3)); - _for_each_inner_iomux_function!(((LCD_DATA8, LCD_DATAn, 8), GPIO16, _3)); - _for_each_inner_iomux_function!(((LCD_DATA9, LCD_DATAn, 9), GPIO17, _3)); - _for_each_inner_iomux_function!(((LCD_DATA10, LCD_DATAn, 10), GPIO18, _3)); - _for_each_inner_iomux_function!(((LCD_DATA11, LCD_DATAn, 11), GPIO19, _3)); - _for_each_inner_iomux_function!(((LCD_DATA12, LCD_DATAn, 12), GPIO33, _3)); - _for_each_inner_iomux_function!(((LCD_DATA13, LCD_DATAn, 13), GPIO34, _3)); - _for_each_inner_iomux_function!(((LCD_DATA14, LCD_DATAn, 14), GPIO35, _3)); - _for_each_inner_iomux_function!(((LCD_DATA15, LCD_DATAn, 15), GPIO36, _3)); - _for_each_inner_iomux_function!(((LCD_DATA16, LCD_DATAn, 16), GPIO37, _3)); - _for_each_inner_iomux_function!(((LCD_DATA17, LCD_DATAn, 17), GPIO38, _3)); - _for_each_inner_iomux_function!(((LCD_DATA18, LCD_DATAn, 18), GPIO39, _3)); - _for_each_inner_iomux_function!(((GMAC_PHY_TXD0, GMAC_PHY_TXDn, 0), GPIO8, _2)); - _for_each_inner_iomux_function!(((GMAC_PHY_TXD1, GMAC_PHY_TXDn, 1), GPIO9, _2)); - _for_each_inner_iomux_function!(((GMAC_PHY_TXD2, GMAC_PHY_TXDn, 2), GPIO10, _2)); - _for_each_inner_iomux_function!(((GMAC_PHY_TXD3, GMAC_PHY_TXDn, 3), GPIO11, _2)); - _for_each_inner_iomux_function!(((GMAC_PHY_TXD0, GMAC_PHY_TXDn, 0), GPIO44, _2)); - _for_each_inner_iomux_function!(((GMAC_PHY_TXD1, GMAC_PHY_TXDn, 1), GPIO45, _2)); - _for_each_inner_iomux_function!(((GMAC_PHY_TXD2, GMAC_PHY_TXDn, 2), GPIO46, _2)); - _for_each_inner_iomux_function!(((GMAC_PHY_TXD3, GMAC_PHY_TXDn, 3), GPIO47, _2)); + _for_each_inner_iomux_function!(((LCD_DATA_19, LCD_DATA_n, 19), GPIO2, _3)); + _for_each_inner_iomux_function!(((LCD_DATA_20, LCD_DATA_n, 20), GPIO3, _3)); + _for_each_inner_iomux_function!(((LCD_DATA_21, LCD_DATA_n, 21), GPIO4, _3)); + _for_each_inner_iomux_function!(((LCD_DATA_22, LCD_DATA_n, 22), GPIO5, _3)); + _for_each_inner_iomux_function!(((LCD_DATA_23, LCD_DATA_n, 23), GPIO7, _3)); + _for_each_inner_iomux_function!(((LCD_DATA_0, LCD_DATA_n, 0), GPIO8, _3)); + _for_each_inner_iomux_function!(((LCD_DATA_1, LCD_DATA_n, 1), GPIO9, _3)); + _for_each_inner_iomux_function!(((LCD_DATA_2, LCD_DATA_n, 2), GPIO10, _3)); + _for_each_inner_iomux_function!(((LCD_DATA_3, LCD_DATA_n, 3), GPIO11, _3)); + _for_each_inner_iomux_function!(((LCD_DATA_4, LCD_DATA_n, 4), GPIO12, _3)); + _for_each_inner_iomux_function!(((LCD_DATA_5, LCD_DATA_n, 5), GPIO13, _3)); + _for_each_inner_iomux_function!(((LCD_DATA_6, LCD_DATA_n, 6), GPIO14, _3)); + _for_each_inner_iomux_function!(((LCD_DATA_7, LCD_DATA_n, 7), GPIO15, _3)); + _for_each_inner_iomux_function!(((LCD_DATA_8, LCD_DATA_n, 8), GPIO16, _3)); + _for_each_inner_iomux_function!(((LCD_DATA_9, LCD_DATA_n, 9), GPIO17, _3)); + _for_each_inner_iomux_function!(((LCD_DATA_10, LCD_DATA_n, 10), GPIO18, _3)); + _for_each_inner_iomux_function!(((LCD_DATA_11, LCD_DATA_n, 11), GPIO19, _3)); + _for_each_inner_iomux_function!(((LCD_DATA_12, LCD_DATA_n, 12), GPIO33, _3)); + _for_each_inner_iomux_function!(((LCD_DATA_13, LCD_DATA_n, 13), GPIO34, _3)); + _for_each_inner_iomux_function!(((LCD_DATA_14, LCD_DATA_n, 14), GPIO35, _3)); + _for_each_inner_iomux_function!(((LCD_DATA_15, LCD_DATA_n, 15), GPIO36, _3)); + _for_each_inner_iomux_function!(((LCD_DATA_16, LCD_DATA_n, 16), GPIO37, _3)); + _for_each_inner_iomux_function!(((LCD_DATA_17, LCD_DATA_n, 17), GPIO38, _3)); + _for_each_inner_iomux_function!(((LCD_DATA_18, LCD_DATA_n, 18), GPIO39, _3)); + _for_each_inner_iomux_function!(((EMAC_TXD0, EMAC_TXDn, 0), GPIO8, _2)); + _for_each_inner_iomux_function!(((EMAC_TXD1, EMAC_TXDn, 1), GPIO9, _2)); + _for_each_inner_iomux_function!(((EMAC_TXD2, EMAC_TXDn, 2), GPIO10, _2)); + _for_each_inner_iomux_function!(((EMAC_TXD3, EMAC_TXDn, 3), GPIO11, _2)); + _for_each_inner_iomux_function!(((EMAC_TXD0, EMAC_TXDn, 0), GPIO44, _2)); + _for_each_inner_iomux_function!(((EMAC_TXD1, EMAC_TXDn, 1), GPIO45, _2)); + _for_each_inner_iomux_function!(((EMAC_TXD2, EMAC_TXDn, 2), GPIO46, _2)); + _for_each_inner_iomux_function!(((EMAC_TXD3, EMAC_TXDn, 3), GPIO47, _2)); _for_each_inner_iomux_function!(((FSPICS0, FSPICSn, 0), GPIO10, _0)); _for_each_inner_iomux_function!(((FSPICS0, FSPICSn, 0), GPIO23, _2)); _for_each_inner_iomux_function!(((FSPICS0, FSPICSn, 0), GPIO52, _2)); @@ -5738,13 +7637,13 @@ macro_rules! for_each_iomux_function { _for_each_inner_iomux_function!(((DBG_PSRAM_DQ5, DBG_PSRAM_DQn, 5), GPIO16, _4)); _for_each_inner_iomux_function!(((DBG_PSRAM_DQ6, DBG_PSRAM_DQn, 6), GPIO17, _4)); _for_each_inner_iomux_function!(((DBG_PSRAM_DQ7, DBG_PSRAM_DQn, 7), GPIO18, _4)); - _for_each_inner_iomux_function!(((GMAC_PHY_RXD3, GMAC_PHY_RXDn, 3), GPIO16, _2)); - _for_each_inner_iomux_function!(((GMAC_PHY_RXD2, GMAC_PHY_RXDn, 2), GPIO17, _2)); - _for_each_inner_iomux_function!(((GMAC_PHY_RXD1, GMAC_PHY_RXDn, 1), GPIO18, _2)); - _for_each_inner_iomux_function!(((GMAC_PHY_RXD0, GMAC_PHY_RXDn, 0), GPIO19, _2)); - _for_each_inner_iomux_function!(((GMAC_PHY_RXD3, GMAC_PHY_RXDn, 3), GPIO38, _2)); - _for_each_inner_iomux_function!(((GMAC_PHY_RXD2, GMAC_PHY_RXDn, 2), GPIO39, _2)); - _for_each_inner_iomux_function!(((GMAC_PHY_RXD1, GMAC_PHY_RXDn, 1), GPIO40, _2)); + _for_each_inner_iomux_function!(((EMAC_RXD3, EMAC_RXDn, 3), GPIO16, _2)); + _for_each_inner_iomux_function!(((EMAC_RXD2, EMAC_RXDn, 2), GPIO17, _2)); + _for_each_inner_iomux_function!(((EMAC_RXD1, EMAC_RXDn, 1), GPIO18, _2)); + _for_each_inner_iomux_function!(((EMAC_RXD0, EMAC_RXDn, 0), GPIO19, _2)); + _for_each_inner_iomux_function!(((EMAC_RXD3, EMAC_RXDn, 3), GPIO38, _2)); + _for_each_inner_iomux_function!(((EMAC_RXD2, EMAC_RXDn, 2), GPIO39, _2)); + _for_each_inner_iomux_function!(((EMAC_RXD1, EMAC_RXDn, 1), GPIO40, _2)); _for_each_inner_iomux_function!(((DBG_PSRAM_DQS_0, DBG_PSRAM_DQS_n, 0), GPIO19, _4)); _for_each_inner_iomux_function!(((SD1_DATA0, SDn_DATAm, 1, 0), GPIO20, _0)); _for_each_inner_iomux_function!(((SD1_DATA1, SDn_DATAm, 1, 1), GPIO21, @@ -5759,76 +7658,76 @@ macro_rules! for_each_iomux_function { _for_each_inner_iomux_function!(((SD2_CDATA3, SDn_CDATAm, 2, 3), GPIO38, _4)); _for_each_inner_iomux_function!(((SD2_CCLK, SDn_CCLK, 2), GPIO39, _4)); _for_each_inner_iomux_function!(((SD2_CCMD, SDn_CCMD, 2), GPIO40, _4)); - _for_each_inner_iomux_function!(((CAM_DATA0, CAM_DATAn, 0), GPIO46, _3)); - _for_each_inner_iomux_function!(((CAM_DATA1, CAM_DATAn, 1), GPIO47, _3)); - _for_each_inner_iomux_function!(((CAM_DATA2, CAM_DATAn, 2), GPIO48, _3)); - _for_each_inner_iomux_function!(((CAM_DATA3, CAM_DATAn, 3), GPIO49, _3)); - _for_each_inner_iomux_function!(((CAM_DATA4, CAM_DATAn, 4), GPIO50, _3)); - _for_each_inner_iomux_function!(((CAM_DATA5, CAM_DATAn, 5), GPIO51, _3)); - _for_each_inner_iomux_function!(((CAM_DATA6, CAM_DATAn, 6), GPIO52, _3)); - _for_each_inner_iomux_function!(((CAM_DATA7, CAM_DATAn, 7), GPIO53, _3)); - _for_each_inner_iomux_function!((all(LCD_DATA19, GPIO2, _3), (LCD_DATA20, GPIO3, - _3), (LCD_DATA21, GPIO4, _3), (LCD_DATA22, GPIO5, _3), (LCD_DATA23, GPIO7, _3), - (GMAC_PHY_TXD0, GPIO8, _2), (LCD_DATA0, GPIO8, _3), (FSPIHD, GPIO9, _0), - (GMAC_PHY_TXD1, GPIO9, _2), (LCD_DATA1, GPIO9, _3), (DBG_PSRAM_CK, GPIO9, _4), - (FSPICS0, GPIO10, _0), (GMAC_PHY_TXD2, GPIO10, _2), (LCD_DATA2, GPIO10, _3), - (DBG_PSRAM_CS, GPIO10, _4), (FSPID, GPIO11, _0), (GMAC_PHY_TXD3, GPIO11, _2), - (LCD_DATA3, GPIO11, _3), (DBG_PSRAM_D, GPIO11, _4), (FSPICLK, GPIO12, _0), - (GMAC_PHY_TXEN, GPIO12, _2), (LCD_DATA4, GPIO12, _3), (DBG_PSRAM_Q, GPIO12, _4), - (FSPIQ, GPIO13, _0), (GMAC_RMII_CLK, GPIO13, _2), (LCD_DATA5, GPIO13, _3), - (DBG_PSRAM_WP, GPIO13, _4), (FSPIWP, GPIO14, _0), (GMAC_RX_CLK, GPIO14, _2), - (LCD_DATA6, GPIO14, _3), (DBG_PSRAM_HOLD, GPIO14, _4), (FSPIIO4, GPIO15, _0), - (GMAC_PHY_RXDV, GPIO15, _2), (LCD_DATA7, GPIO15, _3), (DBG_PSRAM_DQ4, GPIO15, - _4), (FSPIIO5, GPIO16, _0), (GMAC_PHY_RXD3, GPIO16, _2), (LCD_DATA8, GPIO16, _3), - (DBG_PSRAM_DQ5, GPIO16, _4), (FSPIIO6, GPIO17, _0), (GMAC_PHY_RXD2, GPIO17, _2), - (LCD_DATA9, GPIO17, _3), (DBG_PSRAM_DQ6, GPIO17, _4), (FSPIIO7, GPIO18, _0), - (GMAC_PHY_RXD1, GPIO18, _2), (LCD_DATA10, GPIO18, _3), (DBG_PSRAM_DQ7, GPIO18, - _4), (FSPIDQS, GPIO19, _0), (GMAC_PHY_RXD0, GPIO19, _2), (LCD_DATA11, GPIO19, - _3), (DBG_PSRAM_DQS_0, GPIO19, _4), (SD1_DATA0, GPIO20, _0), (FSPICLK, GPIO20, - _2), (DBG_FLASH_CK, GPIO20, _4), (SD1_DATA1, GPIO21, _0), (FSPID, GPIO21, _2), + _for_each_inner_iomux_function!(((CAM_DATA_0, CAM_DATA_n, 0), GPIO46, _3)); + _for_each_inner_iomux_function!(((CAM_DATA_1, CAM_DATA_n, 1), GPIO47, _3)); + _for_each_inner_iomux_function!(((CAM_DATA_2, CAM_DATA_n, 2), GPIO48, _3)); + _for_each_inner_iomux_function!(((CAM_DATA_3, CAM_DATA_n, 3), GPIO49, _3)); + _for_each_inner_iomux_function!(((CAM_DATA_4, CAM_DATA_n, 4), GPIO50, _3)); + _for_each_inner_iomux_function!(((CAM_DATA_5, CAM_DATA_n, 5), GPIO51, _3)); + _for_each_inner_iomux_function!(((CAM_DATA_6, CAM_DATA_n, 6), GPIO52, _3)); + _for_each_inner_iomux_function!(((CAM_DATA_7, CAM_DATA_n, 7), GPIO53, _3)); + _for_each_inner_iomux_function!((all(LCD_DATA_19, GPIO2, _3), (LCD_DATA_20, + GPIO3, _3), (LCD_DATA_21, GPIO4, _3), (LCD_DATA_22, GPIO5, _3), (LCD_DATA_23, + GPIO7, _3), (EMAC_TXD0, GPIO8, _2), (LCD_DATA_0, GPIO8, _3), (FSPIHD, GPIO9, _0), + (EMAC_TXD1, GPIO9, _2), (LCD_DATA_1, GPIO9, _3), (DBG_PSRAM_CK, GPIO9, _4), + (FSPICS0, GPIO10, _0), (EMAC_TXD2, GPIO10, _2), (LCD_DATA_2, GPIO10, _3), + (DBG_PSRAM_CS, GPIO10, _4), (FSPID, GPIO11, _0), (EMAC_TXD3, GPIO11, _2), + (LCD_DATA_3, GPIO11, _3), (DBG_PSRAM_D, GPIO11, _4), (FSPICLK, GPIO12, _0), + (EMAC_TXEN, GPIO12, _2), (LCD_DATA_4, GPIO12, _3), (DBG_PSRAM_Q, GPIO12, _4), + (FSPIQ, GPIO13, _0), (EMAC_RMII_CLK, GPIO13, _2), (LCD_DATA_5, GPIO13, _3), + (DBG_PSRAM_WP, GPIO13, _4), (FSPIWP, GPIO14, _0), (EMAC_RX_CLK, GPIO14, _2), + (LCD_DATA_6, GPIO14, _3), (DBG_PSRAM_HOLD, GPIO14, _4), (FSPIIO4, GPIO15, _0), + (EMAC_RXDV, GPIO15, _2), (LCD_DATA_7, GPIO15, _3), (DBG_PSRAM_DQ4, GPIO15, _4), + (FSPIIO5, GPIO16, _0), (EMAC_RXD3, GPIO16, _2), (LCD_DATA_8, GPIO16, _3), + (DBG_PSRAM_DQ5, GPIO16, _4), (FSPIIO6, GPIO17, _0), (EMAC_RXD2, GPIO17, _2), + (LCD_DATA_9, GPIO17, _3), (DBG_PSRAM_DQ6, GPIO17, _4), (FSPIIO7, GPIO18, _0), + (EMAC_RXD1, GPIO18, _2), (LCD_DATA_10, GPIO18, _3), (DBG_PSRAM_DQ7, GPIO18, _4), + (FSPIDQS, GPIO19, _0), (EMAC_RXD0, GPIO19, _2), (LCD_DATA_11, GPIO19, _3), + (DBG_PSRAM_DQS_0, GPIO19, _4), (SD1_DATA0, GPIO20, _0), (FSPICLK, GPIO20, _2), + (DBG_FLASH_CK, GPIO20, _4), (SD1_DATA1, GPIO21, _0), (FSPID, GPIO21, _2), (DBG_FLASH_D, GPIO21, _4), (SD1_DATA2, GPIO22, _0), (FSPIQ, GPIO22, _2), (DBG_FLASH_CS, GPIO22, _4), (SD1_DATA3, GPIO23, _0), (FSPICS0, GPIO23, _2), (DBG_FLASH_Q, GPIO23, _4), (SD1_CLK, GPIO24, _0), (FSPIHD, GPIO24, _2), (DBG_FLASH_WP, GPIO24, _4), (SD1_CMD, GPIO25, _0), (FSPIWP, GPIO25, _2), (DBG_FLASH_HOLD, GPIO25, _4), (SPICS0, GPIO26, _0), (SPIQ, GPIO27, _0), (SPIWP, GPIO28, _0), (SPIHD, GPIO30, _0), (SPICLK, GPIO31, _0), (SPID, GPIO32, _0), - (LCD_DATA12, GPIO33, _3), (LCD_DATA13, GPIO34, _3), (REF_GMAC_CLK, GPIO35, _2), - (LCD_DATA14, GPIO35, _3), (SD2_CDATA0, GPIO35, _4), (GMAC_PHY_RXDV, GPIO36, _2), - (LCD_DATA15, GPIO36, _3), (SD2_CDATA1, GPIO36, _4), (GMAC_PHY_TXEN, GPIO37, _2), - (LCD_DATA16, GPIO37, _3), (SD2_CDATA2, GPIO37, _4), (GMAC_PHY_RXD3, GPIO38, _2), - (LCD_DATA17, GPIO38, _3), (SD2_CDATA3, GPIO38, _4), (GMAC_PHY_RXD2, GPIO39, _2), - (LCD_DATA18, GPIO39, _3), (SD2_CCLK, GPIO39, _4), (GMAC_PHY_RXD1, GPIO40, _2), - (LCD_PCLK, GPIO40, _3), (SD2_CCMD, GPIO40, _4), (GMAC_RX_CLK, GPIO42, _2), - (GMAC_RMII_CLK, GPIO43, _2), (LCD_H_ENABLE, GPIO43, _3), (GMAC_PHY_TXD0, GPIO44, - _2), (LCD_H_SYNC, GPIO44, _3), (GMAC_PHY_TXD1, GPIO45, _2), (LCD_V_SYNC, GPIO45, - _3), (GMAC_PHY_TXD2, GPIO46, _2), (CAM_DATA0, GPIO46, _3), (GMAC_PHY_TXD3, - GPIO47, _2), (CAM_DATA1, GPIO47, _3), (CAM_DATA2, GPIO48, _3), (CAM_DATA3, - GPIO49, _3), (CAM_DATA4, GPIO50, _3), (CAM_DATA5, GPIO51, _3), (FSPICS0, GPIO52, - _2), (CAM_DATA6, GPIO52, _3), (FSPICLK, GPIO53, _2), (CAM_DATA7, GPIO53, _3), - (MTDO, GPIO54, _0), (FSPID, GPIO54, _2), (CAM_PCLK, GPIO54, _3), (MTCK, GPIO55, - _0), (FSPIQ, GPIO55, _2), (CAM_XCLK, GPIO55, _3), (MTDI, GPIO56, _0), (FSPIHD, - GPIO56, _2), (CAM_V_SYNC, GPIO56, _3), (MTMS, GPIO57, _0), (FSPIWP, GPIO57, _2), + (LCD_DATA_12, GPIO33, _3), (LCD_DATA_13, GPIO34, _3), (REF_50M_CLK, GPIO35, _2), + (LCD_DATA_14, GPIO35, _3), (SD2_CDATA0, GPIO35, _4), (EMAC_RXDV, GPIO36, _2), + (LCD_DATA_15, GPIO36, _3), (SD2_CDATA1, GPIO36, _4), (EMAC_TXEN, GPIO37, _2), + (LCD_DATA_16, GPIO37, _3), (SD2_CDATA2, GPIO37, _4), (EMAC_RXD3, GPIO38, _2), + (LCD_DATA_17, GPIO38, _3), (SD2_CDATA3, GPIO38, _4), (EMAC_RXD2, GPIO39, _2), + (LCD_DATA_18, GPIO39, _3), (SD2_CCLK, GPIO39, _4), (EMAC_RXD1, GPIO40, _2), + (LCD_PCLK, GPIO40, _3), (SD2_CCMD, GPIO40, _4), (EMAC_RX_CLK, GPIO42, _2), + (EMAC_RMII_CLK, GPIO43, _2), (LCD_H_ENABLE, GPIO43, _3), (EMAC_TXD0, GPIO44, _2), + (LCD_H_SYNC, GPIO44, _3), (EMAC_TXD1, GPIO45, _2), (LCD_V_SYNC, GPIO45, _3), + (EMAC_TXD2, GPIO46, _2), (CAM_DATA_0, GPIO46, _3), (EMAC_TXD3, GPIO47, _2), + (CAM_DATA_1, GPIO47, _3), (CAM_DATA_2, GPIO48, _3), (CAM_DATA_3, GPIO49, _3), + (CAM_DATA_4, GPIO50, _3), (CAM_DATA_5, GPIO51, _3), (FSPICS0, GPIO52, _2), + (CAM_DATA_6, GPIO52, _3), (FSPICLK, GPIO53, _2), (CAM_DATA_7, GPIO53, _3), (MTDO, + GPIO54, _0), (FSPID, GPIO54, _2), (CAM_PCLK, GPIO54, _3), (MTCK, GPIO55, _0), + (FSPIQ, GPIO55, _2), (CAM_XCLK, GPIO55, _3), (MTDI, GPIO56, _0), (FSPIHD, GPIO56, + _2), (CAM_V_SYNC, GPIO56, _3), (MTMS, GPIO57, _0), (FSPIWP, GPIO57, _2), (CAM_H_SYNC, GPIO57, _3), (U0TXD, GPIO58, _0), (U0RXD, GPIO59, _0))); - _for_each_inner_iomux_function!((LCD_DATAn((LCD_DATA19, LCD_DATAn, 19), GPIO2, - _3), ((LCD_DATA20, LCD_DATAn, 20), GPIO3, _3), ((LCD_DATA21, LCD_DATAn, 21), - GPIO4, _3), ((LCD_DATA22, LCD_DATAn, 22), GPIO5, _3), ((LCD_DATA23, LCD_DATAn, - 23), GPIO7, _3), ((LCD_DATA0, LCD_DATAn, 0), GPIO8, _3), ((LCD_DATA1, LCD_DATAn, - 1), GPIO9, _3), ((LCD_DATA2, LCD_DATAn, 2), GPIO10, _3), ((LCD_DATA3, LCD_DATAn, - 3), GPIO11, _3), ((LCD_DATA4, LCD_DATAn, 4), GPIO12, _3), ((LCD_DATA5, LCD_DATAn, - 5), GPIO13, _3), ((LCD_DATA6, LCD_DATAn, 6), GPIO14, _3), ((LCD_DATA7, LCD_DATAn, - 7), GPIO15, _3), ((LCD_DATA8, LCD_DATAn, 8), GPIO16, _3), ((LCD_DATA9, LCD_DATAn, - 9), GPIO17, _3), ((LCD_DATA10, LCD_DATAn, 10), GPIO18, _3), ((LCD_DATA11, - LCD_DATAn, 11), GPIO19, _3), ((LCD_DATA12, LCD_DATAn, 12), GPIO33, _3), - ((LCD_DATA13, LCD_DATAn, 13), GPIO34, _3), ((LCD_DATA14, LCD_DATAn, 14), GPIO35, - _3), ((LCD_DATA15, LCD_DATAn, 15), GPIO36, _3), ((LCD_DATA16, LCD_DATAn, 16), - GPIO37, _3), ((LCD_DATA17, LCD_DATAn, 17), GPIO38, _3), ((LCD_DATA18, LCD_DATAn, - 18), GPIO39, _3))); - _for_each_inner_iomux_function!((GMAC_PHY_TXDn((GMAC_PHY_TXD0, GMAC_PHY_TXDn, 0), - GPIO8, _2), ((GMAC_PHY_TXD1, GMAC_PHY_TXDn, 1), GPIO9, _2), ((GMAC_PHY_TXD2, - GMAC_PHY_TXDn, 2), GPIO10, _2), ((GMAC_PHY_TXD3, GMAC_PHY_TXDn, 3), GPIO11, _2), - ((GMAC_PHY_TXD0, GMAC_PHY_TXDn, 0), GPIO44, _2), ((GMAC_PHY_TXD1, GMAC_PHY_TXDn, - 1), GPIO45, _2), ((GMAC_PHY_TXD2, GMAC_PHY_TXDn, 2), GPIO46, _2), - ((GMAC_PHY_TXD3, GMAC_PHY_TXDn, 3), GPIO47, _2))); + _for_each_inner_iomux_function!((LCD_DATA_n((LCD_DATA_19, LCD_DATA_n, 19), GPIO2, + _3), ((LCD_DATA_20, LCD_DATA_n, 20), GPIO3, _3), ((LCD_DATA_21, LCD_DATA_n, 21), + GPIO4, _3), ((LCD_DATA_22, LCD_DATA_n, 22), GPIO5, _3), ((LCD_DATA_23, + LCD_DATA_n, 23), GPIO7, _3), ((LCD_DATA_0, LCD_DATA_n, 0), GPIO8, _3), + ((LCD_DATA_1, LCD_DATA_n, 1), GPIO9, _3), ((LCD_DATA_2, LCD_DATA_n, 2), GPIO10, + _3), ((LCD_DATA_3, LCD_DATA_n, 3), GPIO11, _3), ((LCD_DATA_4, LCD_DATA_n, 4), + GPIO12, _3), ((LCD_DATA_5, LCD_DATA_n, 5), GPIO13, _3), ((LCD_DATA_6, LCD_DATA_n, + 6), GPIO14, _3), ((LCD_DATA_7, LCD_DATA_n, 7), GPIO15, _3), ((LCD_DATA_8, + LCD_DATA_n, 8), GPIO16, _3), ((LCD_DATA_9, LCD_DATA_n, 9), GPIO17, _3), + ((LCD_DATA_10, LCD_DATA_n, 10), GPIO18, _3), ((LCD_DATA_11, LCD_DATA_n, 11), + GPIO19, _3), ((LCD_DATA_12, LCD_DATA_n, 12), GPIO33, _3), ((LCD_DATA_13, + LCD_DATA_n, 13), GPIO34, _3), ((LCD_DATA_14, LCD_DATA_n, 14), GPIO35, _3), + ((LCD_DATA_15, LCD_DATA_n, 15), GPIO36, _3), ((LCD_DATA_16, LCD_DATA_n, 16), + GPIO37, _3), ((LCD_DATA_17, LCD_DATA_n, 17), GPIO38, _3), ((LCD_DATA_18, + LCD_DATA_n, 18), GPIO39, _3))); + _for_each_inner_iomux_function!((EMAC_TXDn((EMAC_TXD0, EMAC_TXDn, 0), GPIO8, _2), + ((EMAC_TXD1, EMAC_TXDn, 1), GPIO9, _2), ((EMAC_TXD2, EMAC_TXDn, 2), GPIO10, _2), + ((EMAC_TXD3, EMAC_TXDn, 3), GPIO11, _2), ((EMAC_TXD0, EMAC_TXDn, 0), GPIO44, _2), + ((EMAC_TXD1, EMAC_TXDn, 1), GPIO45, _2), ((EMAC_TXD2, EMAC_TXDn, 2), GPIO46, _2), + ((EMAC_TXD3, EMAC_TXDn, 3), GPIO47, _2))); _for_each_inner_iomux_function!((FSPICSn((FSPICS0, FSPICSn, 0), GPIO10, _0), ((FSPICS0, FSPICSn, 0), GPIO23, _2), ((FSPICS0, FSPICSn, 0), GPIO52, _2))); _for_each_inner_iomux_function!((FSPIIOn((FSPIIO4, FSPIIOn, 4), GPIO15, _0), @@ -5837,13 +7736,11 @@ macro_rules! for_each_iomux_function { _for_each_inner_iomux_function!((DBG_PSRAM_DQn((DBG_PSRAM_DQ4, DBG_PSRAM_DQn, 4), GPIO15, _4), ((DBG_PSRAM_DQ5, DBG_PSRAM_DQn, 5), GPIO16, _4), ((DBG_PSRAM_DQ6, DBG_PSRAM_DQn, 6), GPIO17, _4), ((DBG_PSRAM_DQ7, DBG_PSRAM_DQn, 7), GPIO18, - _4))); _for_each_inner_iomux_function!((GMAC_PHY_RXDn((GMAC_PHY_RXD3, - GMAC_PHY_RXDn, 3), GPIO16, _2), ((GMAC_PHY_RXD2, GMAC_PHY_RXDn, 2), GPIO17, _2), - ((GMAC_PHY_RXD1, GMAC_PHY_RXDn, 1), GPIO18, _2), ((GMAC_PHY_RXD0, GMAC_PHY_RXDn, - 0), GPIO19, _2), ((GMAC_PHY_RXD3, GMAC_PHY_RXDn, 3), GPIO38, _2), - ((GMAC_PHY_RXD2, GMAC_PHY_RXDn, 2), GPIO39, _2), ((GMAC_PHY_RXD1, GMAC_PHY_RXDn, - 1), GPIO40, _2))); - _for_each_inner_iomux_function!((DBG_PSRAM_DQS_n((DBG_PSRAM_DQS_0, + _4))); _for_each_inner_iomux_function!((EMAC_RXDn((EMAC_RXD3, EMAC_RXDn, 3), + GPIO16, _2), ((EMAC_RXD2, EMAC_RXDn, 2), GPIO17, _2), ((EMAC_RXD1, EMAC_RXDn, 1), + GPIO18, _2), ((EMAC_RXD0, EMAC_RXDn, 0), GPIO19, _2), ((EMAC_RXD3, EMAC_RXDn, 3), + GPIO38, _2), ((EMAC_RXD2, EMAC_RXDn, 2), GPIO39, _2), ((EMAC_RXD1, EMAC_RXDn, 1), + GPIO40, _2))); _for_each_inner_iomux_function!((DBG_PSRAM_DQS_n((DBG_PSRAM_DQS_0, DBG_PSRAM_DQS_n, 0), GPIO19, _4))); _for_each_inner_iomux_function!((SDn_DATAm((SD1_DATA0, SDn_DATAm, 1, 0), GPIO20, _0), ((SD1_DATA1, SDn_DATAm, 1, 1), GPIO21, _0), ((SD1_DATA2, SDn_DATAm, 1, 2), @@ -5856,11 +7753,11 @@ macro_rules! for_each_iomux_function { SDn_CDATAm, 2, 2), GPIO37, _4), ((SD2_CDATA3, SDn_CDATAm, 2, 3), GPIO38, _4))); _for_each_inner_iomux_function!((SDn_CCLK((SD2_CCLK, SDn_CCLK, 2), GPIO39, _4))); _for_each_inner_iomux_function!((SDn_CCMD((SD2_CCMD, SDn_CCMD, 2), GPIO40, _4))); - _for_each_inner_iomux_function!((CAM_DATAn((CAM_DATA0, CAM_DATAn, 0), GPIO46, - _3), ((CAM_DATA1, CAM_DATAn, 1), GPIO47, _3), ((CAM_DATA2, CAM_DATAn, 2), GPIO48, - _3), ((CAM_DATA3, CAM_DATAn, 3), GPIO49, _3), ((CAM_DATA4, CAM_DATAn, 4), GPIO50, - _3), ((CAM_DATA5, CAM_DATAn, 5), GPIO51, _3), ((CAM_DATA6, CAM_DATAn, 6), GPIO52, - _3), ((CAM_DATA7, CAM_DATAn, 7), GPIO53, _3))); + _for_each_inner_iomux_function!((CAM_DATA_n((CAM_DATA_0, CAM_DATA_n, 0), GPIO46, + _3), ((CAM_DATA_1, CAM_DATA_n, 1), GPIO47, _3), ((CAM_DATA_2, CAM_DATA_n, 2), + GPIO48, _3), ((CAM_DATA_3, CAM_DATA_n, 3), GPIO49, _3), ((CAM_DATA_4, CAM_DATA_n, + 4), GPIO50, _3), ((CAM_DATA_5, CAM_DATA_n, 5), GPIO51, _3), ((CAM_DATA_6, + CAM_DATA_n, 6), GPIO52, _3), ((CAM_DATA_7, CAM_DATA_n, 7), GPIO53, _3))); }; } /// Returns the name of the GPIO that provides the given signal, as a string. @@ -5894,25 +7791,25 @@ macro_rules! gpio_for_signal { (LP_GPIO1 $(, $_fallback:literal)?) => { "GPIO1" }; - (LCD_DATA19 $(, $_fallback:literal)?) => { + (LCD_DATA_19 $(, $_fallback:literal)?) => { "GPIO2" }; (LP_GPIO2 $(, $_fallback:literal)?) => { "GPIO2" }; - (LCD_DATA20 $(, $_fallback:literal)?) => { + (LCD_DATA_20 $(, $_fallback:literal)?) => { "GPIO3" }; (LP_GPIO3 $(, $_fallback:literal)?) => { "GPIO3" }; - (LCD_DATA21 $(, $_fallback:literal)?) => { + (LCD_DATA_21 $(, $_fallback:literal)?) => { "GPIO4" }; (LP_GPIO4 $(, $_fallback:literal)?) => { "GPIO4" }; - (LCD_DATA22 $(, $_fallback:literal)?) => { + (LCD_DATA_22 $(, $_fallback:literal)?) => { "GPIO5" }; (LP_GPIO5 $(, $_fallback:literal)?) => { @@ -5921,25 +7818,25 @@ macro_rules! gpio_for_signal { (LP_GPIO6 $(, $_fallback:literal)?) => { "GPIO6" }; - (LCD_DATA23 $(, $_fallback:literal)?) => { + (LCD_DATA_23 $(, $_fallback:literal)?) => { "GPIO7" }; (LP_GPIO7 $(, $_fallback:literal)?) => { "GPIO7" }; - (GMAC_PHY_TXD0 $(, $_fallback:literal)?) => { + (EMAC_TXD0 $(, $_fallback:literal)?) => { "GPIO8" }; - (LCD_DATA0 $(, $_fallback:literal)?) => { + (LCD_DATA_0 $(, $_fallback:literal)?) => { "GPIO8" }; (FSPIHD $(, $_fallback:literal)?) => { "GPIO9" }; - (GMAC_PHY_TXD1 $(, $_fallback:literal)?) => { + (EMAC_TXD1 $(, $_fallback:literal)?) => { "GPIO9" }; - (LCD_DATA1 $(, $_fallback:literal)?) => { + (LCD_DATA_1 $(, $_fallback:literal)?) => { "GPIO9" }; (DBG_PSRAM_CK $(, $_fallback:literal)?) => { @@ -5948,10 +7845,10 @@ macro_rules! gpio_for_signal { (FSPICS0 $(, $_fallback:literal)?) => { "GPIO10" }; - (GMAC_PHY_TXD2 $(, $_fallback:literal)?) => { + (EMAC_TXD2 $(, $_fallback:literal)?) => { "GPIO10" }; - (LCD_DATA2 $(, $_fallback:literal)?) => { + (LCD_DATA_2 $(, $_fallback:literal)?) => { "GPIO10" }; (DBG_PSRAM_CS $(, $_fallback:literal)?) => { @@ -5960,10 +7857,10 @@ macro_rules! gpio_for_signal { (FSPID $(, $_fallback:literal)?) => { "GPIO11" }; - (GMAC_PHY_TXD3 $(, $_fallback:literal)?) => { + (EMAC_TXD3 $(, $_fallback:literal)?) => { "GPIO11" }; - (LCD_DATA3 $(, $_fallback:literal)?) => { + (LCD_DATA_3 $(, $_fallback:literal)?) => { "GPIO11" }; (DBG_PSRAM_D $(, $_fallback:literal)?) => { @@ -5972,10 +7869,10 @@ macro_rules! gpio_for_signal { (FSPICLK $(, $_fallback:literal)?) => { "GPIO12" }; - (GMAC_PHY_TXEN $(, $_fallback:literal)?) => { + (EMAC_TXEN $(, $_fallback:literal)?) => { "GPIO12" }; - (LCD_DATA4 $(, $_fallback:literal)?) => { + (LCD_DATA_4 $(, $_fallback:literal)?) => { "GPIO12" }; (DBG_PSRAM_Q $(, $_fallback:literal)?) => { @@ -5984,10 +7881,10 @@ macro_rules! gpio_for_signal { (FSPIQ $(, $_fallback:literal)?) => { "GPIO13" }; - (GMAC_RMII_CLK $(, $_fallback:literal)?) => { + (EMAC_RMII_CLK $(, $_fallback:literal)?) => { "GPIO13" }; - (LCD_DATA5 $(, $_fallback:literal)?) => { + (LCD_DATA_5 $(, $_fallback:literal)?) => { "GPIO13" }; (DBG_PSRAM_WP $(, $_fallback:literal)?) => { @@ -5996,10 +7893,10 @@ macro_rules! gpio_for_signal { (FSPIWP $(, $_fallback:literal)?) => { "GPIO14" }; - (GMAC_RX_CLK $(, $_fallback:literal)?) => { + (EMAC_RX_CLK $(, $_fallback:literal)?) => { "GPIO14" }; - (LCD_DATA6 $(, $_fallback:literal)?) => { + (LCD_DATA_6 $(, $_fallback:literal)?) => { "GPIO14" }; (DBG_PSRAM_HOLD $(, $_fallback:literal)?) => { @@ -6008,10 +7905,10 @@ macro_rules! gpio_for_signal { (FSPIIO4 $(, $_fallback:literal)?) => { "GPIO15" }; - (GMAC_PHY_RXDV $(, $_fallback:literal)?) => { + (EMAC_RXDV $(, $_fallback:literal)?) => { "GPIO15" }; - (LCD_DATA7 $(, $_fallback:literal)?) => { + (LCD_DATA_7 $(, $_fallback:literal)?) => { "GPIO15" }; (DBG_PSRAM_DQ4 $(, $_fallback:literal)?) => { @@ -6020,10 +7917,10 @@ macro_rules! gpio_for_signal { (FSPIIO5 $(, $_fallback:literal)?) => { "GPIO16" }; - (GMAC_PHY_RXD3 $(, $_fallback:literal)?) => { + (EMAC_RXD3 $(, $_fallback:literal)?) => { "GPIO16" }; - (LCD_DATA8 $(, $_fallback:literal)?) => { + (LCD_DATA_8 $(, $_fallback:literal)?) => { "GPIO16" }; (DBG_PSRAM_DQ5 $(, $_fallback:literal)?) => { @@ -6032,10 +7929,10 @@ macro_rules! gpio_for_signal { (FSPIIO6 $(, $_fallback:literal)?) => { "GPIO17" }; - (GMAC_PHY_RXD2 $(, $_fallback:literal)?) => { + (EMAC_RXD2 $(, $_fallback:literal)?) => { "GPIO17" }; - (LCD_DATA9 $(, $_fallback:literal)?) => { + (LCD_DATA_9 $(, $_fallback:literal)?) => { "GPIO17" }; (DBG_PSRAM_DQ6 $(, $_fallback:literal)?) => { @@ -6044,10 +7941,10 @@ macro_rules! gpio_for_signal { (FSPIIO7 $(, $_fallback:literal)?) => { "GPIO18" }; - (GMAC_PHY_RXD1 $(, $_fallback:literal)?) => { + (EMAC_RXD1 $(, $_fallback:literal)?) => { "GPIO18" }; - (LCD_DATA10 $(, $_fallback:literal)?) => { + (LCD_DATA_10 $(, $_fallback:literal)?) => { "GPIO18" }; (DBG_PSRAM_DQ7 $(, $_fallback:literal)?) => { @@ -6056,10 +7953,10 @@ macro_rules! gpio_for_signal { (FSPIDQS $(, $_fallback:literal)?) => { "GPIO19" }; - (GMAC_PHY_RXD0 $(, $_fallback:literal)?) => { + (EMAC_RXD0 $(, $_fallback:literal)?) => { "GPIO19" }; - (LCD_DATA11 $(, $_fallback:literal)?) => { + (LCD_DATA_11 $(, $_fallback:literal)?) => { "GPIO19" }; (DBG_PSRAM_DQS_0 $(, $_fallback:literal)?) => { @@ -6119,46 +8016,46 @@ macro_rules! gpio_for_signal { (SPID $(, $_fallback:literal)?) => { "GPIO32" }; - (LCD_DATA12 $(, $_fallback:literal)?) => { + (LCD_DATA_12 $(, $_fallback:literal)?) => { "GPIO33" }; (USJ_DM $(, $_fallback:literal)?) => { "GPIO33" }; - (LCD_DATA13 $(, $_fallback:literal)?) => { + (LCD_DATA_13 $(, $_fallback:literal)?) => { "GPIO34" }; (USJ_DP $(, $_fallback:literal)?) => { "GPIO34" }; - (REF_GMAC_CLK $(, $_fallback:literal)?) => { + (REF_50M_CLK $(, $_fallback:literal)?) => { "GPIO35" }; - (LCD_DATA14 $(, $_fallback:literal)?) => { + (LCD_DATA_14 $(, $_fallback:literal)?) => { "GPIO35" }; (SD2_CDATA0 $(, $_fallback:literal)?) => { "GPIO35" }; - (LCD_DATA15 $(, $_fallback:literal)?) => { + (LCD_DATA_15 $(, $_fallback:literal)?) => { "GPIO36" }; (SD2_CDATA1 $(, $_fallback:literal)?) => { "GPIO36" }; - (LCD_DATA16 $(, $_fallback:literal)?) => { + (LCD_DATA_16 $(, $_fallback:literal)?) => { "GPIO37" }; (SD2_CDATA2 $(, $_fallback:literal)?) => { "GPIO37" }; - (LCD_DATA17 $(, $_fallback:literal)?) => { + (LCD_DATA_17 $(, $_fallback:literal)?) => { "GPIO38" }; (SD2_CDATA3 $(, $_fallback:literal)?) => { "GPIO38" }; - (LCD_DATA18 $(, $_fallback:literal)?) => { + (LCD_DATA_18 $(, $_fallback:literal)?) => { "GPIO39" }; (SD2_CCLK $(, $_fallback:literal)?) => { @@ -6191,49 +8088,49 @@ macro_rules! gpio_for_signal { (ADC1_CH3 $(, $_fallback:literal)?) => { "GPIO45" }; - (CAM_DATA0 $(, $_fallback:literal)?) => { + (CAM_DATA_0 $(, $_fallback:literal)?) => { "GPIO46" }; (ADC1_CH4 $(, $_fallback:literal)?) => { "GPIO46" }; - (CAM_DATA1 $(, $_fallback:literal)?) => { + (CAM_DATA_1 $(, $_fallback:literal)?) => { "GPIO47" }; (ADC1_CH5 $(, $_fallback:literal)?) => { "GPIO47" }; - (CAM_DATA2 $(, $_fallback:literal)?) => { + (CAM_DATA_2 $(, $_fallback:literal)?) => { "GPIO48" }; (ADC1_CH6 $(, $_fallback:literal)?) => { "GPIO48" }; - (CAM_DATA3 $(, $_fallback:literal)?) => { + (CAM_DATA_3 $(, $_fallback:literal)?) => { "GPIO49" }; (ADC1_CH7 $(, $_fallback:literal)?) => { "GPIO49" }; - (CAM_DATA4 $(, $_fallback:literal)?) => { + (CAM_DATA_4 $(, $_fallback:literal)?) => { "GPIO50" }; (ADC2_CH0 $(, $_fallback:literal)?) => { "GPIO50" }; - (CAM_DATA5 $(, $_fallback:literal)?) => { + (CAM_DATA_5 $(, $_fallback:literal)?) => { "GPIO51" }; (ADC2_CH1 $(, $_fallback:literal)?) => { "GPIO51" }; - (CAM_DATA6 $(, $_fallback:literal)?) => { + (CAM_DATA_6 $(, $_fallback:literal)?) => { "GPIO52" }; (ADC2_CH2 $(, $_fallback:literal)?) => { "GPIO52" }; - (CAM_DATA7 $(, $_fallback:literal)?) => { + (CAM_DATA_7 $(, $_fallback:literal)?) => { "GPIO53" }; (ADC2_CH3 $(, $_fallback:literal)?) => { @@ -6285,6 +8182,81 @@ macro_rules! gpio_for_signal { $fallback }; } +/// This macro can be used to generate code for each digital GPIO that deep-sleep entry +/// isolates when `gpio.need_soft_isolate_during_pd` is set. +/// +/// For an explanation on the general syntax, as well as usage of individual/repeated +/// matchers, refer to [the crate-level documentation][crate#for_each-macros]. +/// +/// The list excludes low-power pads and pads that interface with flash or PSRAM. Isolating +/// a memory-interface pad cuts instruction fetch. +/// +/// This macro has one option for its "Individual matcher" case: +/// +/// Syntax: `($n:literal)` +/// +/// Macro fragments: +/// +/// - `$n`: the number of the GPIO. For `GPIO8`, `$n` is 8. +/// +/// Example data: `(8)` +#[macro_export] +#[cfg_attr(docsrs, doc(cfg(feature = "_device-selected")))] +macro_rules! for_each_gpio_soft_isolate { + ($($pattern:tt => $code:tt;)*) => { + macro_rules! _for_each_inner_gpio_soft_isolate { $(($pattern) => $code;)* ($other + : tt) => {} } _for_each_inner_gpio_soft_isolate!((8)); + _for_each_inner_gpio_soft_isolate!((9)); + _for_each_inner_gpio_soft_isolate!((10)); + _for_each_inner_gpio_soft_isolate!((11)); + _for_each_inner_gpio_soft_isolate!((12)); + _for_each_inner_gpio_soft_isolate!((13)); + _for_each_inner_gpio_soft_isolate!((14)); + _for_each_inner_gpio_soft_isolate!((15)); + _for_each_inner_gpio_soft_isolate!((16)); + _for_each_inner_gpio_soft_isolate!((17)); + _for_each_inner_gpio_soft_isolate!((18)); + _for_each_inner_gpio_soft_isolate!((19)); + _for_each_inner_gpio_soft_isolate!((20)); + _for_each_inner_gpio_soft_isolate!((21)); + _for_each_inner_gpio_soft_isolate!((22)); + _for_each_inner_gpio_soft_isolate!((23)); + _for_each_inner_gpio_soft_isolate!((24)); + _for_each_inner_gpio_soft_isolate!((25)); + _for_each_inner_gpio_soft_isolate!((33)); + _for_each_inner_gpio_soft_isolate!((34)); + _for_each_inner_gpio_soft_isolate!((35)); + _for_each_inner_gpio_soft_isolate!((36)); + _for_each_inner_gpio_soft_isolate!((37)); + _for_each_inner_gpio_soft_isolate!((38)); + _for_each_inner_gpio_soft_isolate!((39)); + _for_each_inner_gpio_soft_isolate!((40)); + _for_each_inner_gpio_soft_isolate!((42)); + _for_each_inner_gpio_soft_isolate!((43)); + _for_each_inner_gpio_soft_isolate!((44)); + _for_each_inner_gpio_soft_isolate!((45)); + _for_each_inner_gpio_soft_isolate!((46)); + _for_each_inner_gpio_soft_isolate!((47)); + _for_each_inner_gpio_soft_isolate!((48)); + _for_each_inner_gpio_soft_isolate!((49)); + _for_each_inner_gpio_soft_isolate!((50)); + _for_each_inner_gpio_soft_isolate!((51)); + _for_each_inner_gpio_soft_isolate!((52)); + _for_each_inner_gpio_soft_isolate!((53)); + _for_each_inner_gpio_soft_isolate!((54)); + _for_each_inner_gpio_soft_isolate!((55)); + _for_each_inner_gpio_soft_isolate!((56)); + _for_each_inner_gpio_soft_isolate!((57)); + _for_each_inner_gpio_soft_isolate!((58)); + _for_each_inner_gpio_soft_isolate!((59)); + _for_each_inner_gpio_soft_isolate!((60)); + _for_each_inner_gpio_soft_isolate!((61)); + _for_each_inner_gpio_soft_isolate!((all(8), (9), (10), (11), (12), (13), (14), + (15), (16), (17), (18), (19), (20), (21), (22), (23), (24), (25), (33), (34), + (35), (36), (37), (38), (39), (40), (42), (43), (44), (45), (46), (47), (48), + (49), (50), (51), (52), (53), (54), (55), (56), (57), (58), (59), (60), (61))); + }; +} /// Defines the `InputSignal` and `OutputSignal` enums. /// /// This macro is intended to be called in esp-hal only. @@ -6309,12 +8281,21 @@ macro_rules! define_io_mux_signals { U3RXD = 137, U3CTS = 138, U3DSR = 139, - I2SO_BCK = 25, - I2S_MCLK = 26, - I2SO_WS = 27, - I2SI_SD = 28, - I2SI_BCK = 29, - I2SI_WS = 30, + I2S0O_BCK = 25, + I2S0_MCLK = 26, + I2S0O_WS = 27, + I2S0I_SD = 28, + I2S0I_BCK = 29, + I2S0I_WS = 30, + I2S0I_SD1 = 43, + I2S0I_SD2 = 44, + I2S0I_SD3 = 45, + I2S1O_BCK = 31, + I2S1_MCLK = 32, + I2S1O_WS = 33, + I2S1I_SD = 34, + I2S1I_BCK = 35, + I2S1I_WS = 36, FSPICLK = 53, FSPIQ = 54, FSPID = 55, @@ -6330,8 +8311,6 @@ macro_rules! define_io_mux_signals { FSPICS3 = 65, FSPICS4 = 66, FSPICS5 = 67, - SPI3_CS2 = 45, - SPI3_CS1 = 46, SPI3_CK = 47, SPI3_Q = 48, SPI3_D = 49, @@ -6343,6 +8322,38 @@ macro_rules! define_io_mux_signals { I2CEXT1_SCL = 70, I2CEXT1_SDA = 71, USB_JTAG_TDO_BRIDGE = 140, + PCNT0_SIG_CH0 = 141, + PCNT1_SIG_CH0 = 142, + PCNT2_SIG_CH0 = 143, + PCNT3_SIG_CH0 = 144, + PCNT0_SIG_CH1 = 145, + PCNT1_SIG_CH1 = 146, + PCNT2_SIG_CH1 = 147, + PCNT3_SIG_CH1 = 148, + PCNT0_CTRL_CH0 = 149, + PCNT1_CTRL_CH0 = 150, + PCNT2_CTRL_CH0 = 151, + PCNT3_CTRL_CH0 = 152, + PCNT0_CTRL_CH1 = 153, + PCNT1_CTRL_CH1 = 154, + PCNT2_CTRL_CH1 = 155, + PCNT3_CTRL_CH1 = 156, + PCNT1_U0_CTRL_CH0 = 72, + PCNT1_U1_CTRL_CH0 = 73, + PCNT1_U2_CTRL_CH0 = 74, + PCNT1_U3_CTRL_CH0 = 75, + PCNT1_U0_CTRL_CH1 = 76, + PCNT1_U1_CTRL_CH1 = 77, + PCNT1_U2_CTRL_CH1 = 78, + PCNT1_U3_CTRL_CH1 = 79, + PCNT1_U0_SIG_CH0 = 204, + PCNT1_U1_SIG_CH0 = 205, + PCNT1_U2_SIG_CH0 = 206, + PCNT1_U3_SIG_CH0 = 207, + PCNT1_U0_SIG_CH1 = 208, + PCNT1_U1_SIG_CH1 = 209, + PCNT1_U2_SIG_CH1 = 210, + PCNT1_U3_SIG_CH1 = 211, CPU_GPIO_0 = 214, CPU_GPIO_1 = 215, CPU_GPIO_2 = 216, @@ -6363,6 +8374,26 @@ macro_rules! define_io_mux_signals { RMT_SIG_1 = 247, RMT_SIG_2 = 248, RMT_SIG_3 = 249, + CAM_PCLK = 158, + CAM_H_ENABLE = 159, + CAM_H_SYNC = 160, + CAM_V_SYNC = 161, + CAM_DATA_0 = 162, + CAM_DATA_1 = 163, + CAM_DATA_2 = 164, + CAM_DATA_3 = 165, + CAM_DATA_4 = 166, + CAM_DATA_5 = 167, + CAM_DATA_6 = 168, + CAM_DATA_7 = 169, + CAM_DATA_8 = 170, + CAM_DATA_9 = 171, + CAM_DATA_10 = 172, + CAM_DATA_11 = 173, + CAM_DATA_12 = 174, + CAM_DATA_13 = 175, + CAM_DATA_14 = 176, + CAM_DATA_15 = 177, SDHOST_CDATA_IN_41 = 0, SDHOST_CDATA_IN_51 = 1, SDHOST_CDATA_IN_61 = 2, @@ -6379,6 +8410,17 @@ macro_rules! define_io_mux_signals { SDHOST_CARD_WRITE_PRT_2 = 131, SDHOST_DATA_STROBE_1 = 132, SDHOST_DATA_STROBE_2 = 133, + EMAC_MDI = 107, + EMAC_COL = 108, + EMAC_CRS = 109, + EMAC_RXDV = 178, + EMAC_RXD0 = 179, + EMAC_RXD1 = 180, + EMAC_RXD2 = 181, + EMAC_RXD3 = 182, + EMAC_RXER = 183, + EMAC_RX_CLK = 184, + EMAC_TX_CLK = 185, SIG_IN_FUNC251 = 251, SIG_IN_FUNC252 = 252, SIG_IN_FUNC253 = 253, @@ -6400,59 +8442,9 @@ macro_rules! define_io_mux_signals { SPIHD, SPICLK, SPID, - GMAC_PHY_TXD0, - GMAC_PHY_TXD1, - GMAC_PHY_TXD2, - GMAC_PHY_TXD3, - GMAC_PHY_TXEN, - GMAC_RMII_CLK, - GMAC_RX_CLK, - GMAC_PHY_RXDV, - GMAC_PHY_RXD0, - GMAC_PHY_RXD1, - GMAC_PHY_RXD2, - GMAC_PHY_RXD3, - REF_GMAC_CLK, - LCD_DATA0, - LCD_DATA1, - LCD_DATA2, - LCD_DATA3, - LCD_DATA4, - LCD_DATA5, - LCD_DATA6, - LCD_DATA7, - LCD_DATA8, - LCD_DATA9, - LCD_DATA10, - LCD_DATA11, - LCD_DATA12, - LCD_DATA13, - LCD_DATA14, - LCD_DATA15, - LCD_DATA16, - LCD_DATA17, - LCD_DATA18, - LCD_DATA19, - LCD_DATA20, - LCD_DATA21, - LCD_DATA22, - LCD_DATA23, - LCD_PCLK, - LCD_H_ENABLE, - LCD_H_SYNC, - LCD_V_SYNC, - CAM_DATA0, - CAM_DATA1, - CAM_DATA2, - CAM_DATA3, - CAM_DATA4, - CAM_DATA5, - CAM_DATA6, - CAM_DATA7, - CAM_PCLK, + EMAC_RMII_CLK, + REF_50M_CLK, CAM_XCLK, - CAM_V_SYNC, - CAM_H_SYNC, SD2_CDATA0, SD2_CDATA1, SD2_CDATA2, @@ -6505,12 +8497,19 @@ macro_rules! define_io_mux_signals { U3TXD = 137, U3RTS = 138, U3DTR = 116, - I2SO_BCK = 25, - I2S_MCLK = 26, - I2SO_WS = 27, - I2SO_SD = 28, - I2SI_BCK = 29, - I2SI_WS = 30, + I2S0O_BCK = 25, + I2S0_MCLK = 26, + I2S0O_WS = 27, + I2S0O_SD = 28, + I2S0I_BCK = 29, + I2S0I_WS = 30, + I2S0O_SD1 = 43, + I2S1O_BCK = 31, + I2S1_MCLK = 32, + I2S1O_WS = 33, + I2S1O_SD = 34, + I2S1I_BCK = 35, + I2S1I_WS = 36, FSPICLK = 53, FSPIQ = 54, FSPID = 55, @@ -6567,6 +8566,46 @@ macro_rules! define_io_mux_signals { RMT_SIG_1 = 247, RMT_SIG_2 = 248, RMT_SIG_3 = 249, + LCD_CS = 144, + LCD_DC = 145, + LCD_PCLK = 149, + CAM_CLK = 150, + LCD_H_ENABLE = 151, + LCD_H_SYNC = 152, + LCD_V_SYNC = 153, + LCD_DATA_0 = 154, + LCD_DATA_1 = 155, + LCD_DATA_2 = 156, + LCD_DATA_3 = 157, + LCD_DATA_4 = 158, + LCD_DATA_5 = 159, + LCD_DATA_6 = 160, + LCD_DATA_7 = 161, + LCD_DATA_8 = 162, + LCD_DATA_9 = 163, + LCD_DATA_10 = 164, + LCD_DATA_11 = 165, + LCD_DATA_12 = 166, + LCD_DATA_13 = 167, + LCD_DATA_14 = 168, + LCD_DATA_15 = 169, + LCD_DATA_16 = 170, + LCD_DATA_17 = 171, + LCD_DATA_18 = 172, + LCD_DATA_19 = 173, + LCD_DATA_20 = 174, + LCD_DATA_21 = 175, + LCD_DATA_22 = 176, + LCD_DATA_23 = 177, + EMAC_PTP_PPS = 105, + EMAC_MDC = 108, + EMAC_MDO = 109, + EMAC_TXEN = 178, + EMAC_TXD0 = 179, + EMAC_TXD1 = 180, + EMAC_TXD2 = 181, + EMAC_TXD3 = 182, + EMAC_TXER = 183, GPIO = 256, MTDO, MTCK, @@ -6584,59 +8623,9 @@ macro_rules! define_io_mux_signals { SPIHD, SPICLK, SPID, - GMAC_PHY_TXD0, - GMAC_PHY_TXD1, - GMAC_PHY_TXD2, - GMAC_PHY_TXD3, - GMAC_PHY_TXEN, - GMAC_RMII_CLK, - GMAC_RX_CLK, - GMAC_PHY_RXDV, - GMAC_PHY_RXD0, - GMAC_PHY_RXD1, - GMAC_PHY_RXD2, - GMAC_PHY_RXD3, - REF_GMAC_CLK, - LCD_DATA0, - LCD_DATA1, - LCD_DATA2, - LCD_DATA3, - LCD_DATA4, - LCD_DATA5, - LCD_DATA6, - LCD_DATA7, - LCD_DATA8, - LCD_DATA9, - LCD_DATA10, - LCD_DATA11, - LCD_DATA12, - LCD_DATA13, - LCD_DATA14, - LCD_DATA15, - LCD_DATA16, - LCD_DATA17, - LCD_DATA18, - LCD_DATA19, - LCD_DATA20, - LCD_DATA21, - LCD_DATA22, - LCD_DATA23, - LCD_PCLK, - LCD_H_ENABLE, - LCD_H_SYNC, - LCD_V_SYNC, - CAM_DATA0, - CAM_DATA1, - CAM_DATA2, - CAM_DATA3, - CAM_DATA4, - CAM_DATA5, - CAM_DATA6, - CAM_DATA7, - CAM_PCLK, + EMAC_RMII_CLK, + REF_50M_CLK, CAM_XCLK, - CAM_V_SYNC, - CAM_H_SYNC, SD2_CDATA0, SD2_CDATA1, SD2_CDATA2, @@ -6681,12 +8670,12 @@ macro_rules! define_lp_functions { #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[doc(hidden)] pub enum LpFunction { - /// LP IO MUX function 0. - _0 = 0, + /// LP IO MUX function 1. + _1 = 1, } impl LpFunction { /// The function that connects the pad to the LP GPIO peripheral. - pub const LP_GPIO: Self = Self::_0; + pub const LP_GPIO: Self = Self::_1; } }; } diff --git a/esp-metadata-generated/src/lib.rs b/esp-metadata-generated/src/lib.rs index 3db67bf87f6..cef90f0dc15 100644 --- a/esp-metadata-generated/src/lib.rs +++ b/esp-metadata-generated/src/lib.rs @@ -113,6 +113,8 @@ include!("_generated_esp32c6.rs"); include!("_generated_esp32c61.rs"); #[cfg(feature = "esp32h2")] include!("_generated_esp32h2.rs"); +#[cfg(feature = "esp32h4")] +include!("_generated_esp32h4.rs"); #[cfg(feature = "esp32p4")] include!("_generated_esp32p4.rs"); #[cfg(feature = "esp32s2")] diff --git a/esp-metadata/Cargo.toml b/esp-metadata/Cargo.toml index 86f344fdcb5..c1a4317166a 100644 --- a/esp-metadata/Cargo.toml +++ b/esp-metadata/Cargo.toml @@ -17,6 +17,9 @@ check-configs = [ { features = [] }, ] clippy-configs = [] # don't waste time on this +host-test-configs = [ + { features = [] }, +] [dependencies] anyhow = "1.0" diff --git a/esp-metadata/devices/esp32/clocks.toml b/esp-metadata/devices/esp32/clocks.toml index c9c5f45d30f..f46f216372e 100644 --- a/esp-metadata/devices/esp32/clocks.toml +++ b/esp-metadata/devices/esp32/clocks.toml @@ -8,8 +8,9 @@ system_clocks = { clock_tree = [ { name = "XTAL_CLK", type = "source", values = "26, 40", output = "VALUE * 1_000_000", always_on = true }, # 2-40MHz, always on? sw ability to measure using an internal RC clock { name = "PLL_CLK", type = "derived", from = "XTAL_CLK", values = "320, 480", output = "VALUE * 1_000_000", reject = "VALUE == 480_000_000 && divisor(CPU_PLL_DIV) == 4" }, { name = "APLL_CLK", type = "derived", from = "PLL_CLK", values = "16_000_000 ..= 128_000_000", output = "VALUE" }, - { name = "RC_FAST_CLK", type = "source", output = "8_000_000" }, # this is supposed to be adjustable using RTC_CNTL_CK8M_DIV_SEL + { name = "RC_FAST_CLK", type = "source", output = "8_000_000", adjustable = "4_000_000..=12_000_000" }, # this is supposed to be adjustable using RTC_CNTL_CK8M_DIV_SEL { name = "PLL_F160M_CLK", type = "derived", from = "PLL_CLK", output = "160_000_000" }, + { name = "PLL_D2_CLK", type = "generic", output = "PLL_CLK / 2" }, # CPU and related clocks # @@ -28,6 +29,8 @@ system_clocks = { clock_tree = [ # - `output` is an expression describing how the output frequency is calculated. # # Each item may have a `reject` list of conditions to validate the clock tree config. + # Each clock node and mux variant may have a `cfg` rustc cfg expression. The item is omitted + # when that condition is false. # # Free parameters: # - value of XTAL_CLK (can be fixed or "measured") @@ -101,16 +104,22 @@ system_clocks = { clock_tree = [ ] }, # Low-speed clocks - { name = "XTAL32K_CLK", type = "source", output = "32768" }, - { name = "RC_SLOW_CLK", type = "source", output = "150_000" }, + { name = "XTAL32K_CLK", type = "source", output = "32768", cfg = "use_xtal32k" }, + { name = "RC_SLOW_CLK", type = "source", output = "150_000", adjustable = "75_000..=225_000" }, { name = "RC_FAST_DIV_CLK", type = "generic", output = "RC_FAST_CLK / 256" }, { name = "XTAL_DIV_CLK", type = "generic", output = "XTAL_CLK / 4" }, # source: esp-idf SOC_RTC_FAST_CLK_SRC_XTAL_D4 { name = "RTC_SLOW_CLK", type = "mux", variants = [ - { name = "XTAL32K", outputs = "XTAL32K_CLK" }, + { name = "XTAL32K", outputs = "XTAL32K_CLK", cfg = "use_xtal32k" }, { name = "RC_SLOW", outputs = "RC_SLOW_CLK" }, { name = "RC_FAST", outputs = "RC_FAST_DIV_CLK" }, ] }, + # BLE modem-sleep clock. The BTDM blob programs the source and divider. + { name = "BLE_LP_XTAL_CLK", type = "derived", from = "XTAL_CLK", output = "500_000" }, + { name = "BLE_LP_CLK", type = "mux", variants = [ + { name = "XTAL", outputs = "BLE_LP_XTAL_CLK" }, + { name = "RTC_SLOW", outputs = "RTC_SLOW_CLK" }, + ] }, { name = "RTC_FAST_CLK", type = "mux", variants = [ { name = "XTAL", outputs = "XTAL_DIV_CLK" }, { name = "RC", outputs = "RC_FAST_CLK" }, @@ -134,7 +143,7 @@ system_clocks = { clock_tree = [ { name = "TIMG_CALIBRATION_CLOCK", type = "mux", wake_locking = true, variants = [ { name = "RC_SLOW_CLK", outputs = "RC_SLOW_CLK" }, { name = "RC_FAST_DIV_CLK", outputs = "RC_FAST_DIV_CLK" }, - { name = "XTAL32K_CLK", outputs = "XTAL32K_CLK" }, + { name = "XTAL32K_CLK", outputs = "XTAL32K_CLK", cfg = "use_xtal32k" }, ] }, ], template_groups = [ { group = "MCPWM", clocks = [ @@ -169,6 +178,12 @@ system_clocks = { clock_tree = [ { name = "APB", outputs = "APB_CLK", default = true }, ] }, ] }, + { group = "I2S", clocks = [ + { name = "MCLK", type = "generic", wake_locking = true, output = "(sclk * div_a) / (div_num * div_a + div_b)", params = { sclk = [ + { name = "PLL_F160M", outputs = "PLL_F160M_CLK", default = true }, + { name = "APLL", outputs = "APLL_CLK" }, + ], div_num = "1 ..= 255", div_a = "1 ..= 63", div_b = "0 ..= 63" } }, + ] }, ] } peripheral_clocks = { templates = [ diff --git a/esp-metadata/devices/esp32/soc.toml b/esp-metadata/devices/esp32/soc.toml index 814c4156c1b..30241c8bdc1 100644 --- a/esp-metadata/devices/esp32/soc.toml +++ b/esp-metadata/devices/esp32/soc.toml @@ -18,6 +18,9 @@ support_note = "Revisions below v3.0 are not supported." page_size = 0x10000 entry_num = 256 +[device.flash] +support_status = "partial" + [device.rom] has_crc_le = true has_crc_be = true @@ -40,10 +43,10 @@ peripherals = [ { name = "DPORT" }, { name = "SYSTEM", pac = "DPORT" }, { name = "EFUSE", hidden = true }, - { name = "ETH", virtual = true }, - { name = "EMAC_DMA", hidden = true }, + { name = "ETH", virtual = true, interrupts = { peri = "ETH_MAC" } }, + { name = "EMAC_DMA", pac = "GMAC_DMA", hidden = true }, { name = "EMAC_EXT", hidden = true }, - { name = "EMAC_MAC", hidden = true }, + { name = "EMAC_MAC", pac = "GMAC", hidden = true }, { name = "FLASH_ENCRYPTION" }, { name = "FRC_TIMER" }, { name = "GPIO" }, @@ -51,15 +54,15 @@ peripherals = [ { name = "HINF" }, { name = "I2C0", interrupts = { peri = "I2C_EXT0" }, stable = true, clock_group = "I2C" }, { name = "I2C1", interrupts = { peri = "I2C_EXT1" }, stable = true, clock_group = "I2C" }, - { name = "I2S0", interrupts = { peri = "I2S0" } }, - { name = "I2S1", interrupts = { peri = "I2S1" } }, + { name = "I2S0", interrupts = { peri = "I2S0" }, clock_group = "I2S" }, + { name = "I2S1", interrupts = { peri = "I2S1" }, clock_group = "I2S" }, { name = "IO_MUX" }, { name = "LEDC" }, { name = "MCPWM0", clock_group = "MCPWM" }, { name = "MMU_TABLE", hidden = true }, { name = "MCPWM1", clock_group = "MCPWM" }, { name = "NRX" }, - { name = "PCNT" }, + { name = "PCNT", interrupts = { peri = "PCNT" } }, { name = "RMT", clock_group = "RMT" }, { name = "RNG" }, { name = "RSA", interrupts = { peri = "RSA" } }, @@ -95,8 +98,9 @@ peripherals = [ { name = "FLASH", virtual = true }, { name = "PSRAM", virtual = true }, { name = "TOUCH", virtual = true }, - { name = "FROM_CPU_INTR0", virtual = true }, - { name = "FROM_CPU_INTR1", virtual = true }, + { name = "IPC", virtual = true }, + { name = "FROM_CPU_INTR0", virtual = true, hidden = true }, + { name = "FROM_CPU_INTR1", virtual = true, hidden = true }, { name = "FROM_CPU_INTR2", virtual = true }, { name = "FROM_CPU_INTR3", virtual = true }, ] @@ -106,6 +110,7 @@ peripherals = [ [device.adc] support_status = "partial" +line_calibration = true instances = [ { name = "adc1" }, { name = "adc2" }, @@ -188,6 +193,8 @@ support_status = "partial" status_registers = 3 software_interrupt_count = 4 controller = "Xtensa" +# The Bluetooth controller uses `Software0`. +context_switch_source = "ipc" [device.rmt] support_status = "partial" @@ -274,11 +281,18 @@ support_status = "not_supported" [device.ethernet] support_status = "partial" +rx_store_and_forward = true +# Type-2 COE can mark valid frames as checksum errors (and CIC insertion +# is also unreliable), so both directions stay in software. +rx_checksum_offload = false +tx_checksum_offload = false +dma_burst_len = 32 [device.camera] support_status = "not_supported" [device.rgb_display] support_status = "partial" +output_lines = 24 [device.rng] support_status = { status = "partial", issue = 5979 } @@ -312,7 +326,6 @@ wakeup_sources = { ## Interfaces [device.i2s] version = 1 -default_clock_source = 2 mclk_divider_bit_width = 6 max_ws_width = 128 instances = [ @@ -348,6 +361,22 @@ version = 1 channel_count = 8 [device.mcpwm] [device.pcnt] +instances = { + PCNT = { + sys_instance = "Pcnt", + interrupt = "PCNT", + units = [ + { sig_ch0 = "PCNT0_SIG_CH0", sig_ch1 = "PCNT0_SIG_CH1", ctrl_ch0 = "PCNT0_CTRL_CH0", ctrl_ch1 = "PCNT0_CTRL_CH1" }, + { sig_ch0 = "PCNT1_SIG_CH0", sig_ch1 = "PCNT1_SIG_CH1", ctrl_ch0 = "PCNT1_CTRL_CH0", ctrl_ch1 = "PCNT1_CTRL_CH1" }, + { sig_ch0 = "PCNT2_SIG_CH0", sig_ch1 = "PCNT2_SIG_CH1", ctrl_ch0 = "PCNT2_CTRL_CH0", ctrl_ch1 = "PCNT2_CTRL_CH1" }, + { sig_ch0 = "PCNT3_SIG_CH0", sig_ch1 = "PCNT3_SIG_CH1", ctrl_ch0 = "PCNT3_CTRL_CH0", ctrl_ch1 = "PCNT3_CTRL_CH1" }, + { sig_ch0 = "PCNT4_SIG_CH0", sig_ch1 = "PCNT4_SIG_CH1", ctrl_ch0 = "PCNT4_CTRL_CH0", ctrl_ch1 = "PCNT4_CTRL_CH1" }, + { sig_ch0 = "PCNT5_SIG_CH0", sig_ch1 = "PCNT5_SIG_CH1", ctrl_ch0 = "PCNT5_CTRL_CH0", ctrl_ch1 = "PCNT5_CTRL_CH1" }, + { sig_ch0 = "PCNT6_SIG_CH0", sig_ch1 = "PCNT6_SIG_CH1", ctrl_ch0 = "PCNT6_CTRL_CH0", ctrl_ch1 = "PCNT6_CTRL_CH1" }, + { sig_ch0 = "PCNT7_SIG_CH0", sig_ch1 = "PCNT7_SIG_CH1", ctrl_ch0 = "PCNT7_CTRL_CH0", ctrl_ch1 = "PCNT7_CTRL_CH1" }, + ], + }, +} [device.sdmmc] support_status = "partial" @@ -383,6 +412,7 @@ support_status = "not_supported" [device.psram] extmem_origin = 0x3F800000 [device.temp_sensor] +support_status = "not_supported" [device.lp_timer] [device.ulp_fsm] @@ -392,6 +422,7 @@ support_status = { status = "not_supported", issue = 376 } [device.wifi] mac_version = 1 csi_supported = true +has_nan = true [device.bt] support_status = "partial" diff --git a/esp-metadata/devices/esp32c2/clocks.toml b/esp-metadata/devices/esp32c2/clocks.toml index d7926643db3..a678fc3701a 100644 --- a/esp-metadata/devices/esp32c2/clocks.toml +++ b/esp-metadata/devices/esp32c2/clocks.toml @@ -2,11 +2,11 @@ system_clocks = { clock_tree = [ # High-speed clock sources { name = "XTAL_CLK", type = "source", values = "26, 40", output = "VALUE * 1_000_000", always_on = true }, { name = "PLL_CLK", type = "derived", from = "XTAL_CLK", output = "480_000_000" }, - { name = "RC_FAST_CLK", type = "source", output = "17_500_000" }, + { name = "RC_FAST_CLK", type = "source", output = "17_500_000", adjustable = "8_750_000..=26_250_000" }, # Low-speed clocks { name = "OSC_SLOW_CLK", type = "source", output = "32768" }, # external slow clock from GPIO0 - { name = "RC_SLOW_CLK", type = "source", output = "136_000" }, # adjustable via RTC_CNTL_ANA_CLK_DIV + { name = "RC_SLOW_CLK", type = "source", output = "136_000", adjustable = "68_000..=204_000" }, # adjustable via RTC_CNTL_ANA_CLK_DIV { name = "RC_FAST_DIV_CLK", type = "generic", output = "RC_FAST_CLK / 256" }, # 256 is just the default value? RTC_CNTL_FOSC_DIV # CPU clock source dividers @@ -52,6 +52,13 @@ system_clocks = { clock_tree = [ { name = "RC_SLOW", outputs = "RC_SLOW_CLK" }, { name = "RC_FAST", outputs = "RC_FAST_DIV_CLK" }, ] }, + # BLE RTC timer (MODEM_CLKRST). The crystal and RC_SLOW inputs are divided by 5 in hardware. + { name = "BLE_LP_XTAL_CLK", type = "generic", output = "XTAL_CLK / 5" }, + { name = "BLE_LP_RC_SLOW_CLK", type = "generic", output = "RC_SLOW_CLK / 5" }, + { name = "BLE_LP_CLK", type = "generic", output = "sclk / (divisor + 1)", params = { sclk = [ + { name = "XTAL", outputs = "BLE_LP_XTAL_CLK", default = true }, + { name = "RC_SLOW", outputs = "BLE_LP_RC_SLOW_CLK" }, + ], divisor = "0 ..= 255" } }, { name = "RTC_FAST_CLK", type = "mux", variants = [ # RTC_CNTL_FAST_CLK_RTC_SEL { name = "XTAL", outputs = "XTAL_DIV_CLK" }, { name = "RC", outputs = "RC_FAST_CLK_DIV_N" }, @@ -104,10 +111,13 @@ system_clocks = { clock_tree = [ ] }, { group = "SPI", clocks = [ { name = "FUNCTION_CLOCK", type = "mux", wake_locking = true, variants = [ - { name = "XTAL", outputs = "XTAL_CLK", default = true }, - { name = "PLL_40M", outputs = "PLL_40M" }, + { name = "XTAL", outputs = "XTAL_CLK" }, + { name = "PLL_40M", outputs = "PLL_40M", default = true }, ] }, ] }, + { group = "ADC", clocks = [ + { name = "FUNCTION_CLOCK", type = "generic", output = "APB_CLK" }, + ] }, ] } peripheral_clocks = { templates = [ diff --git a/esp-metadata/devices/esp32c2/soc.toml b/esp-metadata/devices/esp32c2/soc.toml index 9ffda83535c..2ef1c4025f6 100644 --- a/esp-metadata/devices/esp32c2/soc.toml +++ b/esp-metadata/devices/esp32c2/soc.toml @@ -17,6 +17,9 @@ trm = "https://www.espressif.com/sites/default/files/documentation/esp8684_te page_size = 0x10000 entry_num = 64 +[device.flash] +support_status = "partial" + [device.rom] has_crc_le = true has_crc_be = true @@ -36,7 +39,7 @@ memory_map = { ranges = [ peripherals = [ { name = "APB_CTRL" }, - { name = "APB_SARADC" }, + { name = "APB_SARADC", clock_group = "ADC" }, { name = "BB" }, { name = "ASSIST_DEBUG" }, { name = "DMA" }, @@ -71,7 +74,7 @@ peripherals = [ { name = "FLASH", virtual = true }, { name = "GPIO_DEDICATED", virtual = true }, { name = "WIFI", virtual = true, interrupts = { mac = "WIFI_MAC", pwr = "WIFI_PWR" }, stable = true }, - { name = "FROM_CPU_INTR0", virtual = true }, + { name = "FROM_CPU_INTR0", virtual = true, hidden = true }, { name = "FROM_CPU_INTR1", virtual = true }, { name = "FROM_CPU_INTR2", virtual = true }, { name = "FROM_CPU_INTR3", virtual = true }, @@ -82,6 +85,11 @@ peripherals = [ [device.adc] support_status = "partial" +controller = "digital" +channel_count = 5 +line_calibration = true +basic_calibration = true +calibration_v1_scheme_supported = true instances = [ { name = "adc1" }, ] @@ -121,8 +129,8 @@ working_modes = [ { id = 7, mode = "affine_point_verification_and_jacobian_point_multiplication" } ] curves = [ - { id = 0, curve = 192 }, - { id = 1, curve = 256 } + { id = 0, curve = "p192" }, + { id = 1, curve = "p256" } ] zero_extend_writes = true @@ -157,7 +165,9 @@ has_pd_en = true support_status = "partial" status_registers = 2 software_interrupt_count = 4 -controller = { Riscv = { flavour = "basic", interrupts = 32, priority_levels = 15 } } +controller = { Riscv = { flavour = "basic", interrupts = 32, priority_levels = 15, context_switch_interrupt = true } } +# The CPU has no CLINT. +context_switch_source = "from_cpu" [device.sha] support_status = "partial" @@ -196,6 +206,7 @@ instances = [ support_status = "partial" instances = [{ name = "timg0" }] timg_has_divcnt_rst = true +wdt_has_conf_update = true [device.uart] support_status = "supported" @@ -246,12 +257,14 @@ channel_count = 6 ## Miscellaneous [device.io_mux] [device.temp_sensor] +support_status = "not_supported" [device.systimer] [device.lp_timer] ## Radio [device.wifi] mac_version = 1 +has_ftm = true [device.bt] support_status = "partial" diff --git a/esp-metadata/devices/esp32c3/clocks.toml b/esp-metadata/devices/esp32c3/clocks.toml index a15c072570a..ab8cc6bfc56 100644 --- a/esp-metadata/devices/esp32c3/clocks.toml +++ b/esp-metadata/devices/esp32c3/clocks.toml @@ -2,11 +2,11 @@ system_clocks = { clock_tree = [ # High-speed clock sources { name = "XTAL_CLK", type = "source", values = "40", output = "VALUE * 1_000_000", always_on = true }, { name = "PLL_CLK", type = "derived", from = "XTAL_CLK", values = "320, 480", output = "VALUE * 1_000_000" }, - { name = "RC_FAST_CLK", type = "source", output = "17_500_000" }, + { name = "RC_FAST_CLK", type = "source", output = "17_500_000", adjustable = "8_750_000..=26_250_000" }, # Low-speed clocks - { name = "XTAL32K_CLK", type = "source", output = "32768" }, - { name = "RC_SLOW_CLK", type = "source", output = "136_000" }, + { name = "XTAL32K_CLK", type = "source", output = "32768", cfg = "use_xtal32k" }, + { name = "RC_SLOW_CLK", type = "source", output = "136_000", adjustable = "68_000..=204_000" }, { name = "RC_FAST_DIV_CLK", type = "generic", output = "RC_FAST_CLK / 256" }, # CPU clock source dividers @@ -43,10 +43,16 @@ system_clocks = { clock_tree = [ { name = "RC_FAST_CLK_DIV_N", type = "generic", params = { divisor = "0 ..= 3" }, output = "RC_FAST_CLK / (divisor + 1)" }, { name = "XTAL_DIV_CLK", type = "generic", output = "XTAL_CLK / 2" }, { name = "RTC_SLOW_CLK", type = "mux", variants = [ - { name = "XTAL32K", outputs = "XTAL32K_CLK" }, + { name = "XTAL32K", outputs = "XTAL32K_CLK", cfg = "use_xtal32k" }, { name = "RC_SLOW", outputs = "RC_SLOW_CLK" }, { name = "RC_FAST", outputs = "RC_FAST_DIV_CLK" }, ] }, + # BLE modem-sleep clock. The BTDM blob programs the source and divider. + { name = "BLE_LP_XTAL_CLK", type = "derived", from = "XTAL_CLK", output = "1_000_000" }, + { name = "BLE_LP_CLK", type = "mux", variants = [ + { name = "XTAL", outputs = "BLE_LP_XTAL_CLK" }, + { name = "RTC_SLOW", outputs = "RTC_SLOW_CLK" }, + ] }, { name = "RTC_FAST_CLK", type = "mux", variants = [ { name = "XTAL", outputs = "XTAL_DIV_CLK" }, { name = "RC", outputs = "RC_FAST_CLK_DIV_N" }, @@ -56,7 +62,7 @@ system_clocks = { clock_tree = [ { name = "LOW_POWER_CLK", type = "mux", variants = [ { name = "XTAL", outputs = "XTAL_CLK" }, { name = "RC_FAST", outputs = "RC_FAST_CLK" }, - { name = "XTAL32K", outputs = "XTAL32K_CLK" }, + { name = "XTAL32K", outputs = "XTAL32K_CLK", cfg = "use_xtal32k" }, { name = "RTC_SLOW", outputs = "RTC_SLOW_CLK" }, ] }, @@ -70,7 +76,7 @@ system_clocks = { clock_tree = [ { name = "TIMG_CALIBRATION_CLOCK", type = "mux", wake_locking = true, variants = [ { name = "RC_SLOW_CLK", outputs = "RC_SLOW_CLK" }, { name = "RC_FAST_DIV_CLK", outputs = "RC_FAST_DIV_CLK" }, - { name = "XTAL32K_CLK", outputs = "XTAL32K_CLK" }, + { name = "XTAL32K_CLK", outputs = "XTAL32K_CLK", cfg = "use_xtal32k" }, ] }, ], template_groups = [ { group = "TIMG", clocks = [ @@ -108,12 +114,47 @@ system_clocks = { clock_tree = [ { name = "RC_FAST", outputs = "RC_FAST_CLK" }, ], div_num = "0 .. 0x100" } }, ] }, + { group = "TSENS", clocks = [ + { name = "SCLK", type = "mux", variants = [ + { name = "RC_FAST", outputs = "RC_FAST_CLK" }, + { name = "XTAL", outputs = "XTAL_CLK", default = true }, + ] }, + ] }, { group = "SPI", clocks = [ { name = "FUNCTION_CLOCK", type = "mux", wake_locking = true, variants = [ - { name = "XTAL", outputs = "XTAL_CLK", default = true }, - { name = "PLL_80M", outputs = "PLL_80M" }, + { name = "XTAL", outputs = "XTAL_CLK" }, + { name = "PLL_80M", outputs = "PLL_80M", default = true }, ] }, ] }, + { group = "ADC", clocks = [ + { name = "FUNCTION_CLOCK", type = "generic", output = "APB_CLK" }, + ] }, + { group = "I2S", + presets = { + CLK = { + type = "generic", + wake_locking = true, + output = "(sclk * div_a) / (div_num * div_a + div_b)", + params = { + sclk = [ + { name = "XTAL", outputs = "XTAL_CLK" }, + { name = "PLL_160M", outputs = "PLL_160M", default = true }, + ], + div_num = "1 ..= 255", + div_a = "1 ..= 511", + div_b = "0 ..= 511", + }, + }, + }, + clocks = [ + { name = "TX_CLK", preset = "CLK" }, + { name = "RX_CLK", preset = "CLK" }, + { name = "MCLK_OUT", type = "mux", variants = [ + { name = "TX", outputs = "TX_CLK" }, + { name = "RX", outputs = "RX_CLK", default = true }, + ] }, + ], + }, ] } peripheral_clocks = { templates = [ diff --git a/esp-metadata/devices/esp32c3/gpio.toml b/esp-metadata/devices/esp32c3/gpio.toml index e283f9bd8f6..7e721471064 100644 --- a/esp-metadata/devices/esp32c3/gpio.toml +++ b/esp-metadata/devices/esp32c3/gpio.toml @@ -9,7 +9,9 @@ pins = [ { pin = 2, functions = { 2 = "FSPIQ" }, limitations = ["strapping"], analog = { 1 = "ADC1_CH2" }, lp = { 0 = "LP_GPIO2" } }, { pin = 3, analog = { 1 = "ADC1_CH3" }, lp = { 0 = "LP_GPIO3" } }, { pin = 4, functions = { 0 = "MTMS", 2 = "FSPIHD" }, analog = { 1 = "ADC1_CH4" }, lp = { 0 = "LP_GPIO4" } }, - { pin = 5, functions = { 0 = "MTDI", 2 = "FSPIWP" }, analog = { 1 = "ADC2_CH0" }, lp = { 0 = "LP_GPIO5" } }, + # GPIO5 is ADC2_CH0, which is left out because ADC2 is unusable on this chip - see + # `[device.adc]` in soc.toml. + { pin = 5, functions = { 0 = "MTDI", 2 = "FSPIWP" }, lp = { 0 = "LP_GPIO5" } }, { pin = 6, functions = { 0 = "MTCK", 2 = "FSPICLK" } }, { pin = 7, functions = { 0 = "MTDO", 2 = "FSPID" } }, { pin = 8, limitations = ["strapping"] }, diff --git a/esp-metadata/devices/esp32c3/soc.toml b/esp-metadata/devices/esp32c3/soc.toml index 43806dc45f1..a9c4546ed44 100644 --- a/esp-metadata/devices/esp32c3/soc.toml +++ b/esp-metadata/devices/esp32c3/soc.toml @@ -17,6 +17,9 @@ trm = "https://www.espressif.com/sites/default/files/documentation/esp32-c3_t page_size = 0x10000 entry_num = 128 +[device.flash] +support_status = "partial" + [device.rom] has_crc_le = true has_crc_be = true @@ -38,7 +41,7 @@ memory_map = { ranges = [ peripherals = [ { name = "AES", interrupts = { peri = "AES" } }, { name = "APB_CTRL" }, - { name = "APB_SARADC" }, + { name = "APB_SARADC", clock_group = "ADC" }, { name = "ASSIST_DEBUG" }, { name = "BB" }, { name = "DMA" }, @@ -53,7 +56,7 @@ peripherals = [ { name = "HMAC" }, { name = "I2C_ANA_MST" }, { name = "I2C0", interrupts = { peri = "I2C_EXT0" }, stable = true, clock_group = "I2C" }, - { name = "I2S0", interrupts = { peri = "I2S0" } }, + { name = "I2S0", interrupts = { peri = "I2S0" }, clock_group = "I2S" }, { name = "INTERRUPT_CORE0" }, { name = "IO_MUX" }, { name = "LEDC" }, @@ -80,13 +83,12 @@ peripherals = [ { name = "XTS_AES" }, { name = "ADC1", virtual = true }, - { name = "ADC2", virtual = true }, { name = "BT", virtual = true, interrupts = { rwbt = "RWBT", rwble = "RWBLE", bb = "BT_BB" } }, { name = "FLASH", virtual = true }, { name = "GPIO_DEDICATED", virtual = true }, - { name = "TSENS", virtual = true }, + { name = "TSENS", virtual = true, clock_group = "TSENS" }, { name = "WIFI", virtual = true, interrupts = { mac = "WIFI_MAC", pwr = "WIFI_PWR" }, stable = true }, - { name = "FROM_CPU_INTR0", virtual = true }, + { name = "FROM_CPU_INTR0", virtual = true, hidden = true }, { name = "FROM_CPU_INTR1", virtual = true }, { name = "FROM_CPU_INTR2", virtual = true }, { name = "FROM_CPU_INTR3", virtual = true }, @@ -97,9 +99,20 @@ peripherals = [ [device.adc] support_status = "partial" +controller = "digital" +channel_count = 5 +line_calibration = true +curve_calibration = true +basic_calibration = true +calibration_v1_scheme_supported = true +# ADC2 is deliberately absent. Its digital controller is broken on this chip and the chip has no +# RTC ADC controller to fall back on, so there is no way to read it reliably. ESP-IDF refuses to +# create a one-shot unit for it unless `CONFIG_ADC_ONESHOT_FORCE_USE_ADC2_ON_C3` is set. +# +# See `SOC_ADC_DIG_SUPPORTED_UNIT` in `components/soc/esp32c3/include/soc/soc_caps.h`, and the +# ESP32-C3 series SoC errata. instances = [ { name = "adc1" }, - { name = "adc2" }, ] [device.aes] @@ -180,7 +193,9 @@ instances = [ support_status = "partial" status_registers = 2 software_interrupt_count = 4 -controller = { Riscv = { flavour = "basic", interrupts = 32, priority_levels = 15 } } +controller = { Riscv = { flavour = "basic", interrupts = 32, priority_levels = 15, context_switch_interrupt = true } } +# The CPU has no CLINT. +context_switch_source = "from_cpu" [device.rmt] support_status = "partial" @@ -242,6 +257,7 @@ instances = [ support_status = "partial" instances = [{ name = "timg0" }, { name = "timg1" }] timg_has_divcnt_rst = true +wdt_has_conf_update = true [device.uart] support_status = "supported" @@ -285,6 +301,13 @@ wakeup_sources = { Bt = 10, } +[device.sleep.retention] +cpu_retention = "rtc_cntl" +cpu_retention_mem_size = 1744 +cpu_retention_mem_align = 16 +cpu_retention_mem_start = 0x3FCC0000 +cpu_retention_mem_end = 0x3FCE0000 + # Other drivers which are partially supported but have no other configuration: ## Crypto @@ -293,7 +316,6 @@ wakeup_sources = { ## Interfaces [device.i2s] version = 2 -default_clock_source = 2 mclk_divider_bit_width = 9 max_ws_width = 128 instances = [ @@ -329,6 +351,7 @@ channel_count = 6 [device.wifi] mac_version = 1 csi_supported = true +has_ftm = true [device.bt] support_status = "partial" diff --git a/esp-metadata/devices/esp32c5/clocks.toml b/esp-metadata/devices/esp32c5/clocks.toml index f62ae1ad50e..35a361b16ac 100644 --- a/esp-metadata/devices/esp32c5/clocks.toml +++ b/esp-metadata/devices/esp32c5/clocks.toml @@ -2,12 +2,12 @@ system_clocks = { clock_tree = [ # High-speed clock sources { name = "XTAL_CLK", type = "source", values = "40, 48", output = "VALUE * 1_000_000", always_on = true }, # TODO: not user-configurable { name = "PLL_CLK", type = "derived", from = "XTAL_CLK", output = "480_000_000" }, - { name = "RC_FAST_CLK", type = "source", output = "20_000_000" }, + { name = "RC_FAST_CLK", type = "source", output = "20_000_000", adjustable = "10_000_000..=30_000_000" }, # Low-speed clocks - { name = "XTAL32K_CLK", type = "source", output = "32768" }, + { name = "XTAL32K_CLK", type = "source", output = "32768", cfg = "use_xtal32k" }, { name = "OSC_SLOW_CLK", type = "source", output = "32768" }, - { name = "RC_SLOW_CLK", type = "source", output = "130_000" }, + { name = "RC_SLOW_CLK", type = "source", output = "130_000", adjustable = "65_000..=195_000" }, # { name = "EXT32K_CLK", type = "source", output = "32768" }, # currently unimplemented # PLL divider taps @@ -46,16 +46,26 @@ system_clocks = { clock_tree = [ ] }, { name = "LP_SLOW_CLK", type = "mux", variants = [ { name = "RC_SLOW", outputs = "RC_SLOW_CLK" }, - { name = "XTAL32K", outputs = "XTAL32K_CLK" }, + { name = "XTAL32K", outputs = "XTAL32K_CLK", cfg = "use_xtal32k" }, #{ name = "EXT32K", outputs = "EXT32K_CLK" }, { name = "OSC_SLOW", outputs = "OSC_SLOW_CLK" }, ] }, - + # BLE RTC timer (MODEM_LPCON). Independent of LP_SLOW_CLK. + { name = "BLE_LP_XTAL_CLK", type = "derived", from = "XTAL_CLK", output = "100_000" }, + { name = "BLE_LP_RC_SLOW_CLK", type = "generic", output = "RC_SLOW_CLK / 5" }, + { name = "BLE_LP_CLK", type = "mux", variants = [ + { name = "XTAL", outputs = "BLE_LP_XTAL_CLK" }, + { name = "RC_SLOW", outputs = "BLE_LP_RC_SLOW_CLK" }, + { name = "XTAL32K", outputs = "XTAL32K_CLK", cfg = "use_xtal32k" }, + ] }, + # Global peripheral-related clocks + { name = "CRYPTO_PLL_DIV", type = "generic", output = "PLL_CLK / 3" }, + { name = "CRYPTO_CLK", type = "mux", variants = [ # PCR_SEC_CONF { name = "XTAL", outputs = "XTAL_CLK" }, { name = "FOSC", outputs = "RC_FAST_CLK" }, - { name = "PLL_F480M", outputs = "PLL_CLK" }, + { name = "PLL_F480M", outputs = "CRYPTO_PLL_DIV" }, ] }, { name = "IOMUX_FUNCTION_CLOCK", type = "mux", always_on = true, variants = [ { name = "XTAL_CLK", outputs = "XTAL_CLK" }, @@ -67,7 +77,7 @@ system_clocks = { clock_tree = [ { name = "RC_SLOW_CLK", outputs = "RC_SLOW_CLK" }, # EXT32K not modeled { name = "RC_FAST_DIV_CLK", outputs = "RC_FAST_CLK" }, - { name = "XTAL32K_CLK", outputs = "XTAL32K_CLK" }, + { name = "XTAL32K_CLK", outputs = "XTAL32K_CLK", cfg = "use_xtal32k" }, ] }, ], template_groups = [ { group = "UART", clocks = [ @@ -100,19 +110,50 @@ system_clocks = { clock_tree = [ { name = "PLL_F80M", outputs = "PLL_F80M", default = true }, ] }, ] }, - { group = "PARL_IO", clocks = [ - { name = "RX_CLOCK", type = "mux", variants = [ - { name = "XTAL_CLK", outputs = "XTAL_CLK" }, - { name = "RC_FAST_CLK", outputs = "RC_FAST_CLK" }, - { name = "PLL_F240M", outputs = "PLL_F240M", default = true }, - # TODO: external clock - ] }, - { name = "TX_CLOCK", type = "mux", variants = [ + { group = "PARL_IO", + presets = { + CLK = { + type = "mux", + variants = [ { name = "XTAL_CLK", outputs = "XTAL_CLK" }, { name = "RC_FAST_CLK", outputs = "RC_FAST_CLK" }, { name = "PLL_F240M", outputs = "PLL_F240M", default = true }, + # TODO: external clock (TX and RX may differ) + ], + }, + }, + clocks = [ + { name = "RX_CLOCK", preset = "CLK" }, + { name = "TX_CLOCK", preset = "CLK" }, + ], + }, + { group = "I2S", + presets = { + CLK = { + type = "generic", + wake_locking = true, + output = "(sclk * div_a) / (div_num * div_a + div_b)", + params = { + sclk = [ + { name = "XTAL", outputs = "XTAL_CLK" }, + { name = "PLL_F240M", outputs = "PLL_F240M" }, + { name = "PLL_F160M", outputs = "PLL_F160M", default = true }, + ], + div_num = "1 ..= 255", + div_a = "1 ..= 511", + div_b = "0 ..= 511", + }, + }, + }, + clocks = [ + { name = "TX_CLK", preset = "CLK" }, + { name = "RX_CLK", preset = "CLK" }, + { name = "MCLK_OUT", type = "mux", variants = [ + { name = "TX", outputs = "TX_CLK" }, + { name = "RX", outputs = "RX_CLK", default = true }, ] }, - ] }, + ], + }, { group = "I2C", clocks = [ { name = "FUNCTION_CLOCK", type = "generic", output = "sclk / (div_num + 1)", params = { sclk = [ { name = "XTAL", outputs = "XTAL_CLK", default = true }, @@ -121,12 +162,26 @@ system_clocks = { clock_tree = [ ] }, { group = "SPI", clocks = [ { name = "FUNCTION_CLOCK", type = "mux", variants = [ - { name = "XTAL", outputs = "XTAL_CLK", default = true }, - { name = "PLL_F160M", outputs = "PLL_F160M" }, + { name = "XTAL", outputs = "XTAL_CLK" }, + { name = "PLL_F160M", outputs = "PLL_F160M", default = true }, { name = "PLL_F120M", outputs = "PLL_F120M" }, { name = "RC_FAST", outputs = "RC_FAST_CLK" }, ] }, ] }, + { group = "TWAI", clocks = [ + # TRM 38.3.1: XTAL is recommended for data rates <= 5 Mbit/s, PLL_F80M above. + { name = "FUNCTION_CLOCK", type = "mux", variants = [ + { name = "XTAL", outputs = "XTAL_CLK" }, + { name = "PLL_F80M", outputs = "PLL_F80M", default = true }, + ] }, + ] }, + { group = "ADC", clocks = [ + { name = "FUNCTION_CLOCK", type = "mux", variants = [ + { name = "XTAL", outputs = "XTAL_CLK" }, + { name = "RC_FAST", outputs = "RC_FAST_CLK" }, + { name = "PLL_F80M", outputs = "PLL_F80M", default = true }, + ] }, + ] }, ] } peripheral_clocks = { templates = [ @@ -160,4 +215,6 @@ peripheral_clocks = { templates = [ { name = "Rsa" }, { name = "Ecc" }, { name = "UsbDevice", keep_enabled = true }, + { name = "Twai0" }, + { name = "Twai1" }, ] } diff --git a/esp-metadata/devices/esp32c5/soc.toml b/esp-metadata/devices/esp32c5/soc.toml index 5356daed68a..fad889ff4b3 100644 --- a/esp-metadata/devices/esp32c5/soc.toml +++ b/esp-metadata/devices/esp32c5/soc.toml @@ -17,6 +17,9 @@ trm = "https://www.espressif.com/sites/default/files/documentation/esp32-c5_t page_size = 0x10000 entry_num = 512 +[device.flash] +support_status = "partial" + [device.rom] has_crc_le = true has_crc_be = true @@ -27,6 +30,7 @@ cpu_has_branch_predictor = true cpu_has_csr_pc = false cpu_csr_prv_mode = 0x810 cpu_mcause_mask = 0x1f +cpu_pmp_granularity = 128 has_swd_watchdog = true @@ -41,10 +45,11 @@ memory_map = { ranges = [ peripherals = [ { name = "AES", interrupts = { peri = "AES" } }, { name = "ASSIST_DEBUG" }, - { name = "APB_SARADC" }, + { name = "APB_SARADC", clock_group = "ADC" }, # { name = "AVC" }, # { name = "BITSCRAMBLER" }, { name = "CACHE" }, + { name = "CLIC", hidden = true }, { name = "CLINT" }, # { name = "CPU_APM" }, # TODO: verify we need it { name = "DMA" }, @@ -62,7 +67,7 @@ peripherals = [ { name = "HUK" }, { name = "I2C_ANA_MST" }, { name = "I2C0", interrupts = { peri = "I2C_EXT0" }, stable = true, clock_group = "I2C" }, - { name = "I2S0", interrupts = { peri = "I2S0" } }, + { name = "I2S0", interrupts = { peri = "I2S0" }, clock_group = "I2S" }, { name = "IEEE802154", interrupts = { mac = "ZB_MAC" } }, { name = "INTERRUPT_CORE0" }, { name = "INTPRI" }, @@ -95,7 +100,7 @@ peripherals = [ # { name = "OTP_DEBUG" }, { name = "PARL_IO", interrupts = { tx = "PARL_IO_TX", rx = "PARL_IO_RX" }, clock_group = "PARL_IO" }, { name = "PAU" }, - { name = "PCNT" }, + { name = "PCNT", interrupts = { peri = "PCNT" } }, { name = "PCR" }, { name = "PMU" }, # { name = "PSRAM_MEM_MONITOR" }, @@ -115,8 +120,8 @@ peripherals = [ { name = "TIMG0", clock_group = "TIMG" }, { name = "TIMG1", clock_group = "TIMG" }, # { name = "TRACE0", pac = "TRACE" }, - # { name = "TWAI0" }, # TODO: too different from what we know - # { name = "TWAI1" }, # TODO: too different from what we know + { name = "TWAI0", interrupts = { peri = "TWAI0", timer = "TWAI0_TIMER" }, clock_group = "TWAI" }, + { name = "TWAI1", interrupts = { peri = "TWAI1", timer = "TWAI1_TIMER" }, clock_group = "TWAI" }, { name = "UART0", interrupts = { peri = "UART0" }, stable = true, clock_group = "UART" }, { name = "UART1", interrupts = { peri = "UART1" }, stable = true, clock_group = "UART" }, { name = "UHCI0" }, @@ -141,6 +146,16 @@ peripherals = [ [device.adc] support_status = "partial" +controller = "digital" +channel_count = 6 +pcr_clock = true +pcr_sar_clk_div = true +line_calibration = true +curve_calibration = true +basic_calibration = true +calibration_v1_scheme_supported = true +channel_compensation = true +sar_power_override = true instances = [{ name = "adc1" }] # TODO: define functionality for PSEUDO register @@ -199,9 +214,9 @@ working_modes = [ { id = 11, mode = "modular_division" } ] curves = [ - { id = 0, curve = 192 }, - { id = 1, curve = 256 }, - { id = 2, curve = 384 } + { id = 0, curve = "p192" }, + { id = 1, curve = "p256" }, + { id = 2, curve = "p384" } ] separate_jacobian_point_memory = true has_memory_clock_gate = true @@ -254,6 +269,7 @@ support_status = "partial" status_registers = 3 software_interrupt_count = 4 controller = { Riscv = { flavour = "clic", interrupts = 48, priority_levels = 8 } } +context_switch_source = "clint" [device.rmt] support_status = "partial" @@ -303,6 +319,7 @@ support_status = "partial" instances = [{ name = "timg0" }, { name = "timg1" }] timg_has_divcnt_rst = true rc_fast_calibration = { divider = 32, min_rev = 0 } +wdt_has_conf_update = true [device.uart] support_status = "supported" @@ -331,7 +348,11 @@ has_region_monitor = true support_status = { status = "not_supported", issue = 5168 } [device.canfd] -support_status = { status = "not_supported", issue = 5163 } +support_status = "partial" +instances = [ + { name = "twai0", sys_instance = "Twai0", rx = "TWAI0_RX", tx = "TWAI0_TX" }, + { name = "twai1", sys_instance = "Twai1", rx = "TWAI1_RX", tx = "TWAI1_TX" }, +] [device.key_manager] support_status = { status = "not_supported", issue = 5171 } @@ -357,7 +378,7 @@ fifo_size = 16 [device.rng] support_status = { status = "partial", issue = 5980 } -trng_supported = false # TODO +trng_supported = true apb_cycle_wait_num = 16 # TODO is_lp_sys = true @@ -366,6 +387,9 @@ is_lp_sys = true mac_version = 3 has_5g = true csi_supported = true +has_wifi6 = true +has_nan = true +has_ftm = true [device.bt] support_status = "partial" @@ -375,18 +399,30 @@ controller = "npl" [device.phy] support_status = "partial" -combo_module = true +combo_module = false # ## Miscellaneous [device.systimer] [device.pcnt] +instances = { + PCNT = { + sys_instance = "Pcnt", + interrupt = "PCNT", + units = [ + { sig_ch0 = "PCNT0_SIG_CH0", sig_ch1 = "PCNT0_SIG_CH1", ctrl_ch0 = "PCNT0_CTRL_CH0", ctrl_ch1 = "PCNT0_CTRL_CH1" }, + { sig_ch0 = "PCNT1_SIG_CH0", sig_ch1 = "PCNT1_SIG_CH1", ctrl_ch0 = "PCNT1_CTRL_CH0", ctrl_ch1 = "PCNT1_CTRL_CH1" }, + { sig_ch0 = "PCNT2_SIG_CH0", sig_ch1 = "PCNT2_SIG_CH1", ctrl_ch0 = "PCNT2_CTRL_CH0", ctrl_ch1 = "PCNT2_CTRL_CH1" }, + { sig_ch0 = "PCNT3_SIG_CH0", sig_ch1 = "PCNT3_SIG_CH1", ctrl_ch0 = "PCNT3_CTRL_CH0", ctrl_ch1 = "PCNT3_CTRL_CH1" }, + ], + }, +} [device.usb_serial_jtag] [device.parl_io] support_status = "partial" version = 2 - -# TODO: model chip select signal (active low) +max_data_width = 8 +has_tx_cs = true [device.ledc] version = 3 @@ -415,6 +451,11 @@ wakeup_sources = { LpCore = 11, } +[device.sleep.retention] +cpu_retention = "software" +cpu_retention_frame = "clic" +supports_top_power_down = true + [device.etm] support_status = { status = "not_supported", issue = 5167 } @@ -426,7 +467,6 @@ support_status = { status = "not_supported", issue = 5444 } [device.i2s] version = 3 -default_clock_source = 2 mclk_divider_bit_width = 9 max_ws_width = 512 clock_configured_by_pcr = true diff --git a/esp-metadata/devices/esp32c6/clocks.toml b/esp-metadata/devices/esp32c6/clocks.toml index ec5184861f9..b45be870918 100644 --- a/esp-metadata/devices/esp32c6/clocks.toml +++ b/esp-metadata/devices/esp32c6/clocks.toml @@ -2,12 +2,12 @@ system_clocks = { clock_tree = [ # High-speed clock sources { name = "XTAL_CLK", type = "source", values = "40", output = "VALUE * 1_000_000", always_on = true }, { name = "PLL_CLK", type = "derived", from = "XTAL_CLK", output = "480_000_000" }, - { name = "RC_FAST_CLK", type = "source", output = "17_500_000" }, + { name = "RC_FAST_CLK", type = "source", output = "17_500_000", adjustable = "8_750_000..=26_250_000" }, # Low-speed clocks - { name = "XTAL32K_CLK", type = "source", output = "32768" }, + { name = "XTAL32K_CLK", type = "source", output = "32768", cfg = "use_xtal32k" }, { name = "OSC_SLOW_CLK", type = "source", output = "32768" }, - { name = "RC_SLOW_CLK", type = "source", output = "136_000" }, + { name = "RC_SLOW_CLK", type = "source", output = "136_000", adjustable = "68_000..=204_000" }, { name = "SOC_ROOT_CLK", type = "mux", variants = [ { name = "XTAL", outputs = "XTAL_CLK", configures = ["HP_ROOT_CLK = 1", "CPU_CLK = LS", "AHB_CLK = LS", "MSPI_FAST_CLK = LS"] }, @@ -63,10 +63,18 @@ system_clocks = { clock_tree = [ { name = "XTAL_D2_CLK", outputs = "XTAL_D2_CLK" }, ] }, { name = "LP_SLOW_CLK", type = "mux", variants = [ - { name = "XTAL32K", outputs = "XTAL32K_CLK" }, + { name = "XTAL32K", outputs = "XTAL32K_CLK", cfg = "use_xtal32k" }, { name = "RC_SLOW", outputs = "RC_SLOW_CLK" }, { name = "OSC_SLOW", outputs = "OSC_SLOW_CLK" }, ] }, + # BLE RTC timer (MODEM_LPCON). Independent of LP_SLOW_CLK. + { name = "BLE_LP_XTAL_CLK", type = "derived", from = "XTAL_CLK", output = "100_000" }, + { name = "BLE_LP_RC_SLOW_CLK", type = "generic", output = "RC_SLOW_CLK / 5" }, + { name = "BLE_LP_CLK", type = "mux", variants = [ + { name = "XTAL", outputs = "BLE_LP_XTAL_CLK" }, + { name = "RC_SLOW", outputs = "BLE_LP_RC_SLOW_CLK" }, + { name = "XTAL32K", outputs = "XTAL32K_CLK", cfg = "use_xtal32k" }, + ] }, # LP_DYN_SLOW_CLK is LP_SLOW_CLK # LP_DYN_FAST_CLK is automatically managed based on power mode. Not sure how to model it, some LP peripherals need it. @@ -75,7 +83,7 @@ system_clocks = { clock_tree = [ { name = "TIMG_CALIBRATION_CLOCK", type = "mux", wake_locking = true, variants = [ { name = "RC_SLOW_CLK", outputs = "LP_SLOW_CLK" }, { name = "RC_FAST_DIV_CLK", outputs = "RC_FAST_CLK" }, - { name = "XTAL32K_CLK", outputs = "XTAL32K_CLK" }, + { name = "XTAL32K_CLK", outputs = "XTAL32K_CLK", cfg = "use_xtal32k" }, ] }, ], template_groups = [ { group = "UART", clocks = [ @@ -116,29 +124,74 @@ system_clocks = { clock_tree = [ { name = "XTAL_CLK", outputs = "XTAL_CLK" }, ] }, ] }, - { group = "PARL_IO", clocks = [ - { name = "RX_CLOCK", type = "mux", wake_locking = true, variants = [ - { name = "XTAL_CLK", outputs = "XTAL_CLK" }, - { name = "RC_FAST_CLK", outputs = "RC_FAST_CLK" }, - { name = "PLL_F240M", outputs = "PLL_F240M", default = true }, - # TODO: external clock - ] }, - { name = "TX_CLOCK", type = "mux", wake_locking = true, variants = [ + { group = "PARL_IO", + presets = { + CLK = { + type = "mux", + wake_locking = true, + variants = [ { name = "XTAL_CLK", outputs = "XTAL_CLK" }, { name = "RC_FAST_CLK", outputs = "RC_FAST_CLK" }, { name = "PLL_F240M", outputs = "PLL_F240M", default = true }, + # TODO: external clock (TX and RX may differ) + ], + }, + }, + clocks = [ + { name = "RX_CLOCK", preset = "CLK" }, + { name = "TX_CLOCK", preset = "CLK" }, + ], + }, + { group = "I2S", + presets = { + CLK = { + type = "generic", + wake_locking = true, + output = "(sclk * div_a) / (div_num * div_a + div_b)", + params = { + sclk = [ + { name = "XTAL", outputs = "XTAL_CLK" }, + { name = "PLL_F240M", outputs = "PLL_F240M" }, + { name = "PLL_F160M", outputs = "PLL_F160M", default = true }, + ], + div_num = "1 ..= 255", + div_a = "1 ..= 511", + div_b = "0 ..= 511", + }, + }, + }, + clocks = [ + { name = "TX_CLK", preset = "CLK" }, + { name = "RX_CLK", preset = "CLK" }, + { name = "MCLK_OUT", type = "mux", variants = [ + { name = "TX", outputs = "TX_CLK" }, + { name = "RX", outputs = "RX_CLK", default = true }, ] }, - ] }, + ], + }, { group = "I2C", clocks = [ { name = "FUNCTION_CLOCK", type = "generic", wake_locking = true, output = "sclk / (div_num + 1)", params = { sclk = [ { name = "XTAL", outputs = "XTAL_CLK", default = true }, { name = "RC_FAST", outputs = "RC_FAST_CLK" }, ], div_num = "0 .. 0x100" } }, ] }, + { group = "TSENS", clocks = [ + { name = "SCLK", type = "mux", variants = [ + { name = "RC_FAST", outputs = "RC_FAST_CLK" }, + { name = "XTAL", outputs = "XTAL_CLK", default = true }, + ] }, + ] }, { group = "SPI", clocks = [ { name = "FUNCTION_CLOCK", type = "mux", wake_locking = true, variants = [ - { name = "PLL_F80M", outputs = "PLL_F80M" }, - { name = "XTAL", outputs = "XTAL_CLK", default = true }, + { name = "PLL_F80M", outputs = "PLL_F80M", default = true }, + { name = "XTAL", outputs = "XTAL_CLK" }, + { name = "RC_FAST", outputs = "RC_FAST_CLK" }, + ] }, + ] }, + { group = "ADC", clocks = [ + { name = "FUNCTION_CLOCK", type = "mux", variants = [ + { name = "XTAL", outputs = "XTAL_CLK" }, + { name = "PLL_F80M", outputs = "PLL_F80M", default = true }, { name = "RC_FAST", outputs = "RC_FAST_CLK" }, ] }, ] }, diff --git a/esp-metadata/devices/esp32c6/soc.toml b/esp-metadata/devices/esp32c6/soc.toml index 59ec0b90a0c..195d902ebe2 100644 --- a/esp-metadata/devices/esp32c6/soc.toml +++ b/esp-metadata/devices/esp32c6/soc.toml @@ -17,6 +17,9 @@ trm = "https://www.espressif.com/sites/default/files/documentation/esp32-c6_t page_size = 0x10000 entry_num = 256 +[device.flash] +support_status = "partial" + [device.rom] has_crc_le = true has_crc_be = true @@ -38,9 +41,10 @@ memory_map = { ranges = [ peripherals = [ { name = "AES", interrupts = { peri = "AES" } }, - { name = "APB_SARADC" }, + { name = "APB_SARADC", clock_group = "ADC" }, { name = "ASSIST_DEBUG" }, { name = "ATOMIC" }, + { name = "CLINT", hidden = true }, { name = "DMA" }, { name = "DS" }, { name = "ECC" }, @@ -54,7 +58,7 @@ peripherals = [ { name = "HP_SYS" }, { name = "I2C_ANA_MST" }, { name = "I2C0", interrupts = { peri = "I2C_EXT0" }, stable = true, clock_group = "I2C" }, - { name = "I2S0", interrupts = { peri = "I2S0" } }, + { name = "I2S0", interrupts = { peri = "I2S0" }, clock_group = "I2S" }, { name = "IEEE802154", interrupts = { mac = "ZB_MAC" } }, { name = "INTERRUPT_CORE0" }, { name = "INTPRI" }, @@ -81,9 +85,10 @@ peripherals = [ { name = "OTP_DEBUG" }, { name = "PARL_IO", interrupts = { peri = "PARL_IO" }, clock_group = "PARL_IO" }, { name = "PAU" }, - { name = "PCNT" }, + { name = "PCNT", interrupts = { peri = "PCNT" } }, { name = "PCR" }, { name = "PLIC_MX" }, + { name = "PLIC_UX", hidden = true }, { name = "PMU" }, { name = "RMT", clock_group = "RMT" }, { name = "RNG", pac = "LP_PERI" }, @@ -112,9 +117,9 @@ peripherals = [ { name = "FLASH", virtual = true }, { name = "GPIO_DEDICATED", virtual = true }, { name = "LP_CORE", virtual = true }, - { name = "TSENS", virtual = true }, + { name = "TSENS", virtual = true, clock_group = "TSENS" }, { name = "WIFI", virtual = true, interrupts = { bb = "WIFI_BB", mac = "WIFI_MAC", pwr = "WIFI_PWR", modem_peri_timeout = "MODEM_PERI_TIMEOUT" }, stable = true }, - { name = "FROM_CPU_INTR0", virtual = true }, + { name = "FROM_CPU_INTR0", virtual = true, hidden = true }, { name = "FROM_CPU_INTR1", virtual = true }, { name = "FROM_CPU_INTR2", virtual = true }, { name = "FROM_CPU_INTR3", virtual = true }, @@ -125,6 +130,15 @@ peripherals = [ [device.adc] support_status = "partial" +controller = "digital" +channel_count = 7 +pcr_clock = true +line_calibration = true +curve_calibration = true +basic_calibration = true +calibration_v1_scheme_supported = true +channel_compensation = true +sar_power_override = true instances = [ { name = "adc1" }, ] @@ -182,8 +196,8 @@ working_modes = [ { id = 7, mode = "affine_point_verification_and_jacobian_point_multiplication" } ] curves = [ - { id = 0, curve = 192 }, - { id = 1, curve = 256 } + { id = 0, curve = "p192" }, + { id = 1, curve = "p256" } ] zero_extend_writes = true has_memory_clock_gate = true @@ -232,7 +246,8 @@ instances = [ support_status = "partial" status_registers = 3 software_interrupt_count = 4 -controller = { Riscv = { flavour = "plic", interrupts = 32, priority_levels = 15 } } +controller = { Riscv = { flavour = "plic", interrupts = 32, priority_levels = 15, context_switch_interrupt = true } } +context_switch_source = "clint" [device.rmt] support_status = "partial" @@ -295,6 +310,7 @@ support_status = "partial" instances = [{ name = "timg0" }, { name = "timg1" }] timg_has_divcnt_rst = true rc_fast_calibration = { divider = 32, min_rev = 1 } +wdt_has_conf_update = true [device.uart] support_status = "supported" @@ -342,9 +358,15 @@ wakeup_sources = { LpCore = 11, } +[device.sleep.retention] +cpu_retention = "software" +cpu_retention_frame = "c6_h2" +supports_top_power_down = true + [device.parl_io] support_status = "partial" version = 1 +max_data_width = 16 # Other drivers which are partially supported but have no other configuration: @@ -354,7 +376,6 @@ version = 1 ## Interfaces [device.i2s] version = 2 -default_clock_source = 2 mclk_divider_bit_width = 9 max_ws_width = 128 clock_configured_by_pcr = true @@ -381,6 +402,18 @@ channel_count = 6 [device.mcpwm] [device.pcnt] +instances = { + PCNT = { + sys_instance = "Pcnt", + interrupt = "PCNT", + units = [ + { sig_ch0 = "PCNT0_SIG_CH0", sig_ch1 = "PCNT0_SIG_CH1", ctrl_ch0 = "PCNT0_CTRL_CH0", ctrl_ch1 = "PCNT0_CTRL_CH1" }, + { sig_ch0 = "PCNT1_SIG_CH0", sig_ch1 = "PCNT1_SIG_CH1", ctrl_ch0 = "PCNT1_CTRL_CH0", ctrl_ch1 = "PCNT1_CTRL_CH1" }, + { sig_ch0 = "PCNT2_SIG_CH0", sig_ch1 = "PCNT2_SIG_CH1", ctrl_ch0 = "PCNT2_CTRL_CH0", ctrl_ch1 = "PCNT2_CTRL_CH1" }, + { sig_ch0 = "PCNT3_SIG_CH0", sig_ch1 = "PCNT3_SIG_CH1", ctrl_ch0 = "PCNT3_CTRL_CH0", ctrl_ch1 = "PCNT3_CTRL_CH1" }, + ], + }, +} [device.sd_slave] support_status = "not_supported" [device.twai] @@ -400,6 +433,7 @@ support_status = "partial" has_wifi6 = true mac_version = 2 csi_supported = true +has_ftm = true [device.bt] support_status = "partial" diff --git a/esp-metadata/devices/esp32c61/clocks.toml b/esp-metadata/devices/esp32c61/clocks.toml index 2f9333c4836..f8546cb81c5 100644 --- a/esp-metadata/devices/esp32c61/clocks.toml +++ b/esp-metadata/devices/esp32c61/clocks.toml @@ -1,13 +1,13 @@ system_clocks = { clock_tree = [ # High-speed clock sources { name = "XTAL_CLK", type = "source", values = "40", output = "VALUE * 1_000_000", always_on = true }, - { name = "RC_FAST_CLK", type = "source", output = "17_500_000" }, + { name = "RC_FAST_CLK", type = "source", output = "17_500_000", adjustable = "8_750_000..=26_250_000" }, { name = "PLL_CLK", type = "derived", from = "XTAL_CLK", output = "480_000_000" }, # Low-speed clocks - { name = "XTAL32K_CLK", type = "source", output = "32768" }, - { name = "OSC_SLOW_CLK", type = "source", output = "32768" }, - { name = "RC_SLOW_CLK", type = "source", output = "136_000" }, + { name = "XTAL32K_CLK", type = "source", output = "32768", cfg = "use_xtal32k" }, + { name = "OSC_SLOW_CLK", type = "source", output = "32768" }, + { name = "RC_SLOW_CLK", type = "source", output = "136_000", adjustable = "68_000..=204_000" }, # PLL divider taps { name = "PLL_F20M", type = "generic", output = "PLL_CLK / 24" }, @@ -40,15 +40,33 @@ system_clocks = { clock_tree = [ ] }, { name = "LP_SLOW_CLK", type = "mux", variants = [ { name = "RC_SLOW", outputs = "RC_SLOW_CLK" }, - { name = "XTAL32K", outputs = "XTAL32K_CLK" }, + { name = "XTAL32K", outputs = "XTAL32K_CLK", cfg = "use_xtal32k" }, { name = "OSC_SLOW", outputs = "OSC_SLOW_CLK" }, ] }, + # BLE RTC timer (MODEM_LPCON). Independent of LP_SLOW_CLK. + { name = "BLE_LP_XTAL_CLK", type = "derived", from = "XTAL_CLK", output = "100_000" }, + { name = "BLE_LP_RC_SLOW_CLK", type = "generic", output = "RC_SLOW_CLK / 5" }, + { name = "BLE_LP_CLK", type = "mux", variants = [ + { name = "XTAL", outputs = "BLE_LP_XTAL_CLK" }, + { name = "RC_SLOW", outputs = "BLE_LP_RC_SLOW_CLK" }, + { name = "XTAL32K", outputs = "XTAL32K_CLK", cfg = "use_xtal32k" }, + ] }, + + # Global peripheral-related clocks + { name = "CRYPTO_PLL_DIV", type = "generic", output = "PLL_CLK / 3" }, + + # PCR.sec_conf.sec_clk_sel: external memory encryption and decryption + { name = "CRYPTO_CLK", type = "mux", variants = [ + { name = "XTAL", outputs = "XTAL_CLK" }, + { name = "RC_FAST", outputs = "RC_FAST_CLK" }, + { name = "PLL_F480M", outputs = "CRYPTO_PLL_DIV" }, + ] }, { name = "TIMG_CALIBRATION_CLOCK", type = "mux", wake_locking = true, variants = [ { name = "OSC_SLOW_CLK", outputs = "OSC_SLOW_CLK" }, { name = "RC_SLOW_CLK", outputs = "RC_SLOW_CLK" }, { name = "RC_FAST_DIV_CLK", outputs = "RC_FAST_CLK" }, - { name = "XTAL32K_CLK", outputs = "XTAL32K_CLK" }, + { name = "XTAL32K_CLK", outputs = "XTAL32K_CLK", cfg = "use_xtal32k" }, ] }, ], template_groups = [ { group = "UART", clocks = [ @@ -79,11 +97,45 @@ system_clocks = { clock_tree = [ ] }, { group = "SPI", clocks = [ { name = "FUNCTION_CLOCK", type = "mux", variants = [ - { name = "XTAL", outputs = "XTAL_CLK", default = true }, - { name = "PLL_F160M", outputs = "PLL_F160M" }, + { name = "XTAL", outputs = "XTAL_CLK" }, + { name = "PLL_F160M", outputs = "PLL_F160M", default = true }, { name = "RC_FAST", outputs = "RC_FAST_CLK" }, ] }, ] }, + { group = "ADC", clocks = [ + { name = "FUNCTION_CLOCK", type = "mux", variants = [ + { name = "XTAL", outputs = "XTAL_CLK" }, + { name = "RC_FAST", outputs = "RC_FAST_CLK" }, + { name = "PLL_F80M", outputs = "PLL_F80M", default = true }, + ] }, + ] }, + { group = "I2S", + presets = { + CLK = { + type = "generic", + wake_locking = true, + output = "(sclk * div_a) / (div_num * div_a + div_b)", + params = { + sclk = [ + { name = "XTAL", outputs = "XTAL_CLK" }, + { name = "PLL_F120M", outputs = "PLL_F120M" }, + { name = "PLL_F160M", outputs = "PLL_F160M", default = true }, + ], + div_num = "1 ..= 255", + div_a = "1 ..= 511", + div_b = "0 ..= 511", + }, + }, + }, + clocks = [ + { name = "TX_CLK", preset = "CLK" }, + { name = "RX_CLK", preset = "CLK" }, + { name = "MCLK_OUT", type = "mux", variants = [ + { name = "TX", outputs = "TX_CLK" }, + { name = "RX", outputs = "RX_CLK", default = true }, + ] }, + ], + }, ] } peripheral_clocks = { templates = [ diff --git a/esp-metadata/devices/esp32c61/soc.toml b/esp-metadata/devices/esp32c61/soc.toml index 37cfce25e54..eacc270a95f 100644 --- a/esp-metadata/devices/esp32c61/soc.toml +++ b/esp-metadata/devices/esp32c61/soc.toml @@ -17,6 +17,9 @@ trm = "https://www.espressif.com/sites/default/files/documentation/esp32-c61_ page_size = 0x10000 entry_num = 512 +[device.flash] +support_status = "partial" + [device.rom] has_crc_le = true has_crc_be = true @@ -27,6 +30,7 @@ cpu_has_branch_predictor = true cpu_has_csr_pc = false cpu_csr_prv_mode = 0x810 cpu_mcause_mask = 0x1f +cpu_pmp_granularity = 128 has_swd_watchdog = true @@ -39,11 +43,12 @@ memory_map = { ranges = [ ] } peripherals = [ - { name = "APB_SARADC" }, + { name = "APB_SARADC", clock_group = "ADC" }, # { name = "AVC" }, { name = "ASSIST_DEBUG"}, - { name = "CLINT" }, { name = "CACHE" }, + { name = "CLIC", hidden = true }, + { name = "CLINT" }, # { name = "CPU_APM" }, # TODO: verify we need it { name = "DMA" }, { name = "ECC" }, @@ -57,7 +62,7 @@ peripherals = [ { name = "HP_SYS" }, { name = "I2C_ANA_MST" }, { name = "I2C0", interrupts = { peri = "I2C_EXT0" }, stable = true, clock_group = "I2C" }, - { name = "I2S0", interrupts = { peri = "I2S0" } }, + { name = "I2S0", interrupts = { peri = "I2S0" }, clock_group = "I2S" }, # { name = "IEEE802154" }, # TODO: add PAC manually later { name = "INTERRUPT_CORE0" }, { name = "INTPRI" }, @@ -116,6 +121,16 @@ peripherals = [ [device.adc] support_status = "partial" +controller = "digital" +channel_count = 4 +pcr_clock = true +pcr_sar_clk_div = true +line_calibration = true +curve_calibration = true +basic_calibration = true +calibration_v1_scheme_supported = true +channel_compensation = true +sar_power_override = true instances = [ { name = "adc1" }, ] @@ -125,12 +140,14 @@ support_status = "partial" status_registers = 3 software_interrupt_count = 4 controller = { Riscv = { flavour = "clic", interrupts = 32, priority_levels = 8 } } +context_switch_source = "clint" [device.timergroup] support_status = "partial" instances = [{ name = "timg0" }, { name = "timg1" }] timg_has_divcnt_rst = true rc_fast_calibration = { divider = 32, min_rev = 0 } +wdt_has_conf_update = true [device.gpio] support_status = "supported" @@ -181,8 +198,8 @@ working_modes = [ { id = 11, mode = "modular_division" } ] curves = [ - { id = 0, curve = 192 }, - { id = 1, curve = 256 } + { id = 0, curve = "p192" }, + { id = 1, curve = "p256" } ] separate_jacobian_point_memory = true has_memory_clock_gate = true @@ -222,9 +239,14 @@ wakeup_sources = { LpCore = 11, } +[device.sleep.retention] +cpu_retention = "software" +cpu_retention_frame = "clic" +supports_top_power_down = true + [device.rng] support_status = { status = "partial", issue = 5981 } -trng_supported = false # TODO +trng_supported = true apb_cycle_wait_num = 16 # TODO is_lp_sys = true @@ -315,7 +337,6 @@ support_status = { status = "not_supported", issue = 5423 } [device.i2s] version = 3 -default_clock_source = 2 mclk_divider_bit_width = 9 max_ws_width = 512 clock_configured_by_pcr = true @@ -348,6 +369,8 @@ support_status = "partial" has_wifi6 = true mac_version = 3 csi_supported = true +has_nan = true +has_ftm = true [device.bt] support_status = "partial" diff --git a/esp-metadata/devices/esp32h2/clocks.toml b/esp-metadata/devices/esp32h2/clocks.toml index 0832bf361be..6539b9a1b49 100644 --- a/esp-metadata/devices/esp32h2/clocks.toml +++ b/esp-metadata/devices/esp32h2/clocks.toml @@ -4,7 +4,7 @@ system_clocks = { clock_tree = [ { name = "PLL_F96M_CLK", type = "derived", from = "XTAL_CLK", output = "96_000_000" }, { name = "PLL_F64M_CLK", type = "generic", output = "PLL_F96M_CLK * 2 / 3" }, { name = "PLL_F48M_CLK", type = "generic", output = "PLL_F96M_CLK / 2" }, - { name = "RC_FAST_CLK", type = "source", output = "8_000_000" }, + { name = "RC_FAST_CLK", type = "source", output = "8_000_000", adjustable = "4_000_000..=12_000_000" }, { name = "IOMUX_FUNCTION_CLOCK", type = "mux", always_on = true, variants = [ { name = "XTAL_CLK", outputs = "XTAL_CLK" }, @@ -12,10 +12,10 @@ system_clocks = { clock_tree = [ ] }, # Low-speed clocks - { name = "XTAL32K_CLK", type = "source", output = "32768" }, + { name = "XTAL32K_CLK", type = "source", output = "32768", cfg = "use_xtal32k" }, { name = "OSC_SLOW_CLK", type = "source", output = "32768" }, - { name = "RC_SLOW_CLK", type = "source", output = "130_000" }, - { name = "PLL_LP_CLK", type = "derived", from = "XTAL32K_CLK", output = "8_000_000" }, + { name = "RC_SLOW_CLK", type = "source", output = "130_000", adjustable = "65_000..=195_000" }, + { name = "PLL_LP_CLK", type = "derived", from = "XTAL32K_CLK", output = "8_000_000", cfg = "use_xtal32k" }, { name = "HP_ROOT_CLK", type = "mux", variants = [ { name = "PLL96", outputs = "PLL_F96M_CLK" }, @@ -34,23 +34,40 @@ system_clocks = { clock_tree = [ { name = "XTAL_D2_CLK", type = "generic", output = "XTAL_CLK / 2" }, { name = "LP_FAST_CLK", type = "mux", variants = [ { name = "RC_FAST_CLK", outputs = "RC_FAST_CLK" }, - { name = "PLL_LP_CLK", outputs = "PLL_LP_CLK" }, + { name = "PLL_LP_CLK", outputs = "PLL_LP_CLK", cfg = "use_xtal32k" }, { name = "XTAL_D2_CLK", outputs = "XTAL_D2_CLK" }, ] }, { name = "LP_SLOW_CLK", type = "mux", variants = [ - { name = "XTAL32K", outputs = "XTAL32K_CLK" }, + { name = "XTAL32K", outputs = "XTAL32K_CLK", cfg = "use_xtal32k" }, { name = "RC_SLOW", outputs = "RC_SLOW_CLK" }, { name = "OSC_SLOW", outputs = "OSC_SLOW_CLK" }, ] }, + # BLE RTC timer (LP_CLKRST.lpperi). Independent of LP_SLOW_CLK. + { name = "BLE_LP_XTAL_CLK", type = "derived", from = "XTAL_CLK", output = "100_000" }, + { name = "BLE_LP_RC_SLOW_CLK", type = "generic", output = "RC_SLOW_CLK / 5" }, + { name = "BLE_LP_CLK", type = "mux", variants = [ + { name = "XTAL", outputs = "BLE_LP_XTAL_CLK" }, + { name = "RC_SLOW", outputs = "BLE_LP_RC_SLOW_CLK" }, + { name = "XTAL32K", outputs = "XTAL32K_CLK", cfg = "use_xtal32k" }, + ] }, # LP_DYN_SLOW_CLK is LP_SLOW_CLK # LP_DYN_FAST_CLK is automatically managed based on power mode. Not sure how to model it, some LP peripherals need it. + # Global peripheral-related clocks + # PCR.sec_conf.sec_clk_sel: external memory encryption and decryption + { name = "CRYPTO_CLK", type = "mux", variants = [ + { name = "XTAL", outputs = "XTAL_CLK" }, + { name = "RC_FAST", outputs = "RC_FAST_CLK" }, + { name = "PLL_F64M", outputs = "PLL_F64M_CLK" }, + { name = "PLL_F96M", outputs = "PLL_F96M_CLK" }, + ] }, + # There are separate clock muxes for each TIMG instance, but esp-hal only uses one. Only modelling # one makes the HAL code simpler. { name = "TIMG_CALIBRATION_CLOCK", type = "mux", wake_locking = true, variants = [ { name = "RC_SLOW_CLK", outputs = "LP_SLOW_CLK" }, { name = "RC_FAST_DIV_CLK", outputs = "RC_FAST_CLK" }, #? - { name = "XTAL32K_CLK", outputs = "XTAL32K_CLK" }, + { name = "XTAL32K_CLK", outputs = "XTAL32K_CLK", cfg = "use_xtal32k" }, ] }, ], template_groups = [ { group = "UART", clocks = [ @@ -90,19 +107,51 @@ system_clocks = { clock_tree = [ { name = "XTAL_CLK", outputs = "XTAL_CLK" }, ] }, ] }, - { group = "PARL_IO", clocks = [ - { name = "RX_CLOCK", type = "mux", wake_locking = true, variants = [ - { name = "XTAL_CLK", outputs = "XTAL_CLK" }, - { name = "RC_FAST_CLK", outputs = "RC_FAST_CLK" }, - { name = "PLL_F96M", outputs = "PLL_F96M_CLK", default = true }, - # TODO: external clock - ] }, - { name = "TX_CLOCK", type = "mux", wake_locking = true, variants = [ + { group = "PARL_IO", + presets = { + CLK = { + type = "mux", + wake_locking = true, + variants = [ { name = "XTAL_CLK", outputs = "XTAL_CLK" }, { name = "RC_FAST_CLK", outputs = "RC_FAST_CLK" }, { name = "PLL_F96M", outputs = "PLL_F96M_CLK", default = true }, + # TODO: external clock (TX and RX may differ) + ], + }, + }, + clocks = [ + { name = "RX_CLOCK", preset = "CLK" }, + { name = "TX_CLOCK", preset = "CLK" }, + ], + }, + { group = "I2S", + presets = { + CLK = { + type = "generic", + wake_locking = true, + output = "(sclk * div_a) / (div_num * div_a + div_b)", + params = { + sclk = [ + { name = "XTAL", outputs = "XTAL_CLK" }, + { name = "PLL_F96M", outputs = "PLL_F96M_CLK", default = true }, + { name = "PLL_F64M", outputs = "PLL_F64M_CLK" }, + ], + div_num = "1 ..= 255", + div_a = "1 ..= 511", + div_b = "0 ..= 511", + }, + }, + }, + clocks = [ + { name = "TX_CLK", preset = "CLK" }, + { name = "RX_CLK", preset = "CLK" }, + { name = "MCLK_OUT", type = "mux", variants = [ + { name = "TX", outputs = "TX_CLK" }, + { name = "RX", outputs = "RX_CLK", default = true }, ] }, - ] }, + ], + }, { group = "I2C", clocks = [ { name = "FUNCTION_CLOCK", type = "generic", wake_locking = true, output = "sclk / (div_num + 1)", params = { sclk = [ { name = "XTAL", outputs = "XTAL_CLK", default = true }, @@ -111,8 +160,15 @@ system_clocks = { clock_tree = [ ] }, { group = "SPI", clocks = [ { name = "FUNCTION_CLOCK", type = "mux", wake_locking = true, variants = [ - { name = "XTAL", outputs = "XTAL_CLK", default = true }, - { name = "PLL_F48M", outputs = "PLL_F48M_CLK" }, + { name = "XTAL", outputs = "XTAL_CLK" }, + { name = "PLL_F48M", outputs = "PLL_F48M_CLK", default = true }, + { name = "RC_FAST", outputs = "RC_FAST_CLK" }, + ] }, + ] }, + { group = "ADC", clocks = [ + { name = "FUNCTION_CLOCK", type = "mux", variants = [ + { name = "XTAL", outputs = "XTAL_CLK" }, + { name = "PLL_F96M", outputs = "PLL_F96M_CLK", default = true }, { name = "RC_FAST", outputs = "RC_FAST_CLK" }, ] }, ] }, diff --git a/esp-metadata/devices/esp32h2/soc.toml b/esp-metadata/devices/esp32h2/soc.toml index 2f645d3dc70..8c6ef50f796 100644 --- a/esp-metadata/devices/esp32h2/soc.toml +++ b/esp-metadata/devices/esp32h2/soc.toml @@ -17,6 +17,9 @@ trm = "https://www.espressif.com/sites/default/files/documentation/esp32-h2_t page_size = 0x10000 entry_num = 256 +[device.flash] +support_status = "partial" + [device.rom] has_crc_le = true has_crc_be = true @@ -38,12 +41,14 @@ memory_map = { ranges = [ peripherals = [ { name = "AES", interrupts = { peri = "AES" } }, - { name = "APB_SARADC" }, + { name = "APB_SARADC", clock_group = "ADC" }, { name = "ASSIST_DEBUG" }, + { name = "CLINT", hidden = true }, { name = "DMA" }, { name = "DS" }, { name = "ECC" }, { name = "EFUSE", hidden = true }, + { name = "EXTMEM", hidden = true }, { name = "GPIO" }, { name = "GPIO_SD", clock_group = "SDM" }, { name = "HMAC" }, @@ -52,7 +57,7 @@ peripherals = [ { name = "I2C_ANA_MST" }, { name = "I2C0", interrupts = { peri = "I2C_EXT0" }, stable = true, clock_group = "I2C" }, { name = "I2C1", interrupts = { peri = "I2C_EXT1" }, stable = true, clock_group = "I2C" }, - { name = "I2S0", interrupts = { peri = "I2S0" } }, + { name = "I2S0", interrupts = { peri = "I2S0" }, clock_group = "I2S" }, { name = "IEEE802154", interrupts = { mac = "ZB_MAC" } }, { name = "INTERRUPT_CORE0" }, { name = "INTPRI" }, @@ -74,9 +79,10 @@ peripherals = [ { name = "OTP_DEBUG" }, { name = "PARL_IO", interrupts = { tx = "PARL_IO_TX", rx = "PARL_IO_RX" }, clock_group = "PARL_IO" }, { name = "PAU" }, - { name = "PCNT" }, + { name = "PCNT", interrupts = { peri = "PCNT" } }, { name = "PCR" }, { name = "PLIC_MX" }, + { name = "PLIC_UX", hidden = true }, { name = "PMU" }, { name = "RMT", clock_group = "RMT" }, { name = "RNG", virtual = true }, # a) RNG is LP_PERI in truth. b) we need to offset the rng_data register at runtime for newer revisions. @@ -113,6 +119,16 @@ peripherals = [ [device.adc] support_status = "partial" +controller = "digital" +channel_count = 5 +pcr_clock = true +pcr_sar_clk_div = true +line_calibration = true +curve_calibration = true +basic_calibration = true +calibration_v1_scheme_supported = true +channel_compensation = true +sar_power_override = true instances = [ { name = "adc1" }, ] @@ -175,8 +191,8 @@ working_modes = [ { id = 11, mode = "modular_division" } ] curves = [ - { id = 0, curve = 192 }, - { id = 1, curve = 256 } + { id = 0, curve = "p192" }, + { id = 1, curve = "p256" } ] zero_extend_writes = true separate_jacobian_point_memory = true @@ -221,6 +237,9 @@ support_status = "partial" status_registers = 2 software_interrupt_count = 4 controller = { Riscv = { flavour = "plic", interrupts = 32, priority_levels = 15 } } +# The PLIC priority threshold does not mask the machine software interrupt, so raising the run +# level masks it in `mie` instead. +context_switch_source = "clint" [device.rmt] support_status = "partial" @@ -286,6 +305,7 @@ support_status = "partial" instances = [{ name = "timg0" }, { name = "timg1" }] timg_has_divcnt_rst = true rc_fast_calibration = { divider = 32, min_rev = 2, tick_enable = true } +wdt_has_conf_update = true [device.uart] support_status = "supported" @@ -312,6 +332,7 @@ apb_cycle_wait_num = 16 # TODO [device.parl_io] support_status = "partial" version = 2 +max_data_width = 8 [device.sleep] support_status = "partial" @@ -333,6 +354,11 @@ wakeup_sources = { LpCore = 11, } +[device.sleep.retention] +cpu_retention = "software" +cpu_retention_frame = "c6_h2" +supports_top_power_down = true + # Other drivers which are partially supported but have no other configuration: ## Crypto @@ -341,7 +367,6 @@ wakeup_sources = { ## Interfaces [device.i2s] version = 3 -default_clock_source = 1 mclk_divider_bit_width = 9 max_ws_width = 512 clock_configured_by_pcr = true @@ -367,6 +392,18 @@ version = 3 channel_count = 6 [device.mcpwm] [device.pcnt] +instances = { + PCNT = { + sys_instance = "Pcnt", + interrupt = "PCNT", + units = [ + { sig_ch0 = "PCNT0_SIG_CH0", sig_ch1 = "PCNT0_SIG_CH1", ctrl_ch0 = "PCNT0_CTRL_CH0", ctrl_ch1 = "PCNT0_CTRL_CH1" }, + { sig_ch0 = "PCNT1_SIG_CH0", sig_ch1 = "PCNT1_SIG_CH1", ctrl_ch0 = "PCNT1_CTRL_CH0", ctrl_ch1 = "PCNT1_CTRL_CH1" }, + { sig_ch0 = "PCNT2_SIG_CH0", sig_ch1 = "PCNT2_SIG_CH1", ctrl_ch0 = "PCNT2_CTRL_CH0", ctrl_ch1 = "PCNT2_CTRL_CH1" }, + { sig_ch0 = "PCNT3_SIG_CH0", sig_ch1 = "PCNT3_SIG_CH1", ctrl_ch0 = "PCNT3_CTRL_CH0", ctrl_ch1 = "PCNT3_CTRL_CH1" }, + ], + }, +} [device.twai] [device.usb_serial_jtag] @@ -375,6 +412,7 @@ channel_count = 6 [device.io_mux] [device.systimer] [device.temp_sensor] +support_status = "not_supported" [device.lp_timer] ## Radio diff --git a/esp-metadata/devices/esp32h4/clocks.toml b/esp-metadata/devices/esp32h4/clocks.toml new file mode 100644 index 00000000000..f7279f376d1 --- /dev/null +++ b/esp-metadata/devices/esp32h4/clocks.toml @@ -0,0 +1,181 @@ +system_clocks = { clock_tree = [ + # High-speed clock sources. + { name = "XTAL_CLK", type = "source", output = "32 * 1_000_000", always_on = true }, + { name = "PLL_F96M_CLK", type = "derived", from = "XTAL_CLK", output = "96_000_000" }, + { name = "PLL_F48M_CLK", type = "generic", output = "PLL_F96M_CLK / 2" }, + + # PCR.iomux_clk_conf.iomux_func_clk_sel: 0 = XTAL, 1 = RC_FAST, 2 = PLL_F48M. The IO MUX clock + # is always running, which is also what keeps PLL_F48M_CLK (and with it the USB Serial/JTAG) + # alive while no other peripheral asks for it. + { name = "IOMUX_FUNCTION_CLOCK", type = "mux", always_on = true, variants = [ + { name = "XTAL_CLK", outputs = "XTAL_CLK" }, + { name = "RC_FAST_CLK", outputs = "RC_FAST_CLK" }, + { name = "PLL_F48M", outputs = "PLL_F48M_CLK", default = true }, + ] }, + + { name = "XTAL_X2_CLK", type = "derived", from = "XTAL_CLK", output = "64_000_000" }, + { name = "RC_FAST_CLK", type = "source", output = "20_000_000", adjustable = "10_000_000..=30_000_000" }, + + # Low-speed clocks + { name = "XTAL32K_CLK", type = "source", output = "32768", cfg = "use_xtal32k" }, + { name = "OSC_SLOW_CLK", type = "source", output = "32768" }, + { name = "RC_SLOW_CLK", type = "source", output = "600_000", adjustable = "300_000..=900_000" }, + # Fixed divider, see rtc_clk_slow_freq_get_hz(). + { name = "RC_SLOW_D4_CLK", type = "generic", output = "RC_SLOW_CLK / 4" }, + + # see soc_cpu_clk_src_t in clk_tree_defs.h. + { name = "HP_ROOT_CLK", type = "mux", variants = [ + { name = "XTAL", outputs = "XTAL_CLK" }, + { name = "RC_FAST", outputs = "RC_FAST_CLK" }, + { name = "XTAL_X2", outputs = "XTAL_X2_CLK" }, + { name = "PLL", outputs = "PLL_F96M_CLK" }, + ] }, + + # The CPU divider must be a power of two (clk_ll_cpu_set_divider() asserts it) + { name = "CPU_CLK", type = "generic", params = { divisor = "0, 1, 3, 7, 15, 31, 63, 127" }, output = "HP_ROOT_CLK / (divisor + 1)", always_on = true }, + # AHB_CLK divides CPU_CLK and must not exceed 32 MHz, see the clock tree figure in the TRM + # and clk_ll_ahb_set_divider(). The PCR_AHB_DIV_NUM register description says it divides + # HP_ROOT_CLK, but that contradicts both. + { name = "AHB_CLK", type = "generic", params = { divisor = "0..=255" }, output = "CPU_CLK / (divisor + 1)", always_on = true }, + # PCR_APB_DIV_NUM - Set as one within (0,1,3) - pcr_reg.h + { name = "APB_CLK", type = "generic", params = { divisor = "0, 1, 3" }, output = "AHB_CLK / (divisor + 1)" }, + + # LP clocks + { name = "XTAL_D2_CLK", type = "generic", output = "XTAL_CLK / 2" }, + # soc_rtc_fast_clk_src_t: 0 = RC_FAST, 1 = XTAL_D2 (the default). + { name = "LP_FAST_CLK", type = "mux", variants = [ + { name = "RC_FAST_CLK", outputs = "RC_FAST_CLK" }, + { name = "XTAL_D2_CLK", outputs = "XTAL_D2_CLK" }, + ] }, + # soc_rtc_slow_clk_src_t: 0 = RC_SLOW_D4 (the default), 1 = XTAL32K, + # 3 = OSC_SLOW. + { name = "LP_SLOW_CLK", type = "mux", variants = [ + { name = "XTAL32K", outputs = "XTAL32K_CLK", cfg = "use_xtal32k" }, + # The mux input is RC_SLOW/4, see rtc_clk_slow_freq_get_hz(). + { name = "RC_SLOW", outputs = "RC_SLOW_D4_CLK" }, + { name = "OSC_SLOW", outputs = "OSC_SLOW_CLK" }, + ] }, + # BLE RTC timer (LP_CLKRST.lpperi). Independent of LP_SLOW_CLK. + { name = "BLE_LP_XTAL_CLK", type = "derived", from = "XTAL_CLK", output = "100_000" }, + { name = "BLE_LP_CLK", type = "mux", variants = [ + { name = "XTAL", outputs = "BLE_LP_XTAL_CLK" }, + { name = "XTAL32K", outputs = "XTAL32K_CLK", cfg = "use_xtal32k" }, + ] }, + + # PCR.timg_cali_clk_conf.timg_cali_clk_sel: 1 = XTAL32K, 3 = RC_SLOW, + # 4 = TIMG_SECURE_CLK, where RC_FAST sits behind a /32 divider. + # The RC_SLOW input is tapped before the /4 divider, so the mux measures RC_SLOW_D4_CLK four + # cycles at a time. `timergroup.rc_slow_calibration` scales the result accordingly. + { name = "TIMG_CALIBRATION_CLOCK", type = "mux", wake_locking = true, variants = [ + { name = "RC_SLOW_CLK", outputs = "RC_SLOW_D4_CLK" }, + { name = "RC_FAST_DIV_CLK", outputs = "RC_FAST_CLK" }, + { name = "XTAL32K_CLK", outputs = "XTAL32K_CLK", cfg = "use_xtal32k" }, + ] }, +], template_groups = [ + # PCR.uartX_sclk_conf.uartX_sclk_sel: 0 = XTAL, 1 = RC_FAST, 2 = PLL_F48M, + # see uart_ll_set_sclk(). + { group = "UART", clocks = [ + { name = "FUNCTION_CLOCK", type = "generic", wake_locking = true, output = "sclk / (div_num + 1)", params = { sclk = [ + { name = "PLL_F48M", outputs = "PLL_F48M_CLK", default = true }, + { name = "RC_FAST", outputs = "RC_FAST_CLK" }, + { name = "XTAL", outputs = "XTAL_CLK" }, + ], div_num = "0 .. 0x100" } }, + { name = "BAUD_RATE_GENERATOR", type = "generic", output = "(FUNCTION_CLOCK * 16) / (integral * 16 + fractional)", params = { fractional = "0..16", integral = "0..0x1000" } }, + ] }, + # PCR.spiX_clkm_conf.spiX_clkm_sel, see TRM 8.5 and SOC_SPI_CLKS. + { group = "SPI", clocks = [ + { name = "FUNCTION_CLOCK", type = "mux", wake_locking = true, variants = [ + { name = "XTAL", outputs = "XTAL_CLK" }, + { name = "PLL_F48M", outputs = "PLL_F48M_CLK", default = true }, + { name = "RC_FAST", outputs = "RC_FAST_CLK" }, + ] }, + ] }, + # PCR.i2s_{tx,rx}_clkm_conf.i2s_{tx,rx}_clkm_sel, see `i2s_ll_tx_clk_set_src`. Source 3 + # is an external clock on the MCLK pad, which the clock tree cannot describe. + { group = "I2S", + presets = { + CLK = { + type = "generic", + wake_locking = true, + output = "(sclk * div_a) / (div_num * div_a + div_b)", + params = { + sclk = [ + { name = "XTAL", outputs = "XTAL_CLK" }, + { name = "PLL_F96M", outputs = "PLL_F96M_CLK", default = true }, + { name = "XTAL_X2", outputs = "XTAL_X2_CLK" }, + ], + div_num = "1 ..= 255", + div_a = "1 ..= 511", + div_b = "0 ..= 511", + }, + }, + }, + clocks = [ + { name = "TX_CLK", preset = "CLK" }, + { name = "RX_CLK", preset = "CLK" }, + { name = "MCLK_OUT", type = "mux", variants = [ + { name = "TX", outputs = "TX_CLK" }, + { name = "RX", outputs = "RX_CLK", default = true }, + ] }, + ], + }, + # PCR.i2cX_sclk_conf.i2cX_sclk_sel: 0 = XTAL, 1 = RC_FAST, see SOC_I2C_CLKS. + { group = "I2C", clocks = [ + { name = "FUNCTION_CLOCK", type = "generic", wake_locking = true, output = "sclk / (div_num + 1)", params = { sclk = [ + { name = "XTAL", outputs = "XTAL_CLK", default = true }, + { name = "RC_FAST", outputs = "RC_FAST_CLK" }, + ], div_num = "0 .. 0x100" } }, + ] }, + # Sources: SOC_GPTIMER_CLKS and SOC_MWDT_CLKS. Like the other chips we default + # to XTAL + { group = "TIMG", clocks = [ + { name = "FUNCTION_CLOCK", type = "mux", variants = [ + { name = "XTAL_CLK", outputs = "XTAL_CLK", default = true }, + { name = "RC_FAST_CLK", outputs = "RC_FAST_CLK" }, + { name = "PLL_F48M", outputs = "PLL_F48M_CLK" }, + ] }, + { name = "WDT_CLOCK", type = "mux", variants = [ + { name = "XTAL_CLK", outputs = "XTAL_CLK", default = true }, + { name = "RC_FAST_CLK", outputs = "RC_FAST_CLK" }, + { name = "PLL_F48M", outputs = "PLL_F48M_CLK" }, + ] }, + ] }, +] } + +peripheral_clocks = { templates = [ + { name = "default_clk_en_template", value = "{{control}}::regs().{{conf_register}}().modify(|_, w| w.{{clk_en_field}}().bit(enable));" }, + { name = "clk_en_template", value = "{{default_clk_en_template}}" }, + { name = "rst_template", value = "{{control}}::regs().{{conf_register}}().modify(|_, w| w.{{rst_field}}().bit(reset));" }, + { name = "control", value = "crate::peripherals::SYSTEM" }, + { name = "conf_register", value = "{{peripheral}}_conf" }, + { name = "clk_en_field", value = "{{peripheral}}_clk_en" }, + { name = "rst_field", value = "{{peripheral}}_rst_en" }, +], peripheral_clocks = [ + { name = "Uart0", template_params = { conf_register = "uart(0).conf", clk_en_field = "clk_en", rst_field = "rst_en" }, keep_enabled = true }, + { name = "Uart1", template_params = { conf_register = "uart(1).conf", clk_en_field = "clk_en", rst_field = "rst_en" } }, + { name = "Timg0", template_params = { conf_register = "timergroup0_conf", clk_en_field = "tg0_clk_en", rst_field = "tg0_rst_en" }, keep_enabled = true }, + { name = "Timg1", template_params = { conf_register = "timergroup1_conf", clk_en_field = "tg1_clk_en", rst_field = "tg1_rst_en" } }, + { name = "Systimer", keep_enabled = true }, + { name = "AhbGdma", template_params = { peripheral = "gdma" } }, + { name = "Aes" }, + { name = "Ecc" }, + { name = "Ledc" }, + # Besides the function clock that drives the glitch filter, the PCNT has a separate register + # clock. Register accesses are dropped while it is gated, and both boot disabled. + { name = "Pcnt", template_params = { clk_en_template = "{{default_clk_en_template}} {{control}}::regs().pcnt_conf().modify(|_, w| w.pcnt_reg_clk_en().bit(enable));", rst_template = "{{control}}::regs().pcnt_conf().modify(|_, w| { w.pcnt_rst_en().bit(reset); w.pcnt_reg_rst_en().bit(reset) });" } }, + # The channel RAM boots powered down and reads return zeros. ESP-IDF's `rmt_hal_init` only + # withdraws the low power request, the power itself stays under hardware control. + { name = "Rmt", template_params = { clk_en_template = "{{default_clk_en_template}} {{control}}::regs().rmt_mem_lp_ctrl().modify(|_, w| w.rmt_mem_lp_en().bit(!enable));" } }, + { name = "Sha" }, + { name = "Spi2", template_params = { peripheral = "spi2" } }, + { name = "Spi3", template_params = { peripheral = "spi3" } }, + { name = "GpioSd", template_params = { clk_en_template = "crate::peripherals::GPIO_SD::regs().clock_gate().modify(|_, w| w.clk_en().bit(enable));", rst_template = "let _ = reset;" } }, + { name = "ParlIo", template_params = { clk_en_field = "parl_clk_en", rst_field = "parl_rst_en" } }, + { name = "I2s0", template_params = { peripheral = "i2s" } }, + { name = "I2cExt0", template_params = { peripheral = "i2c0" } }, + { name = "I2cExt1", template_params = { peripheral = "i2c1" } }, + # The RNG's clocks are not listed here: nothing requests them, and enabling the RNG takes more + # than a clock gate, so `pre_init` runs IDF's `rng_ll_enable` sequence instead. + { name = "Uhci0", template_params = { peripheral = "uhci" } }, + { name = "UsbDevice", keep_enabled = true }, +] } diff --git a/esp-metadata/devices/esp32h4/gpio.toml b/esp-metadata/devices/esp32h4/gpio.toml new file mode 100644 index 00000000000..5dc7778909e --- /dev/null +++ b/esp-metadata/devices/esp32h4/gpio.toml @@ -0,0 +1,294 @@ +version = 3 +has_input_sync = true +# PIN_FUNC_GPIO = 1 (from io_mux_reg.h) +gpio_function = 1 +# From gpio_pins.h: GPIO_MATRIX_CONST_ONE_INPUT = 0x40, GPIO_MATRIX_CONST_ZERO_INPUT = 0x60 +constant_0_input = 0x60 +constant_1_input = 0x40 +# GPIO0-5 double as LP_GPIO0-5 (`RTCIO_LL_GPIO_NUM_OFFSET = 0` and `RTCIO_LL_PIN_FUNC = 1` in +# esp-idf `rtc_io_ll.h`). +pins = [ + # Unlike the two-pad comparators of the other chips, any of these can be selected as one of the three comparison + # channels or as the reference channel. + { pin = 0, analog = { 0 = "ZCD0" }, lp = { 1 = "LP_GPIO0" } }, + { pin = 1, analog = { 0 = "ZCD1" }, lp = { 1 = "LP_GPIO1" } }, + { pin = 2, analog = { 0 = "ZCD2" }, lp = { 1 = "LP_GPIO2" } }, + { pin = 3, analog = { 0 = "ZCD3" }, lp = { 1 = "LP_GPIO3" } }, + { pin = 4, analog = { 0 = "XTAL_32K_N" }, lp = { 1 = "LP_GPIO4" } }, + { pin = 5, analog = { 0 = "XTAL_32K_P" }, lp = { 1 = "LP_GPIO5" } }, + { pin = 6, limitations = ["spi_flash"] }, # SPICS1 + { pin = 7, limitations = ["spi_flash"] }, # SPICS0 + { pin = 8, limitations = ["spi_flash"] }, # SPIQ + { pin = 9, limitations = ["spi_flash"] }, # SPIWP + { pin = 10, limitations = ["spi_flash"] }, # SPIHD + { pin = 11, limitations = ["spi_flash"] }, # SPICLK + { pin = 12, limitations = ["spi_flash"] }, # SPID + { pin = 13, analog = { 0 = "USJ_DM" } }, + { pin = 14, analog = { 0 = "USJ_DP" } }, + { pin = 15, functions = { 2 = "FSPIQ" } }, + { pin = 16, functions = { 2 = "FSPICLK" } }, + { pin = 17, functions = { 2 = "FSPID" } }, + { pin = 18, functions = { 2 = "FSPIWP" } }, + { pin = 19, functions = { 2 = "FSPIHD" } }, + { pin = 20, functions = { 2 = "FSPICS0" } }, + { pin = 21, analog = { 0 = "USB_FS_DM" } }, + { pin = 22, analog = { 0 = "USB_FS_DP" } }, + { pin = 23, functions = { 0 = "U0RXD" } }, + { pin = 24, functions = { 0 = "U0TXD" } }, + # Per the datasheet's Boot Configurations chapter, GPIO25 selects the VO_FLASH voltage and + # GPIO36 the JTAG signal source. The boot mode and ROM message printing are strapped by the + # dedicated STRAP_MODE_0 and STRAP_MODE_1 pins, which are not GPIOs. + { pin = 25, limitations = ["strapping"] }, + { pin = 26 }, + { pin = 27 }, + { pin = 28, functions = { 0 = "MTMS" }, analog = { 0 = "ADC1_CH0" } }, + { pin = 29, functions = { 0 = "MTDI" }, analog = { 0 = "ADC1_CH1" } }, + { pin = 30, functions = { 0 = "MTCK" }, analog = { 0 = "ADC1_CH2" } }, + { pin = 31, functions = { 0 = "MTDO" }, analog = { 0 = "ADC1_CH3" } }, + { pin = 32, functions = { 2 = "FSPICLK" }, analog = { 0 = "ADC1_CH4" } }, + { pin = 33, functions = { 2 = "FSPID" } }, + { pin = 34 }, + { pin = 35 }, + { pin = 36, functions = { 2 = "FSPIQ" }, limitations = ["strapping"] }, + { pin = 37, functions = { 2 = "FSPIWP" } }, + { pin = 38, functions = { 2 = "FSPIHD" } }, + { pin = 39, functions = { 2 = "FSPICS0" } }, +] +input_signals = [ + { name = "EXT_ADC_START", id = 0 }, + { name = "U0RXD", id = 8 }, + { name = "U0CTS", id = 9 }, + { name = "U0DSR", id = 10 }, + { name = "U1RXD", id = 11 }, + { name = "U1CTS", id = 12 }, + { name = "U1DSR", id = 13 }, + { name = "I2S_MCLK", id = 14 }, + { name = "I2SO_BCK", id = 15 }, + { name = "I2SO_WS", id = 16 }, + { name = "I2SI_SD", id = 17 }, + { name = "I2SI_BCK", id = 18 }, + { name = "I2SI_WS", id = 19 }, + { name = "CPU_GPIO_0", id = 29 }, + { name = "CPU_GPIO_1", id = 30 }, + { name = "CPU_GPIO_2", id = 31 }, + { name = "CPU_GPIO_3", id = 32 }, + { name = "CPU_GPIO_4", id = 33 }, + { name = "CPU_GPIO_5", id = 34 }, + { name = "CPU_GPIO_6", id = 35 }, + { name = "CPU_GPIO_7", id = 36 }, + { name = "USB_JTAG_TDO_BRIDGE", id = 37 }, + { name = "USB_FS_IDDIG", id = 43 }, + { name = "USB_FS_AVALID", id = 44 }, + { name = "USB_FS_SRP_BVALID", id = 45 }, + { name = "USB_FS_VBUSVALID", id = 46 }, + { name = "USB_FS_SRP_SESSEND", id = 47 }, + { name = "I2CEXT0_SCL", id = 49 }, + { name = "I2CEXT0_SDA", id = 50 }, + { name = "PARL_RX_DATA0", id = 51 }, + { name = "PARL_RX_DATA1", id = 52 }, + { name = "PARL_RX_DATA2", id = 53 }, + { name = "PARL_RX_DATA3", id = 54 }, + { name = "PARL_RX_DATA4", id = 55 }, + { name = "PARL_RX_DATA5", id = 56 }, + { name = "PARL_RX_DATA6", id = 57 }, + { name = "PARL_RX_DATA7", id = 58 }, + { name = "FSPICLK", id = 59 }, + { name = "FSPIQ", id = 60 }, + { name = "FSPID", id = 61 }, + { name = "FSPIHD", id = 62 }, + { name = "FSPIWP", id = 63 }, + { name = "FSPICS0", id = 64 }, + { name = "PARL_RX_CLK", id = 65 }, + { name = "PARL_TX_CLK", id = 66 }, + { name = "RMT_SIG_0", id = 67 }, + { name = "RMT_SIG_1", id = 68 }, + { name = "TWAI0_RX", id = 69 }, + { name = "PCNT0_RST", id = 77 }, + { name = "PCNT1_RST", id = 78 }, + { name = "PCNT2_RST", id = 79 }, + { name = "PCNT3_RST", id = 80 }, + { name = "PWM0_SYNC0", id = 81 }, + { name = "PWM0_SYNC1", id = 82 }, + { name = "PWM0_SYNC2", id = 83 }, + { name = "PWM0_F0", id = 84 }, + { name = "PWM0_F1", id = 85 }, + { name = "PWM0_F2", id = 86 }, + { name = "PWM0_CAP0", id = 87 }, + { name = "PWM0_CAP1", id = 88 }, + { name = "PWM0_CAP2", id = 89 }, + { name = "SIG_IN_FUNC97", id = 97 }, + { name = "SIG_IN_FUNC98", id = 98 }, + { name = "SIG_IN_FUNC99", id = 99 }, + { name = "SIG_IN_FUNC100", id = 100 }, + { name = "PCNT0_SIG_CH0", id = 102 }, + { name = "PCNT0_SIG_CH1", id = 103 }, + { name = "PCNT0_CTRL_CH0", id = 104 }, + { name = "PCNT0_CTRL_CH1", id = 105 }, + { name = "PCNT1_SIG_CH0", id = 106 }, + { name = "PCNT1_SIG_CH1", id = 107 }, + { name = "PCNT1_CTRL_CH0", id = 108 }, + { name = "PCNT1_CTRL_CH1", id = 109 }, + { name = "PCNT2_SIG_CH0", id = 110 }, + { name = "PCNT2_SIG_CH1", id = 111 }, + { name = "PCNT2_CTRL_CH0", id = 112 }, + { name = "PCNT2_CTRL_CH1", id = 113 }, + { name = "PCNT3_SIG_CH0", id = 114 }, + { name = "PCNT3_SIG_CH1", id = 115 }, + { name = "PCNT3_CTRL_CH0", id = 116 }, + { name = "PCNT3_CTRL_CH1", id = 117 }, + { name = "PWM1_SYNC0", id = 155 }, + { name = "PWM1_SYNC1", id = 156 }, + { name = "PWM1_SYNC2", id = 157 }, + { name = "PWM1_F0", id = 158 }, + { name = "PWM1_F1", id = 159 }, + { name = "PWM1_F2", id = 160 }, + { name = "PWM1_CAP0", id = 161 }, + { name = "PWM1_CAP1", id = 162 }, + { name = "PWM1_CAP2", id = 163 }, + { name = "I2CEXT1_SCL", id = 164 }, + { name = "I2CEXT1_SDA", id = 165 }, + { name = "FSPI3CLK", id = 166 }, + { name = "FSPI3Q", id = 167 }, + { name = "FSPI3D", id = 168 }, + { name = "FSPI3HD", id = 169 }, + { name = "FSPI3WP", id = 170 }, + { name = "FSPI3CS0", id = 171 }, + { name = "CPU_GPIO_8", id = 182 }, + { name = "CPU_GPIO_9", id = 183 }, + { name = "CPU_GPIO_10", id = 184 }, + { name = "CPU_GPIO_11", id = 185 }, + { name = "CPU_GPIO_12", id = 186 }, + { name = "CPU_GPIO_13", id = 187 }, + { name = "CPU_GPIO_14", id = 188 }, + { name = "CPU_GPIO_15", id = 189 }, + + { name = "MTDI" }, + { name = "MTCK" }, + { name = "MTMS" }, +] +output_signals = [ + { name = "LEDC_LS_SIG0", id = 0 }, + { name = "LEDC_LS_SIG1", id = 1 }, + { name = "LEDC_LS_SIG2", id = 2 }, + { name = "LEDC_LS_SIG3", id = 3 }, + { name = "LEDC_LS_SIG4", id = 4 }, + { name = "LEDC_LS_SIG5", id = 5 }, + { name = "LEDC_LS_SIG6", id = 6 }, + { name = "LEDC_LS_SIG7", id = 7 }, + { name = "U0TXD", id = 8 }, + { name = "U0RTS", id = 9 }, + { name = "U0DTR", id = 10 }, + { name = "U1TXD", id = 11 }, + { name = "U1RTS", id = 12 }, + { name = "U1DTR", id = 13 }, + { name = "I2S_MCLK", id = 14 }, + { name = "I2SO_BCK", id = 15 }, + { name = "I2SO_WS", id = 16 }, + { name = "I2SO_SD", id = 17 }, + { name = "I2SI_BCK", id = 18 }, + { name = "I2SI_WS", id = 19 }, + { name = "I2SO_SD1", id = 20 }, + { name = "CPU_GPIO_0", id = 29 }, + { name = "CPU_GPIO_1", id = 30 }, + { name = "CPU_GPIO_2", id = 31 }, + { name = "CPU_GPIO_3", id = 32 }, + { name = "CPU_GPIO_4", id = 33 }, + { name = "CPU_GPIO_5", id = 34 }, + { name = "CPU_GPIO_6", id = 35 }, + { name = "CPU_GPIO_7", id = 36 }, + { name = "USB_JTAG_TRST", id = 37 }, + { name = "USB_SRP_DISCHRGVBUS", id = 43 }, + { name = "USB_OTG_IDPULLUP", id = 44 }, + { name = "USB_OTG_DPPULLDOWN", id = 45 }, + { name = "USB_OTG_DMPULLDOWN", id = 46 }, + { name = "USB_OTG_DRVVBUS", id = 47 }, + { name = "USB_SRP_CHRGVBUS", id = 48 }, + { name = "I2CEXT0_SCL", id = 49 }, + { name = "I2CEXT0_SDA", id = 50 }, + { name = "PARL_TX_DATA0", id = 51 }, + { name = "PARL_TX_DATA1", id = 52 }, + { name = "PARL_TX_DATA2", id = 53 }, + { name = "PARL_TX_DATA3", id = 54 }, + { name = "PARL_TX_DATA4", id = 55 }, + { name = "PARL_TX_DATA5", id = 56 }, + { name = "PARL_TX_DATA6", id = 57 }, + { name = "PARL_TX_DATA7", id = 58 }, + { name = "FSPICLK", id = 59 }, + { name = "FSPIQ", id = 60 }, + { name = "FSPID", id = 61 }, + { name = "FSPIHD", id = 62 }, + { name = "FSPIWP", id = 63 }, + { name = "FSPICS0", id = 64 }, + { name = "PARL_RX_CLK", id = 65 }, + { name = "PARL_TX_CLK", id = 66 }, + { name = "RMT_SIG_0", id = 67 }, + { name = "RMT_SIG_1", id = 68 }, + { name = "TWAI0_TX", id = 69 }, + { name = "PARL_TX_CS", id = 70 }, + { name = "GPIO_SD0", id = 77 }, + { name = "GPIO_SD1", id = 78 }, + { name = "GPIO_SD2", id = 79 }, + { name = "GPIO_SD3", id = 80 }, + { name = "PWM0_0A", id = 81 }, + { name = "PWM0_0B", id = 82 }, + { name = "PWM0_1A", id = 83 }, + { name = "PWM0_1B", id = 84 }, + { name = "PWM0_2A", id = 85 }, + { name = "PWM0_2B", id = 86 }, + { name = "CLK_OUT_OUT1", id = 94 }, + { name = "CLK_OUT_OUT2", id = 95 }, + { name = "CLK_OUT_OUT3", id = 96 }, + { name = "SIG_IN_FUNC97", id = 97 }, + { name = "SIG_IN_FUNC98", id = 98 }, + { name = "SIG_IN_FUNC99", id = 99 }, + { name = "SIG_IN_FUNC100", id = 100 }, + { name = "FSPICS1", id = 102 }, + { name = "FSPICS2", id = 103 }, + { name = "FSPICS3", id = 104 }, + { name = "FSPICS4", id = 105 }, + { name = "FSPICS5", id = 106 }, + { name = "ANT_SEL0", id = 139 }, + { name = "ANT_SEL1", id = 140 }, + { name = "ANT_SEL2", id = 141 }, + { name = "ANT_SEL3", id = 142 }, + { name = "ANT_SEL4", id = 143 }, + { name = "ANT_SEL5", id = 144 }, + { name = "ANT_SEL6", id = 145 }, + { name = "ANT_SEL7", id = 146 }, + { name = "ANT_SEL8", id = 147 }, + { name = "ANT_SEL9", id = 148 }, + { name = "ANT_SEL10", id = 149 }, + { name = "ANT_SEL11", id = 150 }, + { name = "ANT_SEL12", id = 151 }, + { name = "ANT_SEL13", id = 152 }, + { name = "ANT_SEL14", id = 153 }, + { name = "ANT_SEL15", id = 154 }, + { name = "PWM1_0A", id = 155 }, + { name = "PWM1_0B", id = 156 }, + { name = "PWM1_1A", id = 157 }, + { name = "PWM1_1B", id = 158 }, + { name = "PWM1_2A", id = 159 }, + { name = "PWM1_2B", id = 160 }, + { name = "I2CEXT1_SCL", id = 164 }, + { name = "I2CEXT1_SDA", id = 165 }, + { name = "FSPI3CLK", id = 166 }, + { name = "FSPI3Q", id = 167 }, + { name = "FSPI3D", id = 168 }, + { name = "FSPI3HD", id = 169 }, + { name = "FSPI3WP", id = 170 }, + { name = "FSPI3CS0", id = 171 }, + { name = "FSPI3CS1", id = 172 }, + { name = "FSPI3CS2", id = 173 }, + { name = "CPU_GPIO_8", id = 182 }, + { name = "CPU_GPIO_9", id = 183 }, + { name = "CPU_GPIO_10", id = 184 }, + { name = "CPU_GPIO_11", id = 185 }, + { name = "CPU_GPIO_12", id = 186 }, + { name = "CPU_GPIO_13", id = 187 }, + { name = "CPU_GPIO_14", id = 188 }, + { name = "CPU_GPIO_15", id = 189 }, + { name = "GPIO", id = 256 }, + + { name = "MTDO" }, +] + diff --git a/esp-metadata/devices/esp32h4/soc.toml b/esp-metadata/devices/esp32h4/soc.toml new file mode 100644 index 00000000000..a94df458a70 --- /dev/null +++ b/esp-metadata/devices/esp32h4/soc.toml @@ -0,0 +1,493 @@ +# ESP32-H4 Device Metadata +# +# Empty [`device.driver`] tables imply `partial` support status. +# +# If you modify a driver support status, run `cargo xtask update-metadata` to +# update the table in the esp-hal README. + +[device] +name = "esp32h4" +arch = "riscv" +target = "riscv32imafc-unknown-none-elf" +cores = 2 +datasheet = "https://www.espressif.com/sites/default/files/documentation/esp32-h4_datasheet_en.pdf" +trm = "https://www.espressif.com/sites/default/files/documentation/esp32-h4_technical_reference_manual_en.pdf" +support_note = "In early stages of development." + +[device.mmu] +page_size = 0x10000 +entry_num = 512 + +[device.flash] +support_status = "partial" + +[device.rom] +has_crc_le = true +has_crc_be = true +has_md5_bsd = true + +[device.soc] +multi_core_enabled = true +cpu_has_branch_predictor = true +cpu_has_csr_pc = false +cpu_has_zcmp_workaround = true +cpu_csr_prv_mode = 0x810 +cpu_mcause_mask = 0x3f +# ESP-IDF does not define SOC_CPU_PMP_REGION_GRANULARITY for this chip yet. Measured on hardware +# by writing all ones into a free `pmpaddr` and reading it back: the lowest five bits are hardwired +# to zero. +cpu_pmp_granularity = 128 +has_swd_watchdog = true + +# SRAM_SEG_START = 0x40810000, SRAM_SEG_END = 0x4084F350 +# (from esp-idf components/esp_system/ld/esp32h4/memory.ld.in) +# dram2_uninit: SRAM_SEG_END..SOC_ROM_STACK_START (PRO CPU stack, reclaimable) +# SOC_ROM_STACK_START = 0x4085D350 (from soc.h) +memory_map = { ranges = [ + { name = "dram", start = 0x4081_0000, end = 0x4084_F350 }, + { name = "dram2_uninit", start = 0x4084_F350, end = 0x4085_D350 }, + { name = "irom", start = 0x4200_0000, end = 0x4400_0000 }, + { name = "drom", start = 0x4200_0000, end = 0x4400_0000 }, +] } + +peripherals = [ + { name = "AES", interrupts = { peri = "AES" } }, + { name = "APB_SARADC", interrupts = { peri = "APB_ADC" } }, + { name = "ASRC", interrupts = { chnl0 = "ASRC_CHNL0", chnl1 = "ASRC_CHNL1" } }, + { name = "BUS_MONITOR", interrupts = { peri = "BUS_MONITOR" } }, + { name = "CACHE", interrupts = { peri = "CACHE" } }, + { name = "CLIC" }, + { name = "CLINT" }, + { name = "CLINT_OTHER_CORE" }, + { name = "CPU_APM" }, + { name = "DMA" }, + { name = "ECC", interrupts = { peri = "ECC" } }, + { name = "ECDSA", interrupts = { peri = "ECDSA" } }, + { name = "EFUSE", hidden = true }, + { name = "ETM", pac = "SOC_ETM" }, + { name = "GPIO" }, + { name = "GPIO_DEDICATED", virtual = true }, + { name = "GPIO_SD" }, + { name = "HMAC" }, + { name = "HP_APM" }, + { name = "HP_SYS" }, + { name = "HUK", interrupts = { peri = "HUK" } }, + { name = "I2C_ANA_MST" }, + { name = "I2S0", interrupts = { peri = "I2S" }, clock_group = "I2S" }, + { name = "I2C0", interrupts = { peri = "I2C_EXT0" }, stable = true, clock_group = "I2C" }, + { name = "I2C1", interrupts = { peri = "I2C_EXT1" }, stable = true, clock_group = "I2C" }, + { name = "IEEE802154", interrupts = { mac = "ZB_MAC" } }, + { name = "INTERRUPT_CORE0" }, + { name = "INTERRUPT_CORE1" }, + { name = "INTPRI" }, + { name = "IO_MUX" }, + { name = "KEYMNG", interrupts = { peri = "KM" } }, + { name = "LEDC" }, + { name = "LPWR", pac = "LP_CLKRST" }, + { name = "LP_ANA" }, + { name = "LP_AON" }, + { name = "LP_CLKRST" }, + { name = "LP_GPIO" }, + { name = "LP_IO_MUX" }, + { name = "LP_PERI" }, + { name = "LP_TEE" }, + { name = "LP_WDT" }, + { name = "MCPWM0", interrupts = { peri = "MCPWM0" } }, + { name = "MCPWM1", interrupts = { peri = "MCPWM1" } }, + { name = "MEM_MONITOR" }, + { name = "MODEM_LPCON" }, + { name = "MODEM_SYSCON" }, + { name = "PARL_IO", interrupts = { tx = "PARL_IO_TX", rx = "PARL_IO_RX" } }, + { name = "PAU", interrupts = { peri = "PAU" } }, + { name = "PCNT", interrupts = { peri = "PCNT" } }, + { name = "PCR" }, + { name = "PMU", interrupts = { peri = "PMU" } }, + { name = "PVT" }, + { name = "RMT", interrupts = { peri = "RMT" } }, + { name = "RNG" }, + { name = "SHA", interrupts = { peri = "SHA" } }, + { name = "RTC_TIMER", pac = "LP_TIMER" }, + { name = "SPI0" }, + { name = "SPI1" }, + { name = "SPI2", interrupts = { peri = "GPSPI2" }, stable = true, clock_group = "SPI" }, + { name = "SPI3", interrupts = { peri = "GPSPI3" }, stable = true, clock_group = "SPI" }, + { name = "SYSTEM", pac = "PCR" }, + { name = "SYSTIMER" }, + { name = "TEE" }, + { name = "TIMG0", clock_group = "TIMG" }, + { name = "TIMG1", clock_group = "TIMG" }, + { name = "TOUCH", interrupts = { peri = "TOUCH" } }, + { name = "TOUCH_AON" }, + # The single TWAI controller is a CAN-FD, the PAC just keeps the TWAI0 name. + { name = "TWAI0", interrupts = { peri = "TWAI0", timer = "TWAI0_TIMER" } }, + { name = "UART0", interrupts = { peri = "UART0" }, stable = true, clock_group = "UART" }, + { name = "UART1", interrupts = { peri = "UART1" }, stable = true, clock_group = "UART" }, + { name = "UHCI0" }, + { name = "USB_DEVICE", interrupts = { peri = "USB_DEVICE" } }, + { name = "USB_FS", pac = "USB0", interrupts = { peri = "USB_OTG11" } }, + { name = "USB_WRAP", hidden = true }, + { name = "ZERO_DET", interrupts = { peri = "ZERO_DET" } }, # the analog comparator + + { name = "ADC1", virtual = true }, + { name = "BT", virtual = true, interrupts = { mac = "BT_MAC", bb = "BT_BB", lp_timer = "LP_RTC_BLE_TIMER" } }, + { name = "CPU_CTRL", virtual = true }, + { name = "IPC", virtual = true }, + { name = "FLASH", virtual = true }, + { name = "FROM_CPU_INTR0", virtual = true }, + { name = "FROM_CPU_INTR1", virtual = true }, + { name = "FROM_CPU_INTR2", virtual = true }, + { name = "FROM_CPU_INTR3", virtual = true }, +] + +[device.soc.clocks] +# {include clocks.toml} + +[device.gpio] +support_status = "partial" +# {include gpio.toml} + +# The CSR interface is identical to the C6/H2 one (see `dedic_gpio_cpu_ll.h`), but each core has +# its own set of 8 channels: CPU_GPIO_0..7 belong to core 0, CPU_GPIO_8..15 to core 1. +[device.dedicated_gpio] +version = "riscv_v1" +support_status = "partial" +channels = [ + ["CPU_GPIO_0", "CPU_GPIO_1", "CPU_GPIO_2", "CPU_GPIO_3", "CPU_GPIO_4", "CPU_GPIO_5", "CPU_GPIO_6", "CPU_GPIO_7" ], + ["CPU_GPIO_8", "CPU_GPIO_9", "CPU_GPIO_10", "CPU_GPIO_11", "CPU_GPIO_12", "CPU_GPIO_13", "CPU_GPIO_14", "CPU_GPIO_15"], +] + +[device.io_mux] + +[device.lp_io] +support_status = "partial" +version = "v4" + +[device.uart] +support_status = "partial" +instances = [ + { name = "uart0", sys_instance = "Uart0", tx = "U0TXD", rx = "U0RXD", cts = "U0CTS", rts = "U0RTS" }, + { name = "uart1", sys_instance = "Uart1", tx = "U1TXD", rx = "U1RXD", cts = "U1CTS", rts = "U1RTS" }, +] +ram_size = 128 +version = 2 +peripheral_controls_mem_clk = true +has_sclk_enable = true + +[device.uhci] +support_status = "not_supported" +combined_uart_selector_field = true + +[device.i2c_master] +support_status = "partial" +version = 4 +instances = [ + { name = "i2c0", sys_instance = "I2cExt0", scl = "I2CEXT0_SCL", sda = "I2CEXT0_SDA" }, + { name = "i2c1", sys_instance = "I2cExt1", scl = "I2CEXT1_SCL", sda = "I2CEXT1_SDA" }, +] +has_fsm_timeouts = true +has_hw_bus_clear = true +ll_intr_mask = 0x3ffff +fifo_size = 32 +has_bus_timeout_enable = true +max_bus_timeout = 0x1F +can_estimate_nack_reason = true +has_conf_update = true +has_reliable_fsm_reset = true +has_arbitration_en = true +has_tx_fifo_watermark = true +bus_timeout_is_exponential = true +has_pd_en = true + +[device.i2c_slave] +support_status = { status = "not_supported", issue = 1909 } + +[device.spi_master] +support_status = "partial" +version = 3 +fifo_size = 64 +has_app_interrupts = true +has_dma_segmented_transfer = true +instances = [ + { + name = "spi2", + sys_instance = "Spi2", + sclk = "FSPICLK", + sio = ["FSPID", "FSPIQ", "FSPIWP", "FSPIHD"], + cs = ["FSPICS0", "FSPICS1", "FSPICS2", "FSPICS3", "FSPICS4", "FSPICS5"] + }, + { + name = "spi3", + sys_instance = "Spi3", + sclk = "FSPI3CLK", + sio = ["FSPI3D", "FSPI3Q", "FSPI3WP", "FSPI3HD"], + cs = ["FSPI3CS0", "FSPI3CS1", "FSPI3CS2"] + }, +] + +[device.spi_slave] +support_status = "not_supported" +instances = [ + { + name = "spi2", + sys_instance = "Spi2", + sclk = "FSPICLK", + mosi = "FSPID", + miso = "FSPIQ", + cs = "FSPICS0" + }, + { + name = "spi3", + sys_instance = "Spi3", + sclk = "FSPI3CLK", + mosi = "FSPI3D", + miso = "FSPI3Q", + cs = "FSPI3CS0" + }, +] + +[device.i2s] +support_status = "partial" +version = 3 +mclk_divider_bit_width = 9 +max_ws_width = 512 +clock_configured_by_pcr = true +instances = [ + { + name = "i2s0", + sys_instance = "I2s0", + mclk = "I2S_MCLK", + bclk = "I2SO_BCK", + ws = "I2SO_WS", + bclk_rx = "I2SI_BCK", + ws_rx = "I2SI_WS", + dout = ["I2SO_SD", "I2SO_SD1"], + din = ["I2SI_SD"], + pdm_tx = true, + pdm_rx = true, + pcm2pdm = true, + }, +] + +[device.parl_io] +support_status = "not_supported" +version = 2 +max_data_width = 8 +has_tx_cs = true + +[device.rmt] +support_status = "not_supported" +ram_start = 0x6001e400 +channel_ram_size = 48 +channels = ["Tx", "Tx", "Rx", "Rx"] +has_tx_immediate_stop = true +has_tx_loop_count = true +has_tx_loop_auto_stop = true +has_tx_carrier_data_only = true +has_tx_sync = true +has_rx_wrap = true +has_rx_demodulation = true + +[device.canfd] +support_status = "not_supported" + +[device.usb_otg] +support_status = "not_supported" +fifo_depth_words = 256 + +[device.usb_serial_jtag] + +[device.bt] +support_status = "partial" +controller = "btdm2" + +[device.ieee802154] +support_status = "partial" + +[device.phy] +support_status = "partial" + +[device.asrc] +support_status = "not_supported" + +[device.adc] +support_status = "not_supported" + +[device.avc] +support_status = "not_supported" + +[device.temp_sensor] +support_status = "not_supported" + +[device.touch] +support_status = "not_supported" + +[device.ledc] +support_status = "not_supported" +version = 3 +channel_count = 8 + +[device.mcpwm] +support_status = "not_supported" + +[device.pcnt] +support_status = "not_supported" +instances = { + PCNT = { + sys_instance = "Pcnt", + interrupt = "PCNT", + units = [ + { sig_ch0 = "PCNT0_SIG_CH0", sig_ch1 = "PCNT0_SIG_CH1", ctrl_ch0 = "PCNT0_CTRL_CH0", ctrl_ch1 = "PCNT0_CTRL_CH1" }, + { sig_ch0 = "PCNT1_SIG_CH0", sig_ch1 = "PCNT1_SIG_CH1", ctrl_ch0 = "PCNT1_CTRL_CH0", ctrl_ch1 = "PCNT1_CTRL_CH1" }, + { sig_ch0 = "PCNT2_SIG_CH0", sig_ch1 = "PCNT2_SIG_CH1", ctrl_ch0 = "PCNT2_CTRL_CH0", ctrl_ch1 = "PCNT2_CTRL_CH1" }, + { sig_ch0 = "PCNT3_SIG_CH0", sig_ch1 = "PCNT3_SIG_CH1", ctrl_ch0 = "PCNT3_CTRL_CH0", ctrl_ch1 = "PCNT3_CTRL_CH1" }, + ], + }, +} + +[device.lp_timer] + +[device.sdm] +support_status = "not_supported" +channel_count = 4 + +[device.systimer] + +[device.timergroup] +support_status = "partial" +instances = [{ name = "timg0" }, { name = "timg1" }] +timg_has_divcnt_rst = true +# see esp-idf components/esp_hw_support/port/esp32h4/rtc_time.c +rc_fast_calibration = { divider = 32, min_rev = 0 } +# The calibration mux taps RC_SLOW ahead of the /4 divider that produces LP_SLOW_CLK, so we +# counted four input cycles per cycle of the clock we want to measure. esp-idf scales +# `cal_val` the same way, see rtc_clk_cal_internal() in +# components/esp_hw_support/port/esp32h4/rtc_time.c. +rc_slow_calibration = { multiplier = 4 } +wdt_has_conf_update = true + +[device.aes] +support_status = "not_supported" +has_split_text_registers = true +endianness_configurable = false +dma_mode = ["ECB", "CBC", "OFB", "CTR", "CFB8", "CFB128"] +key_length = { options = [ + { bits = 128, encrypt_mode = 0, decrypt_mode = 4 }, + { bits = 256, encrypt_mode = 2, decrypt_mode = 6 } +] } + +[device.ecdsa] +support_status = { status = "not_supported", issue = 5444 } + +[device.ecc] +support_status = "not_supported" +working_modes = [ + { id = 0, mode = "affine_point_multiplication" }, + { id = 2, mode = "affine_point_verification" }, + { id = 3, mode = "affine_point_verification_and_multiplication" }, + { id = 4, mode = "jacobian_point_multiplication" }, + { id = 5, mode = "affine_point_addition" }, + { id = 6, mode = "jacobian_point_verification" }, + { id = 7, mode = "affine_point_verification_and_jacobian_point_multiplication" }, + { id = 8, mode = "modular_addition" }, + { id = 9, mode = "modular_subtraction" }, + { id = 10, mode = "modular_multiplication" }, + { id = 11, mode = "modular_division" }, +] +curves = [ + { id = 0, curve = "p192" }, + { id = 1, curve = "p256" }, + { id = 2, curve = "p384" }, +] +separate_jacobian_point_memory = true +has_memory_clock_gate = true +supports_enhanced_security = true + +[device.hmac] +support_status = { status = "not_supported", issue = 5166 } + +[device.key_manager] +support_status = "not_supported" + +[device.rng] +support_status = { status = "partial", issue = 5979 } +trng_supported = false +apb_cycle_wait_num = 16 + +[device.sha] +support_status = "not_supported" +algo = { + sha1 = 0, + sha224 = 1, + sha256 = 2, + sha384 = 3, + sha512 = 4, + sha512_224 = 5, + sha512_256 = 6, + sha512_t = 7, +} + +[device.sleep] +support_status = "partial" +light_sleep = true +deep_sleep = true +ext1_version = 2 +pin_wakeup_version = 3 +# esp-idf components/esp_hw_support/port/esp32h4/private_include/pmu_bit_defs.h +wakeup_sources = { + Ext1 = 1, + Gpio = 2, + Timer = 4, + Uart0 = 6, + Uart1 = 7, + Bt = 10, + Usb = 14, +} + +[device.assist_debug] +support_status = "not_supported" + +[device.dma] +support_status = "partial" +gdma_version = 3 +separate_in_out_interrupts = true +engines = [ + { + name = "AHB_GDMA", + max_priority = 5, + # Mux IDs below include later peripherals; only list HAL drivers that are enabled. + drivers = ["i2s", "spi_master"], + # Peripheral selector values, TRM table 2.4-1. + peripheral_instances = [ + { name = "SPI3", dma_id = 0 }, + { name = "SPI2", dma_id = 1 }, + { name = "UHCI0", dma_id = 2 }, + { name = "I2S0", dma_id = 3 }, + { name = "AES", dma_id = 4 }, + { name = "SHA", dma_id = 7 }, + { name = "PARL_IO", dma_id = 9 }, + ], + # 10 ~ 15 are the "dummy" selectors used for memory-to-memory transfers. + channels = [ + { name = "DMA_CH0", mem2mem = true, mem2mem_id = 10, interrupt_in = "DMA_IN_CH0", interrupt_out = "DMA_OUT_CH0" }, + { name = "DMA_CH1", mem2mem = true, mem2mem_id = 11, interrupt_in = "DMA_IN_CH1", interrupt_out = "DMA_OUT_CH1" }, + { name = "DMA_CH2", mem2mem = true, mem2mem_id = 12, interrupt_in = "DMA_IN_CH2", interrupt_out = "DMA_OUT_CH2" }, + { name = "DMA_CH3", mem2mem = true, mem2mem_id = 13, interrupt_in = "DMA_IN_CH3", interrupt_out = "DMA_OUT_CH3" }, + { name = "DMA_CH4", mem2mem = true, mem2mem_id = 14, interrupt_in = "DMA_IN_CH4", interrupt_out = "DMA_OUT_CH4" }, + ] + }, +] + +[device.etm] +support_status = "not_supported" + +[device.interrupts] +support_status = "partial" +# 98 interrupt sources => ceil(98/32) = 4 status words +status_registers = 4 +software_interrupt_count = 4 +controller = { Riscv = { flavour = "clic", interrupts = 48, priority_levels = 8 } } +context_switch_source = "ipc" + +[device.psram] +support_status = "not_supported" +extmem_origin = 0x4200_0000 diff --git a/esp-metadata/devices/esp32p4/clocks.toml b/esp-metadata/devices/esp32p4/clocks.toml index 47f354f2228..7001c3d0e47 100644 --- a/esp-metadata/devices/esp32p4/clocks.toml +++ b/esp-metadata/devices/esp32p4/clocks.toml @@ -4,12 +4,12 @@ system_clocks = { clock_tree = [ { name = "CPLL_CLK", type = "derived", from = "XTAL_CLK", values = "360, 400", output = "VALUE * 1_000_000" }, { name = "SPLL_CLK", type = "derived", from = "XTAL_CLK", output = "480 * 1_000_000" }, { name = "MPLL_CLK", type = "derived", from = "XTAL_CLK", values = "320, 400, 500", output = "VALUE * 1_000_000" }, - { name = "RC_FAST_CLK", type = "source", output = "20_000_000" }, + { name = "RC_FAST_CLK", type = "source", output = "20_000_000", adjustable = "10_000_000..=30_000_000" }, # Low-speed clocks - { name = "XTAL32K_CLK", type = "source", output = "32768" }, + { name = "XTAL32K_CLK", type = "source", output = "32768", cfg = "use_xtal32k" }, { name = "OSC_SLOW_CLK", type = "source", output = "32768" }, - { name = "RC_SLOW_CLK", type = "source", output = "136_000" }, + { name = "RC_SLOW_CLK", type = "source", output = "136_000", adjustable = "68_000..=204_000" }, { name = "RC32K_CLK", type = "source", output = "32768" }, # SPLL divider taps @@ -19,6 +19,9 @@ system_clocks = { clock_tree = [ { name = "PLL_F160M", type = "generic", output = "SPLL_CLK / 3" }, { name = "PLL_F240M", type = "generic", output = "SPLL_CLK / 2" }, + # Virtual clock node for peripherals that can be sourced from SPLL but have a 160MHz max constraint. + { name = "SPLL_D3_CLOCK", type = "generic", output = "SPLL_CLK / 3" }, + { name = "IOMUX_FUNCTION_CLOCK", type = "generic", output = "source / (div_num + 1)", always_on = true, params = { @@ -45,7 +48,7 @@ system_clocks = { clock_tree = [ ] }, # TODO: model fractional divider parameters - # CPU_CLK divider (HP_SYS_CLKRST.root_clk_ctrl0.cpu_clk_div_num) + # CPU_CLK divider { name = "CPU_CLK", type = "generic", params = { divisor = "0..256" }, output = "CPU_ROOT_CLK / (divisor + 1)" }, # MEM_CLK divider { name = "MEM_CLK", type = "generic", params = { divisor = "0..256" }, output = "CPU_CLK / (divisor + 1)" }, @@ -61,11 +64,20 @@ system_clocks = { clock_tree = [ ] }, { name = "LP_SLOW_CLK", type = "mux", variants = [ { name = "RC_SLOW", outputs = "RC_SLOW_CLK" }, - { name = "XTAL32K", outputs = "XTAL32K_CLK" }, + { name = "XTAL32K", outputs = "XTAL32K_CLK", cfg = "use_xtal32k" }, #{ name = "RC32K", outputs = "RC32K_CLK" }, { name = "OSC_SLOW", outputs = "OSC_SLOW_CLK" }, ] }, + # Global peripheral-related clocks + # HP_SYS_CLKRST.peri_clk_ctrl25.crypto_clk_src_sel + { name = "CRYPTO_CLK", type = "mux", variants = [ + { name = "XTAL", outputs = "XTAL_CLK" }, + { name = "RC_FAST", outputs = "RC_FAST_CLK" }, + { name = "PLL_F240M", outputs = "PLL_F240M" }, + { name = "PLL_F160M", outputs = "PLL_F160M" }, + ] }, + # TIMG0-only? { name = "TIMG_CALIBRATION_CLOCK", type = "mux", wake_locking = true, variants = [ { name = "MPLL_CLK", outputs = "MPLL_CLK" }, @@ -77,7 +89,7 @@ system_clocks = { clock_tree = [ #{ name = "SDIO_PLL2_CLK", outputs = "SDIO_PLL2_CLK" }, { name = "RC_FAST_DIV_CLK", outputs = "RC_FAST_CLK" }, { name = "RC_SLOW_CLK", outputs = "LP_SLOW_CLK" }, - { name = "XTAL32K_CLK", outputs = "XTAL32K_CLK" }, + { name = "XTAL32K_CLK", outputs = "XTAL32K_CLK", cfg = "use_xtal32k" }, #{ name = "PLL_LP_CLK", outputs = "PLL_LP_CLK" }, ] }, ], template_groups = [ @@ -127,13 +139,39 @@ system_clocks = { clock_tree = [ ] }, { group = "SPI", clocks = [ { name = "FUNCTION_CLOCK", type = "mux", variants = [ - { name = "XTAL", outputs = "XTAL_CLK", default = true }, + { name = "XTAL", outputs = "XTAL_CLK" }, { name = "RC_FAST", outputs = "RC_FAST_CLK" }, # { name = "SDIO_PLL0", outputs = "SDIO_PLL0_CLK" }, # { name = "APLL", outputs = "APLL_CLK" }, - { name = "SPLL", outputs = "SPLL_CLK" }, + { name = "SPLL", outputs = "SPLL_D3_CLOCK", default = true }, ] }, ] }, + { group = "I2S", + presets = { + CLK = { + type = "generic", + wake_locking = true, + output = "(sclk * div_a) / (div_num * div_a + div_b)", + params = { + sclk = [ + { name = "XTAL", outputs = "XTAL_CLK" }, + { name = "PLL_F160M", outputs = "PLL_F160M", default = true }, + ], + div_num = "1 ..= 255", + div_a = "1 ..= 511", + div_b = "0 ..= 511", + }, + }, + }, + clocks = [ + { name = "TX_CLK", preset = "CLK" }, + { name = "RX_CLK", preset = "CLK" }, + { name = "MCLK_OUT", type = "mux", variants = [ + { name = "TX", outputs = "TX_CLK" }, + { name = "RX", outputs = "RX_CLK", default = true }, + ] }, + ], + }, # APLL (register value 1 on PHY_PLL_REFCLK) is intentionally omitted # because it is not yet modelled in the clock tree. { group = "MIPI_DSI", clocks = [ diff --git a/esp-metadata/devices/esp32p4/gpio.toml b/esp-metadata/devices/esp32p4/gpio.toml index cdc4fa032a6..abcff42636e 100644 --- a/esp-metadata/devices/esp32p4/gpio.toml +++ b/esp-metadata/devices/esp32p4/gpio.toml @@ -121,6 +121,22 @@ input_signals = [ { name = "I3C_SLV_SCL", id = 136 }, { name = "I3C_SLV_SDA", id = 137 }, { name = "USB_JTAG_TDO_BRIDGE", id = 140 }, + { name = "PCNT0_SIG_CH0", id = 141 }, + { name = "PCNT1_SIG_CH0", id = 142 }, + { name = "PCNT2_SIG_CH0", id = 143 }, + { name = "PCNT3_SIG_CH0", id = 144 }, + { name = "PCNT0_SIG_CH1", id = 145 }, + { name = "PCNT1_SIG_CH1", id = 146 }, + { name = "PCNT2_SIG_CH1", id = 147 }, + { name = "PCNT3_SIG_CH1", id = 148 }, + { name = "PCNT0_CTRL_CH0", id = 149 }, + { name = "PCNT1_CTRL_CH0", id = 150 }, + { name = "PCNT2_CTRL_CH0", id = 151 }, + { name = "PCNT3_CTRL_CH0", id = 152 }, + { name = "PCNT0_CTRL_CH1", id = 153 }, + { name = "PCNT1_CTRL_CH1", id = 154 }, + { name = "PCNT2_CTRL_CH1", id = 155 }, + { name = "PCNT3_CTRL_CH1", id = 156 }, { name = "CAM_PCLK", id = 158 }, { name = "CAM_H_ENABLE", id = 159 }, { name = "CAM_H_SYNC", id = 160 }, @@ -133,24 +149,24 @@ input_signals = [ { name = "EMAC_RXER", id = 183 }, { name = "EMAC_RX_CLK", id = 184 }, { name = "EMAC_TX_CLK", id = 185 }, - { name = "PARLIO_RX_CLK", id = 186 }, - { name = "PARLIO_TX_CLK", id = 187 }, - { name = "PARLIO_RX_DATA0", id = 188 }, - { name = "PARLIO_RX_DATA1", id = 189 }, - { name = "PARLIO_RX_DATA2", id = 190 }, - { name = "PARLIO_RX_DATA3", id = 191 }, - { name = "PARLIO_RX_DATA4", id = 192 }, - { name = "PARLIO_RX_DATA5", id = 193 }, - { name = "PARLIO_RX_DATA6", id = 194 }, - { name = "PARLIO_RX_DATA7", id = 195 }, - { name = "PARLIO_RX_DATA8", id = 196 }, - { name = "PARLIO_RX_DATA9", id = 197 }, - { name = "PARLIO_RX_DATA10", id = 198 }, - { name = "PARLIO_RX_DATA11", id = 199 }, - { name = "PARLIO_RX_DATA12", id = 200 }, - { name = "PARLIO_RX_DATA13", id = 201 }, - { name = "PARLIO_RX_DATA14", id = 202 }, - { name = "PARLIO_RX_DATA15", id = 203 }, + { name = "PARL_RX_CLK", id = 186 }, + { name = "PARL_TX_CLK", id = 187 }, + { name = "PARL_RX_DATA0", id = 188 }, + { name = "PARL_RX_DATA1", id = 189 }, + { name = "PARL_RX_DATA2", id = 190 }, + { name = "PARL_RX_DATA3", id = 191 }, + { name = "PARL_RX_DATA4", id = 192 }, + { name = "PARL_RX_DATA5", id = 193 }, + { name = "PARL_RX_DATA6", id = 194 }, + { name = "PARL_RX_DATA7", id = 195 }, + { name = "PARL_RX_DATA8", id = 196 }, + { name = "PARL_RX_DATA9", id = 197 }, + { name = "PARL_RX_DATA10", id = 198 }, + { name = "PARL_RX_DATA11", id = 199 }, + { name = "PARL_RX_DATA12", id = 200 }, + { name = "PARL_RX_DATA13", id = 201 }, + { name = "PARL_RX_DATA14", id = 202 }, + { name = "PARL_RX_DATA15", id = 203 }, # CPU GPIO: channels 0-7 belong to core 0, channels 8-15 to core 1 { name = "CPU_GPIO_0", id = 214 }, { name = "CPU_GPIO_1", id = 215 }, @@ -358,24 +374,24 @@ output_signals = [ { name = "EMAC_TXD2", id = 181 }, { name = "EMAC_TXD3", id = 182 }, { name = "EMAC_TXER", id = 183 }, - { name = "PARLIO_RX_CLK", id = 186 }, - { name = "PARLIO_TX_CLK", id = 187 }, - { name = "PARLIO_TX_DATA0", id = 188 }, - { name = "PARLIO_TX_DATA1", id = 189 }, - { name = "PARLIO_TX_DATA2", id = 190 }, - { name = "PARLIO_TX_DATA3", id = 191 }, - { name = "PARLIO_TX_DATA4", id = 192 }, - { name = "PARLIO_TX_DATA5", id = 193 }, - { name = "PARLIO_TX_DATA6", id = 194 }, - { name = "PARLIO_TX_DATA7", id = 195 }, - { name = "PARLIO_TX_DATA8", id = 196 }, - { name = "PARLIO_TX_DATA9", id = 197 }, - { name = "PARLIO_TX_DATA10", id = 198 }, - { name = "PARLIO_TX_DATA11", id = 199 }, - { name = "PARLIO_TX_DATA12", id = 200 }, - { name = "PARLIO_TX_DATA13", id = 201 }, - { name = "PARLIO_TX_DATA14", id = 202 }, - { name = "PARLIO_TX_DATA15", id = 203 }, + { name = "PARL_RX_CLK", id = 186 }, + { name = "PARL_TX_CLK", id = 187 }, + { name = "PARL_TX_DATA0", id = 188 }, + { name = "PARL_TX_DATA1", id = 189 }, + { name = "PARL_TX_DATA2", id = 190 }, + { name = "PARL_TX_DATA3", id = 191 }, + { name = "PARL_TX_DATA4", id = 192 }, + { name = "PARL_TX_DATA5", id = 193 }, + { name = "PARL_TX_DATA6", id = 194 }, + { name = "PARL_TX_DATA7", id = 195 }, + { name = "PARL_TX_DATA8", id = 196 }, + { name = "PARL_TX_DATA9", id = 197 }, + { name = "PARL_TX_DATA10", id = 198 }, + { name = "PARL_TX_DATA11", id = 199 }, + { name = "PARL_TX_DATA12", id = 200 }, + { name = "PARL_TX_DATA13", id = 201 }, + { name = "PARL_TX_DATA14", id = 202 }, + { name = "PARL_TX_DATA15", id = 203 }, { name = "CONSTANT0", id = 212 }, { name = "CONSTANT1", id = 213 }, # CPU GPIO: channels 0-7 belong to core 0, channels 8-15 to core 1 @@ -395,7 +411,7 @@ output_signals = [ { name = "CPU_GPIO_13", id = 227 }, { name = "CPU_GPIO_14", id = 228 }, { name = "CPU_GPIO_15", id = 229 }, - { name = "PARLIO_TX_CS", id = 242 }, + { name = "PARL_TX_CS", id = 242 }, { name = "EMAC_PTP_PPS", id = 243 }, { name = "ANA_COMP0", id = 244 }, { name = "ANA_COMP1", id = 245 }, diff --git a/esp-metadata/devices/esp32p4/soc.toml b/esp-metadata/devices/esp32p4/soc.toml index 0343772bb47..c80d19eea46 100644 --- a/esp-metadata/devices/esp32p4/soc.toml +++ b/esp-metadata/devices/esp32p4/soc.toml @@ -16,7 +16,10 @@ support_note = "Revisions below v3.0 are not supported." [device.mmu] page_size = 0x10000 -entry_num = 512 +entry_num = 1024 + +[device.flash] +support_status = "partial" [device.rom] has_crc_le = true @@ -28,23 +31,22 @@ support_status = "partial" status_registers = 5 software_interrupt_count = 4 controller = { Riscv = { flavour = "clic", interrupts = 48, priority_levels = 8 } } +context_switch_source = "ipc" [device.soc] cpu_has_branch_predictor = true multi_core_enabled = true cpu_has_csr_pc = false +cpu_has_zcmp_workaround = true cpu_mcause_mask = 0x3f +cpu_pmp_granularity = 128 internal_memory_cached = true has_swd_watchdog = true -# HP L2MEM: 0x4FF0_0000 - 0x4FFC_0000 (768 KB) -# ROM bootloader reserves 0x4FF0_0000 - 0x4FF4_0000 (256 KB) -# dram: usable application RAM (after ROM reserved region) -# dram2_uninit: ROM reserved area, reclaimable after 2nd-stage bootloader memory_map = { ranges = [ - { name = "dram", start = 0x4FF4_0000, end = 0x4FFC_0000 }, - { name = "dram2_uninit", start = 0x4FF0_0000, end = 0x4FF4_0000 }, + { name = "dram", start = 0x4FF4_0000, end = 0x4FFA_DFC0 }, + { name = "dram2_uninit", start = 0x4FFA_DFC0, end = 0x4FFB_EFC0 }, { name = "irom", start = 0x4000_0000, end = 0x4400_0000 }, { name = "drom", start = 0x4000_0000, end = 0x4400_0000 }, ] } @@ -57,11 +59,14 @@ peripherals = [ { name = "SYSTEM", pac = "HP_SYS" }, { name = "HP_SYS" }, { name = "HP_SYS_CLKRST" }, - { name = "RNG", pac = "LP_SYS" }, + { name = "RNG", pac = "LP_TRNG" }, { name = "INTERRUPT_CORE0" }, { name = "INTERRUPT_CORE1" }, { name = "LP_I2C_ANA_MST" }, + { name = "CACHE", hidden = true }, { name = "CLIC" }, + { name = "CLINT" }, + { name = "CLINT_OTHER_CORE" }, { name = "IO_MUX" }, { name = "IOMUX_MSPI_PIN", hidden = true }, { name = "LP_I2C0" }, @@ -75,6 +80,7 @@ peripherals = [ { name = "LP_WDT" }, { name = "LPWR", pac = "LP_SYS" }, { name = "PMU" }, + { name = "PAU" }, { name = "SYSTIMER" }, { name = "TIMG0", clock_group = "TIMG" }, { name = "TIMG1", clock_group = "TIMG" }, @@ -92,9 +98,9 @@ peripherals = [ { name = "SPI3", interrupts = { peri = "SPI3" }, stable = true, clock_group = "SPI" }, { name = "I2C0", interrupts = { peri = "I2C0" }, stable = true, clock_group = "I2C" }, { name = "I2C1", interrupts = { peri = "I2C1" }, stable = true, clock_group = "I2C" }, - { name = "I2S0", interrupts = { peri = "I2S0" } }, - { name = "I2S1", interrupts = { peri = "I2S1" } }, - { name = "I2S2", interrupts = { peri = "I2S2" } }, + { name = "I2S0", interrupts = { peri = "I2S0" }, clock_group = "I2S" }, + { name = "I2S1", interrupts = { peri = "I2S1" }, clock_group = "I2S" }, + { name = "I2S2", interrupts = { peri = "I2S2" }, clock_group = "I2S" }, { name = "TWAI0", interrupts = { peri = "TWAI0" } }, { name = "TWAI1", interrupts = { peri = "TWAI1" } }, { name = "TWAI2", interrupts = { peri = "TWAI2" } }, @@ -103,9 +109,9 @@ peripherals = [ { name = "DMA", pac = "AHB_DMA" }, { name = "AXI_GDMA", pac = "AXI_DMA" }, - { name = "ETH", virtual = true }, - { name = "EMAC_DMA", hidden = true }, - { name = "EMAC_MAC", hidden = true }, + { name = "ETH", virtual = true, interrupts = { peri = "ETH_MAC" } }, + { name = "EMAC_DMA", pac = "GMAC_DMA", hidden = true }, + { name = "EMAC_MAC", pac = "GMAC", hidden = true }, { name = "MIPI_DSI", virtual = true, interrupts = { dsi = "DSI", bridge = "DSI_BRIDGE" }, clock_group = "MIPI_DSI" }, { name = "VDMA", pac = "DMA", hidden = true }, { name = "MIPI_DSI_HOST", hidden = true }, @@ -118,7 +124,7 @@ peripherals = [ { name = "PCNT", interrupts = { peri = "PCNT" } }, { name = "APB_SARADC", pac = "ADC" }, { name = "LP_ADC" }, - { name = "RMT", virtual = true, interrupts = { peri = "RMT" }, clock_group = "RMT" }, # PAC field names differ from ESP32-S3; overlay_rmt maps them. + { name = "RMT", interrupts = { peri = "RMT" }, clock_group = "RMT" }, { name = "AES", interrupts = { peri = "AES" } }, { name = "SHA", interrupts = { peri = "SHA" } }, { name = "RSA", interrupts = { peri = "RSA" } }, @@ -133,6 +139,7 @@ peripherals = [ { name = "PSRAM", virtual = true, clock_group = "PSRAM" }, { name = "GPIO_DEDICATED", virtual = true }, { name = "CPU_CTRL", virtual = true }, + { name = "IPC", virtual = true }, { name = "FROM_CPU_INTR0", virtual = true }, { name = "FROM_CPU_INTR1", virtual = true }, { name = "FROM_CPU_INTR2", virtual = true }, @@ -167,6 +174,7 @@ instances = [ ] timg_has_timer1 = true timg_has_divcnt_rst = true +wdt_has_conf_update = true [device.spi_master] support_status = "supported" @@ -269,6 +277,11 @@ support_status = "not_supported" [device.adc] support_status = "partial" +line_calibration = true +curve_calibration = true +basic_calibration = true +calibration_v1_scheme_supported = true +channel_compensation = true instances = [ { name = "adc1" }, { name = "adc2" }, @@ -290,6 +303,10 @@ support_status = "not_supported" [device.ethernet] support_status = "partial" mii_via_gpio_matrix = true +dma_burst_len = 32 +rx_store_and_forward = false # RX FIFO is only 256B, too small for a full frame +rx_checksum_offload = true +tx_checksum_offload = false # TX FIFO is too small for store-and-forward insertion [device.mipi_csi] support_status = "not_supported" @@ -307,9 +324,8 @@ support_status = "not_supported" [device.i2s] support_status = "partial" version = 3 -default_clock_source = 3 clock_configured_by_hp_sys_clkrst = true -mclk_divider_bit_width = 6 +mclk_divider_bit_width = 9 max_ws_width = 128 supports_pdm_rx_hp_filter = true instances = [ @@ -375,9 +391,22 @@ ram_size = 32 # placeholder; LP UART RAM size on P4 needs verification [device.mcpwm] support_status = "not_supported" # 2 instances (MCPWM0/1) [device.pcnt] -support_status = "not_supported" +support_status = "partial" +instances = { + PCNT = { + sys_instance = "Pcnt", + interrupt = "PCNT", + units = [ + { sig_ch0 = "PCNT0_SIG_CH0", sig_ch1 = "PCNT0_SIG_CH1", ctrl_ch0 = "PCNT0_CTRL_CH0", ctrl_ch1 = "PCNT0_CTRL_CH1" }, + { sig_ch0 = "PCNT1_SIG_CH0", sig_ch1 = "PCNT1_SIG_CH1", ctrl_ch0 = "PCNT1_CTRL_CH0", ctrl_ch1 = "PCNT1_CTRL_CH1" }, + { sig_ch0 = "PCNT2_SIG_CH0", sig_ch1 = "PCNT2_SIG_CH1", ctrl_ch0 = "PCNT2_CTRL_CH0", ctrl_ch1 = "PCNT2_CTRL_CH1" }, + { sig_ch0 = "PCNT3_SIG_CH0", sig_ch1 = "PCNT3_SIG_CH1", ctrl_ch0 = "PCNT3_CTRL_CH0", ctrl_ch1 = "PCNT3_CTRL_CH1" }, + ], + }, +} [device.rgb_display] -support_status = "not_supported" # LCD path of LCD_CAM block +support_status = "not_supported" +output_lines = 24 [device.rmt] support_status = "partial" @@ -394,13 +423,14 @@ has_rx_demodulation = true [device.parl_io] support_status = "not_supported" -version = 1 # FIXME placeholder +version = 2 +max_data_width = 16 +has_tx_cs = true [device.rng] support_status = { status = "partial", issue = 5982 } -trng_supported = false # TODO -apb_cycle_wait_num = 16 # placeholder -is_lp_sys = true +trng_supported = true +apb_cycle_wait_num = 16 # TODO [device.lp_timer] support_status = "partial" @@ -464,6 +494,11 @@ wakeup_sources = { Timer = 13, } +[device.sleep.retention] +cpu_retention = "software" +cpu_retention_frame = "p4" +supports_top_power_down = true + [device.spi_slave] support_status = "partial" instances = [ @@ -560,9 +595,9 @@ working_modes = [ { id = 11, mode = "modular_division" } ] curves = [ - { id = 0, curve = 192 }, - { id = 1, curve = 256 }, - { id = 2, curve = 384 }, + { id = 0, curve = "p192" }, + { id = 1, curve = "p256" }, + { id = 2, curve = "p384" }, ] separate_jacobian_point_memory = true has_memory_clock_gate = true diff --git a/esp-metadata/devices/esp32s2/clocks.toml b/esp-metadata/devices/esp32s2/clocks.toml index c70a25f825f..75671d67bc2 100644 --- a/esp-metadata/devices/esp32s2/clocks.toml +++ b/esp-metadata/devices/esp32s2/clocks.toml @@ -2,7 +2,8 @@ system_clocks = { clock_tree = [ { name = "XTAL_CLK", type = "source", values = "40", output = "VALUE * 1_000_000", always_on = true }, { name = "PLL_CLK", type = "derived", from = "XTAL_CLK", values = "320, 480", output = "VALUE * 1_000_000" }, # TODO reject = "VALUE == 320_000_000 && CPU_PLL_DIV_OUT == 240_000_000" { name = "APLL_CLK", type = "derived", from = "PLL_CLK", values = "16_000_000 ..= 128_000_000", output = "VALUE" }, - { name = "RC_FAST_CLK", type = "source", output = "8_000_000" }, # this is supposed to be adjustable using RTC_CNTL_CK8M_DIV_SEL + { name = "PLL_F160M_CLK", type = "derived", from = "PLL_CLK", output = "160_000_000" }, + { name = "RC_FAST_CLK", type = "source", output = "8_000_000", adjustable = "4_000_000..=12_000_000" }, # this is supposed to be adjustable using RTC_CNTL_CK8M_DIV_SEL # Represents SEL0 = 1, 3 { name = "CPU_PLL_DIV_IN", type = "mux", variants = [ @@ -48,13 +49,13 @@ system_clocks = { clock_tree = [ ] }, # Low-speed clocks - { name = "XTAL32K_CLK", type = "source", output = "32768" }, - { name = "RC_SLOW_CLK", type = "source", output = "90_000" }, + { name = "XTAL32K_CLK", type = "source", output = "32768", cfg = "use_xtal32k" }, + { name = "RC_SLOW_CLK", type = "source", output = "90_000", adjustable = "45_000..=135_000" }, { name = "RC_FAST_DIV_CLK", type = "generic", output = "RC_FAST_CLK / 256" }, { name = "XTAL_DIV_CLK", type = "generic", output = "XTAL_CLK / 4" }, # source: esp-idf SOC_RTC_FAST_CLK_SRC_XTAL_D4 { name = "RTC_SLOW_CLK", type = "mux", variants = [ - { name = "XTAL32K", outputs = "XTAL32K_CLK" }, + { name = "XTAL32K", outputs = "XTAL32K_CLK", cfg = "use_xtal32k" }, { name = "RC_SLOW", outputs = "RC_SLOW_CLK" }, { name = "RC_FAST", outputs = "RC_FAST_DIV_CLK" }, ] }, @@ -74,7 +75,7 @@ system_clocks = { clock_tree = [ { name = "TIMG_CALIBRATION_CLOCK", type = "mux", wake_locking = true, variants = [ { name = "RTC_CLK", outputs = "RTC_SLOW_CLK" }, { name = "RC_FAST_DIV_CLK", outputs = "RC_FAST_DIV_CLK" }, - { name = "XTAL32K_CLK", outputs = "XTAL32K_CLK" }, + { name = "XTAL32K_CLK", outputs = "XTAL32K_CLK", cfg = "use_xtal32k" }, ] }, ], template_groups = [ { group = "TIMG", clocks = [ @@ -111,6 +112,12 @@ system_clocks = { clock_tree = [ { name = "APB", outputs = "APB_CLK", default = true }, ] }, ] }, + { group = "I2S", clocks = [ + { name = "MCLK", type = "generic", wake_locking = true, output = "(sclk * div_a) / (div_num * div_a + div_b)", params = { sclk = [ + { name = "PLL_F160M", outputs = "PLL_F160M_CLK", default = true }, + { name = "APLL", outputs = "APLL_CLK" }, + ], div_num = "1 ..= 255", div_a = "1 ..= 63", div_b = "0 ..= 63" } }, + ] }, ] } peripheral_clocks = { templates = [ diff --git a/esp-metadata/devices/esp32s2/soc.toml b/esp-metadata/devices/esp32s2/soc.toml index 4c20284329f..5b33054f88a 100644 --- a/esp-metadata/devices/esp32s2/soc.toml +++ b/esp-metadata/devices/esp32s2/soc.toml @@ -17,6 +17,9 @@ trm = "https://www.espressif.com/sites/default/files/documentation/esp32-s2_t page_size = 0x10000 entry_num = 256 +[device.flash] +support_status = "partial" + [device.rom] has_crc_le = true has_md5_bsd = true @@ -45,12 +48,12 @@ peripherals = [ { name = "I2C_ANA_MST" }, { name = "I2C0", interrupts = { peri = "I2C_EXT0" }, stable = true, clock_group = "I2C" }, { name = "I2C1", interrupts = { peri = "I2C_EXT1" }, stable = true, clock_group = "I2C" }, - { name = "I2S0", interrupts = { peri = "I2S0" } }, + { name = "I2S0", interrupts = { peri = "I2S0" }, clock_group = "I2S" }, { name = "INTERRUPT_CORE0" }, { name = "IO_MUX" }, { name = "LEDC" }, { name = "NRX" }, - { name = "PCNT" }, + { name = "PCNT", interrupts = { peri = "PCNT" } }, { name = "PMS" }, { name = "RMT", clock_group = "RMT" }, { name = "RNG" }, @@ -98,6 +101,10 @@ peripherals = [ [device.adc] support_status = "partial" +controller = "rtc" +line_calibration = true +basic_calibration = true +calibration_v1_scheme_supported = true instances = [ { name = "adc1" }, { name = "adc2" }, @@ -211,6 +218,7 @@ support_status = "partial" status_registers = 3 software_interrupt_count = 4 controller = "Xtensa" +context_switch_source = "software0" [device.rmt] support_status = "partial" @@ -303,6 +311,7 @@ support_status = "not_supported" [device.rgb_display] # via I2S support_status = "not_supported" +output_lines = 24 [device.spi_lcd] # the LCD mode of GP-SPI2 support_status = { status = "not_supported", issue = 5374 } @@ -361,7 +370,6 @@ wakeup_sources = { ## Interfaces [device.i2s] version = 1 -default_clock_source = 2 mclk_divider_bit_width = 6 max_ws_width = 128 instances = [ @@ -382,6 +390,18 @@ instances = [ version = 2 channel_count = 8 [device.pcnt] +instances = { + PCNT = { + sys_instance = "Pcnt", + interrupt = "PCNT", + units = [ + { sig_ch0 = "PCNT0_SIG_CH0", sig_ch1 = "PCNT0_SIG_CH1", ctrl_ch0 = "PCNT0_CTRL_CH0", ctrl_ch1 = "PCNT0_CTRL_CH1" }, + { sig_ch0 = "PCNT1_SIG_CH0", sig_ch1 = "PCNT1_SIG_CH1", ctrl_ch0 = "PCNT1_CTRL_CH0", ctrl_ch1 = "PCNT1_CTRL_CH1" }, + { sig_ch0 = "PCNT2_SIG_CH0", sig_ch1 = "PCNT2_SIG_CH1", ctrl_ch0 = "PCNT2_CTRL_CH0", ctrl_ch1 = "PCNT2_CTRL_CH1" }, + { sig_ch0 = "PCNT3_SIG_CH0", sig_ch1 = "PCNT3_SIG_CH1", ctrl_ch0 = "PCNT3_CTRL_CH0", ctrl_ch1 = "PCNT3_CTRL_CH1" }, + ], + }, +} [device.twai] [device.usb_otg] fifo_depth_words = 256 @@ -394,6 +414,7 @@ extmem_origin = 0x3f500000 [device.systimer] [device.temp_sensor] +support_status = "not_supported" [device.ulp_fsm] support_status = { status = "not_supported", issue = 376 } [device.ulp_riscv] @@ -403,5 +424,7 @@ support_status = { status = "not_supported", issue = 376 } [device.wifi] mac_version = 1 csi_supported = true +has_nan = true +has_ftm = true [device.phy] diff --git a/esp-metadata/devices/esp32s3/clocks.toml b/esp-metadata/devices/esp32s3/clocks.toml index ec03acd5032..06d9106567a 100644 --- a/esp-metadata/devices/esp32s3/clocks.toml +++ b/esp-metadata/devices/esp32s3/clocks.toml @@ -2,11 +2,11 @@ system_clocks = { clock_tree = [ # High-speed clock sources { name = "XTAL_CLK", type = "source", values = "40", output = "VALUE * 1_000_000", always_on = true }, { name = "PLL_CLK", type = "derived", from = "XTAL_CLK", values = "320, 480", output = "VALUE * 1_000_000", reject = "VALUE == 320_000_000 && CPU_PLL_DIV_OUT == 240_000_000" }, - { name = "RC_FAST_CLK", type = "source", output = "17_500_000" }, + { name = "RC_FAST_CLK", type = "source", output = "17_500_000", adjustable = "8_750_000..=26_250_000" }, # Low-speed clocks - { name = "XTAL32K_CLK", type = "source", output = "32768" }, - { name = "RC_SLOW_CLK", type = "source", output = "136_000" }, + { name = "XTAL32K_CLK", type = "source", output = "32768", cfg = "use_xtal32k" }, + { name = "RC_SLOW_CLK", type = "source", output = "136_000", adjustable = "68_000..=204_000" }, { name = "RC_FAST_DIV_CLK", type = "generic", output = "RC_FAST_CLK / 256" }, # CPU clock source dividers @@ -44,10 +44,16 @@ system_clocks = { clock_tree = [ { name = "RC_FAST_CLK_DIV_N", type = "generic", params = { divisor = "0 ..= 3" }, output = "RC_FAST_CLK / (divisor + 1)" }, { name = "XTAL_DIV_CLK", type = "generic", output = "XTAL_CLK / 2" }, { name = "RTC_SLOW_CLK", type = "mux", variants = [ - { name = "XTAL32K", outputs = "XTAL32K_CLK" }, + { name = "XTAL32K", outputs = "XTAL32K_CLK", cfg = "use_xtal32k" }, { name = "RC_SLOW", outputs = "RC_SLOW_CLK" }, { name = "RC_FAST", outputs = "RC_FAST_DIV_CLK" }, ] }, + # BLE modem-sleep clock. The BTDM blob programs the source and divider. + { name = "BLE_LP_XTAL_CLK", type = "derived", from = "XTAL_CLK", output = "1_000_000" }, + { name = "BLE_LP_CLK", type = "mux", variants = [ + { name = "XTAL", outputs = "BLE_LP_XTAL_CLK" }, + { name = "RTC_SLOW", outputs = "RTC_SLOW_CLK" }, + ] }, { name = "RTC_FAST_CLK", type = "mux", variants = [ { name = "XTAL", outputs = "XTAL_DIV_CLK" }, { name = "RC", outputs = "RC_FAST_CLK_DIV_N" }, @@ -57,7 +63,7 @@ system_clocks = { clock_tree = [ { name = "LOW_POWER_CLK", type = "mux", variants = [ { name = "XTAL", outputs = "XTAL_CLK" }, { name = "RC_FAST", outputs = "RC_FAST_CLK" }, - { name = "XTAL32K", outputs = "XTAL32K_CLK" }, + { name = "XTAL32K", outputs = "XTAL32K_CLK", cfg = "use_xtal32k" }, { name = "RTC_SLOW", outputs = "RTC_SLOW_CLK" }, ] }, @@ -72,7 +78,7 @@ system_clocks = { clock_tree = [ { name = "TIMG_CALIBRATION_CLOCK", type = "mux", wake_locking = true, variants = [ { name = "RC_SLOW_CLK", outputs = "RC_SLOW_CLK" }, { name = "RC_FAST_DIV_CLK", outputs = "RC_FAST_DIV_CLK" }, - { name = "XTAL32K_CLK", outputs = "XTAL32K_CLK" }, + { name = "XTAL32K_CLK", outputs = "XTAL32K_CLK", cfg = "use_xtal32k" }, ] }, ], template_groups = [ { group = "MCPWM", clocks = [ @@ -129,10 +135,37 @@ system_clocks = { clock_tree = [ ] }, { group = "SPI", clocks = [ { name = "FUNCTION_CLOCK", type = "mux", wake_locking = true, variants = [ - { name = "XTAL", outputs = "XTAL_CLK", default = true }, - { name = "APB", outputs = "APB_CLK" }, # PLL_F80M? + { name = "XTAL", outputs = "XTAL_CLK" }, + { name = "APB", outputs = "APB_CLK", default = true }, # PLL_F80M? ] }, ] }, + { group = "I2S", + presets = { + CLK = { + type = "generic", + wake_locking = true, + output = "(sclk * div_a) / (div_num * div_a + div_b)", + params = { + sclk = [ + { name = "XTAL", outputs = "XTAL_CLK" }, + { name = "PLL_D2", outputs = "PLL_D2" }, + { name = "PLL_160M", outputs = "PLL_160M", default = true }, + ], + div_num = "1 ..= 255", + div_a = "1 ..= 511", + div_b = "0 ..= 511", + }, + }, + }, + clocks = [ + { name = "TX_CLK", preset = "CLK" }, + { name = "RX_CLK", preset = "CLK" }, + { name = "MCLK_OUT", type = "mux", variants = [ + { name = "TX", outputs = "TX_CLK" }, + { name = "RX", outputs = "RX_CLK", default = true }, + ] }, + ], + }, ] } peripheral_clocks = { templates = [ diff --git a/esp-metadata/devices/esp32s3/soc.toml b/esp-metadata/devices/esp32s3/soc.toml index e57d23f708e..543216b9b8f 100644 --- a/esp-metadata/devices/esp32s3/soc.toml +++ b/esp-metadata/devices/esp32s3/soc.toml @@ -17,6 +17,9 @@ trm = "https://www.espressif.com/sites/default/files/documentation/esp32-s3_t page_size = 0x10000 entry_num = 384 +[device.flash] +support_status = "partial" + [device.rom] has_crc_le = true has_crc_be = true @@ -49,8 +52,8 @@ peripherals = [ { name = "I2C_ANA_MST" }, { name = "I2C0", interrupts = { peri = "I2C_EXT0" }, stable = true, clock_group = "I2C" }, { name = "I2C1", interrupts = { peri = "I2C_EXT1" }, stable = true, clock_group = "I2C" }, - { name = "I2S0", interrupts = { peri = "I2S0" } }, - { name = "I2S1", interrupts = { peri = "I2S1" } }, + { name = "I2S0", interrupts = { peri = "I2S0" }, clock_group = "I2S" }, + { name = "I2S1", interrupts = { peri = "I2S1" }, clock_group = "I2S" }, { name = "INTERRUPT_CORE0" }, { name = "INTERRUPT_CORE1" }, { name = "IO_MUX" }, @@ -60,7 +63,7 @@ peripherals = [ { name = "RTC_TIMER", pac = "RTC_CNTL" }, { name = "MCPWM0", clock_group = "MCPWM" }, { name = "MCPWM1", clock_group = "MCPWM" }, - { name = "PCNT" }, + { name = "PCNT", interrupts = { peri = "PCNT" } }, { name = "PERI_BACKUP" }, { name = "RMT", clock_group = "RMT" }, { name = "RNG" }, @@ -100,8 +103,9 @@ peripherals = [ { name = "PSRAM", virtual = true }, { name = "ULP_RISCV_CORE", virtual = true }, { name = "WIFI", virtual = true, interrupts = { mac = "WIFI_MAC", pwr = "WIFI_PWR" }, stable = true }, - { name = "FROM_CPU_INTR0", virtual = true }, - { name = "FROM_CPU_INTR1", virtual = true }, + { name = "IPC", virtual = true }, + { name = "FROM_CPU_INTR0", virtual = true, hidden = true }, + { name = "FROM_CPU_INTR1", virtual = true, hidden = true }, { name = "FROM_CPU_INTR2", virtual = true }, { name = "FROM_CPU_INTR3", virtual = true }, ] @@ -111,6 +115,11 @@ peripherals = [ [device.adc] support_status = "partial" +controller = "rtc" +line_calibration = true +curve_calibration = true +basic_calibration = true +calibration_v1_scheme_supported = true instances = [ { name = "adc1" }, { name = "adc2" }, @@ -210,6 +219,7 @@ support_status = "partial" status_registers = 4 software_interrupt_count = 4 controller = "Xtensa" +context_switch_source = "software0" [device.rmt] support_status = "partial" @@ -360,6 +370,14 @@ wakeup_sources = { UlpRiscvTrap = 13 } +[device.sleep.retention] +cpu_retention = "rtc_cntl" +supports_tagmem_power_down = true +cpu_retention_mem_size = 8800 +cpu_retention_mem_align = 16 +cpu_retention_mem_start = 0x3FC88000 +cpu_retention_mem_end = 0x3FCF0000 + # Other drivers which are partially supported but have no other configuration: ## Crypto @@ -368,8 +386,7 @@ wakeup_sources = { ## Interfaces [device.i2s] version = 2 -default_clock_source = 2 -mclk_divider_bit_width = 6 +mclk_divider_bit_width = 9 max_ws_width = 128 instances = [ { @@ -404,11 +421,25 @@ instances = [ [device.camera] [device.rgb_display] +output_lines = 16 + [device.ledc] version = 2 channel_count = 8 [device.mcpwm] [device.pcnt] +instances = { + PCNT = { + sys_instance = "Pcnt", + interrupt = "PCNT", + units = [ + { sig_ch0 = "PCNT0_SIG_CH0", sig_ch1 = "PCNT0_SIG_CH1", ctrl_ch0 = "PCNT0_CTRL_CH0", ctrl_ch1 = "PCNT0_CTRL_CH1" }, + { sig_ch0 = "PCNT1_SIG_CH0", sig_ch1 = "PCNT1_SIG_CH1", ctrl_ch0 = "PCNT1_CTRL_CH0", ctrl_ch1 = "PCNT1_CTRL_CH1" }, + { sig_ch0 = "PCNT2_SIG_CH0", sig_ch1 = "PCNT2_SIG_CH1", ctrl_ch0 = "PCNT2_CTRL_CH0", ctrl_ch1 = "PCNT2_CTRL_CH1" }, + { sig_ch0 = "PCNT3_SIG_CH0", sig_ch1 = "PCNT3_SIG_CH1", ctrl_ch0 = "PCNT3_CTRL_CH0", ctrl_ch1 = "PCNT3_CTRL_CH1" }, + ], + }, +} [device.sdmmc] support_status = "partial" @@ -461,6 +492,7 @@ octal_spi = true [device.systimer] [device.temp_sensor] +support_status = "not_supported" [device.ulp_fsm] support_status = { status = "not_supported", issue = 376 } [device.ulp_riscv] @@ -470,6 +502,7 @@ support_status = { status = "not_supported", issue = 376 } [device.wifi] mac_version = 1 csi_supported = true +has_ftm = true [device.bt] support_status = "partial" diff --git a/esp-metadata/devices/esp32s31/clocks.toml b/esp-metadata/devices/esp32s31/clocks.toml index 0d9d8d843ee..e8a6f4db3d6 100644 --- a/esp-metadata/devices/esp32s31/clocks.toml +++ b/esp-metadata/devices/esp32s31/clocks.toml @@ -3,12 +3,12 @@ system_clocks = { clock_tree = [ { name = "XTAL_CLK", type = "source", output = "40_000_000", always_on = true }, { name = "BBPLL_CLK", type = "derived", from = "XTAL_CLK", output = "480 * 1_000_000" }, { name = "CPLL_CLK", type = "derived", from = "XTAL_CLK", output = "320 * 1_000_000" }, - { name = "MPLL_CLK", type = "derived", from = "XTAL_CLK", output = "500 * 1_000_000" }, - { name = "RC_FAST_CLK", type = "source", output = "17_500_000" }, + { name = "MPLL_CLK", type = "derived", from = "XTAL_CLK", values = "400, 500", output = "VALUE * 1_000_000" }, + { name = "RC_FAST_CLK", type = "source", output = "17_500_000", adjustable = "8_750_000..=26_250_000" }, # Low-speed clocks - { name = "XTAL32K_CLK", type = "source", output = "32768" }, - { name = "RC_SLOW_CLK", type = "source", output = "136_000" }, + { name = "XTAL32K_CLK", type = "source", output = "32768", cfg = "use_xtal32k" }, + { name = "RC_SLOW_CLK", type = "source", output = "136_000", adjustable = "68_000..=204_000" }, # BBPLL divider taps (480MHz / N) { name = "PLL_F20M", type = "generic", output = "BBPLL_CLK / 24" }, @@ -17,8 +17,12 @@ system_clocks = { clock_tree = [ { name = "PLL_F160M", type = "generic", output = "BBPLL_CLK / 3" }, { name = "PLL_F240M", type = "generic", output = "BBPLL_CLK / 2" }, - { name = "PLL_F25M", type = "generic", output = "MPLL_CLK / 20" }, - { name = "PLL_F50M", type = "generic", output = "MPLL_CLK / 10" }, + # Virtual clock node for peripherals that can be sourced from BBPLL but have a 160MHz max constraint. + { name = "BBPLL_D3_CLOCK", type = "generic", output = "BBPLL_CLK / 3" }, + + # Their dividers follow the MPLL rate, see enable_mpll_clk_impl. + { name = "PLL_F25M", type = "derived", from = "MPLL_CLK", output = "25_000_000" }, + { name = "PLL_F50M", type = "derived", from = "MPLL_CLK", output = "50_000_000" }, # XTAL half { name = "XTAL_D2_CLK", type = "generic", output = "XTAL_CLK / 2" }, @@ -32,9 +36,12 @@ system_clocks = { clock_tree = [ ] }, { name = "CPU_CLK", type = "generic", params = { divisor = "0..256" }, output = "CPU_ROOT_CLK / (divisor + 1)" }, - { name = "AHB_CLK", type = "generic", params = { divisor = "0..256" }, output = "CPU_CLK / (divisor + 1)" }, + # MEM_CLK divider + { name = "MEM_CLK", type = "generic", params = { divisor = "0..2" }, output = "CPU_CLK / (divisor + 1)" }, + # SYS_CLK divider + { name = "SYS_CLK", type = "generic", params = { divisor = "0..256" }, output = "CPU_CLK / (divisor + 1)" }, # APB is a core system bus and must not be released with a peripheral clock. - { name = "APB_CLK", type = "generic", params = { divisor = "0..256" }, output = "AHB_CLK / (divisor + 1)", always_on = true }, + { name = "APB_CLK", type = "generic", params = { divisor = "0..256" }, output = "SYS_CLK / (divisor + 1)", always_on = true }, # LP clocks { name = "LP_FAST_CLK", type = "mux", variants = [ @@ -43,7 +50,21 @@ system_clocks = { clock_tree = [ ] }, { name = "LP_SLOW_CLK", type = "mux", variants = [ { name = "RC_SLOW", outputs = "RC_SLOW_CLK" }, - { name = "XTAL32K", outputs = "XTAL32K_CLK" }, + { name = "XTAL32K", outputs = "XTAL32K_CLK", cfg = "use_xtal32k" }, + ] }, + # BLE RTC timer (MODEM_LPCON). Independent of LP_SLOW_CLK. + { name = "BLE_LP_XTAL_CLK", type = "derived", from = "XTAL_CLK", output = "100_000" }, + { name = "BLE_LP_CLK", type = "mux", variants = [ + { name = "XTAL", outputs = "BLE_LP_XTAL_CLK" }, + { name = "XTAL32K", outputs = "XTAL32K_CLK", cfg = "use_xtal32k" }, + ] }, + + # Global peripheral-related clocks + # HP_SYS_CLKRST.crypto_ctrl0.crypto_clk_src_sel + { name = "CRYPTO_CLK", type = "mux", variants = [ + { name = "XTAL", outputs = "XTAL_CLK" }, + { name = "RC_FAST", outputs = "RC_FAST_CLK" }, + { name = "PLL_F240M", outputs = "PLL_F240M" }, ] }, { @@ -59,7 +80,7 @@ system_clocks = { clock_tree = [ { name = "TIMG_CALIBRATION_CLOCK", type = "mux", wake_locking = true, variants = [ { name = "RC_SLOW_CLK", outputs = "RC_SLOW_CLK" }, { name = "RC_FAST_DIV_CLK", outputs = "RC_FAST_CLK" }, - { name = "XTAL32K_CLK", outputs = "XTAL32K_CLK" }, + { name = "XTAL32K_CLK", outputs = "XTAL32K_CLK", cfg = "use_xtal32k" }, ] }, ], template_groups = [ { group = "PSRAM", clocks = [ @@ -92,9 +113,8 @@ system_clocks = { clock_tree = [ ] }, { group = "SPI", clocks = [ { name = "FUNCTION_CLOCK", type = "mux", variants = [ - { name = "BBPLL", outputs = "BBPLL_CLK" }, - # the TRM/HW default is BBPLL - but won't achieve < ~500KHz SCLK - { name = "XTAL", outputs = "XTAL_CLK", default = true }, + { name = "BBPLL", outputs = "BBPLL_D3_CLOCK", default = true }, + { name = "XTAL", outputs = "XTAL_CLK" }, { name = "RC_FAST", outputs = "RC_FAST_CLK" }, ] }, ] }, @@ -104,6 +124,34 @@ system_clocks = { clock_tree = [ { name = "RC_FAST", outputs = "RC_FAST_CLK" }, ], div_num = "0 .. 0x100" } }, ] }, + # APLL (register value 1) is intentionally omitted because it is not yet modelled in the + # clock tree. + { group = "I2S", + presets = { + CLK = { + type = "generic", + wake_locking = true, + output = "(sclk * div_a) / (div_num * div_a + div_b)", + params = { + sclk = [ + { name = "XTAL", outputs = "XTAL_CLK", default = true }, + ], + # `div_n` is 8 bits; X/Y/Z (the A/B encoding) are 9 bits each. + div_num = "1 ..= 256", + div_a = "1 ..= 511", + div_b = "0 ..= 511", + }, + }, + }, + clocks = [ + { name = "TX_CLK", preset = "CLK" }, + { name = "RX_CLK", preset = "CLK" }, + { name = "MCLK_OUT", type = "mux", variants = [ + { name = "TX", outputs = "TX_CLK" }, + { name = "RX", outputs = "RX_CLK", default = true }, + ] }, + ], + }, { group = "RMT", clocks = [ { name = "SCLK", type = "mux", wake_locking = true, variants = [ { name = "PLL_F80M", outputs = "PLL_F80M", default = true }, @@ -114,6 +162,17 @@ system_clocks = { clock_tree = [ { group = "SDM", clocks = [ { name = "FUNCTION_CLOCK", type = "generic", output = "IOMUX_FUNCTION_CLOCK" }, ] }, + # Function clocks live in HP_SYS_CLKRST. The divider register stores N - 1. + { group = "LCD_CAM", clocks = [ + { name = "LCD_CLOCK", type = "generic", wake_locking = true, output = "(sclk * div_a) / (div_num * div_a + div_b)", params = { sclk = [ + { name = "XTAL_CLK", outputs = "XTAL_CLK", default = true }, + { name = "PLL_F160M", outputs = "PLL_F160M" }, + ], div_num = "1 ..= 256", div_a = "1 ..= 255", div_b = "0 ..= 255" } }, + { name = "CAM_CLOCK", type = "generic", wake_locking = true, output = "(sclk * div_a) / (div_num * div_a + div_b)", params = { sclk = [ + { name = "XTAL_CLK", outputs = "XTAL_CLK", default = true }, + { name = "PLL_F160M", outputs = "PLL_F160M" }, + ], div_num = "1 ..= 256", div_a = "1 ..= 255", div_b = "0 ..= 255" } }, + ] }, ] } peripheral_clocks = { templates = [ @@ -149,7 +208,24 @@ peripheral_clocks = { templates = [ { name = "Spi3", template_params = { peripheral = "gpspi3" } }, { name = "I2c0", template_params = { clk_en = "{{apb_clk}} {{peri_clk}}", ctrl_reg = "i2c_ctrl0(0)" } }, { name = "I2c1", template_params = { clk_en = "{{apb_clk}} {{peri_clk}}", ctrl_reg = "i2c_ctrl0(1)" } }, + { name = "I2s0", template_params = { + clk_en = "{{apb_clk}}", + rst_en = ".apb_rst_en().bit(reset)", + ctrl_reg = "i2s0_ctrl0()", + clk_en_template = "{{default_clk_template}} crate::peripherals::HP_ALIVE_SYS::regs().hp_pad_i2s0_ctrl().modify(|_, w| w.hp_pad_i2s0_mclk_en().bit(enable));" + } }, + { name = "I2s1", template_params = { + clk_en = "{{apb_clk}}", + rst_en = ".apb_rst_en().bit(reset)", + ctrl_reg = "i2s1_ctrl0()", + clk_en_template = "{{default_clk_template}} crate::peripherals::HP_ALIVE_SYS::regs().hp_pad_i2s1_ctrl().modify(|_, w| w.hp_pad_i2s1_mclk_en().bit(enable));" + } }, { name = "SdioHost", template_params = { clk_en = "{{sys_clk}}", rst_template = "crate::peripherals::CNNT_SYS::regs().sys_hp_sdmmc_ctrl().modify(|_, w| w.sys_sdmmc_rst_en().bit(reset));" } }, + # EMAC bus clock; the hardware reset lives in CNNT_SYS and is pulsed during clock setup. + { name = "Emac", template_params = { + clk_en_template = "crate::peripherals::HP_SYS_CLKRST::regs().emac_ctrl0().modify(|_, w| w.sys_clk_en().bit(enable));", + rst_template = "{{no_rst}}" + } }, # DMA engines { name = "AxiGdma", template_params = { peripheral = "axi_pdma", clk_en = "{{sys_clk}}" } }, { name = "AhbGdma", template_params = { peripheral = "ahb_pdma", clk_en = "{{sys_clk}}" } }, @@ -162,7 +238,7 @@ peripheral_clocks = { templates = [ clk_en_template = "{{default_clk_template}} crate::peripherals::CNNT_SYS::regs().sys_hp_usb_device_ctrl().modify(|_, w| w.sys_usb_device_48m_clk_en().bit(enable));", rst_template = "crate::peripherals::CNNT_SYS::regs().sys_hp_usb_device_ctrl().modify(|_, w| w.sys_usb_device_rst_en().bit(reset));" }, keep_enabled = true }, - # Crypto - there is a crypto_clk_en bit as well, luckily it starts as 1 + # Crypto - crypto_sys_clk_en and crypto_sec_clk_en gate the whole domain, CRYPTO_CLK drives those { name = "Aes", template_params = { ctrl_reg = "crypto_ctrl0()", clk_en = "{{crypto_clk}}", rst_en = "{{crypto_rst}}" } }, { name = "Ecc", template_params = { ctrl_reg = "crypto_ctrl0()", clk_en = "{{crypto_clk}}", rst_en = "{{crypto_rst}}" } }, { name = "Sha", template_params = { ctrl_reg = "crypto_ctrl0()", clk_en = "{{crypto_clk}}", rst_en = "{{crypto_rst}}" } }, @@ -171,11 +247,16 @@ peripheral_clocks = { templates = [ { name = "Systimer", template_params = { clk_en = "{{apb_clk}} {{peri_clk}}" }, keep_enabled = true }, { name = "Timg0", template_params = { peripheral = "timergrp0", clk_en = "{{apb_clk}}" }, keep_enabled = true }, { name = "Timg1", template_params = { peripheral = "timergrp1", clk_en = "{{apb_clk}}" } }, - # ADC -- clock and reset live in LP_PERI, not HP_SYS_CLKRST. - { name = "ApbSarAdc", template_params = { + # ADC -- clock and reset live in LP_PERI, not HP_SYS_CLKRST. `lp_adc_clk_en` resets to 1 and + # the PMU needs it while it powers the TOP domain down: gating it off leaves a deep sleep that + # the wakeup sources never end. + { name = "ApbSarAdc", keep_enabled = true, template_params = { clk_en_template = "crate::peripherals::LP_PERI::regs().adc_ctrl().modify(|_, w| w.lp_adc_clk_en().bit(enable));", rst_template = "crate::peripherals::LP_PERI::regs().adc_ctrl().modify(|_, w| w.lp_adc_rst_en().bit(reset));" } }, { name = "Rmt", template_params = { clk_en = "{{sys_clk}}" } }, + { name = "LcdCam", template_params = { peripheral = "lcdcam", rst_en = ".apb_rst_en().bit(reset).rst_en().bit(reset)" } }, + { name = "Pcnt", template_params = { clk_en = ".pcnt0_apb_clk_en().bit(enable)", rst_en = ".pcnt0_rst_en().bit(reset)" } }, + { name = "Pcnt1", template_params = { ctrl_reg = "pcnt_ctrl0()", clk_en = ".pcnt1_apb_clk_en().bit(enable)", rst_en = ".pcnt1_rst_en().bit(reset)" } }, { name = "GpioSd", template_params = { clk_en_template = "crate::peripherals::GPIO_SD::regs().clock_gate().modify(|_, w| w.clk_en().bit(enable));", rst_template = "{{no_rst}}" } }, ] } diff --git a/esp-metadata/devices/esp32s31/gpio.toml b/esp-metadata/devices/esp32s31/gpio.toml index 58a221a4dca..67cdacb990e 100644 --- a/esp-metadata/devices/esp32s31/gpio.toml +++ b/esp-metadata/devices/esp32s31/gpio.toml @@ -2,63 +2,65 @@ version = 3 has_input_sync = true # PIN_FUNC_GPIO = 1 (from io_mux_reg.h) gpio_function = 1 +# SOC_GPIO_NEED_SOFT_ISOLATE_DURING_PD +need_soft_isolate_during_pd = true # From gpio_reg.h: 0x80 = constantly high, 0xC0 = constantly low constant_0_input = 0xc0 constant_1_input = 0x80 # GPIO29 and GPIO41 are not bonded. pins = [ - { pin = 0, lp = { 0 = "LP_GPIO0" }, analog = { 0 = "XTAL_32K_N" } }, - { pin = 1, lp = { 0 = "LP_GPIO1" }, analog = { 0 = "XTAL_32K_P" } }, - { pin = 2, functions = { 3 = "LCD_DATA19" }, lp = { 0 = "LP_GPIO2" } }, - { pin = 3, functions = { 3 = "LCD_DATA20" }, lp = { 0 = "LP_GPIO3" } }, - { pin = 4, functions = { 3 = "LCD_DATA21" }, lp = { 0 = "LP_GPIO4" } }, - { pin = 5, functions = { 3 = "LCD_DATA22" }, lp = { 0 = "LP_GPIO5" } }, - { pin = 6, lp = { 0 = "LP_GPIO6" } }, - { pin = 7, functions = { 3 = "LCD_DATA23" }, lp = { 0 = "LP_GPIO7" } }, - { pin = 8, functions = { 2 = "GMAC_PHY_TXD0", 3 = "LCD_DATA0" } }, - { pin = 9, functions = { 0 = "FSPIHD", 2 = "GMAC_PHY_TXD1", 3 = "LCD_DATA1", 4 = "DBG_PSRAM_CK" } }, - { pin = 10, functions = { 0 = "FSPICS0", 2 = "GMAC_PHY_TXD2", 3 = "LCD_DATA2", 4 = "DBG_PSRAM_CS" } }, - { pin = 11, functions = { 0 = "FSPID", 2 = "GMAC_PHY_TXD3", 3 = "LCD_DATA3", 4 = "DBG_PSRAM_D" } }, - { pin = 12, functions = { 0 = "FSPICLK", 2 = "GMAC_PHY_TXEN", 3 = "LCD_DATA4", 4 = "DBG_PSRAM_Q" } }, - { pin = 13, functions = { 0 = "FSPIQ", 2 = "GMAC_RMII_CLK", 3 = "LCD_DATA5", 4 = "DBG_PSRAM_WP" } }, - { pin = 14, functions = { 0 = "FSPIWP", 2 = "GMAC_RX_CLK", 3 = "LCD_DATA6", 4 = "DBG_PSRAM_HOLD" } }, - { pin = 15, functions = { 0 = "FSPIIO4", 2 = "GMAC_PHY_RXDV", 3 = "LCD_DATA7", 4 = "DBG_PSRAM_DQ4" } }, - { pin = 16, functions = { 0 = "FSPIIO5", 2 = "GMAC_PHY_RXD3", 3 = "LCD_DATA8", 4 = "DBG_PSRAM_DQ5" } }, - { pin = 17, functions = { 0 = "FSPIIO6", 2 = "GMAC_PHY_RXD2", 3 = "LCD_DATA9", 4 = "DBG_PSRAM_DQ6" } }, - { pin = 18, functions = { 0 = "FSPIIO7", 2 = "GMAC_PHY_RXD1", 3 = "LCD_DATA10", 4 = "DBG_PSRAM_DQ7" } }, - { pin = 19, functions = { 0 = "FSPIDQS", 2 = "GMAC_PHY_RXD0", 3 = "LCD_DATA11", 4 = "DBG_PSRAM_DQS_0" } }, - { pin = 20, functions = { 0 = "SD1_DATA0", 2 = "FSPICLK", 4 = "DBG_FLASH_CK" } }, # SDMMC is CNNT - { pin = 21, functions = { 0 = "SD1_DATA1", 2 = "FSPID", 4 = "DBG_FLASH_D" } }, # SDMMC is CNNT - { pin = 22, functions = { 0 = "SD1_DATA2", 2 = "FSPIQ", 4 = "DBG_FLASH_CS" } }, # SDMMC is CNNT - { pin = 23, functions = { 0 = "SD1_DATA3", 2 = "FSPICS0", 4 = "DBG_FLASH_Q" } }, # SDMMC is CNNT - { pin = 24, functions = { 0 = "SD1_CLK", 2 = "FSPIHD", 4 = "DBG_FLASH_WP" } }, # SDMMC is CNNT - { pin = 25, functions = { 0 = "SD1_CMD", 2 = "FSPIWP", 4 = "DBG_FLASH_HOLD" } }, # SDMMC is CNNT + { pin = 0, lp = { 1 = "LP_GPIO0" }, analog = { 0 = "XTAL_32K_N" } }, + { pin = 1, lp = { 1 = "LP_GPIO1" }, analog = { 0 = "XTAL_32K_P" } }, + { pin = 2, functions = { 3 = "LCD_DATA_19" }, lp = { 1 = "LP_GPIO2" } }, + { pin = 3, functions = { 3 = "LCD_DATA_20" }, lp = { 1 = "LP_GPIO3" } }, + { pin = 4, functions = { 3 = "LCD_DATA_21" }, lp = { 1 = "LP_GPIO4" } }, + { pin = 5, functions = { 3 = "LCD_DATA_22" }, lp = { 1 = "LP_GPIO5" } }, + { pin = 6, lp = { 1 = "LP_GPIO6" } }, + { pin = 7, functions = { 3 = "LCD_DATA_23" }, lp = { 1 = "LP_GPIO7" } }, + { pin = 8, functions = { 2 = "EMAC_TXD0", 3 = "LCD_DATA_0" } }, + { pin = 9, functions = { 0 = "FSPIHD", 2 = "EMAC_TXD1", 3 = "LCD_DATA_1", 4 = "DBG_PSRAM_CK" } }, + { pin = 10, functions = { 0 = "FSPICS0", 2 = "EMAC_TXD2", 3 = "LCD_DATA_2", 4 = "DBG_PSRAM_CS" } }, + { pin = 11, functions = { 0 = "FSPID", 2 = "EMAC_TXD3", 3 = "LCD_DATA_3", 4 = "DBG_PSRAM_D" } }, + { pin = 12, functions = { 0 = "FSPICLK", 2 = "EMAC_TXEN", 3 = "LCD_DATA_4", 4 = "DBG_PSRAM_Q" } }, + { pin = 13, functions = { 0 = "FSPIQ", 2 = "EMAC_RMII_CLK", 3 = "LCD_DATA_5", 4 = "DBG_PSRAM_WP" } }, + { pin = 14, functions = { 0 = "FSPIWP", 2 = "EMAC_RX_CLK", 3 = "LCD_DATA_6", 4 = "DBG_PSRAM_HOLD" } }, + { pin = 15, functions = { 0 = "FSPIIO4", 2 = "EMAC_RXDV", 3 = "LCD_DATA_7", 4 = "DBG_PSRAM_DQ4" } }, + { pin = 16, functions = { 0 = "FSPIIO5", 2 = "EMAC_RXD3", 3 = "LCD_DATA_8", 4 = "DBG_PSRAM_DQ5" } }, + { pin = 17, functions = { 0 = "FSPIIO6", 2 = "EMAC_RXD2", 3 = "LCD_DATA_9", 4 = "DBG_PSRAM_DQ6" } }, + { pin = 18, functions = { 0 = "FSPIIO7", 2 = "EMAC_RXD1", 3 = "LCD_DATA_10", 4 = "DBG_PSRAM_DQ7" } }, + { pin = 19, functions = { 0 = "FSPIDQS", 2 = "EMAC_RXD0", 3 = "LCD_DATA_11", 4 = "DBG_PSRAM_DQS_0" } }, + { pin = 20, functions = { 0 = "SD1_DATA0", 2 = "FSPICLK", 4 = "DBG_FLASH_CK" } }, # SDMMC is CNNT + { pin = 21, functions = { 0 = "SD1_DATA1", 2 = "FSPID", 4 = "DBG_FLASH_D" } }, # SDMMC is CNNT + { pin = 22, functions = { 0 = "SD1_DATA2", 2 = "FSPIQ", 4 = "DBG_FLASH_CS" } }, # SDMMC is CNNT + { pin = 23, functions = { 0 = "SD1_DATA3", 2 = "FSPICS0", 4 = "DBG_FLASH_Q" } }, # SDMMC is CNNT + { pin = 24, functions = { 0 = "SD1_CLK", 2 = "FSPIHD", 4 = "DBG_FLASH_WP" } }, # SDMMC is CNNT + { pin = 25, functions = { 0 = "SD1_CMD", 2 = "FSPIWP", 4 = "DBG_FLASH_HOLD" } }, # SDMMC is CNNT { pin = 26, functions = { 0 = "SPICS0" }, limitations = ["spi_flash"] }, { pin = 27, functions = { 0 = "SPIQ" }, limitations = ["spi_flash", "strapping"] }, { pin = 28, functions = { 0 = "SPIWP" }, limitations = ["spi_flash", "strapping"] }, { pin = 30, functions = { 0 = "SPIHD" }, limitations = ["spi_flash"] }, { pin = 31, functions = { 0 = "SPICLK" }, limitations = ["spi_flash"] }, { pin = 32, functions = { 0 = "SPID" }, limitations = ["spi_flash"] }, - { pin = 33, functions = { 3 = "LCD_DATA12" }, analog = { 0 = "USJ_DM" } }, - { pin = 34, functions = { 3 = "LCD_DATA13" }, analog = { 0 = "USJ_DP" } }, - { pin = 35, functions = { 2 = "REF_GMAC_CLK", 3 = "LCD_DATA14", 4 = "SD2_CDATA0" } }, - { pin = 36, functions = { 2 = "GMAC_PHY_RXDV", 3 = "LCD_DATA15", 4 = "SD2_CDATA1" }, limitations = ["strapping"] }, - { pin = 37, functions = { 2 = "GMAC_PHY_TXEN", 3 = "LCD_DATA16", 4 = "SD2_CDATA2" }, limitations = ["strapping"] }, - { pin = 38, functions = { 2 = "GMAC_PHY_RXD3", 3 = "LCD_DATA17", 4 = "SD2_CDATA3" }, limitations = ["strapping"] }, - { pin = 39, functions = { 2 = "GMAC_PHY_RXD2", 3 = "LCD_DATA18", 4 = "SD2_CCLK" }, limitations = ["strapping"] }, - { pin = 40, functions = { 2 = "GMAC_PHY_RXD1", 3 = "LCD_PCLK", 4 = "SD2_CCMD" }, limitations = ["strapping"] }, - { pin = 42, functions = { 2 = "GMAC_RX_CLK" }, analog = { 1 = "ADC1_CH0" } }, - { pin = 43, functions = { 2 = "GMAC_RMII_CLK", 3 = "LCD_H_ENABLE" }, analog = { 1 = "ADC1_CH1" } }, - { pin = 44, functions = { 2 = "GMAC_PHY_TXD0", 3 = "LCD_H_SYNC" }, analog = { 1 = "ADC1_CH2" } }, - { pin = 45, functions = { 2 = "GMAC_PHY_TXD1", 3 = "LCD_V_SYNC" }, analog = { 1 = "ADC1_CH3" } }, - { pin = 46, functions = { 2 = "GMAC_PHY_TXD2", 3 = "CAM_DATA0" }, analog = { 1 = "ADC1_CH4" } }, - { pin = 47, functions = { 2 = "GMAC_PHY_TXD3", 3 = "CAM_DATA1" }, analog = { 1 = "ADC1_CH5" } }, - { pin = 48, functions = { 3 = "CAM_DATA2" }, analog = { 1 = "ADC1_CH6" } }, - { pin = 49, functions = { 3 = "CAM_DATA3" }, analog = { 1 = "ADC1_CH7" } }, - { pin = 50, functions = { 3 = "CAM_DATA4" }, analog = { 1 = "ADC2_CH0" } }, - { pin = 51, functions = { 3 = "CAM_DATA5" }, analog = { 1 = "ADC2_CH1" } }, - { pin = 52, functions = { 2 = "FSPICS0", 3 = "CAM_DATA6" }, analog = { 1 = "ADC2_CH2" } }, - { pin = 53, functions = { 2 = "FSPICLK", 3 = "CAM_DATA7" }, analog = { 1 = "ADC2_CH3" } }, + { pin = 33, functions = { 3 = "LCD_DATA_12" }, analog = { 0 = "USJ_DM" } }, + { pin = 34, functions = { 3 = "LCD_DATA_13" }, analog = { 0 = "USJ_DP" } }, + { pin = 35, functions = { 2 = "REF_50M_CLK", 3 = "LCD_DATA_14", 4 = "SD2_CDATA0" } }, + { pin = 36, functions = { 2 = "EMAC_RXDV", 3 = "LCD_DATA_15", 4 = "SD2_CDATA1" }, limitations = ["strapping"] }, + { pin = 37, functions = { 2 = "EMAC_TXEN", 3 = "LCD_DATA_16", 4 = "SD2_CDATA2" }, limitations = ["strapping"] }, + { pin = 38, functions = { 2 = "EMAC_RXD3", 3 = "LCD_DATA_17", 4 = "SD2_CDATA3" }, limitations = ["strapping"] }, + { pin = 39, functions = { 2 = "EMAC_RXD2", 3 = "LCD_DATA_18", 4 = "SD2_CCLK" }, limitations = ["strapping"] }, + { pin = 40, functions = { 2 = "EMAC_RXD1", 3 = "LCD_PCLK", 4 = "SD2_CCMD" }, limitations = ["strapping"] }, + { pin = 42, functions = { 2 = "EMAC_RX_CLK" }, analog = { 1 = "ADC1_CH0" } }, + { pin = 43, functions = { 2 = "EMAC_RMII_CLK", 3 = "LCD_H_ENABLE" }, analog = { 1 = "ADC1_CH1" } }, + { pin = 44, functions = { 2 = "EMAC_TXD0", 3 = "LCD_H_SYNC" }, analog = { 1 = "ADC1_CH2" } }, + { pin = 45, functions = { 2 = "EMAC_TXD1", 3 = "LCD_V_SYNC" }, analog = { 1 = "ADC1_CH3" } }, + { pin = 46, functions = { 2 = "EMAC_TXD2", 3 = "CAM_DATA_0" }, analog = { 1 = "ADC1_CH4" } }, + { pin = 47, functions = { 2 = "EMAC_TXD3", 3 = "CAM_DATA_1" }, analog = { 1 = "ADC1_CH5" } }, + { pin = 48, functions = { 3 = "CAM_DATA_2" }, analog = { 1 = "ADC1_CH6" } }, + { pin = 49, functions = { 3 = "CAM_DATA_3" }, analog = { 1 = "ADC1_CH7" } }, + { pin = 50, functions = { 3 = "CAM_DATA_4" }, analog = { 1 = "ADC2_CH0" } }, + { pin = 51, functions = { 3 = "CAM_DATA_5" }, analog = { 1 = "ADC2_CH1" } }, + { pin = 52, functions = { 2 = "FSPICS0", 3 = "CAM_DATA_6" }, analog = { 1 = "ADC2_CH2" } }, + { pin = 53, functions = { 2 = "FSPICLK", 3 = "CAM_DATA_7" }, analog = { 1 = "ADC2_CH3" } }, { pin = 54, functions = { 0 = "MTDO", 2 = "FSPID", 3 = "CAM_PCLK" }, analog = { 1 = "ADC2_CH4" }, limitations = ["jtag"] }, { pin = 55, functions = { 0 = "MTCK", 2 = "FSPIQ", 3 = "CAM_XCLK" }, analog = { 1 = "ADC2_CH5" }, limitations = ["jtag"] }, { pin = 56, functions = { 0 = "MTDI", 2 = "FSPIHD", 3 = "CAM_V_SYNC" }, analog = { 1 = "ADC2_CH6" }, limitations = ["jtag"] }, @@ -83,12 +85,22 @@ input_signals = [ { name = "U3CTS", id = 138 }, { name = "U3DSR", id = 139 }, # I2S0 - { name = "I2SO_BCK", id = 25 }, - { name = "I2S_MCLK", id = 26 }, - { name = "I2SO_WS", id = 27 }, - { name = "I2SI_SD", id = 28 }, - { name = "I2SI_BCK", id = 29 }, - { name = "I2SI_WS", id = 30 }, + { name = "I2S0O_BCK", id = 25 }, + { name = "I2S0_MCLK", id = 26 }, + { name = "I2S0O_WS", id = 27 }, + { name = "I2S0I_SD", id = 28 }, + { name = "I2S0I_BCK", id = 29 }, + { name = "I2S0I_WS", id = 30 }, + { name = "I2S0I_SD1", id = 43 }, + { name = "I2S0I_SD2", id = 44 }, + { name = "I2S0I_SD3", id = 45 }, + # I2S1 + { name = "I2S1O_BCK", id = 31 }, + { name = "I2S1_MCLK", id = 32 }, + { name = "I2S1O_WS", id = 33 }, + { name = "I2S1I_SD", id = 34 }, + { name = "I2S1I_BCK", id = 35 }, + { name = "I2S1I_WS", id = 36 }, # SPI2 (FSPI) { name = "FSPICLK", id = 53 }, { name = "FSPIQ", id = 54 }, @@ -105,9 +117,7 @@ input_signals = [ { name = "FSPICS3", id = 65 }, { name = "FSPICS4", id = 66 }, { name = "FSPICS5", id = 67 }, - # SPI3 - { name = "SPI3_CS2", id = 45 }, - { name = "SPI3_CS1", id = 46 }, + # SPI3 (CS1/CS2 are output-only) { name = "SPI3_CK", id = 47 }, { name = "SPI3_Q", id = 48 }, { name = "SPI3_D", id = 49 }, @@ -121,6 +131,40 @@ input_signals = [ { name = "I2CEXT1_SDA", id = 71 }, # USB JTAG { name = "USB_JTAG_TDO_BRIDGE", id = 140 }, + # PCNT0 (HAL unit N uses PCNTn_*) + { name = "PCNT0_SIG_CH0", id = 141 }, + { name = "PCNT1_SIG_CH0", id = 142 }, + { name = "PCNT2_SIG_CH0", id = 143 }, + { name = "PCNT3_SIG_CH0", id = 144 }, + { name = "PCNT0_SIG_CH1", id = 145 }, + { name = "PCNT1_SIG_CH1", id = 146 }, + { name = "PCNT2_SIG_CH1", id = 147 }, + { name = "PCNT3_SIG_CH1", id = 148 }, + { name = "PCNT0_CTRL_CH0", id = 149 }, + { name = "PCNT1_CTRL_CH0", id = 150 }, + { name = "PCNT2_CTRL_CH0", id = 151 }, + { name = "PCNT3_CTRL_CH0", id = 152 }, + { name = "PCNT0_CTRL_CH1", id = 153 }, + { name = "PCNT1_CTRL_CH1", id = 154 }, + { name = "PCNT2_CTRL_CH1", id = 155 }, + { name = "PCNT3_CTRL_CH1", id = 156 }, + # PCNT1 instance (IDF PCNT1_*_INn; HAL names PCNT1_Un_* for unit n) + { name = "PCNT1_U0_CTRL_CH0", id = 72 }, + { name = "PCNT1_U1_CTRL_CH0", id = 73 }, + { name = "PCNT1_U2_CTRL_CH0", id = 74 }, + { name = "PCNT1_U3_CTRL_CH0", id = 75 }, + { name = "PCNT1_U0_CTRL_CH1", id = 76 }, + { name = "PCNT1_U1_CTRL_CH1", id = 77 }, + { name = "PCNT1_U2_CTRL_CH1", id = 78 }, + { name = "PCNT1_U3_CTRL_CH1", id = 79 }, + { name = "PCNT1_U0_SIG_CH0", id = 204 }, + { name = "PCNT1_U1_SIG_CH0", id = 205 }, + { name = "PCNT1_U2_SIG_CH0", id = 206 }, + { name = "PCNT1_U3_SIG_CH0", id = 207 }, + { name = "PCNT1_U0_SIG_CH1", id = 208 }, + { name = "PCNT1_U1_SIG_CH1", id = 209 }, + { name = "PCNT1_U2_SIG_CH1", id = 210 }, + { name = "PCNT1_U3_SIG_CH1", id = 211 }, # CPU GPIO { name = "CPU_GPIO_0", id = 214 }, { name = "CPU_GPIO_1", id = 215 }, @@ -143,6 +187,27 @@ input_signals = [ { name = "RMT_SIG_1", id = 247 }, { name = "RMT_SIG_2", id = 248 }, { name = "RMT_SIG_3", id = 249 }, + # LCD_CAM + { name = "CAM_PCLK", id = 158 }, + { name = "CAM_H_ENABLE", id = 159 }, + { name = "CAM_H_SYNC", id = 160 }, + { name = "CAM_V_SYNC", id = 161 }, + { name = "CAM_DATA_0", id = 162 }, + { name = "CAM_DATA_1", id = 163 }, + { name = "CAM_DATA_2", id = 164 }, + { name = "CAM_DATA_3", id = 165 }, + { name = "CAM_DATA_4", id = 166 }, + { name = "CAM_DATA_5", id = 167 }, + { name = "CAM_DATA_6", id = 168 }, + { name = "CAM_DATA_7", id = 169 }, + { name = "CAM_DATA_8", id = 170 }, + { name = "CAM_DATA_9", id = 171 }, + { name = "CAM_DATA_10", id = 172 }, + { name = "CAM_DATA_11", id = 173 }, + { name = "CAM_DATA_12", id = 174 }, + { name = "CAM_DATA_13", id = 175 }, + { name = "CAM_DATA_14", id = 176 }, + { name = "CAM_DATA_15", id = 177 }, # SDMMC { name = "SDHOST_CDATA_IN_41", id = 0 }, { name = "SDHOST_CDATA_IN_51", id = 1 }, @@ -161,6 +226,18 @@ input_signals = [ { name = "SDHOST_CARD_WRITE_PRT_2", id = 131 }, { name = "SDHOST_DATA_STROBE_1", id = 132 }, { name = "SDHOST_DATA_STROBE_2", id = 133 }, + # Ethernet (names match ESP32/ESP32-P4; SVD uses GMAC_/GMII_ prefixes) + { name = "EMAC_MDI", id = 107 }, + { name = "EMAC_COL", id = 108 }, + { name = "EMAC_CRS", id = 109 }, + { name = "EMAC_RXDV", id = 178 }, + { name = "EMAC_RXD0", id = 179 }, + { name = "EMAC_RXD1", id = 180 }, + { name = "EMAC_RXD2", id = 181 }, + { name = "EMAC_RXD3", id = 182 }, + { name = "EMAC_RXER", id = 183 }, + { name = "EMAC_RX_CLK", id = 184 }, + { name = "EMAC_TX_CLK", id = 185 }, # Spare functions { name = "SIG_IN_FUNC251", id = 251 }, { name = "SIG_IN_FUNC252", id = 252 }, @@ -185,59 +262,9 @@ input_signals = [ { name = "SPIHD" }, { name = "SPICLK" }, { name = "SPID" }, - { name = "GMAC_PHY_TXD0" }, - { name = "GMAC_PHY_TXD1" }, - { name = "GMAC_PHY_TXD2" }, - { name = "GMAC_PHY_TXD3" }, - { name = "GMAC_PHY_TXEN" }, - { name = "GMAC_RMII_CLK" }, - { name = "GMAC_RX_CLK" }, - { name = "GMAC_PHY_RXDV" }, - { name = "GMAC_PHY_RXD0" }, - { name = "GMAC_PHY_RXD1" }, - { name = "GMAC_PHY_RXD2" }, - { name = "GMAC_PHY_RXD3" }, - { name = "REF_GMAC_CLK" }, - { name = "LCD_DATA0" }, - { name = "LCD_DATA1" }, - { name = "LCD_DATA2" }, - { name = "LCD_DATA3" }, - { name = "LCD_DATA4" }, - { name = "LCD_DATA5" }, - { name = "LCD_DATA6" }, - { name = "LCD_DATA7" }, - { name = "LCD_DATA8" }, - { name = "LCD_DATA9" }, - { name = "LCD_DATA10" }, - { name = "LCD_DATA11" }, - { name = "LCD_DATA12" }, - { name = "LCD_DATA13" }, - { name = "LCD_DATA14" }, - { name = "LCD_DATA15" }, - { name = "LCD_DATA16" }, - { name = "LCD_DATA17" }, - { name = "LCD_DATA18" }, - { name = "LCD_DATA19" }, - { name = "LCD_DATA20" }, - { name = "LCD_DATA21" }, - { name = "LCD_DATA22" }, - { name = "LCD_DATA23" }, - { name = "LCD_PCLK" }, - { name = "LCD_H_ENABLE" }, - { name = "LCD_H_SYNC" }, - { name = "LCD_V_SYNC" }, - { name = "CAM_DATA0" }, - { name = "CAM_DATA1" }, - { name = "CAM_DATA2" }, - { name = "CAM_DATA3" }, - { name = "CAM_DATA4" }, - { name = "CAM_DATA5" }, - { name = "CAM_DATA6" }, - { name = "CAM_DATA7" }, - { name = "CAM_PCLK" }, + { name = "EMAC_RMII_CLK" }, + { name = "REF_50M_CLK" }, { name = "CAM_XCLK" }, - { name = "CAM_V_SYNC" }, - { name = "CAM_H_SYNC" }, { name = "SD2_CDATA0" }, { name = "SD2_CDATA1" }, { name = "SD2_CDATA2" }, @@ -289,12 +316,20 @@ output_signals = [ { name = "U3RTS", id = 138 }, { name = "U3DTR", id = 116 }, # I2S0 - { name = "I2SO_BCK", id = 25 }, - { name = "I2S_MCLK", id = 26 }, - { name = "I2SO_WS", id = 27 }, - { name = "I2SO_SD", id = 28 }, - { name = "I2SI_BCK", id = 29 }, - { name = "I2SI_WS", id = 30 }, + { name = "I2S0O_BCK", id = 25 }, + { name = "I2S0_MCLK", id = 26 }, + { name = "I2S0O_WS", id = 27 }, + { name = "I2S0O_SD", id = 28 }, + { name = "I2S0I_BCK", id = 29 }, + { name = "I2S0I_WS", id = 30 }, + { name = "I2S0O_SD1", id = 43 }, + # I2S1 + { name = "I2S1O_BCK", id = 31 }, + { name = "I2S1_MCLK", id = 32 }, + { name = "I2S1O_WS", id = 33 }, + { name = "I2S1O_SD", id = 34 }, + { name = "I2S1I_BCK", id = 35 }, + { name = "I2S1I_WS", id = 36 }, # SPI2 { name = "FSPICLK", id = 53 }, { name = "FSPIQ", id = 54 }, @@ -357,6 +392,48 @@ output_signals = [ { name = "RMT_SIG_1", id = 247 }, { name = "RMT_SIG_2", id = 248 }, { name = "RMT_SIG_3", id = 249 }, + # LCD_CAM + { name = "LCD_CS", id = 144 }, + { name = "LCD_DC", id = 145 }, + { name = "LCD_PCLK", id = 149 }, + { name = "CAM_CLK", id = 150 }, + { name = "LCD_H_ENABLE", id = 151 }, + { name = "LCD_H_SYNC", id = 152 }, + { name = "LCD_V_SYNC", id = 153 }, + { name = "LCD_DATA_0", id = 154 }, + { name = "LCD_DATA_1", id = 155 }, + { name = "LCD_DATA_2", id = 156 }, + { name = "LCD_DATA_3", id = 157 }, + { name = "LCD_DATA_4", id = 158 }, + { name = "LCD_DATA_5", id = 159 }, + { name = "LCD_DATA_6", id = 160 }, + { name = "LCD_DATA_7", id = 161 }, + { name = "LCD_DATA_8", id = 162 }, + { name = "LCD_DATA_9", id = 163 }, + { name = "LCD_DATA_10", id = 164 }, + { name = "LCD_DATA_11", id = 165 }, + { name = "LCD_DATA_12", id = 166 }, + { name = "LCD_DATA_13", id = 167 }, + { name = "LCD_DATA_14", id = 168 }, + { name = "LCD_DATA_15", id = 169 }, + { name = "LCD_DATA_16", id = 170 }, + { name = "LCD_DATA_17", id = 171 }, + { name = "LCD_DATA_18", id = 172 }, + { name = "LCD_DATA_19", id = 173 }, + { name = "LCD_DATA_20", id = 174 }, + { name = "LCD_DATA_21", id = 175 }, + { name = "LCD_DATA_22", id = 176 }, + { name = "LCD_DATA_23", id = 177 }, + # Ethernet (names match ESP32/ESP32-P4; SVD uses GMAC_/GMII_ prefixes) + { name = "EMAC_PTP_PPS", id = 105 }, + { name = "EMAC_MDC", id = 108 }, + { name = "EMAC_MDO", id = 109 }, + { name = "EMAC_TXEN", id = 178 }, + { name = "EMAC_TXD0", id = 179 }, + { name = "EMAC_TXD1", id = 180 }, + { name = "EMAC_TXD2", id = 181 }, + { name = "EMAC_TXD3", id = 182 }, + { name = "EMAC_TXER", id = 183 }, # GPIO passthrough { name = "GPIO", id = 256 }, @@ -377,59 +454,9 @@ output_signals = [ { name = "SPIHD" }, { name = "SPICLK" }, { name = "SPID" }, - { name = "GMAC_PHY_TXD0" }, - { name = "GMAC_PHY_TXD1" }, - { name = "GMAC_PHY_TXD2" }, - { name = "GMAC_PHY_TXD3" }, - { name = "GMAC_PHY_TXEN" }, - { name = "GMAC_RMII_CLK" }, - { name = "GMAC_RX_CLK" }, - { name = "GMAC_PHY_RXDV" }, - { name = "GMAC_PHY_RXD0" }, - { name = "GMAC_PHY_RXD1" }, - { name = "GMAC_PHY_RXD2" }, - { name = "GMAC_PHY_RXD3" }, - { name = "REF_GMAC_CLK" }, - { name = "LCD_DATA0" }, - { name = "LCD_DATA1" }, - { name = "LCD_DATA2" }, - { name = "LCD_DATA3" }, - { name = "LCD_DATA4" }, - { name = "LCD_DATA5" }, - { name = "LCD_DATA6" }, - { name = "LCD_DATA7" }, - { name = "LCD_DATA8" }, - { name = "LCD_DATA9" }, - { name = "LCD_DATA10" }, - { name = "LCD_DATA11" }, - { name = "LCD_DATA12" }, - { name = "LCD_DATA13" }, - { name = "LCD_DATA14" }, - { name = "LCD_DATA15" }, - { name = "LCD_DATA16" }, - { name = "LCD_DATA17" }, - { name = "LCD_DATA18" }, - { name = "LCD_DATA19" }, - { name = "LCD_DATA20" }, - { name = "LCD_DATA21" }, - { name = "LCD_DATA22" }, - { name = "LCD_DATA23" }, - { name = "LCD_PCLK" }, - { name = "LCD_H_ENABLE" }, - { name = "LCD_H_SYNC" }, - { name = "LCD_V_SYNC" }, - { name = "CAM_DATA0" }, - { name = "CAM_DATA1" }, - { name = "CAM_DATA2" }, - { name = "CAM_DATA3" }, - { name = "CAM_DATA4" }, - { name = "CAM_DATA5" }, - { name = "CAM_DATA6" }, - { name = "CAM_DATA7" }, - { name = "CAM_PCLK" }, + { name = "EMAC_RMII_CLK" }, + { name = "REF_50M_CLK" }, { name = "CAM_XCLK" }, - { name = "CAM_V_SYNC" }, - { name = "CAM_H_SYNC" }, { name = "SD2_CDATA0" }, { name = "SD2_CDATA1" }, { name = "SD2_CDATA2" }, @@ -456,7 +483,7 @@ output_signals = [ ] [device.lp_io] -support_status = "not_supported" +support_status = "partial" version = "esp32s31" lp_input_signals = [ { name = "LP_I2C_SCL", id = 0 }, diff --git a/esp-metadata/devices/esp32s31/soc.toml b/esp-metadata/devices/esp32s31/soc.toml index 143912ffe91..d383a3c9c7a 100644 --- a/esp-metadata/devices/esp32s31/soc.toml +++ b/esp-metadata/devices/esp32s31/soc.toml @@ -18,6 +18,9 @@ support_note = "In early stages of development." page_size = 0x10000 entry_num = 1024 +[device.flash] +support_status = "partial" + [device.rom] has_crc_le = true has_crc_be = true @@ -27,17 +30,19 @@ has_md5_bsd = true multi_core_enabled = true cpu_has_branch_predictor = true cpu_has_csr_pc = false +cpu_has_zcmp_workaround = true cpu_csr_prv_mode = 0x810 cpu_mcause_mask = 0x3f +cpu_pmp_granularity = 128 has_swd_watchdog = true -# SRAM_START = 0x2F000000, SRAM_SEG_END = 0x2F07AFC0 (from esp-idf ld.hp_mem_defs) -# dram2_uninit: SRAM_SEG_END..SOC_ROM_STACK_START (PRO CPU stack, reclaimable) +# SOC_DRAM_LOW = 0x2F000000, SOC_DRAM_HIGH = 0x2F080000 (from soc.h) # SOC_ROM_STACK_START = 0x2F07CFB0 (from soc.h) memory_map = { ranges = [ - { name = "dram", start = 0x2F00_0000, end = 0x2F07_AFC0 }, - { name = "dram2_uninit", start = 0x2F07_AFC0, end = 0x2F07_CFB0 }, + { name = "dram", start = 0x2F00_0000, end = 0x2F08_0000 }, + # start address from the 2nd stage bootloader's linker script: https://github.com/espressif/esp-idf/blob/383dda6c182/components/bootloader/subproject/main/ld/esp32s31/bootloader.memory.ld.in#L52 + { name = "dram2_uninit", start = 0x2F06_CFB0, end = 0x2F07_CFB0 }, { name = "irom", start = 0x4000_0000, end = 0x5000_0000 }, { name = "drom", start = 0x4000_0000, end = 0x5000_0000 }, ] } @@ -48,8 +53,13 @@ peripherals = [ { name = "ASSIST_DEBUG" }, { name = "CACHE" }, { name = "CLIC" }, + { name = "CLINT" }, + { name = "CLINT_OTHER_CORE" }, { name = "CNNT_SYS", hidden = true }, { name = "CNNT_IO_MUX", hidden = true }, + { name = "ETH", virtual = true, interrupts = { peri = "SBD" } }, + { name = "EMAC_DMA", pac = "GMAC_DMA", hidden = true }, + { name = "EMAC_MAC", pac = "GMAC", hidden = true }, { name = "ECC" }, { name = "EFUSE", hidden = true }, { name = "GPIO" }, @@ -61,9 +71,13 @@ peripherals = [ { name = "HP_SYS_CLKRST" }, { name = "I2C0", interrupts = { peri = "I2C0" }, clock_group = "I2C", stable = true }, { name = "I2C1", interrupts = { peri = "I2C1" }, clock_group = "I2C", stable = true }, + { name = "I2S0", interrupts = { peri = "I2S0" }, clock_group = "I2S" }, + { name = "I2S1", interrupts = { peri = "I2S1" }, clock_group = "I2S" }, + { name = "IEEE802154", interrupts = { mac = "MODEM_ZB_MAC" } }, { name = "INTERRUPT_CORE0" }, { name = "INTERRUPT_CORE1" }, { name = "IO_MUX" }, + { name = "LCD_CAM", interrupts = { peri = "LCD_CAM" }, clock_group = "LCD_CAM" }, { name = "IOMUX_MSPI_PIN", hidden = true }, { name = "LP_AON_CLK_RST", pac = "LP_AON_CLKRST" }, { name = "LP_APM" }, @@ -78,10 +92,12 @@ peripherals = [ { name = "MODEM_LPCON" }, { name = "MODEM_SYSCON" }, { name = "PAU" }, + { name = "PCNT", interrupts = { peri = "PCNT0" } }, + { name = "PCNT1", interrupts = { peri = "PCNT1" } }, { name = "PMU" }, { name = "RTC_TIMER", pac = "LP_TIMER" }, { name = "RNG", pac = "TRNG" }, - { name = "RMT", virtual = true, interrupts = { peri = "RMT" }, clock_group = "RMT" }, # PAC field names differ from ESP32-S3; overlay_rmt maps them. + { name = "RMT", interrupts = { peri = "RMT" }, clock_group = "RMT" }, { name = "RSA", interrupts = { peri = "RSA" } }, { name = "SPI0" }, { name = "SPI1" }, @@ -108,10 +124,13 @@ peripherals = [ { name = "ADC1", virtual = true }, { name = "ADC2", virtual = true }, + { name = "BT", virtual = true, interrupts = { mac = "MODEM_BT_MAC", bb = "MODEM_BT_BB", lp_timer = "MODEM_LP_TIMER" } }, { name = "FLASH", virtual = true }, { name = "PSRAM", virtual = true, clock_group = "PSRAM" }, { name = "GPIO_DEDICATED", virtual = true }, + { name = "WIFI", virtual = true, interrupts = { bb = "MODEM_WIFI_BB", mac = "MODEM_WIFI_MAC", pwr = "MODEM_WIFI_PWR" }, stable = true }, { name = "CPU_CTRL", virtual = true }, + { name = "IPC", virtual = true }, { name = "FROM_CPU_INTR0", virtual = true }, { name = "FROM_CPU_INTR1", virtual = true }, { name = "FROM_CPU_INTR2", virtual = true }, @@ -127,12 +146,15 @@ support_status = "partial" status_registers = 6 software_interrupt_count = 4 controller = { Riscv = { flavour = "clic", interrupts = 48, priority_levels = 8 } } +context_switch_source = "ipc" [device.timergroup] support_status = "partial" instances = [{ name = "timg0" }, { name = "timg1" }] +timg_has_timer1 = true timg_has_divcnt_rst = true rc_fast_calibration = { divider = 50, min_rev = 0 } +wdt_has_conf_update = true [device.gpio] support_status = "supported" @@ -153,8 +175,8 @@ support_status = "supported" instances = [ { name = "uart0", sys_instance = "Uart0", tx = "U0TXD", rx = "U0RXD", cts = "U0CTS", rts = "U0RTS" }, { name = "uart1", sys_instance = "Uart1", tx = "U1TXD", rx = "U1RXD", cts = "U1CTS", rts = "U1RTS" }, - { name = "uart2", sys_instance = "Uart2", tx = "U2TXD", rx = "U2RXD", cts = "U2CTS", rts = "U2RTS" }, - { name = "uart3", sys_instance = "Uart3", tx = "U3TXD", rx = "U3RXD", cts = "U3CTS", rts = "U3RTS" }, + { name = "uart2", sys_instance = "Uart2", tx = "U2TXD", rx = "U2RXD", cts = "U2CTS", rts = "U2RTS", wakeup_source = false }, + { name = "uart3", sys_instance = "Uart3", tx = "U3TXD", rx = "U3RXD", cts = "U3CTS", rts = "U3RTS", wakeup_source = false }, ] ram_size = 128 version = 2 @@ -198,12 +220,12 @@ has_region_monitor = true [device.rng] support_status = { status = "partial", issue = 5977 } -trng_supported = false # TODO +trng_supported = true apb_cycle_wait_num = 16 # TODO is_lp_sys = false [device.sleep] -support_status = "not_supported" +support_status = "partial" light_sleep = true deep_sleep = true ext1_version = 3 @@ -221,6 +243,11 @@ wakeup_sources = { Bt = 25, } +[device.sleep.retention] +cpu_retention = "software" +cpu_retention_frame = "s31" +supports_top_power_down = true + [device.usb_otg_hs] fifo_depth_words = 896 @@ -279,9 +306,11 @@ engines = [ name = "AHB_GDMA", max_priority = 15, burst_sizes = [0, 4, 16, 32, 64], - drivers = ["uhci"], + drivers = ["uhci", "i2s"], peripheral_instances = [ { name = "UHCI0", dma_id = 0 }, + { name = "I2S0", dma_id = 1 }, + { name = "I2S1", dma_id = 5 }, ], channels = [ { name = "DMA_CH0", mem2mem = true, mem2mem_id = 9, interrupt_in = "AHB_PDMA_IN_CH0", interrupt_out = "AHB_PDMA_OUT_CH0" }, @@ -295,9 +324,9 @@ engines = [ name = "AXI_GDMA", max_priority = 15, burst_sizes = [8, 16, 32, 64, 128], - drivers = ["spi_master", "spi_slave", "aes"], + drivers = ["spi_master", "spi_slave", "aes", "lcd_cam"], peripheral_instances = [ - # LCD_CAM + { name = "LCD_CAM", dma_id = 0 }, { name = "SPI2", dma_id = 1 }, { name = "SPI3", dma_id = 2 }, # PARL_IO @@ -313,7 +342,7 @@ engines = [ ] [device.ecc] -support_status = { status = "partial", issue = 5972 } +support_status = "partial" working_modes = [ { id = 0, mode = "affine_point_multiplication" }, { id = 2, mode = "affine_point_verification" }, @@ -328,10 +357,10 @@ working_modes = [ { id = 11, mode = "modular_division" } ] curves = [ - { id = 0, curve = 192 }, - { id = 1, curve = 256 }, - { id = 2, curve = 384 }, - # TODO: SM2 = 3 + { id = 0, curve = "p192" }, + { id = 1, curve = "p256" }, + { id = 2, curve = "p384" }, + { id = 3, curve = "sm2" }, ] separate_jacobian_point_memory = true has_memory_clock_gate = true @@ -364,7 +393,7 @@ algo = { sha512_224 = 5, sha512_256 = 6, sha512_t = 7, - # TODO: sm3 = 14 + sm3 = 14, } [device.hmac] @@ -384,33 +413,95 @@ instances = [ [device.usb_serial_jtag] support_status = "partial" +[device.camera] +support_status = "partial" + # Peripherals the chip has, that no driver reaches yet. [device.avc] support_status = "not_supported" [device.bit_scrambler] support_status = "not_supported" -[device.camera] -support_status = "not_supported" [device.dac] support_status = "not_supported" [device.ethernet] -support_status = "not_supported" +support_status = "partial" +mii_via_gpio_matrix = true +dma_burst_len = 16 +has_rgmii = true +rx_checksum_offload = true +tx_checksum_offload = false # TX FIFO is too small for store-and-forward insertion [device.etm] support_status = "not_supported" [device.i2c_slave] support_status = "not_supported" [device.i2s] -support_status = "not_supported" +support_status = "partial" +version = 3 +clock_configured_by_hp_sys_clkrst = true +mclk_divider_bit_width = 8 +max_ws_width = 512 +supports_pdm_rx_hp_filter = true +instances = [ + { + name = "i2s0", + sys_instance = "I2s0", + mclk = "I2S0_MCLK", + bclk = "I2S0O_BCK", + ws = "I2S0O_WS", + bclk_rx = "I2S0I_BCK", + ws_rx = "I2S0I_WS", + dout = ["I2S0O_SD", "I2S0O_SD1"], + din = ["I2S0I_SD", "I2S0I_SD1", "I2S0I_SD2", "I2S0I_SD3"], + pdm_tx = true, + pdm_rx = true, + pcm2pdm = true, + pdm2pcm = true, + }, + { + name = "i2s1", + sys_instance = "I2s1", + mclk = "I2S1_MCLK", + bclk = "I2S1O_BCK", + ws = "I2S1O_WS", + bclk_rx = "I2S1I_BCK", + ws_rx = "I2S1I_WS", + dout = ["I2S1O_SD"], + din = ["I2S1I_SD"], + pdm_tx = true, + pdm_rx = true, + }, +] [device.ieee802154] -support_status = "not_supported" [device.key_manager] support_status = "not_supported" [device.mcpwm] support_status = "not_supported" [device.pcnt] -support_status = "not_supported" +instances = { + PCNT = { + sys_instance = "Pcnt", + interrupt = "PCNT0", + units = [ + { sig_ch0 = "PCNT0_SIG_CH0", sig_ch1 = "PCNT0_SIG_CH1", ctrl_ch0 = "PCNT0_CTRL_CH0", ctrl_ch1 = "PCNT0_CTRL_CH1" }, + { sig_ch0 = "PCNT1_SIG_CH0", sig_ch1 = "PCNT1_SIG_CH1", ctrl_ch0 = "PCNT1_CTRL_CH0", ctrl_ch1 = "PCNT1_CTRL_CH1" }, + { sig_ch0 = "PCNT2_SIG_CH0", sig_ch1 = "PCNT2_SIG_CH1", ctrl_ch0 = "PCNT2_CTRL_CH0", ctrl_ch1 = "PCNT2_CTRL_CH1" }, + { sig_ch0 = "PCNT3_SIG_CH0", sig_ch1 = "PCNT3_SIG_CH1", ctrl_ch0 = "PCNT3_CTRL_CH0", ctrl_ch1 = "PCNT3_CTRL_CH1" }, + ], + }, + PCNT1 = { + sys_instance = "Pcnt1", + interrupt = "PCNT1", + units = [ + { sig_ch0 = "PCNT1_U0_SIG_CH0", sig_ch1 = "PCNT1_U0_SIG_CH1", ctrl_ch0 = "PCNT1_U0_CTRL_CH0", ctrl_ch1 = "PCNT1_U0_CTRL_CH1" }, + { sig_ch0 = "PCNT1_U1_SIG_CH0", sig_ch1 = "PCNT1_U1_SIG_CH1", ctrl_ch0 = "PCNT1_U1_CTRL_CH0", ctrl_ch1 = "PCNT1_U1_CTRL_CH1" }, + { sig_ch0 = "PCNT1_U2_SIG_CH0", sig_ch1 = "PCNT1_U2_SIG_CH1", ctrl_ch0 = "PCNT1_U2_CTRL_CH0", ctrl_ch1 = "PCNT1_U2_CTRL_CH1" }, + { sig_ch0 = "PCNT1_U3_SIG_CH0", sig_ch1 = "PCNT1_U3_SIG_CH1", ctrl_ch0 = "PCNT1_U3_CTRL_CH0", ctrl_ch1 = "PCNT1_U3_CTRL_CH1" }, + ], + }, +} [device.rgb_display] -support_status = "not_supported" +support_status = "partial" +output_lines = 24 [device.sdm] support_status = "partial" @@ -443,7 +534,9 @@ has_rx_demodulation = true [device.parl_io] support_status = "not_supported" -version = 1 # FIXME placeholder +version = 2 +max_data_width = 16 +has_tx_cs = true [device.sdmmc] support_status = "partial" @@ -473,16 +566,21 @@ slot_config = [ ## Radio [device.wifi] -support_status = "not_supported" -mac_version = 1 # FIXME: placeholder -csi_supported = true # FIXME: placeholder +support_status = "partial" +mac_version = 3 +has_wifi6 = true +csi_supported = true +has_nan = true +has_ftm = true [device.bt] -support_status = "not_supported" -controller = "npl" # FIXME: placeholder +support_status = "partial" +# IDF `porting_btdm` (nested config + `esp_*` VHCI), not the ESP32/C3/S3 OSI table +controller = "btdm2" [device.phy] -support_status = "not_supported" +support_status = "partial" +combo_module = false [device.ledc] support_status = "not_supported" @@ -494,6 +592,7 @@ support_status = "not_supported" ram_size = 20 # FIXME: placeholder [device.psram] +support_status = "partial" extmem_origin = 0x5000_0000 octal_spi = true diff --git a/esp-metadata/src/cfg.rs b/esp-metadata/src/cfg.rs index 78af7402eed..529288d705c 100644 --- a/esp-metadata/src/cfg.rs +++ b/esp-metadata/src/cfg.rs @@ -1,4 +1,5 @@ pub(crate) mod aes; +pub(crate) mod canfd; pub(crate) mod dma; pub(crate) mod ecc; pub(crate) mod gpio; @@ -6,6 +7,7 @@ pub(crate) mod i2c_master; pub(crate) mod i2s; pub(crate) mod interrupt; pub(crate) mod lp_io; +pub(crate) mod pcnt; pub(crate) mod rmt; pub(crate) mod rsa; pub(crate) mod sdm; @@ -19,6 +21,7 @@ pub(crate) mod timergroup; pub(crate) mod uart; pub(crate) use aes::*; +pub(crate) use canfd::*; pub(crate) use dma::*; pub(crate) use ecc::*; pub(crate) use gpio::*; @@ -26,6 +29,7 @@ pub(crate) use i2c_master::*; pub(crate) use i2s::*; pub(crate) use interrupt::*; pub(crate) use lp_io::*; +pub(crate) use pcnt::*; pub(crate) use rmt::*; pub(crate) use sdm::*; pub(crate) use sdmmc::*; @@ -37,7 +41,7 @@ pub(crate) use spi_slave::*; pub(crate) use timergroup::*; pub(crate) use uart::*; -use crate::support_status::{SupportStatus, SupportStatusLevel}; +use crate::support_status::{DriverStability, SupportStatus, SupportStatusLevel}; pub(crate) trait GenericProperty { fn cfgs(&self) -> Option> { @@ -110,6 +114,52 @@ pub(crate) struct PeriInstance { pub instance_config: I, } +/// Accepts either a sequence of `{ name, ... }` tables or a map keyed by instance name. +pub(crate) fn deserialize_peri_instances<'de, D, I>( + deserializer: D, +) -> Result>, D::Error> +where + D: serde::Deserializer<'de>, + I: serde::Deserialize<'de>, +{ + struct InstancesVisitor(core::marker::PhantomData); + + impl<'de, I: serde::Deserialize<'de>> serde::de::Visitor<'de> for InstancesVisitor { + type Value = Vec>; + + fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result { + formatter.write_str("a sequence or a map of peripheral instances") + } + + fn visit_seq
(self, mut seq: A) -> Result + where + A: serde::de::SeqAccess<'de>, + { + let mut instances = Vec::new(); + while let Some(instance) = seq.next_element()? { + instances.push(instance); + } + Ok(instances) + } + + fn visit_map(self, mut map: A) -> Result + where + A: serde::de::MapAccess<'de>, + { + let mut instances = Vec::new(); + while let Some((name, instance_config)) = map.next_entry()? { + instances.push(PeriInstance { + name, + instance_config, + }); + } + Ok(instances) + } + } + + deserializer.deserialize_any(InstancesVisitor(core::marker::PhantomData)) +} + /// A single cell in the peripheral support table. pub(crate) struct SupportItem { /// The human-readable name of the driver in the table (leftmost cell.) @@ -120,26 +170,35 @@ pub(crate) struct SupportItem { /// The heading of the table the driver is listed in. Groups are written in /// the order they first appear in. pub group: &'static str, + /// Driver-wide API stability status. + pub stability: DriverStability, /// If true, this driver is not shown in the peripheral support table. pub hide_from_peri_table: bool, } +fn default_cpu_pmp_granularity() -> Option { + Some(4) +} + /// Define driver configuration structs, and a PeriConfig struct /// that contains all of them. macro_rules! driver_configs { (@ignore $t:tt) => {}; - (@property (u32) $self:ident, $config:ident) => { Value::Number($self.$config) }; - (@property (bool) $self:ident, $config:ident) => { Value::Boolean($self.$config) }; - (@property (String) $self:ident, $config:ident) => { Value::String($self.$config.clone()) }; - (@property (Vec) $self:ident, $config:ident) => { Value::NumberList($self.$config.clone()) }; - (@property (Vec) $self:ident, $config:ident) => { Value::StringList($self.$config.clone()) }; - (@property (Option) $self:ident, $config:ident) => { Value::from($self.$config) }; - (@property ($($other:ty)*) $self:ident, $config:ident) => { Value::Generic(Box::new($self.$config.clone())) }; + (@property (u32) $self:ident, $config:ident) => { Value::Number($self.$config) }; + (@property (bool) $self:ident, $config:ident) => { Value::Boolean($self.$config) }; + (@property (String) $self:ident, $config:ident) => { Value::String($self.$config.clone()) }; + (@property (Vec) $self:ident, $config:ident) => { Value::NumberList($self.$config.clone()) }; + (@property (Vec) $self:ident, $config:ident) => { Value::StringList($self.$config.clone()) }; + (@property (Option) $self:ident, $config:ident) => { Value::from($self.$config) }; + (@property (Option) $self:ident, $config:ident) => { $self.$config.clone().map_or(Value::Unset, Value::String) }; + (@property ($($other:ty)*) $self:ident, $config:ident) => { Value::Generic(Box::new($self.$config.clone())) }; (@is_optional Option<$t:ty>) => { true }; (@is_optional $t:ty) => { false }; (@default $default:literal) => { $default }; (@default $default:literal $opt:literal) => { $opt }; + (@stability) => { DriverStability::Unstable }; + (@stability $stability:expr) => { $stability }; // Creates a single struct (@one @@ -159,6 +218,7 @@ macro_rules! driver_configs { // The list of peripherals for which this driver is implemented. // If empty, the driver supports a single instance only. #[serde(default)] + #[serde(deserialize_with = "deserialize_peri_instances")] pub instances: Vec)?>, $( $(#[$meta])* @@ -193,6 +253,8 @@ macro_rules! driver_configs { // Driver name, used in the generated documentation. name: $name:literal, + $(stability: $stability:expr,)? + $(hide_from_peri_table: $hide:literal,)? // When set, the type must provide `fn computed_properties(&self) -> impl Iterator`. @@ -228,6 +290,7 @@ macro_rules! driver_configs { name: $name, config_group: stringify!($driver), group: $table_group, + stability: driver_configs!(@stability $($stability)?), hide_from_peri_table: driver_configs!(@default false $($hide)?), }, )+)+ @@ -299,6 +362,7 @@ driver_configs![ GpioProperties { driver: gpio, name: "GPIO", + stability: DriverStability::Stable, has_computed_properties: true, properties: { /// Digital GPIO register-layout generation derived from the chip SVD. @@ -312,6 +376,15 @@ driver_configs![ remap_iomux_pin_registers: bool, #[serde(default)] // currently 0 in all devices func_in_sel_offset: u32, + /// Whether the digital pads must be isolated in software when a power domain that + /// feeds them is powered down (`SOC_GPIO_NEED_SOFT_ISOLATE_DURING_PD` in ESP-IDF). + /// + /// This is independent of `sleep.deep_sleep_needs_gpio_isolation`. That flag covers + /// chips that cannot hold a single pad through a deep sleep. This flag covers chips + /// that can hold a pad, but still leak current unless software disconnects the + /// unused digital pads. + #[serde(default)] + need_soft_isolate_during_pd: bool, #[serde(flatten)] pins_and_signals: GpioPinsAndSignals, @@ -351,6 +424,7 @@ driver_configs![ UartProperties { driver: uart, name: "UART", + stability: DriverStability::Stable, properties: { ram_size: u32, version: u32, @@ -382,6 +456,7 @@ driver_configs![ I2cMasterProperties { driver: i2c_master, name: "I2C master", + stability: DriverStability::Stable, properties: { /// Register-layout generation derived from the chip SVD. Also bumped when only the /// function clock configuration differs. @@ -449,6 +524,7 @@ driver_configs![ SpiMasterProperties { driver: spi_master, name: "SPI master", + stability: DriverStability::Stable, properties: { /// Register-layout generation derived from the chip SVD. version: u32, @@ -495,8 +571,6 @@ driver_configs![ properties: { /// Register-layout generation derived from the chip SVD. version: Option, - /// Default clock source selector written to the I2S clock source register. - default_clock_source: Option, /// Width of the MCLK divider field in the I2S clock register. mclk_divider_bit_width: Option, /// Largest WS divider value supported by the peripheral. @@ -521,8 +595,21 @@ driver_configs![ driver: parl_io, name: "PARL_IO", properties: { + /// Register block. + /// + /// `1` uses `tx_cfg0` and `rx_cfg0`, stores a byte length, and shares one interrupt. + /// `2` uses separate data, clock, and general registers, stores a bit length, and + /// has separate TX and RX interrupts. version: u32, - // TODO: model signal counts, RC CLK out capability, etc. + /// Number of data lines on the TX unit and on the RX unit. + /// + /// The driver accepts 8 and 16. + max_data_width: u32, + /// The TX unit has a dedicated chip-select output, `PARL_TX_CS`. + /// + /// When this is false, the most significant TX data line carries the valid signal. + #[serde(default)] + has_tx_cs: bool, } }, RmtProperties { @@ -574,7 +661,7 @@ driver_configs![ name: "TWAI", properties: {} }, - CanFdProperties { + CanFdProperties { driver: canfd, name: "CANFD", properties: {} @@ -619,6 +706,12 @@ driver_configs![ has_5g: bool, #[serde(default)] csi_supported: bool, + /// The Wi-Fi blobs contain Wi-Fi Aware (NAN) code (`SOC_WIFI_NAN_SUPPORT`). + #[serde(default)] + has_nan: bool, + /// The Wi-Fi blobs contain Fine Timing Measurement code (`SOC_WIFI_FTM_SUPPORT`). + #[serde(default)] + has_ftm: bool, } }, IeeeProperties { @@ -632,6 +725,26 @@ driver_configs![ properties: { #[serde(default)] mii_via_gpio_matrix: bool, + /// When true, the RX FIFO can hold a full frame and DMAOMR.RSF is + /// enabled so the DMA can drop FCS/length errors as complete frames. + #[serde(default)] + rx_store_and_forward: bool, + /// When true, Type-2 RX IP checksum offload (`MAC.config.IPC`) is + /// enabled and the driver inspects RDES4. False on chips whose COE + /// can false-positive on valid frames. + #[serde(default)] + rx_checksum_offload: bool, + /// When true, TX IP/TCP/UDP checksum insertion (`TDES0.CIC`) is + /// enabled and DMAOMR.TSF is set so the MAC sees the whole frame. + /// Requires a TX FIFO that can hold a full frame. + #[serde(default)] + tx_checksum_offload: bool, + /// Programmable DMA burst length (`DMABUSMODE.PBL`). A 32-beat burst + /// overflows the AXI bus on some chips. + dma_burst_len: u32, + /// When true, the MAC exposes RGMII (1000 Mbps) pads in addition to RMII/MII. + #[serde(default)] + has_rgmii: bool, } }, PhyProperties { @@ -666,7 +779,9 @@ driver_configs![ RgbProperties { driver: rgb_display, name: "RGB display", // LCD_CAM, ESP32 I2S, S2 I2S - properties: {} + properties: { + output_lines: u32, + } }, SpiLcdProperties { driver: spi_lcd, @@ -722,7 +837,30 @@ driver_configs![ AdcProperties { driver: adc, name: "ADC", - properties: {} + properties: { + #[serde(default)] + controller: Option, + #[serde(default)] + channel_count: Option, + + #[serde(default)] + line_calibration: bool, + #[serde(default)] + curve_calibration: bool, + #[serde(default)] + basic_calibration: bool, + #[serde(default)] + calibration_v1_scheme_supported: bool, + #[serde(default)] + channel_compensation: bool, + + #[serde(default)] + pcr_clock: bool, + #[serde(default)] + pcr_sar_clk_div: bool, + #[serde(default)] + sar_power_override: bool, + } }, AvcProperties { driver: avc, @@ -750,6 +888,7 @@ driver_configs![ LedcProperties { driver: ledc, name: "LEDC", + stability: DriverStability::Overhaul { issue: Some(2286) }, properties: { /// Register-layout generation derived from the chip SVD. version: u32, @@ -761,7 +900,7 @@ driver_configs![ name: "MCPWM", properties: {} }, - PcntProperties { + PcntProperties { driver: pcnt, name: "PCNT", properties: {} @@ -792,9 +931,13 @@ driver_configs![ timg_has_timer1: bool, #[serde(default)] timg_has_divcnt_rst: bool, + #[serde(default)] + wdt_has_conf_update: bool, #[serde(default)] rc_fast_calibration: Option, + #[serde(default)] + rc_slow_calibration: Option, } }, ] @@ -850,6 +993,7 @@ driver_configs![ RngProperties { driver: rng, name: "RNG", + stability: DriverStability::Stable, properties: { apb_cycle_wait_num: u32, #[serde(default)] @@ -909,6 +1053,13 @@ driver_configs![ /// Whether deep-sleep entry must isolate the digital pads to prevent a leakage current. #[serde(default)] deep_sleep_needs_gpio_isolation: bool, + /// CPU retention capabilities and reachable retention-memory bounds. + /// + /// Not `Option`: an absent table must emit no symbols at all, and an optional + /// property also emits `_is_set`, which would claim retention on the chips + /// that have none. `cfgs()` returns `None` when the table is empty. + #[serde(default)] + retention: SleepRetentionProperties, } }, UlpFsmProperties { @@ -962,6 +1113,7 @@ driver_configs![ properties: { status_registers: u32, controller: InterruptControllerProperties, + context_switch_source: ContextSwitchSource, #[serde(flatten)] software_interrupt_properties: SoftwareInterruptProperties, } @@ -977,6 +1129,11 @@ driver_configs![ entry_num: u32, } }, + FlashProperties { + driver: flash, + name: "Flash", + properties: {} + }, PsramProperties { driver: psram, name: "PSRAM", @@ -1012,6 +1169,10 @@ driver_configs![ cpu_has_branch_predictor: bool, #[serde(default)] cpu_has_csr_pc: bool, + // Interrupts can fire mid-instruction while mstatus.mie is cleared, masking them + // requires raising the interrupt threshold as well. + #[serde(default)] + cpu_has_zcmp_workaround: bool, #[serde(default)] multi_core_enabled: bool, #[serde(default)] @@ -1022,6 +1183,10 @@ driver_configs![ has_swd_watchdog: bool, #[serde(default)] cpu_mcause_mask: u32, + /// PMP address matching granularity, in bytes. + /// ESP-IDF: `SOC_CPU_PMP_REGION_GRANULARITY`. + #[serde(default = "default_cpu_pmp_granularity")] + cpu_pmp_granularity: Option, #[serde(flatten)] config: SocConfig, } diff --git a/esp-metadata/src/cfg/canfd.rs b/esp-metadata/src/cfg/canfd.rs new file mode 100644 index 00000000000..ab1a3794346 --- /dev/null +++ b/esp-metadata/src/cfg/canfd.rs @@ -0,0 +1,64 @@ +use proc_macro2::TokenStream; +use quote::{format_ident, quote}; + +use crate::{cfg::CanFdProperties, generate_for_each_macro}; + +/// Instance configuration, used in [device.canfd.instances] +#[derive(Debug, Default, Clone, serde::Deserialize, serde::Serialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct CanFdInstanceConfig { + /// The name of the instance in the `esp_hal::system::Peripheral` enum + pub sys_instance: String, + + /// IOMUX signal name of the instance's RX signal. + pub rx: String, + + /// IOMUX signal name of the instance's TX signal. + pub tx: String, +} + +/// Generates `for_each_canfd!` which can be used to implement the CAN FD +/// Instance trait for the relevant peripherals. The macro generates code +/// for each [device.canfd.instances[X]] instance. +pub(crate) fn generate_canfd_peripherals(canfd: &CanFdProperties) -> TokenStream { + let instance_cfgs = canfd + .instances + .iter() + .map(|instance| { + let instance_config = &instance.instance_config; + + let instance = format_ident!("{}", instance.name.to_uppercase()); + + let sys = format_ident!("{}", instance_config.sys_instance); + let rx = format_ident!("{}", instance_config.rx); + let tx = format_ident!("{}", instance_config.tx); + + // The order and meaning of these tokens must match their use in the + // `for_each_canfd!` call. + quote! { + #instance, #sys, #rx, #tx + } + }) + .collect::>(); + + let for_each = generate_for_each_macro("canfd", &[("all", &instance_cfgs)]); + quote! { + /// This macro can be used to generate code for each peripheral instance of the CAN FD driver. + /// + /// For an explanation on the general syntax, as well as usage of individual/repeated + /// matchers, refer to [the crate-level documentation][crate#for_each-macros]. + /// + /// This macro has one option for its "Individual matcher" case: + /// + /// Syntax: `($instance:ident, $sys:ident, $rx:ident, $tx:ident)` + /// + /// Macro fragments: + /// + /// - `$instance`: the name of the CAN FD instance + /// - `$sys`: the name of the instance as it is in the `esp_hal::system::Peripheral` enum. + /// - `$rx`, `$tx`: signal names. + /// + /// Example data: `(TWAI0, Twai0, TWAI0_RX, TWAI0_TX)` + #for_each + } +} diff --git a/esp-metadata/src/cfg/ecc.rs b/esp-metadata/src/cfg/ecc.rs index 26f2a159311..c0ba44c0cf8 100644 --- a/esp-metadata/src/cfg/ecc.rs +++ b/esp-metadata/src/cfg/ecc.rs @@ -18,7 +18,26 @@ struct WorkingModeEntry { #[serde(deny_unknown_fields)] struct CurveEntry { id: u32, - curve: u32, + curve: Curve, +} + +#[derive(Debug, Clone, Copy, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +enum Curve { + P192, + P256, + P384, + Sm2, +} + +impl Curve { + fn bits(self) -> u32 { + match self { + Self::P192 => 192, + Self::P256 | Self::Sm2 => 256, + Self::P384 => 384, + } + } } #[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] @@ -61,7 +80,7 @@ impl super::GenericProperty for EccDriverProperties { } for curve in self.curves.iter() { - cfgs.push(format!("ecc_has_curve_p{}", curve.curve)); + cfgs.push(format!("ecc_has_curve_{:?}", curve.curve).to_lowercase()); } Some(cfgs) @@ -71,7 +90,7 @@ impl super::GenericProperty for EccDriverProperties { let mem_block_size = self .curves .iter() - .map(|entry| entry.curve / 8) + .map(|entry| entry.curve.bits() / 8) .max() .unwrap(); @@ -102,9 +121,9 @@ impl super::GenericProperty for EccDriverProperties { .curves .iter() .map(|entry| { - let name = quote::format_ident!("P{}", entry.curve); + let name = quote::format_ident!("{}", format!("{:?}", entry.curve)); let id = crate::number(entry.id); - let curve = crate::number(entry.curve); + let curve = crate::number(entry.curve.bits()); quote::quote! { #id, #name, #curve } diff --git a/esp-metadata/src/cfg/gpio.rs b/esp-metadata/src/cfg/gpio.rs index 5cceed0b160..37b0e4d6c7c 100644 --- a/esp-metadata/src/cfg/gpio.rs +++ b/esp-metadata/src/cfg/gpio.rs @@ -227,7 +227,7 @@ impl FunctionMap { /// Returns the signal associated with the nth alternate function. /// /// Note that not all alternate functions are defined. The number of the - /// GPIO function is available separately. Not all alternate function have + /// GPIO function is available separately. Not all alternate functions have /// IO signals. pub fn get(&self, af: usize) -> Option<&str> { match af { @@ -470,9 +470,9 @@ pub(crate) fn generate_gpios( af: Option<&TokenStream>, lp_groups: Option<&TokenStream>, ) { - // Split "NAMEnumber" format fragments into the NAME and the number. The function - // returns `None` if the input string is not in this format. The NAME part can be - // empty (i.e. this function can return `Some("", number)`). + // Split `name` + `number` fragments (e.g. `UART0`) into the name and the number. + // The function returns `None` if the input string is not in this format. The name + // part can be empty (i.e. this function can return `Some("", number)`). fn split_signal_with_number(fragment: &str) -> Option<(&str, usize)> { // Find the first character that is not a letter. let Some(breakpoint) = fragment @@ -677,6 +677,7 @@ pub(crate) fn generate_gpios( let lp_functions_enum = render_lp_functions(gpio); let gpio_for_signal = render_gpio_for_signal(gpio); + let gpio_soft_isolate = render_gpio_soft_isolate(gpio); quote! { /// This macro can be used to generate code for each `GPIOn` instance. @@ -789,6 +790,8 @@ pub(crate) fn generate_gpios( #gpio_for_signal + #gpio_soft_isolate + /// Defines the `InputSignal` and `OutputSignal` enums. /// /// This macro is intended to be called in esp-hal only. @@ -838,6 +841,61 @@ pub(crate) fn generate_gpios( } } +/// Lists the digital pads that sleep entry isolates when `need_soft_isolate_during_pd` is set. +/// +/// The list is separate from `for_each_gpio`: it contains only the pads that software may +/// disconnect. Low-power pads keep their own supply, and flash or PSRAM pads must keep the memory +/// interface. +fn render_gpio_soft_isolate(gpio: &super::GpioProperties) -> TokenStream { + if !gpio.need_soft_isolate_during_pd { + return quote! {}; + } + + let pins = gpio + .pins_and_signals + .pins + .iter() + .filter(|pin| { + let has_lp = (0..LowPowerMap::COUNT).any(|af| pin.lp.get(af).is_some()); + let memory_interface = pin.limitations.iter().any(|limitation| { + matches!( + limitation, + PinLimitation::SpiFlash + | PinLimitation::OctalFlash + | PinLimitation::SpiPsram + | PinLimitation::OctalPsram + ) + }); + !has_lp && !memory_interface + }) + .map(|pin| number(pin.pin)) + .collect::>(); + + let for_each = generate_for_each_macro("gpio_soft_isolate", &[("all", &pins)]); + + quote! { + /// This macro can be used to generate code for each digital GPIO that deep-sleep entry + /// isolates when `gpio.need_soft_isolate_during_pd` is set. + /// + /// For an explanation on the general syntax, as well as usage of individual/repeated + /// matchers, refer to [the crate-level documentation][crate#for_each-macros]. + /// + /// The list excludes low-power pads and pads that interface with flash or PSRAM. Isolating + /// a memory-interface pad cuts instruction fetch. + /// + /// This macro has one option for its "Individual matcher" case: + /// + /// Syntax: `($n:literal)` + /// + /// Macro fragments: + /// + /// - `$n`: the number of the GPIO. For `GPIO8`, `$n` is 8. + /// + /// Example data: `(8)` + #for_each + } +} + /// Picks the pad to advertise out of the pads that can carry a signal. /// /// Pads are expected in ascending pin number order. Pads that need special attention are only diff --git a/esp-metadata/src/cfg/interrupt.rs b/esp-metadata/src/cfg/interrupt.rs index 274eab3a1ff..fc3bde85c05 100644 --- a/esp-metadata/src/cfg/interrupt.rs +++ b/esp-metadata/src/cfg/interrupt.rs @@ -31,6 +31,34 @@ impl GenericProperty for SoftwareInterruptProperties { } } +/// The interrupt that a CPU raises to switch tasks on itself. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ContextSwitchSource { + /// The `Software0` CPU-internal interrupt. + Software0, + /// The machine software interrupt of the CLINT. + Clint, + /// The `FROM_CPU_INTR0` peripheral interrupt. + FromCpu, + /// The inter-processor call, which the chip also uses for cross-core switches. + Ipc, +} + +/// Generates the `context_switch_source` cfg. +impl GenericProperty for ContextSwitchSource { + fn cfgs(&self) -> Option> { + let source = match self { + Self::Software0 => "software0", + Self::Clint => "clint", + Self::FromCpu => "from_cpu", + Self::Ipc => "ipc", + }; + + Some(vec![format!("context_switch_source=\"{source}\"")]) + } +} + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum RiscvFlavour { @@ -74,6 +102,12 @@ pub struct RiscvControllerProperties { interrupts: u32, /// Priority levels above 0 priority_levels: u32, + /// Takes the first direct-bindable interrupt line for the context switch. + /// + /// A chip whose CPU raises its own machine software interrupt takes the switch in a CLINT + /// line instead, and leaves every direct-bindable line to applications. + #[serde(default)] + context_switch_interrupt: bool, } impl RiscvControllerProperties { @@ -134,6 +168,7 @@ impl GenericProperty for InterruptControllerProperties { Reserved, Vector, Disabled, + ContextSwitch, } // interrupt number => class @@ -155,10 +190,19 @@ impl GenericProperty for InterruptControllerProperties { assert_ne!(classes[properties.disabled_interrupt()], Class::Vector); classes[properties.disabled_interrupt()] = Class::Disabled; + if properties.context_switch_interrupt { + let first = classes + .iter() + .position(|class| *class == Class::Interrupt) + .expect("No interrupt line is free for the context switch"); + classes[first] = Class::ContextSwitch; + } + let mut all = vec![]; let mut vector = vec![]; let mut reserved = vec![]; let mut direct_bindable = vec![]; + let mut context_switch = vec![]; for (i, class) in classes.iter().enumerate() { let intr_number = number(i); @@ -166,13 +210,14 @@ impl GenericProperty for InterruptControllerProperties { Class::Interrupt => direct_bindable.len(), Class::Vector => vector.len(), Class::Reserved => reserved.len(), - Class::Disabled => 0, + Class::Disabled | Class::ContextSwitch => 0, }); let class_name = match class { Class::Interrupt => format_ident!("direct_bindable"), Class::Vector => format_ident!("vector"), Class::Reserved => format_ident!("reserved"), Class::Disabled => format_ident!("disabled"), + Class::ContextSwitch => format_ident!("context_switch"), }; let tokens = quote! { [#class_name #idx_in_class] #intr_number }; @@ -182,6 +227,7 @@ impl GenericProperty for InterruptControllerProperties { Class::Interrupt => direct_bindable.push(tokens), Class::Vector => vector.push(tokens), Class::Reserved => reserved.push(tokens), + Class::ContextSwitch => context_switch.push(tokens), Class::Disabled => {} } } @@ -193,6 +239,7 @@ impl GenericProperty for InterruptControllerProperties { ("direct_bindable", &direct_bindable), ("vector", &vector), ("reserved", &reserved), + ("context_switch", &context_switch), ], ); diff --git a/esp-metadata/src/cfg/pcnt.rs b/esp-metadata/src/cfg/pcnt.rs new file mode 100644 index 00000000000..0fd5f4524bb --- /dev/null +++ b/esp-metadata/src/cfg/pcnt.rs @@ -0,0 +1,159 @@ +use std::collections::BTreeSet; + +use convert_case::{Case, Casing}; +use proc_macro2::TokenStream; +use quote::{format_ident, quote}; + +use crate::{cfg::PcntProperties, generate_for_each_macro, number}; + +/// Instance configuration, used in `[device.pcnt]` `instances = { ... }`. +/// +/// The map key is the PAC/virtual register-block singleton (`PCNT`, `PCNT1`). +#[derive(Debug, Default, Clone, serde::Deserialize, serde::Serialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct PcntInstanceConfig { + /// The name of the instance in the `esp_hal::system::Peripheral` enum. + pub sys_instance: String, + /// Shared peripheral interrupt for this register block. + pub interrupt: String, + /// Units in this register block, in hardware index order. + #[serde(default)] + pub units: Vec, +} + +/// GPIO matrix signals for one unit in a PCNT register block. +#[derive(Debug, Default, Clone, serde::Deserialize, serde::Serialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct PcntUnitSignals { + pub sig_ch0: String, + pub sig_ch1: String, + pub ctrl_ch0: String, + pub ctrl_ch1: String, +} + +/// Index of a PCNT register block: `PCNT` → 0, `PCNT1` → 1. +fn pcnt_block_index(regs: &str) -> u32 { + let Some(rest) = regs.strip_prefix("PCNT") else { + panic!("PCNT instance name must be `PCNT` or `PCNTn`, got {regs}"); + }; + if rest.is_empty() { + 0 + } else { + rest.parse() + .unwrap_or_else(|_| panic!("PCNT instance name must be `PCNT` or `PCNTn`, got {regs}")) + } +} + +pub(crate) fn singleton_name(regs: &str, unit: usize) -> String { + format!("PCNT{}_UNIT{unit}", pcnt_block_index(regs)) +} + +/// Generates `for_each_pcnt_unit!` which can be used to implement the PCNT +/// `Instance` trait for each unit singleton. +pub(crate) fn generate_pcnt_peripherals(pcnt: &PcntProperties) -> TokenStream { + let names = pcnt + .instances + .iter() + .flat_map(|instance| { + instance + .instance_config + .units + .iter() + .enumerate() + .map(|(unit, _)| { + let name = format_ident!("{}", singleton_name(&instance.name, unit)); + quote! { #name } + }) + }) + .collect::>(); + + let instance_cfgs = pcnt + .instances + .iter() + .flat_map(|instance| { + let cfg = &instance.instance_config; + instance + .instance_config + .units + .iter() + .enumerate() + .map(move |(unit, signals)| { + let peri = format_ident!("{}", singleton_name(&instance.name, unit)); + let variant = + format_ident!("{}", singleton_name(&instance.name, unit).to_case(Case::Pascal)); + let sys = format_ident!("{}", cfg.sys_instance); + let regs = format_ident!("{}", instance.name); + let unit = number(unit as u32); + let interrupt = format_ident!("{}", cfg.interrupt); + let sig_ch0 = format_ident!("{}", signals.sig_ch0); + let sig_ch1 = format_ident!("{}", signals.sig_ch1); + let ctrl_ch0 = format_ident!("{}", signals.ctrl_ch0); + let ctrl_ch1 = format_ident!("{}", signals.ctrl_ch1); + + quote! { + #peri, #variant, #sys, #regs, #unit, #interrupt, #sig_ch0, #sig_ch1, #ctrl_ch0, #ctrl_ch1 + } + }) + }) + .collect::>(); + + let mut seen = BTreeSet::new(); + let interrupts = pcnt + .instances + .iter() + .filter_map(|instance| { + let irq = &instance.instance_config.interrupt; + seen.insert(irq.clone()).then(|| { + let interrupt = format_ident!("{irq}"); + quote! { #interrupt } + }) + }) + .collect::>(); + + let mut seen = BTreeSet::new(); + let register_blocks = pcnt + .instances + .iter() + .filter_map(|instance| { + seen.insert(instance.name.clone()).then(|| { + let regs = format_ident!("{}", instance.name); + quote! { #regs } + }) + }) + .collect::>(); + + let for_each = generate_for_each_macro( + "pcnt_unit", + &[ + ("names", &names), + ("all", &instance_cfgs), + ("interrupt", &interrupts), + ("regs", ®ister_blocks), + ], + ); + + quote! { + /// This macro can be used to generate code for each PCNT unit. + /// + /// For an explanation on the general syntax, as well as usage of individual/repeated + /// matchers, refer to [the crate-level documentation][crate#for_each-macros]. + /// + /// This macro has four options for its "Individual matcher" case: + /// + /// - `names`: `($instance:ident)` + /// - `all`: `($peri:ident, $variant:ident, $sys:ident, $regs:ident, $unit:literal, $interrupt:ident, $sig_ch0:ident, $sig_ch1:ident, $ctrl_ch0:ident, $ctrl_ch1:ident)` + /// - `interrupt`: `($interrupt:ident)` (repeated: one ident per unique IRQ) + /// - `regs`: `($regs:ident)` (repeated: one ident per register block) + /// + /// Macro fragments: + /// + /// - `$peri`: unit singleton name (`PCNT0_UNIT0`, `PCNT1_UNIT0`, …) + /// - `$variant`: `AnyPcntUnit` enum variant (`Pcnt0Unit0`, `Pcnt1Unit0`, …) + /// - `$sys`: `esp_hal::system::Peripheral` variant for clocks + /// - `$regs`: register-block singleton (`PCNT`, `PCNT1`) + /// - `$unit`: hardware unit index within that register block + /// - `$interrupt`: shared peripheral interrupt + /// - `$sig_ch0`, `$sig_ch1`, `$ctrl_ch0`, `$ctrl_ch1`: GPIO matrix input signals + #for_each + } +} diff --git a/esp-metadata/src/cfg/sha.rs b/esp-metadata/src/cfg/sha.rs index 1882c275f07..3d94602fbc2 100644 --- a/esp-metadata/src/cfg/sha.rs +++ b/esp-metadata/src/cfg/sha.rs @@ -26,10 +26,11 @@ pub struct ShaAlgoMap { sha512_224: Option, sha512_256: Option, sha512_t: Option, + sm3: Option, } -impl super::GenericProperty for ShaAlgoMap { - fn macros(&self) -> Option { +impl ShaAlgoMap { + fn algorithms(&self) -> impl Iterator { let modes = [ ("SHA-1", self.sha1), ("SHA-224", self.sha224), @@ -39,12 +40,28 @@ impl super::GenericProperty for ShaAlgoMap { ("SHA-512/224", self.sha512_224), ("SHA-512/256", self.sha512_256), ("SHA-512/t", self.sha512_t), + ("SM3", self.sm3), ]; - let algos = modes + modes .into_iter() .filter_map(|(name, mode)| mode.map(|m| (name, m))) - .filter_map(|(name, mode)| ShaAlgo::new(name).map(|name| (name, mode))) + .filter_map(|(name, mode)| ShaAlgo::new(name).map(|algo| (algo, mode))) + } +} + +impl super::GenericProperty for ShaAlgoMap { + fn cfgs(&self) -> Option> { + Some( + self.algorithms() + .map(|(algo, _)| format!("sha_has_{}", algo.ident.to_string().to_lowercase())) + .collect(), + ) + } + + fn macros(&self) -> Option { + let algos = self + .algorithms() .map(|(algo, mode)| { let mode = number(mode); quote! { #algo, #mode } @@ -124,6 +141,15 @@ impl ShaAlgo { insecure_against_collision: false, insecure_against_length_extension: false, }, + Self { + name: "SM3", + ident: format_ident!("Sm3"), + digest_len: 32, + block_size: 64, + message_len_bytes: 8, + insecure_against_collision: false, + insecure_against_length_extension: true, + }, ]; for a in known { @@ -164,3 +190,25 @@ impl ToTokens for ShaAlgo { ); } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::cfg::GenericProperty; + + #[test] + fn cfgs_only_include_implemented_algorithms() { + let modes = ShaAlgoMap { + sha1: Some(0), + sha512_224: Some(5), + sha512_t: Some(7), + sm3: Some(14), + ..Default::default() + }; + + assert_eq!( + modes.cfgs().unwrap(), + ["sha_has_sha1", "sha_has_sha512_224", "sha_has_sm3"] + ); + } +} diff --git a/esp-metadata/src/cfg/sleep.rs b/esp-metadata/src/cfg/sleep.rs index 464dfdd4d65..00929c804df 100644 --- a/esp-metadata/src/cfg/sleep.rs +++ b/esp-metadata/src/cfg/sleep.rs @@ -3,7 +3,98 @@ use indexmap::IndexMap; use quote::{format_ident, quote}; use serde::{Deserialize, Serialize}; -use crate::{generate_for_each_macro, number}; +use crate::{cfg::GenericProperty, generate_for_each_macro, number}; + +/// Light-sleep CPU retention capabilities and memory placement constraints. +/// +/// Declared in `[device.sleep.retention]` so these keys are not captured by +/// [`WakeupSources`]'s flattened wakeup-source map. +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct SleepRetentionProperties { + /// How the chip retains CPU state across light sleep with CPU power-down. + cpu_retention: Option, + /// Register context frame shape for software CPU retention. + cpu_retention_frame: Option, + #[serde(default)] + supports_top_power_down: bool, + #[serde(default)] + supports_tagmem_power_down: bool, + /// Bytes the CPU frames need, including the DMA descriptor that precedes them. + /// + /// The size is the mark that esp-hal describes the frames of this chip, so it also drives the + /// `supports_cpu_power_down` cfg. A chip that has the hardware but no frame layout keeps the + /// CPU domain powered. + cpu_retention_mem_size: Option, + cpu_retention_mem_align: Option, + /// First address the retention DMA can reach. + cpu_retention_mem_start: Option, + /// First address past the range the retention DMA can reach. + cpu_retention_mem_end: Option, +} + +impl GenericProperty for SleepRetentionProperties { + fn cfgs(&self) -> Option> { + let mut cfgs = vec![]; + + if let Some(mode) = &self.cpu_retention { + cfgs.push(format!("cpu_retention=\"{mode}\"")); + } + if let Some(frame) = &self.cpu_retention_frame { + cfgs.push(format!("cpu_retention_frame=\"{frame}\"")); + } + if self.cpu_retention.is_some() { + cfgs.push("supports_cpu_power_down".to_string()); + } + if self.supports_top_power_down { + cfgs.push("supports_top_power_down".to_string()); + } + if self.supports_tagmem_power_down { + cfgs.push("supports_tagmem_power_down".to_string()); + } + + if cfgs.is_empty() { None } else { Some(cfgs) } + } + + fn property_macro_branches(&self) -> proc_macro2::TokenStream { + let mut branches = quote! {}; + + if let Some(size) = self.cpu_retention_mem_size { + let size = number(size); + branches.extend(quote! { + ("sleep.cpu_retention_mem_size") => { + #size + }; + }); + } + if let Some(align) = self.cpu_retention_mem_align { + let align = number(align); + branches.extend(quote! { + ("sleep.cpu_retention_mem_align") => { + #align + }; + }); + } + if let Some(start) = self.cpu_retention_mem_start { + let start = number(start); + branches.extend(quote! { + ("sleep.cpu_retention_mem_start") => { + #start + }; + }); + } + if let Some(end) = self.cpu_retention_mem_end { + let end = number(end); + branches.extend(quote! { + ("sleep.cpu_retention_mem_end") => { + #end + }; + }); + } + + branches + } +} /// The set of wakeup sources supported by a chip. /// diff --git a/esp-metadata/src/cfg/soc.rs b/esp-metadata/src/cfg/soc.rs index 1bd7ba340d5..c8bc3ab51a2 100644 --- a/esp-metadata/src/cfg/soc.rs +++ b/esp-metadata/src/cfg/soc.rs @@ -141,7 +141,69 @@ pub struct SystemClocks { #[serde(deny_unknown_fields)] struct ClockGroup { group: String, - clocks: Vec, + /// Reusable node definitions for this group. Map keys are preset names (TOML 1.1). + #[serde(default)] + presets: IndexMap, + clocks: Vec, +} + +/// A clock in a template group: a full node, or an instantiation of a group preset. +#[derive(Debug, Clone, Deserialize)] +#[serde(untagged)] +enum GroupClock { + Inline(ClockTreeItem), + Preset(PresetClockRef), +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +struct PresetClockRef { + name: String, + preset: String, + #[serde(default)] + wake_locking: Option, + #[serde(default)] + always_on: Option, +} + +struct ResolvedGroupClock { + item: ClockTreeItem, + /// Name used to generate `*Config` types (`CLK` → `ParlIoClkConfig`). + config_type_stem: String, +} + +impl ClockGroup { + fn resolved_clocks(&self) -> Result> { + self.clocks + .iter() + .map(|clock| match clock { + GroupClock::Inline(item) => Ok(ResolvedGroupClock { + config_type_stem: item.name().to_string(), + item: item.clone(), + }), + GroupClock::Preset(inst) => { + let mut item = self.presets.get(&inst.preset).cloned().ok_or_else(|| { + anyhow::anyhow!( + "Clock group `{}` has no preset `{}`", + self.group, + inst.preset + ) + })?; + item.set_name(inst.name.clone()); + if let Some(wake_locking) = inst.wake_locking { + item.set_wake_locking(wake_locking); + } + if let Some(always_on) = inst.always_on { + item.set_always_on(always_on); + } + Ok(ResolvedGroupClock { + item, + config_type_stem: inst.preset.clone(), + }) + } + }) + .collect() + } } pub(crate) struct ProcessedClockData { @@ -177,6 +239,10 @@ pub(crate) struct ClockTreeNodeInstance { /// Must be in CONSTANT_CASE, e.g. UART. group_template: String, + /// Stem for the generated config type. For a preset instantiation this is the preset name + /// (e.g. `CLK` → `ParlIoClkConfig`), otherwise the template node name. + config_type_stem: String, + properties: ManagementProperties, } @@ -262,6 +328,21 @@ impl ClockTreeNodeInstance { } } + /// Frequency of this node when it can be evaluated without an instance receiver. + /// + /// Non-configurable per-instance nodes still have a closed-form formula (for example a + /// fixed divider from a system clock), so their frequency can be inlined even though + /// `try_frequency_call` rejects the method form that takes `self`. + fn try_frequency_expr(&self, tree: &ProcessedClockData) -> Option { + if let Some(freq) = self.try_frequency_call() { + return Some(freq); + } + if !self.is_configurable() { + return Some(self.node_frequency_impl(tree, &[])); + } + None + } + fn always_on(&self) -> bool { self.node.always_on() } @@ -277,7 +358,11 @@ impl ClockTreeNodeInstance { /// Returns the name of the clock configuration type. The corresponding field in the /// `ClockConfig` struct will have this type. fn config_type_name(&self) -> Ident { - clock_tree::config_type_name(&self.group_template, self.node.name()) + clock_tree::config_type_name(&self.group_template, &self.config_type_stem) + } + + pub(crate) fn config_type_stem(&self) -> &str { + &self.config_type_stem } fn apply_configuration( @@ -342,6 +427,10 @@ impl ClockTreeNodeInstance { self.suffix_function("frequency") } + fn rustc_cfg_attr(&self) -> TokenStream { + clock_tree::rustc_cfg_attr(self.node.rustc_cfg()) + } + fn config_frequency_function_name(&self) -> Ident { self.suffix_function("config_frequency") } @@ -350,6 +439,15 @@ impl ClockTreeNodeInstance { self.suffix_function("source_frequency") } + fn root_source_function_name(&self) -> Ident { + self.suffix_function("root_source") + } + + /// Returns the name this node has as a variant of the `ClockSource` enum. + fn clock_source_variant_name(&self) -> Ident { + format_ident!("{}", self.name().to_case(Case::Pascal)) + } + fn config_apply_function_name(&self) -> Ident { self.prefix_function("configure") } @@ -366,6 +464,15 @@ impl ClockTreeNodeInstance { format_ident!("{}_FREQ_CACHE", self.node_ident_base()) } + fn adjusted_frequency_static_name(&self) -> Ident { + format_ident!("{}_FREQUENCY", self.node_ident_base()) + } + + /// Returns true if the node needs a function that refreshes its downstream frequency caches. + fn has_refresh_downstream_function(&self) -> bool { + self.is_configurable() || self.node.adjustable_range().is_some() + } + pub(super) fn refresh_downstream_function_name(&self) -> Ident { format_ident!( "refresh_{}_downstream", @@ -409,7 +516,7 @@ impl ClockTreeNodeInstance { let request_direct_dependencies = self.node.request_direct_dependencies(self, tree); let release_direct_dependencies = self.node.release_direct_dependencies(self, tree); - // Only configurables have an apply fn + // Only configurable clock nodes have an apply fn let apply_fn = ty_name .as_ref() .map(|_| self.node.config_apply_function(self, tree)); @@ -439,6 +546,18 @@ impl ClockTreeNodeInstance { } } } + SourceFrequencySignature::SameAsConfig => { + let path = if receiver.is_empty() { + quote! {} + } else { + quote! { Self:: } + }; + quote! { + pub fn #source_frequency_function_name(source: #ty_name) -> u32 { + #path #config_frequency_function_name(source) + } + } + } SourceFrequencySignature::Selector { param_type, param_name, @@ -489,6 +608,7 @@ impl ClockTreeNodeInstance { } else { None }, + cfg: self.node.rustc_cfg().map(str::to_string), request: Function { _name: request_fn_name.to_string(), implementation: if always_on { @@ -510,7 +630,6 @@ impl ClockTreeNodeInstance { } else if self.properties.has_enable() { quote! { pub fn #request_fn_name(#(#receiver,)* clocks: &mut ClockTree) { - trace!(#request_trace); trace!(#enable_trace); #request_direct_dependencies #(#receiver.)* #enable_fn_impl_name(clocks, true); @@ -546,7 +665,6 @@ impl ClockTreeNodeInstance { } else if self.properties.has_enable() { quote! { pub fn #release_fn_name(#(#receiver,)* clocks: &mut ClockTree) { - trace!(#release_trace); trace!(#disable_trace); #(#receiver.)* #enable_fn_impl_name(clocks, false); #release_direct_dependencies @@ -588,7 +706,6 @@ impl ClockTreeNodeInstance { #[allow(unused_variables)] pub fn #config_frequency_function_name( #(#config_fn_self,)* - clocks: &mut ClockTree, config: #ty_name, ) -> u32 { #frequency_function_impl @@ -608,10 +725,8 @@ impl ClockTreeNodeInstance { let config_fn_self = needs_instance.then_some(quote! { self }).into_iter(); quote! { - #[allow(unused_variables)] pub fn #config_frequency_function_name( #(#config_fn_self,)* - clocks: &mut ClockTree, config: #ty_name, ) -> u32 { #frequency_function_impl @@ -621,6 +736,45 @@ impl ClockTreeNodeInstance { #cache_load } } + } else if let Some((min, max)) = self.node.adjustable_range() { + let static_name = self.adjusted_frequency_static_name(); + let nominal_function_name = self.suffix_function("nominal_frequency"); + let set_function_name = self.prefix_function("set"); + let set_function_name = format_ident!("{set_function_name}_frequency"); + let refresh_fn = self.refresh_downstream_function_name(); + let out_of_range_msg = format!( + "Ignoring out-of-range {} frequency: {{}} Hz", + self.name_str() + ); + let update_msg = format!( + "Updating {} frequency to {{}} Hz (nominal {{}} Hz)", + self.name_str() + ); + let min = number(min); + let max = number(max); + + quote! { + static #static_name: ::core::sync::atomic::AtomicU32 = + ::core::sync::atomic::AtomicU32::new(#nominal_function_name()); + + pub const fn #nominal_function_name() -> u32 { + #frequency_function_impl + } + + pub fn #frequency_function_name() -> u32 { + #static_name.load(::core::sync::atomic::Ordering::Acquire) + } + + pub fn #set_function_name(clocks: &mut ClockTree, frequency: u32) { + if !(#min..=#max).contains(&frequency) { + warn!(#out_of_range_msg, frequency); + return; + } + debug!(#update_msg, frequency, #nominal_function_name()); + #static_name.store(frequency, ::core::sync::atomic::Ordering::Release); + #refresh_fn(clocks); + } + } } else { quote! { pub fn #frequency_function_name(#(#receiver)*) -> u32 { @@ -718,10 +872,11 @@ impl SystemClocks { let mut clock_tree_state_field_initializers = vec![]; let mut clock_tree_refcount_field_decls = vec![]; let mut clock_tree_refcount_field_inits = vec![]; - let mut configurables = vec![]; + let mut configurable_fields = vec![]; let mut system_config_steps = HashMap::new(); let mut first_instances = HashSet::new(); + let mut emitted_config_types = HashSet::new(); let mut instance_enums = Vec::new(); for (group_template, instances) in tree.group_instances.iter() { @@ -752,8 +907,16 @@ impl SystemClocks { clock_item.node.name() )); if is_first_instance { + let cfg_attr = clock_item.rustc_cfg_attr(); if clock_item.emits_config_type(tree) { - clock_tree_node_defs.push(clock_item.config_type()); + let type_key = clock_item.config_type_name().to_string(); + if emitted_config_types.insert(type_key) { + let config_type = clock_item.config_type(); + clock_tree_node_defs.push(quote! { + #cfg_attr + #config_type + }); + } } let instance_count = @@ -765,13 +928,23 @@ impl SystemClocks { if let Some(refcount_field) = clock_item.properties.refcount_field() { if let Some(instance_count) = instance_count.as_ref() { - clock_tree_refcount_field_decls - .push(quote! { #refcount_field: [u32; #instance_count] }); - clock_tree_refcount_field_inits - .push(quote! { #refcount_field: [0; #instance_count] }); + clock_tree_refcount_field_decls.push(quote! { + #cfg_attr + #refcount_field: [u32; #instance_count] + }); + clock_tree_refcount_field_inits.push(quote! { + #cfg_attr + #refcount_field: [0; #instance_count] + }); } else { - clock_tree_refcount_field_decls.push(quote! { #refcount_field: u32 }); - clock_tree_refcount_field_inits.push(quote! { #refcount_field: 0 }); + clock_tree_refcount_field_decls.push(quote! { + #cfg_attr + #refcount_field: u32 + }); + clock_tree_refcount_field_inits.push(quote! { + #cfg_attr + #refcount_field: 0 + }); } } @@ -827,6 +1000,12 @@ impl SystemClocks { if func.is_empty() { continue; } + if let Some(cfg) = clock_item.node.rustc_cfg() { + let cfg_doc = format!(" #[cfg({cfg})]"); + doclines.push(quote! { + #[doc = #cfg_doc] + }); + } let func = func.to_string(); doclines.push(quote! { #[doc = #func] @@ -861,7 +1040,10 @@ impl SystemClocks { quote! { #(#[doc = #doc])* } }); - configurables.push(quote! { + let cfg_attr = clock_item.rustc_cfg_attr(); + + configurable_fields.push(quote! { + #cfg_attr #docline pub #name: Option<#config_type_name>, }); @@ -869,6 +1051,7 @@ impl SystemClocks { system_config_steps.insert( clock_item.name_str(), quote! { + #cfg_attr if let Some(config) = self.#name { #config_apply_function_name(clocks, config); } @@ -942,6 +1125,7 @@ impl SystemClocks { let cache_name = node.freq_cache_static_name(); let config_freq_fn = node.config_frequency_function_name(); + let cfg_attr = node.rustc_cfg_attr(); if node.properties.receiver.is_some() { let instances = tree.group_instances.get(&node.group_template).unwrap(); @@ -955,14 +1139,15 @@ impl SystemClocks { ); freq_cache_statics.push(quote! { + #cfg_attr static #cache_name: [::core::sync::atomic::AtomicU32; #instance_count] = [const { ::core::sync::atomic::AtomicU32::new(0) }; #instance_count]; }); // Refresh stmt for template nodes uses an `instance` variable (passed by caller). let config_freq_call = if node.config_frequency_needs_instance(tree) { - quote! { instance.#config_freq_fn(clocks, config) } + quote! { instance.#config_freq_fn(config) } } else { - quote! { #instance_type::#config_freq_fn(clocks, config) } + quote! { #instance_type::#config_freq_fn(config) } }; refresh_stmt_by_key.insert( template_key.clone(), @@ -979,6 +1164,7 @@ impl SystemClocks { let config_field = node.properties.indexed_config_accessor(); freq_cache_statics.push(quote! { + #cfg_attr static #cache_name: ::core::sync::atomic::AtomicU32 = ::core::sync::atomic::AtomicU32::new(0); }); @@ -987,7 +1173,7 @@ impl SystemClocks { quote! { if let Some(config) = #config_field { #cache_name.store( - #config_freq_fn(clocks, config), + #config_freq_fn(config), ::core::sync::atomic::Ordering::Release, ); } @@ -1025,7 +1211,7 @@ impl SystemClocks { let Some(node) = tree.try_get_node(&node_name) else { continue; }; - if !node.is_configurable() { + if !node.has_refresh_downstream_function() { continue; } @@ -1037,6 +1223,7 @@ impl SystemClocks { let fn_name = node.refresh_downstream_function_name(); let self_stmt = refresh_stmt_by_key.get(&template_key).cloned(); + let cfg_attr = node.rustc_cfg_attr(); // Build calls to direct configurable children's refresh functions. let children = tree @@ -1077,6 +1264,7 @@ impl SystemClocks { child_calls.push(template_group_loop(tree, group, &fns)); } downstream_refresh_fns.push(quote! { + #cfg_attr fn #fn_name(clocks: &mut ClockTree, instance: #enum_name) { #self_stmt #(#child_calls)* @@ -1107,6 +1295,7 @@ impl SystemClocks { child_calls.push(template_group_loop(tree, group, &fns)); } downstream_refresh_fns.push(quote! { + #cfg_attr fn #fn_name(clocks: &mut ClockTree) { #self_stmt #(#child_calls)* @@ -1115,6 +1304,123 @@ impl SystemClocks { } } + // The clock source each node runs on. Sleep code keeps the answer powered, so that a + // peripheral which must keep running through a sleep does not have to know what feeds it. + let mut clock_source_variants: Vec = vec![]; + let mut root_source_fns: Vec = vec![]; + let mut resolvable_nodes: HashSet = HashSet::new(); + + for node_name in tree.dependency_graph.iter() { + let Some(node) = tree.try_get_node(&node_name) else { + continue; + }; + + // A node of a template group has one configuration per instance, and nothing needs a + // clock of one through a sleep yet. + if node.properties.receiver.is_some() { + continue; + } + + let cfg_attr = node.rustc_cfg_attr(); + let fn_name = node.root_source_function_name(); + let docline = format!( + " Returns the clock source that `{}` currently runs on.", + node.name_str() + ); + + // Resolve an upstream node to the call that answers for it, or give up if that node + // has no answer itself. + let upstream_call = |name: &str| { + let upstream = node.resolve_node(tree, name); + resolvable_nodes + .contains(upstream.name_str()) + .then(|| upstream.root_source_function_name()) + }; + + // A source answers without reading the tree. + let mut param = quote! { clocks }; + + let body = match node.node.root_source(node, tree) { + clock_tree::RootSource::Itself => { + let variant = node.clock_source_variant_name(); + let docline = format!(" `{}`.", node.name_str()); + clock_source_variants.push(quote! { + #cfg_attr + #[doc = #docline] + #variant, + }); + + param = quote! { _clocks }; + quote! { Some(ClockSource::#variant) } + } + clock_tree::RootSource::PassThrough(upstream) => { + let Some(call) = upstream_call(&upstream) else { + continue; + }; + quote! { #call(clocks) } + } + // A selector with a single option has no configuration to read. + clock_tree::RootSource::Selector { arms, .. } if !node.is_configurable() => { + let [arm] = arms.as_slice() else { + continue; + }; + let Some(call) = upstream_call(&arm.upstream) else { + continue; + }; + quote! { #call(clocks) } + } + clock_tree::RootSource::Selector { subject, arms } => { + let mut branches = Vec::with_capacity(arms.len()); + for arm in arms.iter() { + let Some(call) = upstream_call(&arm.upstream) else { + break; + }; + let cfg_attr = &arm.cfg_attr; + let pattern = &arm.pattern; + branches.push(quote! { #cfg_attr #pattern => #call(clocks), }); + } + if branches.len() != arms.len() { + continue; + } + + let config_field = node.properties.indexed_config_accessor(); + quote! { + let config = #config_field?; + match #subject { + #(#branches)* + } + } + } + clock_tree::RootSource::Unknown => continue, + }; + + resolvable_nodes.insert(node.name_str().clone()); + root_source_fns.push(quote! { + #cfg_attr + #[doc = #docline] + pub fn #fn_name(#param: &mut ClockTree) -> Option { + #body + } + }); + } + + // A chip without a clock tree has no sources to name, and an empty enum is not useful. + let clock_sources = (!clock_source_variants.is_empty()).then(|| { + quote! { + /// The clock sources of the device. + /// + /// A clock source is a node of the clock tree that other nodes derive their output + /// from. Ask a node which source it runs on with its `..._root_source` function. + #[derive(Debug, enumset::EnumSetType)] + #[cfg_attr(feature = "defmt", derive(defmt::Format))] + pub enum ClockSource { + #(#clock_source_variants)* + } + + #(#root_source_fns)* + } + }); + Ok(quote! { #[macro_export] /// ESP-HAL must provide implementation for the following functions: @@ -1153,6 +1459,8 @@ impl SystemClocks { #(#freq_cache_statics)* + #clock_sources + #(#clock_tree_node_impls)* /// Clock tree configuration. @@ -1166,7 +1474,7 @@ impl SystemClocks { #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[instability::unstable] pub struct ClockConfig { - #(#configurables)* + #(#configurable_fields)* } impl ClockConfig { @@ -1202,17 +1510,29 @@ impl SystemClocks { "{path}.{}", node.name().from_case(Case::Constant).to_case(Case::Snake) ); - node.property_macro_branches(&path, "") + node.property_macro_branches(&path, "", node.name()) })); branches.extend(self.template_groups.iter().flat_map(|group| { - group.clocks.iter().map(|node| { - let path = format!( - "{path}.{}.{}", - group.group.from_case(Case::Constant).to_case(Case::Snake), - node.name().from_case(Case::Constant).to_case(Case::Snake) - ); - node.property_macro_branches(&path, &group.group) - }) + group + .resolved_clocks() + .unwrap_or_else(|err| panic!("{err}")) + .into_iter() + .map(|resolved| { + let path = format!( + "{path}.{}.{}", + group.group.from_case(Case::Constant).to_case(Case::Snake), + resolved + .item + .name() + .from_case(Case::Constant) + .to_case(Case::Snake) + ); + resolved.item.property_macro_branches( + &path, + &group.group, + &resolved.config_type_stem, + ) + }) })); branches } @@ -1465,6 +1785,7 @@ impl DeviceClocks { name: name.clone(), group_instance: String::new(), group_template: String::new(), + config_type_stem: name.clone(), properties: ManagementProperties { name: format_ident!( "{}", @@ -1495,15 +1816,15 @@ impl DeviceClocks { // A peripheral can have any number of clock sources. We'll turn them into clock tree // nodes here. - for def in self + for resolved in self .system_clocks .template_groups .iter() .find(|g| g.group == *group_name) .ok_or_else(|| anyhow::anyhow!("Clock group {group_name} not found"))? - .clocks - .iter() + .resolved_clocks()? { + let def = &resolved.item; let name = format!("{peri_name}_{}", def.name()); let instance_ty = format_ident!( "{}Instance", @@ -1519,6 +1840,7 @@ impl DeviceClocks { name: name.clone(), group_instance: peri_name.clone(), group_template: group_name.clone(), + config_type_stem: resolved.config_type_stem.clone(), properties: ManagementProperties { name: format_ident!( "{}", @@ -1666,8 +1988,14 @@ impl DeviceClocks { push_node_cfgs(node.name().to_string(), node); } for group in config.clocks.system_clocks.template_groups.iter() { - for node in group.clocks.iter() { - push_node_cfgs(format!("{}_{}", group.group, node.name()), node); + for resolved in group + .resolved_clocks() + .unwrap_or_else(|err| panic!("{err}")) + { + push_node_cfgs( + format!("{}_{}", group.group, resolved.item.name()), + &resolved.item, + ); } } diff --git a/esp-metadata/src/cfg/soc/clock_tree.rs b/esp-metadata/src/cfg/soc/clock_tree.rs index 251f03347c5..a7ddf6d75ba 100644 --- a/esp-metadata/src/cfg/soc/clock_tree.rs +++ b/esp-metadata/src/cfg/soc/clock_tree.rs @@ -64,6 +64,17 @@ mod generic; mod mux; mod source; +/// Builds `#[cfg(...)]` from a metadata `cfg` property, or an empty token stream. +pub(crate) fn rustc_cfg_attr(cfg: Option<&str>) -> TokenStream { + let Some(cfg) = cfg.filter(|cfg| !cfg.is_empty()) else { + return quote! {}; + }; + let cfg = TokenStream::from_str(cfg).unwrap_or_else(|err| { + panic!("Invalid clock-tree `cfg` expression `{cfg}`: {err}"); + }); + quote! { #[cfg(#cfg)] } +} + /// Returns the name of the config type generated for a node. /// /// `group` is the template group the node belongs to, or an empty string for standalone nodes. @@ -87,9 +98,40 @@ pub(crate) struct Function { pub implementation: TokenStream, } +/// One arm of a [`RootSource::Selector`]. +pub(crate) struct RootSourceArm { + /// The `#[cfg(...)]` of the selected option, if it has one. + pub cfg_attr: TokenStream, + /// The configuration value that selects this arm. + pub pattern: TokenStream, + /// The name of the node this arm selects. + pub upstream: String, +} + +/// How a clock tree node reaches the clock source it runs on. +pub(crate) enum RootSource { + /// The node is a clock source. + Itself, + + /// The node always runs on the output of one other node. + PassThrough(String), + + /// The node's configuration selects which other node it runs on. + Selector { + /// The value to match, with the node's configuration in scope as `config`. + subject: TokenStream, + arms: Vec, + }, + + /// The node cannot answer. + Unknown, +} + pub(crate) enum SourceFrequencySignature { Skip, Parameterless(TokenStream), + /// Same signature and result as the node's `config_frequency` function. + SameAsConfig, Selector { param_type: TokenStream, param_name: Ident, @@ -99,6 +141,7 @@ pub(crate) enum SourceFrequencySignature { pub(crate) struct ClockNodeFunctions { pub impl_type: Option, + pub cfg: Option, pub request: Function, pub release: Function, @@ -112,12 +155,24 @@ pub(crate) struct ClockNodeFunctions { impl ClockNodeFunctions { pub fn implement_functions(&self) -> TokenStream { - let request_impl = &self.request.implementation; - let release_impl = &self.release.implementation; - let apply_impl = &self.apply_config.implementation; - let current_config_impl = &self.current_config.implementation; - let frequency_impl = &self.frequency.implementation; - let source_frequency_impl = &self.source_frequency.implementation; + let cfg_attr = rustc_cfg_attr(self.cfg.as_deref()); + let wrap = |implementation: &TokenStream| { + if implementation.is_empty() { + quote! {} + } else { + quote! { + #cfg_attr + #implementation + } + } + }; + + let apply_impl = wrap(&self.apply_config.implementation); + let current_config_impl = wrap(&self.current_config.implementation); + let request_impl = wrap(&self.request.implementation); + let release_impl = wrap(&self.release.implementation); + let frequency_impl = wrap(&self.frequency.implementation); + let source_frequency_impl = wrap(&self.source_frequency.implementation); quote! { #apply_impl @@ -435,6 +490,12 @@ pub(crate) trait ClockTreeNodeType: Any { Bounds::UNKNOWN } + /// Returns the range (`min`, `max`) that the node's frequency can be adjusted to at runtime, + /// or `None` if the node is not adjustable. + fn adjustable_range(&self) -> Option<(u32, u32)> { + None + } + /// Returns which clock nodes' configurations are affected when this node is configured. // TODO: pass instance to apply template naming scheme to returned clocks // (e.g. FUNCTION_CLOCK -> UART0_FUNCTION_CLOCK) @@ -450,6 +511,19 @@ pub(crate) trait ClockTreeNodeType: Any { vec![] } + /// Returns how the node reaches the clock source it runs on. + /// + /// Sleep code needs this to keep a clock running through a sleep: it asks a node for the source + /// it currently runs on, and keeps that source powered. The default implementation has no + /// answer, which leaves the node without a getter. + fn root_source( + &self, + _instance: &ClockTreeNodeInstance, + _tree: &ProcessedClockData, + ) -> RootSource { + RootSource::Unknown + } + fn always_on(&self) -> bool { false } @@ -552,9 +626,22 @@ pub(crate) trait ClockTreeNodeType: Any { /// /// `group` is the name of the template group the node belongs to, or an empty string for /// standalone nodes. It is needed to reconstruct the names of the generated config types. - fn property_macro_branches(&self, _path: &str, _group: &str) -> TokenStream { + /// + /// `config_type_stem` is the clock name used in the generated config type (`PARL_IO` + `CLK` → + /// `ParlIoClkConfig`). For a preset instantiation this is the preset name, not the node name. + fn property_macro_branches( + &self, + _path: &str, + _group: &str, + _config_type_stem: &str, + ) -> TokenStream { quote! {} } + + /// Optional `#[cfg(...)]` expression that disables this node when false. + fn rustc_cfg(&self) -> Option<&str> { + None + } } /// Represents a clock tree item. @@ -602,12 +689,52 @@ impl ClockTreeItem { } } - pub(crate) fn property_macro_branches(&self, path: &str, group: &str) -> TokenStream { + pub(crate) fn property_macro_branches( + &self, + path: &str, + group: &str, + config_type_stem: &str, + ) -> TokenStream { + match self { + ClockTreeItem::Multiplexer(mux) => { + mux.property_macro_branches(path, group, config_type_stem) + } + ClockTreeItem::Source(src) => { + src.property_macro_branches(path, group, config_type_stem) + } + ClockTreeItem::Generic(div) => { + div.property_macro_branches(path, group, config_type_stem) + } + ClockTreeItem::Derived(drv) => { + drv.property_macro_branches(path, group, config_type_stem) + } + } + } + + pub(crate) fn set_name(&mut self, name: String) { + match self { + ClockTreeItem::Multiplexer(mux) => mux.name = name, + ClockTreeItem::Source(src) => src.name = name, + ClockTreeItem::Generic(div) => div.name = name, + ClockTreeItem::Derived(drv) => drv.source_options.name = name, + } + } + + pub(crate) fn set_wake_locking(&mut self, wake_locking: bool) { + match self { + ClockTreeItem::Multiplexer(mux) => mux.set_wake_locking(wake_locking), + ClockTreeItem::Source(src) => src.set_wake_locking(wake_locking), + ClockTreeItem::Generic(div) => div.set_wake_locking(wake_locking), + ClockTreeItem::Derived(drv) => drv.source_options.set_wake_locking(wake_locking), + } + } + + pub(crate) fn set_always_on(&mut self, always_on: bool) { match self { - ClockTreeItem::Multiplexer(mux) => mux.property_macro_branches(path, group), - ClockTreeItem::Source(src) => src.property_macro_branches(path, group), - ClockTreeItem::Generic(div) => div.property_macro_branches(path, group), - ClockTreeItem::Derived(drv) => drv.property_macro_branches(path, group), + ClockTreeItem::Multiplexer(mux) => mux.set_always_on(always_on), + ClockTreeItem::Source(src) => src.set_always_on(always_on), + ClockTreeItem::Generic(div) => div.set_always_on(always_on), + ClockTreeItem::Derived(drv) => drv.source_options.set_always_on(always_on), } } } diff --git a/esp-metadata/src/cfg/soc/clock_tree/generic.rs b/esp-metadata/src/cfg/soc/clock_tree/generic.rs index 9d5a481a6c0..2d6b90410d1 100644 --- a/esp-metadata/src/cfg/soc/clock_tree/generic.rs +++ b/esp-metadata/src/cfg/soc/clock_tree/generic.rs @@ -23,6 +23,8 @@ use crate::{ ConfiguresExpression, Expression, RejectExpression, + RootSource, + RootSourceArm, SourceFrequencySignature, ValidationContext, ValuesExpression, @@ -99,6 +101,10 @@ impl<'de> Deserialize<'de> for NodeParameter { #[serde(deny_unknown_fields)] pub struct Generic { /// The unique name of the clock tree item. + /// + /// Empty when this node is a group preset; the map key / instantiating clock supplies the + /// name. + #[serde(default)] pub name: String, #[serde(default)] @@ -107,6 +113,10 @@ pub struct Generic { #[serde(default)] wake_locking: bool, + /// Optional `#[cfg(...)]` expression. The node is omitted when the condition is false. + #[serde(default)] + cfg: Option, + /// The expression that calculates the clock node's output frequency. output: Expression, @@ -122,6 +132,16 @@ pub struct Generic { params: IndexMap, } +impl Generic { + pub(crate) fn set_wake_locking(&mut self, wake_locking: bool) { + self.wake_locking = wake_locking; + } + + pub(crate) fn set_always_on(&mut self, always_on: bool) { + self.always_on = always_on; + } +} + impl ClockTreeNodeType for Generic { fn name(&self) -> &str { &self.name @@ -161,6 +181,10 @@ impl ClockTreeNodeType for Generic { self.wake_locking } + fn rustc_cfg(&self) -> Option<&str> { + self.cfg.as_deref() + } + fn validate_source_data( &self, instance: &ClockTreeNodeInstance, @@ -287,6 +311,7 @@ impl ClockTreeNodeType for Generic { let mux_param_field = format_ident!("{mux_param}"); let param_ty_name = self.param_type_name(instance, mux_param); let branches = mux_inputs.iter().filter_map(|variant| { + let cfg_attr = variant.cfg_attr(); let name = variant.config_enum_variant_name(); let variant_configures = variant.configures.iter().map(|cfg_expr| { let affected_node = instance.resolve_node(tree, &cfg_expr.effect().node); @@ -294,6 +319,7 @@ impl ClockTreeNodeType for Generic { }); Some(quote! { + #cfg_attr #param_ty_name::#name => { #(#variant_configures)* } @@ -312,14 +338,13 @@ impl ClockTreeNodeType for Generic { if let Some(refcount_accessor) = instance.properties.refcount_accessor() { quote! { #configures - if #refcount_accessor > 0 { + let active = #refcount_accessor > 0; + if active { #request_upstream - #hal_impl(clocks, old_config, config); - if let Some(old_config) = old_config { - #release_upstream - } - } else { - #hal_impl(clocks, old_config, config); + } + #hal_impl(clocks, old_config, config); + if active && let Some(old_config) = old_config { + #release_upstream } } } else { @@ -504,6 +529,37 @@ impl ClockTreeNodeType for Generic { }) } + fn root_source( + &self, + instance: &ClockTreeNodeInstance, + _tree: &ProcessedClockData, + ) -> RootSource { + let source_param_name = self.clock_source_parameter(); + match self.upstream_clocks() { + ClockSource::Fixed(input) => RootSource::PassThrough(input.to_string()), + ClockSource::Mux(inputs) => { + let ty_name = self.param_type_name(instance, source_param_name); + let param_name = format_ident!("{source_param_name}"); + let arms = inputs + .iter() + .map(|variant| { + let name = variant.config_enum_variant_name(); + RootSourceArm { + cfg_attr: variant.cfg_attr(), + pattern: quote! { #ty_name::#name }, + upstream: variant.outputs.clone(), + } + }) + .collect(); + + RootSource::Selector { + subject: quote! { config.#param_name() }, + arms, + } + } + } + } + fn node_source_frequency_impl( &self, instance: &ClockTreeNodeInstance, @@ -517,7 +573,7 @@ impl ClockTreeNodeType for Generic { match self.upstream_clocks() { ClockSource::Fixed(input) => { let source_node = instance.resolve_node(tree, input); - let Some(body) = source_node.try_frequency_call() else { + let Some(body) = source_node.try_frequency_expr(tree) else { return SourceFrequencySignature::Skip; }; SourceFrequencySignature::Parameterless(body) @@ -529,12 +585,13 @@ impl ClockTreeNodeType for Generic { let mut variants = Vec::with_capacity(inputs.len()); let mut variant_frequencies = Vec::with_capacity(inputs.len()); for variant in inputs { + let cfg_attr = variant.cfg_attr(); let name = variant.config_enum_variant_name(); let source_node = instance.resolve_node(tree, &variant.outputs); - let Some(frequency) = source_node.try_frequency_call() else { + let Some(frequency) = source_node.try_frequency_expr(tree) else { return SourceFrequencySignature::Skip; }; - variants.push(quote! { #ty_name::#name }); + variants.push(quote! { #cfg_attr #ty_name::#name }); variant_frequencies.push(frequency); } @@ -619,11 +676,12 @@ impl ClockTreeNodeType for Generic { let (variants, variant_frequencies) = inputs .iter() .map(|variant| { + let cfg_attr = variant.cfg_attr(); let name = variant.config_enum_variant_name(); let source_node = instance.resolve_node(tree, &variant.outputs); ( - quote! { #ty_name::#name }, + quote! { #cfg_attr #ty_name::#name }, source_node.frequency_call_with_receiver(frequency_receiver), ) }) @@ -706,14 +764,14 @@ impl ClockTreeNodeType for Generic { match param { NodeParameter::Value(_) => { quote! { - pub(crate) fn #param_name(self) -> u32 { + pub fn #param_name(self) -> u32 { self.#param_name as u32 } } } NodeParameter::Source(_) => { quote! { - pub(crate) fn #param_name(self) -> #param_ty { + pub fn #param_name(self) -> #param_ty { self.#param_name } } @@ -798,7 +856,12 @@ impl ClockTreeNodeType for Generic { self.impl_release_upstream(instance, tree, quote! { unwrap!(#config_field) }) } - fn property_macro_branches(&self, path: &str, group: &str) -> TokenStream { + fn property_macro_branches( + &self, + path: &str, + group: &str, + config_type_stem: &str, + ) -> TokenStream { let mut branches = quote! {}; for (param_name, param) in self.params.iter() { let path = format!("{path}.{param_name}"); @@ -823,10 +886,11 @@ impl ClockTreeNodeType for Generic { } } NodeParameter::Source(variants) => { - let ty = param_type_name(group, &self.name, param_name); + let ty = param_type_name(group, config_type_stem, param_name); let options = variants.iter().map(|variant| { + let cfg_attr = variant.cfg_attr(); let variant = variant.config_enum_variant_name(); - quote! { crate::soc::clocks::#ty::#variant } + quote! { #cfg_attr crate::soc::clocks::#ty::#variant } }); branches.extend(quote! { (#path) => { @@ -926,11 +990,13 @@ impl Generic { let param = self.clock_source_parameter(); let ty_name = self.param_type_name(instance, param); let request_upstream_branches = mux_inputs.iter().map(|variant| { + let cfg_attr = variant.cfg_attr(); let match_arm = variant.config_enum_variant_name(); let upstream_node = instance.resolve_node(tree, &variant.outputs); let upstream_receiver = upstream_node.properties.receiver(); let function = op(upstream_node); quote! { + #cfg_attr #ty_name::#match_arm => #(#upstream_receiver.)*#function(clocks) } }); @@ -981,7 +1047,11 @@ impl Generic { } // Enum parameter - param_type_name(&instance.group_template, &self.name, param_name) + param_type_name( + &instance.group_template, + instance.config_type_stem(), + param_name, + ) } fn parameter_config_type_impl( diff --git a/esp-metadata/src/cfg/soc/clock_tree/mux.rs b/esp-metadata/src/cfg/soc/clock_tree/mux.rs index 1ba5f26ff18..5992744d460 100644 --- a/esp-metadata/src/cfg/soc/clock_tree/mux.rs +++ b/esp-metadata/src/cfg/soc/clock_tree/mux.rs @@ -13,9 +13,12 @@ use crate::cfg::{ Bounds, ClockTreeNodeType, ConfiguresExpression, + RootSource, + RootSourceArm, SourceFrequencySignature, ValidationContext, config_type_name, + rustc_cfg_attr, }, soc::ProcessedClockData, }; @@ -24,6 +27,10 @@ use crate::cfg::{ #[serde(deny_unknown_fields)] pub struct Multiplexer { /// The unique name of the clock tree item. + /// + /// Empty when this multiplexer is a group preset; the map key / instantiating clock supplies + /// the name. + #[serde(default)] pub name: String, #[serde(default)] @@ -32,10 +39,24 @@ pub struct Multiplexer { #[serde(default)] wake_locking: bool, + /// Optional `#[cfg(...)]` expression. The node is omitted when the condition is false. + #[serde(default)] + cfg: Option, + // reject: Option, pub variants: Vec, } +impl Multiplexer { + pub(crate) fn set_wake_locking(&mut self, wake_locking: bool) { + self.wake_locking = wake_locking; + } + + pub(crate) fn set_always_on(&mut self, always_on: bool) { + self.always_on = always_on; + } +} + impl ClockTreeNodeType for Multiplexer { fn name(&self) -> &str { &self.name @@ -53,6 +74,10 @@ impl ClockTreeNodeType for Multiplexer { self.wake_locking } + fn rustc_cfg(&self) -> Option<&str> { + self.cfg.as_deref() + } + fn input_clocks( &self, instance: &ClockTreeNodeInstance, @@ -160,6 +185,31 @@ impl ClockTreeNodeType for Multiplexer { .any(|variant| !variant.configures.is_empty()) } + fn root_source( + &self, + instance: &ClockTreeNodeInstance, + _tree: &ProcessedClockData, + ) -> RootSource { + let ty_name = instance.config_type_name(); + let arms = self + .variants + .iter() + .map(|variant| { + let name = variant.config_enum_variant_name(); + RootSourceArm { + cfg_attr: variant.cfg_attr(), + pattern: quote! { #ty_name::#name }, + upstream: variant.outputs.clone(), + } + }) + .collect(); + + RootSource::Selector { + subject: quote! { config }, + arms, + } + } + fn node_source_frequency_impl( &self, instance: &ClockTreeNodeInstance, @@ -173,15 +223,20 @@ impl ClockTreeNodeType for Multiplexer { let mut variant_frequencies = Vec::with_capacity(self.variants.len()); let mut variants = Vec::with_capacity(self.variants.len()); for variant in &self.variants { + let cfg_attr = variant.cfg_attr(); let name = variant.config_enum_variant_name(); let upstream_node = instance.resolve_node(tree, &variant.outputs); - let Some(frequency) = upstream_node.try_frequency_call() else { + let Some(frequency) = upstream_node.try_frequency_expr(tree) else { return SourceFrequencySignature::Skip; }; - variants.push(quote! { #ty_name::#name }); + variants.push(quote! { #cfg_attr #ty_name::#name }); variant_frequencies.push(frequency); } + if self.is_configurable() && !self.config_frequency_needs_instance(instance, tree) { + return SourceFrequencySignature::SameAsConfig; + } + SourceFrequencySignature::Selector { param_type: quote! { #ty_name }, param_name: format_ident!("source"), @@ -193,6 +248,20 @@ impl ClockTreeNodeType for Multiplexer { } } + fn config_frequency_needs_instance( + &self, + instance: &ClockTreeNodeInstance, + tree: &ProcessedClockData, + ) -> bool { + self.variants.iter().any(|variant| { + instance + .resolve_node(tree, &variant.outputs) + .properties + .receiver + .is_some() + }) + } + fn skips_frequency_cache( &self, _instance: &ClockTreeNodeInstance, @@ -212,8 +281,9 @@ impl ClockTreeNodeType for Multiplexer { .variants .iter() .map(|variant| { + let cfg_attr = variant.cfg_attr(); let name = variant.config_enum_variant_name(); - quote! { #ty_name::#name } + quote! { #cfg_attr #ty_name::#name } }) .collect::>(); @@ -222,9 +292,13 @@ impl ClockTreeNodeType for Multiplexer { .iter() .map(|variant| { let upstream_node = instance.resolve_node(tree, &variant.outputs); - let frequency_fn = upstream_node.frequency_function_name(); - let receiver = upstream_node.properties.receiver(); - quote! { #(#receiver.)* #frequency_fn() } + if let Some(frequency) = upstream_node.try_frequency_expr(tree) { + frequency + } else { + let frequency_fn = upstream_node.frequency_function_name(); + let receiver = upstream_node.properties.receiver(); + quote! { #(#receiver.)* #frequency_fn() } + } }) .collect::>(); @@ -249,11 +323,13 @@ impl ClockTreeNodeType for Multiplexer { } else { quote! {} }; + let cfg_attr = instance.rustc_cfg_attr(); let variants = self.variants.iter().map(|v| v.config_enum_variant()); let docline = format!("The list of clock signals that the `{clock_name}` multiplexer can output."); quote! { + #cfg_attr #[doc = #docline] #[derive(Debug, #derive_default Clone, Copy, PartialEq, Eq, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] @@ -285,15 +361,21 @@ impl ClockTreeNodeType for Multiplexer { self.impl_release_upstream(instance, tree, quote! { unwrap!(#config_field) }) } - fn property_macro_branches(&self, path: &str, group: &str) -> TokenStream { + fn property_macro_branches( + &self, + path: &str, + group: &str, + config_type_stem: &str, + ) -> TokenStream { if !self.is_configurable() { return quote! {}; } - let ty = config_type_name(group, &self.name); + let ty = config_type_name(group, config_type_stem); let options = self.variants.iter().map(|variant| { + let cfg_attr = variant.cfg_attr(); let variant = variant.config_enum_variant_name(); - quote! { crate::soc::clocks::#ty::#variant } + quote! { #cfg_attr crate::soc::clocks::#ty::#variant } }); quote! { @@ -362,8 +444,10 @@ impl Multiplexer { } let name = variant.config_enum_variant_name(); + let cfg_attr = variant.cfg_attr(); Some(quote! { + #cfg_attr #ty_name::#name => { #variant_configures } @@ -381,23 +465,25 @@ impl Multiplexer { } }; - let apply_and_switch_input = quote! { - #request_upstream - #hal_impl(clocks, old_selector, new_selector); - if let Some(old_selector) = old_selector { - #release_upstream - } - }; let apply_impl = if let Some(refcount_accessor) = instance.properties.refcount_accessor() { quote! { - if #refcount_accessor > 0 { - #apply_and_switch_input - } else { - #hal_impl(clocks, old_selector, new_selector); + let active = #refcount_accessor > 0; + if active { + #request_upstream + } + #hal_impl(clocks, old_selector, new_selector); + if active && let Some(old_selector) = old_selector { + #release_upstream } } } else { - apply_and_switch_input + quote! { + #request_upstream + #hal_impl(clocks, old_selector, new_selector); + if let Some(old_selector) = old_selector { + #release_upstream + } + } }; quote! { @@ -422,12 +508,14 @@ impl Multiplexer { if self.variants.len() > 1 { let ty_name = instance.config_type_name(); let request_upstream_branches = self.variants.iter().map(|variant| { + let cfg_attr = variant.cfg_attr(); let match_arm = variant.config_enum_variant_name(); let upstream_node = instance.resolve_node(tree, &variant.outputs); let receiver = upstream_node.properties.receiver(); let func = upstream_node.request_fn_name(); quote! { + #cfg_attr #ty_name::#match_arm => #(#receiver.)*#func(clocks) } }); @@ -464,11 +552,13 @@ impl Multiplexer { if self.variants.len() > 1 { let ty_name = instance.config_type_name(); let release_upstream_branches = self.variants.iter().map(|variant| { + let cfg_attr = variant.cfg_attr(); let match_arm = variant.config_enum_variant_name(); let upstream_node = instance.resolve_node(tree, &variant.outputs); let receiver = upstream_node.properties.receiver(); let func = upstream_node.release_fn_name(); quote! { + #cfg_attr #ty_name::#match_arm => #(#receiver.)*#func(clocks) } }); @@ -522,8 +612,15 @@ pub struct MultiplexerVariant { pub configures: Vec, #[serde(default)] pub default: bool, + /// Optional `#[cfg(...)]` expression. The variant is omitted when the condition is false. + #[serde(default)] + pub cfg: Option, } impl MultiplexerVariant { + pub fn cfg_attr(&self) -> TokenStream { + rustc_cfg_attr(self.cfg.as_deref()) + } + pub fn config_enum_variant_name(&self) -> Ident { format_ident!( "{}", @@ -540,6 +637,7 @@ impl MultiplexerVariant { pub fn config_enum_variant(&self) -> TokenStream { let docline = format!(" Selects `{}`.", self.outputs); let name = self.config_enum_variant_name(); + let cfg_attr = self.cfg_attr(); let default = if self.default { quote! { @@ -550,6 +648,7 @@ impl MultiplexerVariant { }; quote! { + #cfg_attr #default #[doc = #docline] #name, diff --git a/esp-metadata/src/cfg/soc/clock_tree/source.rs b/esp-metadata/src/cfg/soc/clock_tree/source.rs index a16053d0ebb..b5a1f381186 100644 --- a/esp-metadata/src/cfg/soc/clock_tree/source.rs +++ b/esp-metadata/src/cfg/soc/clock_tree/source.rs @@ -44,6 +44,7 @@ use crate::{ ClockTreeNodeType, Expression, RejectExpression, + RootSource, SourceFrequencySignature, ValidationContext, ValuesExpression, @@ -58,6 +59,7 @@ use crate::{ #[derive(Debug, Clone, Deserialize)] pub struct Source { /// The unique name of the clock tree item. + #[serde(default)] pub name: String, #[serde(default)] @@ -66,6 +68,10 @@ pub struct Source { #[serde(default)] wake_locking: bool, + /// Optional `#[cfg(...)]` expression. The node is omitted when the condition is false. + #[serde(default)] + cfg: Option, + /// If set, this expression will be used to validate the clock configuration. /// /// The expression may refer to clock sources, or any of the clock tree item's properties (e.g. @@ -77,9 +83,24 @@ pub struct Source { #[serde(default)] values: Option, + /// The range (`min..=max`) that the frequency of a fixed source can be adjusted to at + /// runtime, e.g. after it has been measured. + #[serde(default)] + adjustable: Option, + output: OutputExpression, } +impl Source { + pub(crate) fn set_wake_locking(&mut self, wake_locking: bool) { + self.wake_locking = wake_locking; + } + + pub(crate) fn set_always_on(&mut self, always_on: bool) { + self.always_on = always_on; + } +} + impl ClockTreeNodeType for Source { fn name(&self) -> &str { &self.name @@ -91,7 +112,15 @@ impl ClockTreeNodeType for Source { variables.insert("VALUE", values.bounds()); } - self.output.0.bounds_in_tree(&variables, instance, tree) + let bounds = self.output.0.bounds_in_tree(&variables, instance, tree); + match self.adjustable_range() { + Some((min, max)) => bounds.union(Bounds::new(min as u64, max as u64)), + None => bounds, + } + } + + fn adjustable_range(&self) -> Option<(u32, u32)> { + self.adjustable.as_ref().and_then(|range| range.as_range()) } fn always_on(&self) -> bool { @@ -102,11 +131,38 @@ impl ClockTreeNodeType for Source { self.wake_locking } - fn validate_source_data( + fn root_source( &self, _instance: &ClockTreeNodeInstance, + _tree: &ProcessedClockData, + ) -> RootSource { + RootSource::Itself + } + + fn rustc_cfg(&self) -> Option<&str> { + self.cfg.as_deref() + } + + fn validate_source_data( + &self, + instance: &ClockTreeNodeInstance, _ctx: &ValidationContext<'_>, ) -> Result<()> { + if let Some(range) = self.adjustable.as_ref() { + anyhow::ensure!( + range.as_range().is_some(), + "`adjustable` must be a single range (`min..=max`)" + ); + anyhow::ensure!( + !self.is_configurable(), + "`adjustable` is only supported on fixed sources" + ); + anyhow::ensure!( + instance.properties.receiver.is_none(), + "`adjustable` is not supported on clock group nodes" + ); + } + Ok(()) } @@ -351,6 +407,14 @@ impl ClockTreeNodeType for DerivedClockSource { vec![self.from.clone()] } + fn root_source( + &self, + _instance: &ClockTreeNodeInstance, + _tree: &ProcessedClockData, + ) -> RootSource { + RootSource::PassThrough(self.from.clone()) + } + fn validate_source_data( &self, instance: &ClockTreeNodeInstance, @@ -361,6 +425,10 @@ impl ClockTreeNodeType for DerivedClockSource { "Clock `{}` is not defined", self.from ); + anyhow::ensure!( + self.source_options.adjustable.is_none(), + "`adjustable` is not supported on derived sources" + ); self.source_options.validate_source_data(instance, ctx) } @@ -369,6 +437,10 @@ impl ClockTreeNodeType for DerivedClockSource { self.source_options.is_configurable() } + fn rustc_cfg(&self) -> Option<&str> { + self.source_options.rustc_cfg() + } + fn config_apply_function( &self, instance: &ClockTreeNodeInstance, @@ -401,8 +473,14 @@ impl ClockTreeNodeType for DerivedClockSource { fn config_type(&self, instance: &ClockTreeNodeInstance) -> TokenStream { let extra_docs = format!("Depends on `{}`.", self.from); - self.source_options - .impl_config_type(instance, Some(&extra_docs)) + let cfg_attr = instance.rustc_cfg_attr(); + let ty = self + .source_options + .impl_config_type(instance, Some(&extra_docs)); + quote! { + #cfg_attr + #ty + } } fn request_direct_dependencies( diff --git a/esp-metadata/src/cfg/timergroup.rs b/esp-metadata/src/cfg/timergroup.rs index 843351bb057..efbefe72ec0 100644 --- a/esp-metadata/src/cfg/timergroup.rs +++ b/esp-metadata/src/cfg/timergroup.rs @@ -12,6 +12,31 @@ pub struct RcFastCalibrationProperties { tick_enable: bool, } +/// The RC_SLOW calibration input may be tapped ahead of the divider that produces the RTC slow +/// clock, in which case the calibration counts `multiplier` input cycles per measured cycle. +#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RcSlowCalibrationProperties { + multiplier: u32, +} + +impl GenericProperty for RcSlowCalibrationProperties { + fn cfgs(&self) -> Option> { + Some(vec![String::from( + "timergroup_rc_slow_calibration_multiplier", + )]) + } + + fn property_macro_branches(&self) -> proc_macro2::TokenStream { + let multiplier = number(self.multiplier); + quote! { + ("timergroup.rc_slow_calibration_multiplier") => { + #multiplier + }; + } + } +} + impl GenericProperty for RcFastCalibrationProperties { fn cfgs(&self) -> Option> { let mut cfgs = vec![String::from("timergroup_rc_fast_calibration_divider")]; diff --git a/esp-metadata/src/lib.rs b/esp-metadata/src/lib.rs index 3d2aa2b4104..d3716be8d54 100644 --- a/esp-metadata/src/lib.rs +++ b/esp-metadata/src/lib.rs @@ -19,7 +19,7 @@ mod support_status; use crate::{ cfg::{SupportItem, Value}, - support_status::SupportStatusLevel, + support_status::{DriverStability, SupportStatus, SupportStatusLevel}, }; /// Path of the metadata cache shared with the devtool. @@ -235,6 +235,8 @@ string_enum! { Esp32c61 = "esp32c61", /// ESP32-H2 Esp32h2 = "esp32h2", + /// ESP32-H4 + Esp32h4 = "esp32h4", /// ESP32-P4 (chip revision v3.x / eco5 only) Esp32p4 = "esp32p4", /// ESP32-S2 @@ -300,6 +302,7 @@ impl Chip { Chip::Esp32c6 => "Esp32c6", Chip::Esp32c61 => "Esp32c61", Chip::Esp32h2 => "Esp32h2", + Chip::Esp32h4 => "Esp32h4", Chip::Esp32p4 => "Esp32p4", Chip::Esp32s2 => "Esp32s2", Chip::Esp32s3 => "Esp32s3", @@ -316,6 +319,7 @@ impl Chip { Chip::Esp32c6 => "ESP32-C6", Chip::Esp32c61 => "ESP32-C61", Chip::Esp32h2 => "ESP32-H2", + Chip::Esp32h4 => "ESP32-H4", Chip::Esp32p4 => "ESP32-P4", Chip::Esp32s2 => "ESP32-S2", Chip::Esp32s3 => "ESP32-S3", @@ -454,6 +458,7 @@ impl Config { Chip::Esp32c6 => cached_device_config!("devices/esp32c6/soc.toml"), Chip::Esp32c61 => cached_device_config!("devices/esp32c61/soc.toml"), Chip::Esp32h2 => cached_device_config!("devices/esp32h2/soc.toml"), + Chip::Esp32h4 => cached_device_config!("devices/esp32h4/soc.toml"), Chip::Esp32p4 => cached_device_config!("devices/esp32p4/soc.toml"), Chip::Esp32s2 => cached_device_config!("devices/esp32s2/soc.toml"), Chip::Esp32s3 => cached_device_config!("devices/esp32s3/soc.toml"), @@ -495,6 +500,25 @@ impl Config { .validate_mem2mem(dma.mem2mem_requires_peripheral)?; } + if let Some(adc) = &self.device.peri_config.adc + && adc.support_status.is_supported() + { + let chip = &self.device.name; + ensure!( + matches!( + adc.controller.as_deref(), + None | Some("rtc") | Some("digital") + ), + "{chip}: adc.controller must be rtc, digital, or unset" + ); + if adc.controller.as_deref() == Some("digital") { + ensure!( + adc.channel_count.is_some_and(|count| count > 0), + "{chip}: digital ADC needs adc.channel_count" + ); + } + } + Ok(()) } @@ -733,6 +757,12 @@ impl Config { if let Some(peri) = self.device.peri_config.spi_slave.as_ref() { tokens.extend(cfg::generate_spi_slave_peripherals(peri)); }; + if let Some(peri) = self.device.peri_config.pcnt.as_ref() { + tokens.extend(cfg::generate_pcnt_peripherals(peri)); + }; + if let Some(peri) = self.device.peri_config.canfd.as_ref() { + tokens.extend(cfg::generate_canfd_peripherals(peri)); + }; tokens.extend(self.generate_peripherals_macro()); @@ -836,6 +866,22 @@ This pin may be available with certain limitations. Check your hardware to make } } + if let Some(pcnt) = self.device.peri_config.pcnt.as_ref() + && pcnt.support_status.is_supported() + { + for instance in pcnt.instances.iter() { + for unit in 0..instance.instance_config.units.len() { + let name = format_ident!("{}", cfg::singleton_name(&instance.name, unit)); + let singleton_doc = format!("{} peripheral singleton", name); + let tokens = quote! { + #[doc = #singleton_doc] #name <= virtual () + }; + all_peripherals.push(quote! { @peri_type #tokens (unstable) }); + singleton_peripherals.push(unstable_singleton("e! {}, &name)); + } + } + } + if let Some(sdm) = self.device.peri_config.sdm.as_ref() && sdm.support_status.is_supported() { @@ -1506,35 +1552,114 @@ pub fn generate_lib_rs() -> TokenStream { } } -pub fn generate_chip_support_status(output: &mut impl Write) -> std::fmt::Result { - // The legend applies to every table, so it is written once, before the - // first one. - SupportStatusLevel::write_legend(output)?; - writeln!(output)?; +impl SupportItem { + fn chip_status(&self, chip: Chip) -> SupportStatus { + Config::for_chip(&chip) + .device + .peri_config + .support_status(self.config_group) + } - let visible = PeriConfig::drivers() - .iter() - .filter(|driver| !driver.hide_from_peri_table) - .collect::>(); + /// Returns true if this driver is supported (partially or fully) on at least one chip. + fn is_implemented(&self) -> bool { + Chip::iter().any(|chip| self.chip_status(chip).is_supported()) + } + /// Returns the driver-wide icon and optional tracking issue for the README summary table. + fn readme_status(&self) -> (&'static str, Option) { + if self.is_implemented() { + (self.stability.icon(), self.stability.issue()) + } else { + let mut not_supported = Chip::iter().filter_map(|chip| { + let status = self.chip_status(chip); + (status.status == SupportStatusLevel::NotSupported).then_some(status.issue) + }); + + let shared_issue = not_supported.next().flatten().and_then(|first| { + not_supported + .all(|issue| issue == Some(first)) + .then_some(first) + }); + + (SupportStatusLevel::NotSupported.icon(), shared_issue) + } + } + + fn write_html_api_cell(&self, output: &mut impl Write) -> std::fmt::Result { + if self.is_implemented() { + write_html_status_cell( + output, + Some("api-col"), + self.stability.icon(), + self.stability.short_label(), + self.stability.issue(), + ) + } else { + write!( + output, + r#"—"# + ) + } + } +} + +impl SupportStatus { + fn write_html_cell(&self, output: &mut impl Write) -> std::fmt::Result { + match self.status { + SupportStatusLevel::NotAvailable => { + write!( + output, + r#"—"# + ) + } + level => write_html_status_cell(output, None, level.icon(), level.status(), self.issue), + } + } +} + +fn visible_driver_groups() -> Vec<(&'static str, Vec<&'static SupportItem>)> { // A group is written where its first driver is declared, so the order of // the tables is controlled by the order of the driver definitions. - let mut groups = Vec::new(); - for driver in visible.iter() { - if !groups.contains(&driver.group) { - groups.push(driver.group); + let mut groups: Vec<(&'static str, Vec<&'static SupportItem>)> = Vec::new(); + for driver in PeriConfig::drivers() + .iter() + .filter(|driver| !driver.hide_from_peri_table) + { + if let Some((_, drivers)) = groups.iter_mut().find(|(group, _)| *group == driver.group) { + drivers.push(driver); + } else { + groups.push((driver.group, vec![driver])); } } + groups +} - let mut issues = Vec::new(); - for group in groups { - let drivers = visible - .iter() - .filter(|driver| driver.group == group) - .copied() - .collect::>(); +const PERIPHERAL_SUPPORT_INDEX_URL: &str = + "https://docs.espressif.com/projects/rust/esp-hal/main/index.html"; + +fn group_slug(group: &str) -> String { + group.to_ascii_lowercase().replace(' ', "-") +} + +pub fn generate_chip_support_status(output: &mut impl Write) -> std::fmt::Result { + writeln!( + output, + "For a detailed per-chip support matrix, see the [documentation index]({PERIPHERAL_SUPPORT_INDEX_URL}#peripheral-support)." + )?; + writeln!(output)?; + + // The legend applies to every table, so it is written once, before the + // first one. + DriverStability::write_legend(output)?; + writeln!(output)?; - writeln!(output, "### {group}")?; + let mut issues = Vec::new(); + for (group, drivers) in visible_driver_groups() { + let slug = group_slug(group); + writeln!( + output, + "### [{group}]({PERIPHERAL_SUPPORT_INDEX_URL}#{slug})" + )?; writeln!(output)?; write_support_table(output, &drivers, &mut issues)?; writeln!(output)?; @@ -1569,6 +1694,7 @@ fn write_support_table( issues: &mut Vec, ) -> std::fmt::Result { let nothing = ""; + let status_header = "Status"; // The width of the first column is calculated per table, so that adding a // driver only reflows the table it is added to. @@ -1579,50 +1705,119 @@ fn write_support_table( .unwrap(); // Header - write!(output, "| {:driver_col_width$} |", "Driver")?; - for chip in Chip::iter() { - write!(output, " {} |", chip.pretty_name())?; - } - writeln!(output)?; + writeln!( + output, + "| {:driver_col_width$} | {status_header} |", + "Driver" + )?; // Header separator - write!(output, "| {nothing:- std::fmt::Result { + let chip_headers: String = Chip::iter() + .map(|chip| format!("{}", chip.pretty_name())) + .collect(); + + for (group, drivers) in visible_driver_groups() { + let slug = group_slug(group); + let count = drivers.len(); + let driver_word = if count == 1 { "driver" } else { "drivers" }; + + writeln!( + output, + r#"
+ + {group} + {count} {driver_word} + +
+ + + + + + {chip_headers} + + + "# + )?; + + for driver in drivers { + write!( + output, + r#" "#, + driver.name + )?; + driver.write_html_api_cell(output)?; + for chip in Chip::iter() { + driver.chip_status(chip).write_html_cell(output)?; } + writeln!(output, "")?; } - writeln!(output)?; + + writeln!( + output, + r#" +
DriverAPI
{}
+
+
"# + )?; } Ok(()) } +fn write_html_status_cell( + output: &mut impl Write, + class: Option<&str>, + icon: &str, + label: &str, + issue: Option, +) -> std::fmt::Result { + let class_attr = match class { + Some(c) => format!(r#" class="{c}""#), + None => String::new(), + }; + if let Some(issue) = issue { + write!( + output, + r#"
{icon}"# + ) + } else { + write!( + output, + r#"{icon}"# + ) + } +} + pub fn generate_supported_devices_table(output: &mut impl Write) -> std::fmt::Result { writeln!(output, "| Chip | Documentation | Target | Note |")?; writeln!(output, "| :---: | :-----------: | :----: | :---: |")?; diff --git a/esp-metadata/src/main.rs b/esp-metadata/src/main.rs index 78b748b24d7..4975c77b72f 100644 --- a/esp-metadata/src/main.rs +++ b/esp-metadata/src/main.rs @@ -17,7 +17,7 @@ use esp_metadata::{Chip, Config, TokenStream}; /// Bump when the cache layout changes. Devtools that expect a different /// version refuse to use the cache instead of regenerating it, because /// regeneration cannot resolve a version mismatch. -const CACHE_VERSION: u32 = 1; +const CACHE_VERSION: u32 = 2; const USAGE: &str = "\ Usage: cargo update-metadata [--check] @@ -224,6 +224,8 @@ struct Cache { symbols: Vec, /// Every symbol with a value defined by any chip. kv_symbols: Vec, + /// Pre-rendered HTML peripheral support matrix for the `esp-hal` documentation index. + peripheral_support_html: String, chips: BTreeMap, } @@ -306,11 +308,15 @@ fn dump_cache(workspace: &Path) -> Result { .filter(|symbol| !kv_symbols.contains(symbol)) .collect::>(); + let mut peripheral_support_html = String::new(); + esp_metadata::generate_chip_support_status_html(&mut peripheral_support_html)?; + let cache = Cache { version: CACHE_VERSION, hash: esp_metadata::input_hash(workspace)?, symbols: symbols.into_iter().collect(), kv_symbols: kv_symbols.into_iter().collect(), + peripheral_support_html, chips, }; diff --git a/esp-metadata/src/support_status.rs b/esp-metadata/src/support_status.rs index de78e1751cc..e229c446795 100644 --- a/esp-metadata/src/support_status.rs +++ b/esp-metadata/src/support_status.rs @@ -7,6 +7,69 @@ use serde::{ de::{self, MapAccess, Visitor}, }; +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub(crate) enum DriverStability { + Stable, + #[default] + Unstable, + Overhaul { + issue: Option, + }, +} + +impl DriverStability { + pub fn icon(self) -> &'static str { + match self { + DriverStability::Stable => "✔️", + DriverStability::Unstable => "🚧", + DriverStability::Overhaul { .. } => "⚠️", + } + } + + pub fn label(self) -> &'static str { + match self { + DriverStability::Stable => "Stable", + DriverStability::Unstable => "Unstable (requires the `unstable` feature)", + DriverStability::Overhaul { .. } => { + "Planned overhaul (unstable, expect major breaking changes)" + } + } + } + + pub fn short_label(self) -> &'static str { + match self { + DriverStability::Stable => "Stable", + DriverStability::Unstable => "Unstable", + DriverStability::Overhaul { .. } => "Planned overhaul", + } + } + + pub fn issue(self) -> Option { + match self { + DriverStability::Overhaul { issue } => issue, + _ => None, + } + } + + pub(crate) fn write_legend(output: &mut impl fmt::Write) -> fmt::Result { + writeln!( + output, + " * {}: {}", + SupportStatusLevel::NotSupported.icon(), + SupportStatusLevel::NotSupported.status() + )?; + for s in [ + DriverStability::Overhaul { issue: None }, + DriverStability::Unstable, + DriverStability::Stable, + ] { + writeln!(output, " * {}: {}", s.icon(), s.label())?; + } + + Ok(()) + } +} + #[derive(Debug, Default, Clone, Copy, PartialEq, Deserialize, Serialize)] #[serde(rename_all = "snake_case")] pub(crate) enum SupportStatusLevel { @@ -35,28 +98,6 @@ impl SupportStatusLevel { SupportStatusLevel::Supported => "Supported", } } - - pub(crate) fn write_legend(output: &mut impl fmt::Write) -> fmt::Result { - for s in [ - SupportStatusLevel::NotAvailable, - SupportStatusLevel::NotSupported, - SupportStatusLevel::Partial, - SupportStatusLevel::Supported, - ] { - writeln!( - output, - " * {}: {}", - if s.icon().is_empty() { - "Empty cell" - } else { - s.icon() - }, - s.status() - )?; - } - - Ok(()) - } } impl FromStr for SupportStatusLevel { diff --git a/esp-phy/CHANGELOG.md b/esp-phy/CHANGELOG.md index 52429b4dc6c..c1e658b64cc 100644 --- a/esp-phy/CHANGELOG.md +++ b/esp-phy/CHANGELOG.md @@ -19,6 +19,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Removed +## [v0.3.0] - 2026-09-15 + +### Added + +- Support for ESP32-S31 (#6296) +- set_wifi_rx_enabled to toggle the default Wi-Fi RX state on combo modules. (#5776) + +### Changed + +- Updated radio blobs to ESP-IDF `6.1-255-g4dbfecac7e3`. (#6271) +- updated defmt to 1.1 (#5752) + ## [v0.2.0] - 2026-04-16 ### Added @@ -50,4 +62,5 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 [v0.1.0]: https://github.com/esp-rs/esp-hal/releases/tag/esp-phy-v0.1.0 [v0.1.1]: https://github.com/esp-rs/esp-hal/compare/esp-phy-v0.1.0...esp-phy-v0.1.1 [v0.2.0]: https://github.com/esp-rs/esp-hal/compare/esp-phy-v0.1.1...esp-phy-v0.2.0 -[Unreleased]: https://github.com/esp-rs/esp-hal/compare/esp-phy-v0.2.0...HEAD +[v0.3.0]: https://github.com/esp-rs/esp-hal/compare/esp-phy-v0.2.0...esp-phy-v0.3.0 +[Unreleased]: https://github.com/esp-rs/esp-hal/compare/esp-phy-v0.3.0...HEAD diff --git a/esp-phy/Cargo.toml b/esp-phy/Cargo.toml index 7c8617551cc..fcbc73028a5 100644 --- a/esp-phy/Cargo.toml +++ b/esp-phy/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "esp-phy" -version = "0.2.0" +version = "0.3.0" edition = "2024" description = "PHY initialization" documentation = "https://docs.espressif.com/projects/rust/esp-phy/latest/" @@ -16,6 +16,9 @@ chip-features-matter = true doc-config = { features = ["defmt"] } check-configs = [ { features = [] }, + { features = ["defmt"] }, + { features = ["log-04"] }, + { features = [], env = { ESP_PHY_CONFIG_PHY_ENABLE_USB = "false" }, if = 'soc_has_usb_device && soc_has_wifi' }, ] clippy-configs = [ { features = ["defmt"] }, @@ -31,39 +34,41 @@ bench = false [dependencies] document-features = "0.2" -esp-hal = { version = "~1.2.0-rc.0", path = "../esp-hal", default-features = false } -esp-metadata-generated = { version = "0.5.0", path = "../esp-metadata-generated" } +esp-hal = { version = "~1.2.0", path = "../esp-hal", default-features = false } +esp-metadata-generated = { version = "0.6.0", path = "../esp-metadata-generated" } esp-sync = { version = "0.3.0", path = "../esp-sync" } # Make sure these are aligned with esp-radio's dependencies, too! -esp-wifi-sys-esp32 = { version = "0.2.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "2ea8e3e" } -esp-wifi-sys-esp32c2 = { version = "0.2.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "2ea8e3e" } -esp-wifi-sys-esp32c3 = { version = "0.2.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "2ea8e3e" } -esp-wifi-sys-esp32c5 = { version = "0.2.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "2ea8e3e" } -esp-wifi-sys-esp32c6 = { version = "0.2.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "2ea8e3e" } -esp-wifi-sys-esp32c61 = { version = "0.2.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "2ea8e3e" } -esp-wifi-sys-esp32h2 = { version = "0.2.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "2ea8e3e" } -esp-wifi-sys-esp32s2 = { version = "0.2.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "2ea8e3e" } -esp-wifi-sys-esp32s3 = { version = "0.2.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "2ea8e3e" } - -esp32 = { version = "0.41", features = ["critical-section"], optional = true } -esp32c2 = { version = "0.30", features = ["critical-section"], optional = true } -esp32c3 = { version = "0.33", features = ["critical-section"], optional = true } -esp32c5 = { version = "0.3", features = ["critical-section"], optional = true } -esp32c6 = { version = "0.24", features = ["critical-section"], optional = true } -esp32c61 = { version = "0.4", features = ["critical-section"], optional = true } -esp32h2 = { version = "0.20", features = ["critical-section"], optional = true } -esp32s2 = { version = "0.32", features = ["critical-section"], optional = true } -esp32s3 = { version = "0.36", features = ["critical-section"], optional = true } +esp-wifi-sys-esp32 = { version = "0.3.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "5afc3a3" } +esp-wifi-sys-esp32c2 = { version = "0.3.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "5afc3a3" } +esp-wifi-sys-esp32c3 = { version = "0.3.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "5afc3a3" } +esp-wifi-sys-esp32c5 = { version = "0.3.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "5afc3a3" } +esp-wifi-sys-esp32c6 = { version = "0.3.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "5afc3a3" } +esp-wifi-sys-esp32c61 = { version = "0.3.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "5afc3a3" } +esp-wifi-sys-esp32h2 = { version = "0.3.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "5afc3a3" } +esp-wifi-sys-esp32h4 = { version = "0.3.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "5afc3a3" } +esp-wifi-sys-esp32s2 = { version = "0.3.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "5afc3a3" } +esp-wifi-sys-esp32s3 = { version = "0.3.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "5afc3a3" } +esp-wifi-sys-esp32s31 = { version = "0.3.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "5afc3a3" } -embassy-sync = "0.8" +esp32 = { version = "0.42", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32c2 = { version = "0.31", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32c3 = { version = "0.34", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32c5 = { version = "0.4", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32c6 = { version = "0.25", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32c61 = { version = "0.5", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32h2 = { version = "0.21", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32h4 = { version = "0.1", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32s2 = { version = "0.33", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32s3 = { version = "0.37", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32s31 = { version = "0.3", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } defmt = { version = "1.1", optional = true } log-04 = { version = "0.4.27", package = "log", optional = true } [build-dependencies] esp-config = { version = "0.8.0", path = "../esp-config", features = ["build"] } -esp-metadata-generated = { version = "0.5.0", path = "../esp-metadata-generated", features = ["build-script"] } +esp-metadata-generated = { version = "0.6.0", path = "../esp-metadata-generated", features = ["build-script"] } [features] #! ### Logging Feature Flags @@ -119,6 +124,13 @@ esp32h2 = [ "esp-metadata-generated/esp32h2", ] ## +esp32h4 = [ + "esp-hal/esp32h4", + "dep:esp-wifi-sys-esp32h4", + "dep:esp32h4", + "esp-metadata-generated/esp32h4", +] +## esp32 = [ "esp-hal/esp32", "dep:esp-wifi-sys-esp32", @@ -139,3 +151,10 @@ esp32s3 = [ "dep:esp32s3", "esp-metadata-generated/esp32s3", ] +## +esp32s31 = [ + "esp-hal/esp32s31", + "dep:esp-wifi-sys-esp32s31", + "dep:esp32s31", + "esp-metadata-generated/esp32s31", +] diff --git a/esp-phy/esp_config.yml b/esp-phy/esp_config.yml index 21dccfa59f9..3f019b3793c 100644 --- a/esp-phy/esp_config.yml +++ b/esp-phy/esp_config.yml @@ -7,6 +7,9 @@ options: Turn off for best WiFi performance." default: - value: true + if: "soc_has_usb_device && soc_has_wifi" + - value: false + active: "soc_has_usb_device && soc_has_wifi" - name: phy_skip_calibration_after_deep_sleep description: "Use PHY_RF_CAL_NONE after deep sleep." diff --git a/esp-phy/src/lib.rs b/esp-phy/src/lib.rs index ab6d0cb6773..5e7e19ae73d 100644 --- a/esp-phy/src/lib.rs +++ b/esp-phy/src/lib.rs @@ -23,7 +23,7 @@ mod fmt; pub(crate) mod reg_access; -use core::{cell::Cell, marker::PhantomData}; +use core::marker::PhantomData; use esp_hal::system::Cpu; #[cfg(esp32)] @@ -31,37 +31,32 @@ use esp_hal::time::{Duration, Instant}; use esp_sync::{NonReentrantMutex, RawMutex}; /// Tracks the number of references to the PHY clock. -static PHY_CLOCK_REF_COUNTER: embassy_sync::blocking_mutex::Mutex> = - embassy_sync::blocking_mutex::Mutex::new(Cell::new(0)); +static PHY_CLOCK_REF_COUNTER: NonReentrantMutex = NonReentrantMutex::new(0); fn increase_phy_clock_ref_count_internal() { - PHY_CLOCK_REF_COUNTER.lock(|phy_clock_ref_counter| { - let phy_clock_ref_count = phy_clock_ref_counter.get(); + PHY_CLOCK_REF_COUNTER.with(|refcount| { + let count = *refcount; - if phy_clock_ref_count == 0 { + if count == 0 { phy_clocks::enable_phy(true); } - let new_phy_clock_ref_count = unwrap!( - phy_clock_ref_count.checked_add(1), - "PHY clock ref count overflowed." - ); - phy_clock_ref_counter.set(new_phy_clock_ref_count); + *refcount = unwrap!(count.checked_add(1), "PHY clock ref count overflowed."); }) } fn decrease_phy_clock_ref_count_internal() { - PHY_CLOCK_REF_COUNTER.lock(|phy_clock_ref_counter| { - let new_phy_clock_ref_count = unwrap!( - phy_clock_ref_counter.get().checked_sub(1), + PHY_CLOCK_REF_COUNTER.with(|refcount| { + let count = unwrap!( + refcount.checked_sub(1), "PHY clock ref count underflowed. Either you forgot a PhyClockGuard, or used PhyController::decrease_phy_clock_ref_count incorrectly." ); - if new_phy_clock_ref_count == 0 { + if count == 0 { phy_clocks::enable_phy(false); } - phy_clock_ref_counter.set(new_phy_clock_ref_count); + *refcount = count; }) } @@ -105,10 +100,14 @@ pub(crate) mod sys { pub use esp_wifi_sys_esp32c61::*; #[cfg(esp32h2)] pub use esp_wifi_sys_esp32h2::*; + #[cfg(esp32h4)] + pub use esp_wifi_sys_esp32h4::*; #[cfg(esp32s2)] pub use esp_wifi_sys_esp32s2::*; #[cfg(esp32s3)] pub use esp_wifi_sys_esp32s3::*; + #[cfg(esp32s31)] + pub use esp_wifi_sys_esp32s31::*; } mod common_adapter; @@ -206,23 +205,13 @@ impl PhyState { // turning Wi-Fi RX on/off via `set_wifi_rx_enabled` when it enables/disables the PHY. // This mirrors `esp_phy_load_cal_and_init` in ESP-IDF. cfg_select! { - esp32c5 => { - // C5 is intentionally excluded: ESP-IDF leaves `SOC_PHY_COMBO_MODULE` undefined - // for C5, so it doesn't call `phy_init_param_set` there. See: - // https://github.com/espressif/esp-idf/blob/7e3df61a/components/soc/esp32c5/include/soc/soc_caps.h#L658 - // TODO: enable for C5. - } phy_combo_module => unsafe { sys::include::phy_init_param_set(1); }, _ => {} } - #[cfg(all( - phy_enable_usb, - any(soc_has_usb_fs, soc_has_usb_device), - not(any(esp32s2, esp32h2)) - ))] + #[cfg(phy_enable_usb)] unsafe { // FIXME: we should be using from esp-wifi-sys, but the function is missing for C6 // (CONFIG_ESP_PHY_ENABLE_USB is not defined) @@ -298,16 +287,18 @@ impl PhyState { self.phy_clock_state_transition_timestamp = now; self.mac_clock_delta_since_last_call += delta; } - if self.calibrated { - unsafe { - sys::include::phy_wakeup_init(); + phy_clocks::with_calibration_clocks(|| { + if self.calibrated { + unsafe { + sys::include::phy_wakeup_init(); + } + #[cfg(phy_backed_up_digital_register_count_is_set)] + self.restore_digital_regs(); + } else { + self.calibrate(); + self.calibrated = true; } - #[cfg(phy_backed_up_digital_register_count_is_set)] - self.restore_digital_regs(); - } else { - self.calibrate(); - self.calibrated = true; - } + }); } #[cfg(esp32)] if let Some(cb) = self.mac_time_update_cb { @@ -354,7 +345,8 @@ impl PhyState { fn is_reset_from_deepsleep() -> bool { // feature gated to avoid forgetting to double check the correct value for future chips #[cfg(any( - esp32, esp32c2, esp32c3, esp32c5, esp32c6, esp32c61, esp32h2, esp32s2, esp32s3 + esp32, esp32c2, esp32c3, esp32c5, esp32c6, esp32c61, esp32h2, esp32h4, esp32s2, esp32s3, + esp32s31 ))] const CORE_DEEP_SLEEP: u32 = 5; @@ -449,15 +441,6 @@ pub fn disable_phy_with_wifi_rx() { /// On non-combo modules this is a no-op. fn set_wifi_rx_enabled(enabled: bool) { cfg_select! { - esp32c5 => { - // C5 is excluded for the same reason as `phy_init_param_set` (ESP-IDF leaves - // `SOC_PHY_COMBO_MODULE` undefined for C5, see: - // https://github.com/espressif/esp-idf/blob/7e3df61a/components/soc/esp32c5/include/soc/soc_caps.h#L658); - // its Wi-Fi adapter only calls `phy_wifi_enable_set` alongside a `set_bb_wdg` - // workaround we don't implement yet. TODO: enable for C5 once `set_bb_wdg` - // is handled. - let _ = enabled; - } phy_combo_module => unsafe { sys::include::phy_wifi_enable_set(enabled as u8); }, diff --git a/esp-phy/src/phy_clocks/mod.rs b/esp-phy/src/phy_clocks/mod.rs index 19a50d33660..d1ebaae70d9 100644 --- a/esp-phy/src/phy_clocks/mod.rs +++ b/esp-phy/src/phy_clocks/mod.rs @@ -5,10 +5,51 @@ #[cfg_attr(esp32c6, path = "phy_clocks_ll_esp32c6.rs")] #[cfg_attr(esp32c61, path = "phy_clocks_ll_esp32c61.rs")] #[cfg_attr(esp32h2, path = "phy_clocks_ll_esp32h2.rs")] +#[cfg_attr(esp32h4, path = "phy_clocks_ll_esp32h4.rs")] #[cfg_attr(esp32s2, path = "phy_clocks_ll_esp32s2.rs")] #[cfg_attr(esp32s3, path = "phy_clocks_ll_esp32s3.rs")] +#[cfg_attr(esp32s31, path = "phy_clocks_ll_esp32s31.rs")] mod phy_clocks_ll; pub(crate) fn enable_phy(enable: bool) { + debug!("enable_phy({:?})", enable); phy_clocks_ll::enable_phy(enable); } + +/// Runs `f` with the modem clocks that the PHY initialization and wake-up sequences access. +/// +/// Without them, `phy_wakeup_init` on the ESP32-C61 stalls on every register access for about +/// 11 ms. The previous state of the clocks is restored afterwards, because Wi-Fi and BLE own some +/// of them. +#[cfg(any(esp32c5, esp32c6, esp32c61))] +pub(crate) fn with_calibration_clocks(f: impl FnOnce() -> R) -> R { + use phy_clocks_ll::{CALIBRATION_CLK_CONF_MASK, CALIBRATION_CLK_CONF1_MASK}; + + let syscon = regs!(MODEM_SYSCON); + let clk_conf = syscon.clk_conf().read().bits() & CALIBRATION_CLK_CONF_MASK; + let clk_conf1 = syscon.clk_conf1().read().bits() & CALIBRATION_CLK_CONF1_MASK; + + syscon + .clk_conf() + .modify(|r, w| unsafe { w.bits(r.bits() | CALIBRATION_CLK_CONF_MASK) }); + syscon + .clk_conf1() + .modify(|r, w| unsafe { w.bits(r.bits() | CALIBRATION_CLK_CONF1_MASK) }); + + let result = f(); + + syscon + .clk_conf() + .modify(|r, w| unsafe { w.bits(r.bits() & !CALIBRATION_CLK_CONF_MASK | clk_conf) }); + syscon + .clk_conf1() + .modify(|r, w| unsafe { w.bits(r.bits() & !CALIBRATION_CLK_CONF1_MASK | clk_conf1) }); + + result +} + +/// Runs `f`. On this chip, other code already keeps the clocks running that the PHY accesses. +#[cfg(not(any(esp32c5, esp32c6, esp32c61)))] +pub(crate) fn with_calibration_clocks(f: impl FnOnce() -> R) -> R { + f() +} diff --git a/esp-phy/src/phy_clocks/phy_clocks_ll_esp32c5.rs b/esp-phy/src/phy_clocks/phy_clocks_ll_esp32c5.rs index c47b61e6433..ec6bf91eaa0 100644 --- a/esp-phy/src/phy_clocks/phy_clocks_ll_esp32c5.rs +++ b/esp-phy/src/phy_clocks/phy_clocks_ll_esp32c5.rs @@ -23,21 +23,10 @@ pub(crate) fn enable_phy(en: bool) { .clk_conf() .modify(|_, w| w.clk_coex_en().bit(en)); - regs!(MODEM_SYSCON).clk_conf1().modify(|_, w| { - w.clk_wifi_apb_en().bit(en); - w.clk_wifibb_22m_en().bit(en); - w.clk_fe_40m_en().bit(en); - w.clk_fe_80m_en().bit(en); - w.clk_wifibb_44m_en().bit(en); - w.clk_wifimac_en().bit(en) - }); - - regs!(MODEM_SYSCON) - .clk_conf1() - .modify(|r, w| unsafe { w.bits(r.bits() | 0x1fb) }); - regs!(MODEM_SYSCON).clk_conf1().modify(|_, w| { w.clk_fe_apb_en().bit(en); + w.clk_fe_20m_en().bit(en); + w.clk_fe_40m_en().bit(en); w.clk_fe_80m_en().bit(en); w.clk_fe_160m_en().bit(en); w.clk_fe_dac_en().bit(en); @@ -45,3 +34,9 @@ pub(crate) fn enable_phy(en: bool) { w.clk_fe_adc_en().bit(en) }); } + +/// `MODEM_SYSCON.clk_conf`: `clk_modem_sec_apb_en`. +pub(crate) const CALIBRATION_CLK_CONF_MASK: u32 = 1 << 28; +/// `MODEM_SYSCON.clk_conf1`: `clk_wifibb_*_en` (bits 0-8), `clk_wifi_apb_en`, `clk_bt_apb_en` and +/// `clk_btbb_en`. +pub(crate) const CALIBRATION_CLK_CONF1_MASK: u32 = 0x1ff | 1 << 10 | 1 << 16 | 1 << 17; diff --git a/esp-phy/src/phy_clocks/phy_clocks_ll_esp32c6.rs b/esp-phy/src/phy_clocks/phy_clocks_ll_esp32c6.rs index 3d7b6998fef..8552891a27e 100644 --- a/esp-phy/src/phy_clocks/phy_clocks_ll_esp32c6.rs +++ b/esp-phy/src/phy_clocks/phy_clocks_ll_esp32c6.rs @@ -1,4 +1,13 @@ pub(crate) fn enable_phy(en: bool) { + // The PHY owns the front-end clocks, as in ESP-IDF's `PHY_CLOCK_DEPS`. Every radio needs them + // while the PHY is on, and `phy_wakeup_init` needs them too, so a radio must not gate them + // while it dozes. + regs!(MODEM_SYSCON).clk_conf1().modify(|_, w| { + w.clk_fe_apb_en().bit(en); + w.clk_fe_cal_160m_en().bit(en); + w.clk_fe_160m_en().bit(en); + w.clk_fe_80m_en().bit(en) + }); regs!(MODEM_LPCON) .clk_conf() .modify(|_, w| w.clk_i2c_mst_en().bit(en)); @@ -6,3 +15,8 @@ pub(crate) fn enable_phy(en: bool) { .i2c_mst_clk_conf() .modify(|_, w| w.clk_i2c_mst_sel_160m().bit(en)); } + +/// `MODEM_SYSCON.clk_conf`: `clk_modem_sec_apb_en`. +pub(crate) const CALIBRATION_CLK_CONF_MASK: u32 = 1 << 28; +/// `MODEM_SYSCON.clk_conf1`: `clk_wifibb_*_en` (bits 0-8), `clk_bt_apb_en` and `clk_bt_en`. +pub(crate) const CALIBRATION_CLK_CONF1_MASK: u32 = 0x1ff | 1 << 17 | 1 << 18; diff --git a/esp-phy/src/phy_clocks/phy_clocks_ll_esp32c61.rs b/esp-phy/src/phy_clocks/phy_clocks_ll_esp32c61.rs index c47b61e6433..ec6bf91eaa0 100644 --- a/esp-phy/src/phy_clocks/phy_clocks_ll_esp32c61.rs +++ b/esp-phy/src/phy_clocks/phy_clocks_ll_esp32c61.rs @@ -23,21 +23,10 @@ pub(crate) fn enable_phy(en: bool) { .clk_conf() .modify(|_, w| w.clk_coex_en().bit(en)); - regs!(MODEM_SYSCON).clk_conf1().modify(|_, w| { - w.clk_wifi_apb_en().bit(en); - w.clk_wifibb_22m_en().bit(en); - w.clk_fe_40m_en().bit(en); - w.clk_fe_80m_en().bit(en); - w.clk_wifibb_44m_en().bit(en); - w.clk_wifimac_en().bit(en) - }); - - regs!(MODEM_SYSCON) - .clk_conf1() - .modify(|r, w| unsafe { w.bits(r.bits() | 0x1fb) }); - regs!(MODEM_SYSCON).clk_conf1().modify(|_, w| { w.clk_fe_apb_en().bit(en); + w.clk_fe_20m_en().bit(en); + w.clk_fe_40m_en().bit(en); w.clk_fe_80m_en().bit(en); w.clk_fe_160m_en().bit(en); w.clk_fe_dac_en().bit(en); @@ -45,3 +34,9 @@ pub(crate) fn enable_phy(en: bool) { w.clk_fe_adc_en().bit(en) }); } + +/// `MODEM_SYSCON.clk_conf`: `clk_modem_sec_apb_en`. +pub(crate) const CALIBRATION_CLK_CONF_MASK: u32 = 1 << 28; +/// `MODEM_SYSCON.clk_conf1`: `clk_wifibb_*_en` (bits 0-8), `clk_wifi_apb_en`, `clk_bt_apb_en` and +/// `clk_btbb_en`. +pub(crate) const CALIBRATION_CLK_CONF1_MASK: u32 = 0x1ff | 1 << 10 | 1 << 16 | 1 << 17; diff --git a/esp-phy/src/phy_clocks/phy_clocks_ll_esp32h4.rs b/esp-phy/src/phy_clocks/phy_clocks_ll_esp32h4.rs new file mode 100644 index 00000000000..bfbd6c65285 --- /dev/null +++ b/esp-phy/src/phy_clocks/phy_clocks_ll_esp32h4.rs @@ -0,0 +1,14 @@ +pub(crate) fn enable_phy(en: bool) { + // IDF `PHY_CLOCK_DEPS`: the common and private FE clocks and the analog I2C master. + regs!(MODEM_SYSCON).clk_conf1().modify(|_, w| { + w.clk_fe_apb_en().bit(en); + w.clk_fe_32m_en().bit(en); + w.clk_fe_16m_en().bit(en); + w.clk_fe_adc_en().bit(en); + w.clk_fe_sdm_en().bit(en) + }); + + regs!(MODEM_LPCON) + .clk_conf() + .modify(|_, w| w.clk_i2c_mst_en().bit(en)); +} diff --git a/esp-phy/src/phy_clocks/phy_clocks_ll_esp32s31.rs b/esp-phy/src/phy_clocks/phy_clocks_ll_esp32s31.rs new file mode 100644 index 00000000000..8696946d9ed --- /dev/null +++ b/esp-phy/src/phy_clocks/phy_clocks_ll_esp32s31.rs @@ -0,0 +1,70 @@ +pub(crate) fn enable_phy(en: bool) { + if en { + // IDF `modem_clock_hal_enable_soc_pll_source_cg` (0x3d). PHY calibration + // talks to analog via I2C and needs the modem PLL, not XTAL-only 0x25. + regs!(HP_SYS_CLKRST).modem_conf().modify(|_, w| { + w.modem_apb_clk_en().set_bit(); + w.modem_rst_en().clear_bit(); + w.modem_clk_en().set_bit(); + w.modem_clk_source_sel().set_bit(); + w.modem_pll_clk_en().set_bit(); + w.modem_xtal_clk_en().set_bit() + }); + } + + regs!(MODEM_SYSCON) + .clk_conf_power_st() + .modify(|_, w| unsafe { + w.clk_modem_apb_st_map().bits(6); + w.clk_modem_peri_st_map().bits(4); + w.clk_wifi_st_map().bits(6); + w.clk_bt_st_map().bits(6); + w.clk_fe_st_map().bits(6); + w.clk_zb_st_map().bits(4) + }); + + regs!(MODEM_LPCON) + .clk_conf_power_st() + .modify(|_, w| unsafe { + w.clk_lp_apb_st_map().bits(6); + w.clk_i2c_mst_st_map().bits(6); + w.clk_coex_st_map().bits(6); + w.clk_wifipwr_st_map().bits(6) + }); + + regs!(MODEM_SYSCON) + .clk_conf() + .modify(|_, w| w.clk_i2c_mst_sel_160m().bit(en)); + // `clk_wifipwr_en` stays on after the first enable. It drives the timer that wakes the modem + // for the next beacon, and the PHY is disabled at every doze. + if en { + regs!(MODEM_LPCON) + .clk_conf() + .modify(|_, w| w.clk_wifipwr_en().set_bit()); + } + + regs!(MODEM_SYSCON).clk_conf1().modify(|_, w| { + w.clk_fe_apb_en().bit(en); + w.clk_fe_20m_en().bit(en); + w.clk_fe_40m_en().bit(en); + w.clk_fe_80m_en().bit(en); + w.clk_fe_160m_en().bit(en); + w.clk_fe_dac_en().bit(en); + w.clk_fe_pwdet_adc_en().bit(en); + w.clk_fe_adc_en().bit(en); + + // Treat this as shared, BLE needs it. + // Must be kept enabled or many things fail. + w.clk_wifi_apb_en().bit(true); + w.clk_wifibb_80x1_en().bit(true); + + w.clk_wifibb_160x1_en().bit(en); + w.clk_wifibb_40x1_en().bit(en); + w.clk_wifibb_80x_en().bit(en); + w.clk_wifibb_40x_en().bit(en); + w.clk_wifibb_80m_en().bit(en); + w.clk_wifibb_44m_en().bit(en); + w.clk_wifibb_40m_en().bit(en); + w.clk_wifibb_22m_en().bit(en) + }); +} diff --git a/esp-phy/src/phy_init_data/mod.rs b/esp-phy/src/phy_init_data/mod.rs index dffc82f9d57..a0b24858634 100644 --- a/esp-phy/src/phy_init_data/mod.rs +++ b/esp-phy/src/phy_init_data/mod.rs @@ -5,7 +5,9 @@ #[cfg_attr(esp32c6, path = "phy_init_data_esp32c6.rs")] #[cfg_attr(esp32c61, path = "phy_init_data_esp32c61.rs")] #[cfg_attr(esp32h2, path = "phy_init_data_esp32h2.rs")] +#[cfg_attr(esp32h4, path = "phy_init_data_esp32h4.rs")] #[cfg_attr(esp32s2, path = "phy_init_data_esp32s2.rs")] #[cfg_attr(esp32s3, path = "phy_init_data_esp32s3.rs")] +#[cfg_attr(esp32s31, path = "phy_init_data_esp32s31.rs")] mod chip_phy_init_data; pub(crate) use chip_phy_init_data::PHY_INIT_DATA_DEFAULT; diff --git a/esp-phy/src/phy_init_data/phy_init_data_esp32h4.rs b/esp-phy/src/phy_init_data/phy_init_data_esp32h4.rs new file mode 100644 index 00000000000..feb21ef0e1b --- /dev/null +++ b/esp-phy/src/phy_init_data/phy_init_data_esp32h4.rs @@ -0,0 +1,146 @@ +use crate::sys::include::esp_phy_init_data_t; + +const CONFIG_ESP_PHY_MAX_TX_POWER: u8 = 20; + +const fn limit(val: u8, low: u8, high: u8) -> u8 { + if val < low { + low + } else if val > high { + high + } else { + val + } +} + +pub(crate) static PHY_INIT_DATA_DEFAULT: esp_phy_init_data_t = esp_phy_init_data_t { + params: [ + 0x01, + 0x00, + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x54), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x54), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x54), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x50), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x50), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x4c), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x4c), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x4c), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x4c), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x48), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x28), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x28), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x28), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x28), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x4c), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x4c), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x4c), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x4c), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x48), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x28), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x28), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x28), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x28), + 0x00, + 0x00, + 0x00, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0xff, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0x9B, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ], +}; diff --git a/esp-phy/src/phy_init_data/phy_init_data_esp32s31.rs b/esp-phy/src/phy_init_data/phy_init_data_esp32s31.rs new file mode 100644 index 00000000000..0a549171181 --- /dev/null +++ b/esp-phy/src/phy_init_data/phy_init_data_esp32s31.rs @@ -0,0 +1,146 @@ +use crate::sys::include::esp_phy_init_data_t; + +const CONFIG_ESP_PHY_MAX_TX_POWER: u8 = 20; + +const fn limit(val: u8, low: u8, high: u8) -> u8 { + if val < low { + low + } else if val > high { + high + } else { + val + } +} + +pub(crate) static PHY_INIT_DATA_DEFAULT: esp_phy_init_data_t = esp_phy_init_data_t { + params: [ + 0x1, + 0x0, + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x54), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x54), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x50), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x50), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x4C), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x48), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x50), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x50), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x4c), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x48), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x40), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x3C), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x3C), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x3C), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x4c), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x4c), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x48), + limit(CONFIG_ESP_PHY_MAX_TX_POWER * 4, 0, 0x44), + 0x0, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0x51, + ], +}; diff --git a/esp-phy/src/reg_access.rs b/esp-phy/src/reg_access.rs index 5f073260dcc..b7f9d2fb633 100644 --- a/esp-phy/src/reg_access.rs +++ b/esp-phy/src/reg_access.rs @@ -17,10 +17,14 @@ pub(crate) use esp32c6 as pac; pub(crate) use esp32c61 as pac; #[cfg(esp32h2)] pub(crate) use esp32h2 as pac; +#[cfg(esp32h4)] +pub(crate) use esp32h4 as pac; #[cfg(esp32s2)] pub(crate) use esp32s2 as pac; #[cfg(esp32s3)] pub(crate) use esp32s3 as pac; +#[cfg(esp32s31)] +pub(crate) use esp32s31 as pac; /// Get a peripheral register block reference from the PAC. macro_rules! regs { diff --git a/esp-println/CHANGELOG.md b/esp-println/CHANGELOG.md index 5fab1e855ca..4bc313b9c03 100644 --- a/esp-println/CHANGELOG.md +++ b/esp-println/CHANGELOG.md @@ -9,8 +9,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- Initial ESP32-P4 (chip revision v3.0+) support (#5400) -- Add ESP32-S31 support (#5922) ### Changed @@ -21,6 +19,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Removed +## [v0.18.0] - 2026-08-25 + +### Added + +- Initial ESP32-P4 (chip revision v3.0+) support (#5400) +- Add ESP32-S31 support (#5922) +- USB Serial/JTAG support for ESP32-S31 (#6184) + +### Changed + +- updated defmt to 1.1 (#5752) + ## [v0.17.0] - 2026-04-16 ### Added @@ -136,4 +146,5 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 [v0.16.0]: https://github.com/esp-rs/esp-hal/compare/esp-println-v0.15.0...esp-println-v0.16.0 [v0.16.1]: https://github.com/esp-rs/esp-hal/compare/esp-println-v0.16.0...esp-println-v0.16.1 [v0.17.0]: https://github.com/esp-rs/esp-hal/compare/esp-println-v0.16.1...esp-println-v0.17.0 -[Unreleased]: https://github.com/esp-rs/esp-hal/compare/esp-println-v0.17.0...HEAD +[v0.18.0]: https://github.com/esp-rs/esp-hal/compare/esp-println-v0.17.0...esp-println-v0.18.0 +[Unreleased]: https://github.com/esp-rs/esp-hal/compare/esp-println-v0.18.0...HEAD diff --git a/esp-println/Cargo.toml b/esp-println/Cargo.toml index 07a721d1956..a06ccdff61b 100644 --- a/esp-println/Cargo.toml +++ b/esp-println/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "esp-println" -version = "0.17.0" +version = "0.18.0" edition = "2024" rust-version = "1.95.0" description = "Provides `print!` and `println!` implementations for various Espressif devices" @@ -51,7 +51,7 @@ defmt = { version = "1.1", optional = true } log-04 = { package = "log", version = "0.4", optional = true } [build-dependencies] -esp-metadata-generated = { version = "0.5.0", path = "../esp-metadata-generated", features = ["build-script"] } +esp-metadata-generated = { version = "0.6.0", path = "../esp-metadata-generated", features = ["build-script"] } log-04 = { package = "log", version = "0.4" } [features] @@ -64,6 +64,7 @@ esp32c5 = ["esp-metadata-generated/esp32c5", "esp-sync?/esp32c5"] esp32c6 = ["esp-metadata-generated/esp32c6", "esp-sync?/esp32c6"] esp32c61 = ["esp-metadata-generated/esp32c61", "esp-sync?/esp32c61"] esp32h2 = ["esp-metadata-generated/esp32h2", "esp-sync?/esp32h2"] +esp32h4 = ["esp-metadata-generated/esp32h4", "esp-sync?/esp32h4"] esp32p4 = ["esp-metadata-generated/esp32p4", "esp-sync?/esp32p4"] esp32s2 = ["esp-metadata-generated/esp32s2", "esp-sync?/esp32s2"] esp32s3 = ["esp-metadata-generated/esp32s3", "esp-sync?/esp32s3"] diff --git a/esp-println/build.rs b/esp-println/build.rs index f198fd2e292..5705cc5e49e 100644 --- a/esp-println/build.rs +++ b/esp-println/build.rs @@ -14,7 +14,7 @@ fn main() -> Result<(), Box> { if cfg!(feature = "jtag-serial") && !has_jtag_serial { panic!( - "The `jtag-serial` feature is only supported by the ESP32-C3, ESP32-C5, ESP32-C6, ESP32-C61, ESP32-H2, ESP32-P4, ESP32-S3, and ESP32-S31" + "The `jtag-serial` feature is only supported by the ESP32-C3, ESP32-C5, ESP32-C6, ESP32-C61, ESP32-H2, ESP32-H4, ESP32-P4, ESP32-S3, and ESP32-S31" ); } diff --git a/esp-println/src/lib.rs b/esp-println/src/lib.rs index 2001f338eee..737acdb2722 100644 --- a/esp-println/src/lib.rs +++ b/esp-println/src/lib.rs @@ -151,6 +151,7 @@ type PrinterImpl = noop::Printer; feature = "esp32c6", feature = "esp32c61", feature = "esp32h2", + feature = "esp32h4", feature = "esp32p4", feature = "esp32s3", feature = "esp32s31" @@ -182,11 +183,13 @@ mod auto_printer { ))] const USB_DEVICE_INT_RAW: *const u32 = 0x6000f008 as *const u32; #[cfg(feature = "esp32s3")] - const USB_DEVICE_INT_RAW: *const u32 = 0x60038000 as *const u32; + const USB_DEVICE_INT_RAW: *const u32 = 0x60038008 as *const u32; #[cfg(feature = "esp32p4")] const USB_DEVICE_INT_RAW: *const u32 = 0x500D2008 as *const u32; #[cfg(feature = "esp32s31")] const USB_DEVICE_INT_RAW: *const u32 = 0x20391008 as *const u32; + #[cfg(feature = "esp32h4")] + const USB_DEVICE_INT_RAW: *const u32 = 0x6001D008 as *const u32; const SOF_INT_MASK: u32 = 0b10; @@ -219,6 +222,7 @@ mod auto_printer { feature = "esp32c6", feature = "esp32c61", feature = "esp32h2", + feature = "esp32h4", feature = "esp32p4", feature = "esp32s3", feature = "esp32s31" @@ -237,6 +241,7 @@ mod auto_printer { feature = "esp32c6", feature = "esp32c61", feature = "esp32h2", + feature = "esp32h4", feature = "esp32p4", feature = "esp32s3", feature = "esp32s31" @@ -285,6 +290,12 @@ mod serial_jtag_printer { #[cfg(feature = "esp32s31")] const SERIAL_JTAG_CONF_REG: usize = 0x2039_1004; + // ESP32-H4: USB_DEVICE peripheral at 0x6001_D000 per PAC. + #[cfg(feature = "esp32h4")] + const SERIAL_JTAG_FIFO_REG: usize = 0x6001_D000; + #[cfg(feature = "esp32h4")] + const SERIAL_JTAG_CONF_REG: usize = 0x6001_D004; + /// A previous wait has timed out. We use this flag to avoid blocking /// forever if there is no host attached. static TIMED_OUT: AtomicBool = AtomicBool::new(false); @@ -360,64 +371,11 @@ mod serial_jtag_printer { } } -#[cfg(all(any(feature = "uart", feature = "auto"), feature = "esp32"))] -mod uart_printer { - use super::LockToken; - const UART_TX_ONE_CHAR: usize = 0x4000_9200; - - pub struct Printer; - impl Printer { - pub fn write_bytes_in_cs(bytes: &[u8], _token: LockToken<'_>) { - for &b in bytes { - unsafe { - let uart_tx_one_char: unsafe extern "C" fn(u8) -> i32 = - core::mem::transmute(UART_TX_ONE_CHAR); - uart_tx_one_char(b) - }; - } - } - - pub fn flush(_token: LockToken<'_>) {} - } -} - -#[cfg(all(any(feature = "uart", feature = "auto"), feature = "esp32s2"))] -mod uart_printer { - use super::LockToken; - pub struct Printer; - impl Printer { - pub fn write_bytes_in_cs(bytes: &[u8], _token: LockToken<'_>) { - // On ESP32-S2 the UART_TX_ONE_CHAR ROM-function seems to have some issues. - for chunk in bytes.chunks(64) { - for &b in chunk { - unsafe { - // write FIFO - (0x3f400000 as *mut u32).write_volatile(b as u32); - }; - } - - // wait for TX_DONE - while unsafe { (0x3f400004 as *const u32).read_volatile() } & (1 << 14) == 0 {} - unsafe { - // reset TX_DONE - (0x3f400010 as *mut u32).write_volatile(1 << 14); - } - } - } - - pub fn flush(_token: LockToken<'_>) {} - } -} - -#[cfg(all( - any(feature = "uart", feature = "auto"), - not(any(feature = "esp32", feature = "esp32s2")) -))] +#[cfg(any(feature = "uart", feature = "auto"))] mod uart_printer { use super::LockToken; trait Functions { const TX_ONE_CHAR: usize; - const CHUNK_SIZE: usize = 32; fn tx_byte(b: u8) { unsafe { @@ -427,15 +385,13 @@ mod uart_printer { } } - fn flush(); + fn flush() {} } struct Device; - // ESP32-P4: resolve through the linker-provided ROM symbol - // (`esp_rom_uart_tx_one_char` -> `uart_tx_one_char2 = 0x4fc0_0058`, - // see esp-rom-sys/ld/esp32p4/rom/esp32p4.rom.api.ld) instead of - // hardcoding the address. Matches the c5/c6/c61/h2 channel-aware path. + // ESP32-P4: resolve through the linker-provided ROM symbol instead of + // hardcoding the address. #[cfg(any(feature = "esp32p4", feature = "esp32s31"))] impl Functions for Device { // Unused -- tx_byte() below resolves through the linker. @@ -449,90 +405,57 @@ mod uart_printer { esp_rom_uart_tx_one_char(b); } } + } - fn flush() { - // tx_one_char waits for TX FIFO space - } + #[cfg(feature = "esp32")] + impl Functions for Device { + const TX_ONE_CHAR: usize = 0x4000_9200; + } + + #[cfg(feature = "esp32s2")] + impl Functions for Device { + const TX_ONE_CHAR: usize = 0x4001_2B10; } #[cfg(feature = "esp32c2")] impl Functions for Device { const TX_ONE_CHAR: usize = 0x4000_005C; - - fn flush() { - // tx_one_char waits for empty - } } #[cfg(feature = "esp32c3")] impl Functions for Device { const TX_ONE_CHAR: usize = 0x4000_0068; - - fn flush() { - unsafe { - const TX_FLUSH: usize = 0x4000_0080; - const GET_CHANNEL: usize = 0x4000_058C; - let tx_flush: unsafe extern "C" fn(u8) = core::mem::transmute(TX_FLUSH); - let get_channel: unsafe extern "C" fn() -> u8 = core::mem::transmute(GET_CHANNEL); - - const G_USB_PRINT_ADDR: usize = 0x3FCD_FFD0; - let g_usb_print = G_USB_PRINT_ADDR as *mut bool; - - let channel = if *g_usb_print { - // Flush USB-JTAG - 3 - } else { - get_channel() - }; - tx_flush(channel); - } - } } #[cfg(feature = "esp32s3")] impl Functions for Device { const TX_ONE_CHAR: usize = 0x4000_0648; - - fn flush() { - unsafe { - const TX_FLUSH: usize = 0x4000_0690; - const GET_CHANNEL: usize = 0x4000_1A58; - let tx_flush: unsafe extern "C" fn(u8) = core::mem::transmute(TX_FLUSH); - let get_channel: unsafe extern "C" fn() -> u8 = core::mem::transmute(GET_CHANNEL); - - const G_USB_PRINT_ADDR: usize = 0x3FCE_FFB8; - let g_usb_print = G_USB_PRINT_ADDR as *mut bool; - - let channel = if *g_usb_print { - // Flush USB-JTAG - 4 - } else { - get_channel() - }; - tx_flush(channel); - } - } } #[cfg(any( feature = "esp32c5", feature = "esp32c6", feature = "esp32c61", - feature = "esp32h2" + feature = "esp32h2", + feature = "esp32h4" ))] impl Functions for Device { const TX_ONE_CHAR: usize = 0x4000_0058; fn flush() { - unsafe { - const TX_FLUSH: usize = 0x4000_0074; + const TX_FLUSH: usize = 0x4000_0074; - #[cfg(not(any(feature = "esp32c5", feature = "esp32c61")))] - const GET_CHANNEL: usize = 0x4000_003C; - - #[cfg(any(feature = "esp32c5", feature = "esp32c61"))] - const GET_CHANNEL: usize = 0x4000_0038; + const GET_CHANNEL: usize = if cfg!(any( + feature = "esp32c5", + feature = "esp32c61", + feature = "esp32h4" + )) { + 0x4000_0038 + } else { + 0x4000_003C + }; + unsafe { let tx_flush: unsafe extern "C" fn(u8) = core::mem::transmute(TX_FLUSH); let get_channel: unsafe extern "C" fn() -> u8 = core::mem::transmute(GET_CHANNEL); @@ -544,16 +467,14 @@ mod uart_printer { pub struct Printer; impl Printer { pub fn write_bytes_in_cs(bytes: &[u8], _token: LockToken<'_>) { - for chunk in bytes.chunks(Device::CHUNK_SIZE) { - for &b in chunk { - Device::tx_byte(b); - } - - Device::flush(); + for &b in bytes { + Device::tx_byte(b); } } - pub fn flush(_token: LockToken<'_>) {} + pub fn flush(_token: LockToken<'_>) { + Device::flush(); + } } } diff --git a/esp-radio-rtos-driver/CHANGELOG.md b/esp-radio-rtos-driver/CHANGELOG.md index ec435880313..39d64e53235 100644 --- a/esp-radio-rtos-driver/CHANGELOG.md +++ b/esp-radio-rtos-driver/CHANGELOG.md @@ -19,6 +19,44 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Removed +## [v0.4.2] - 2026-09-15 + +### Added + +- Support for ESP32-S31 (#6296) +- `QueueHandle` and `SemaphoreHandle` are now `Send` and `Sync` (#6222) +- Configurable `CompatTimer` thread priority. (#5908) + +### Changed + +- Made `CompatTimer` const-generic (the thread priority) (#5908) +- updated defmt to 1.1 (#5752) + +### Removed + +- `CompatTimer::new` (#5908) + +## [v0.4.1] - 2026-09-01 + +### Added + +- `QueueHandle` and `SemaphoreHandle` are now `Send` and `Sync` (#6222) + +## [v0.4.0] - 2026-08-25 + +### Added + +- Configurable `CompatTimer` thread priority. (#5908) + +### Changed + +- Made `CompatTimer` const-generic (the thread priority) (#5908) +- updated defmt to 1.1 (#5752) + +### Removed + +- `CompatTimer::new` (#5908) + ## [v0.3.0] - 2026-04-16 ### Added @@ -62,4 +100,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 [v0.1.0]: https://github.com/esp-rs/esp-hal/releases/tag/esp-radio-rtos-driver-v0.1.0 [v0.2.0]: https://github.com/esp-rs/esp-hal/compare/esp-radio-rtos-driver-v0.1.0...esp-radio-rtos-driver-v0.2.0 [v0.3.0]: https://github.com/esp-rs/esp-hal/compare/esp-radio-rtos-driver-v0.2.0...esp-radio-rtos-driver-v0.3.0 -[Unreleased]: https://github.com/esp-rs/esp-hal/compare/esp-radio-rtos-driver-v0.3.0...HEAD +[v0.4.0]: https://github.com/esp-rs/esp-hal/compare/esp-radio-rtos-driver-v0.3.0...esp-radio-rtos-driver-v0.4.0 +[v0.4.1]: https://github.com/esp-rs/esp-hal/compare/esp-radio-rtos-driver-v0.4.0...esp-radio-rtos-driver-v0.4.1 +[v0.4.2]: https://github.com/esp-rs/esp-hal/compare/esp-radio-rtos-driver-v0.4.1...esp-radio-rtos-driver-v0.4.2 +[Unreleased]: https://github.com/esp-rs/esp-hal/compare/esp-radio-rtos-driver-v0.4.2...HEAD diff --git a/esp-radio-rtos-driver/Cargo.toml b/esp-radio-rtos-driver/Cargo.toml index fb10fd8058c..e9274ae4b6b 100644 --- a/esp-radio-rtos-driver/Cargo.toml +++ b/esp-radio-rtos-driver/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "esp-radio-rtos-driver" -version = "0.3.0" +version = "0.4.2" edition = "2024" rust-version = "1.95.0" description = "Task scheduler interface for esp-radio" @@ -39,8 +39,10 @@ esp32c5 = ["esp-sync?/esp32c5"] esp32c6 = ["esp-sync?/esp32c6"] esp32c61 = ["esp-sync?/esp32c61"] esp32h2 = ["esp-sync?/esp32h2"] +esp32h4 = ["esp-sync?/esp32h4"] esp32s2 = ["esp-sync?/esp32s2"] esp32s3 = ["esp-sync?/esp32s3"] +esp32s31 = ["esp-sync?/esp32s31"] # Logging Feature Flags log-04 = ["dep:log-04"] diff --git a/esp-radio-rtos-driver/src/queue.rs b/esp-radio-rtos-driver/src/queue.rs index ece947fe34b..3ba0e2e83b2 100644 --- a/esp-radio-rtos-driver/src/queue.rs +++ b/esp-radio-rtos-driver/src/queue.rs @@ -54,6 +54,11 @@ unsafe extern "Rust" { item: *const u8, higher_prio_task_waken: Option<&mut bool>, ) -> bool; + fn esp_rtos_queue_try_send_to_front_from_isr( + queue: QueuePtr, + item: *const u8, + higher_prio_task_waken: Option<&mut bool>, + ) -> bool; fn esp_rtos_queue_receive(queue: QueuePtr, item: *mut u8, timeout_us: Option) -> bool; fn esp_rtos_queue_receive_with_deadline( queue: QueuePtr, @@ -222,6 +227,23 @@ pub trait QueueImplementation { higher_prio_task_waken: Option<&mut bool>, ) -> bool; + /// Attempts to enqueues an item at the front of the queue. + /// + /// If the queue is full, this function will immediately return `false`. + /// + /// The `higher_prio_task_waken` parameter is an optional mutable reference to a boolean flag. + /// If the flag is `Some`, the implementation may set it to `true` to request a context switch. + /// + /// # Safety + /// + /// The caller must ensure that `item` can be dereferenced and points to an allocation of + /// a size equal to the queue's item size. + unsafe fn try_send_to_front_from_isr( + queue: QueuePtr, + item: *const u8, + higher_prio_task_waken: Option<&mut bool>, + ) -> bool; + /// Dequeues an item from the queue. /// /// If the queue is empty, this function will block for the given timeout. If timeout is None, @@ -370,6 +392,22 @@ macro_rules! register_queue_implementation { } } + #[unsafe(no_mangle)] + #[inline] + fn esp_rtos_queue_try_send_to_front_from_isr( + queue: $crate::queue::QueuePtr, + item: *const u8, + higher_prio_task_waken: Option<&mut bool>, + ) -> bool { + unsafe { + <$t as $crate::queue::QueueImplementation>::try_send_to_front_from_isr( + queue, + item, + higher_prio_task_waken, + ) + } + } + #[unsafe(no_mangle)] #[inline] fn esp_rtos_queue_receive( @@ -431,6 +469,10 @@ macro_rules! register_queue_implementation { /// This handle is used to interact with queues created by the driver implementation. #[repr(transparent)] pub struct QueueHandle(QueuePtr); + +unsafe impl Send for QueueHandle {} +unsafe impl Sync for QueueHandle {} + impl QueueHandle { /// Creates a new queue instance. #[inline] @@ -564,6 +606,28 @@ impl QueueHandle { } } + /// Attempts to enqueues an item at the front of the queue. + /// + /// If the queue is full, this function will immediately return `false`. + /// + /// If a higher priority task is woken up by this operation, the `higher_prio_task_waken` flag + /// is set to `true`. + /// + /// # Safety + /// + /// The caller must ensure that `item` can be dereferenced and points to an allocation of + /// a size equal to the queue's item size. + #[inline] + pub unsafe fn try_send_to_front_from_isr( + &self, + item: *const u8, + higher_priority_task_waken: Option<&mut bool>, + ) -> bool { + unsafe { + esp_rtos_queue_try_send_to_front_from_isr(self.0, item, higher_priority_task_waken) + } + } + /// Dequeues an item from the queue. /// /// If the queue is empty, this function will block for the given timeout. If timeout is None, @@ -867,6 +931,27 @@ mod implementation { } } + unsafe fn try_send_to_front_from_isr( + queue: QueuePtr, + item: *const u8, + mut higher_prio_task_waken: Option<&mut bool>, + ) -> bool { + let queue = unsafe { CompatQueue::from_ptr(queue) }; + + if queue + .semaphore_empty + .try_take_from_isr(higher_prio_task_waken.as_deref_mut()) + { + queue.with(|inner| inner.send_to_front(item)); + queue + .semaphore_full + .try_give_from_isr(higher_prio_task_waken); + true + } else { + false + } + } + unsafe fn receive(queue: QueuePtr, item: *mut u8, timeout_us: Option) -> bool { let deadline_instant = timeout_us.map(|timeout| now() + timeout as u64); unsafe { Self::receive_with_deadline(queue, item, deadline_instant) } diff --git a/esp-radio-rtos-driver/src/semaphore.rs b/esp-radio-rtos-driver/src/semaphore.rs index 4e6987b933d..4c6acff8b0e 100644 --- a/esp-radio-rtos-driver/src/semaphore.rs +++ b/esp-radio-rtos-driver/src/semaphore.rs @@ -325,6 +325,10 @@ macro_rules! register_semaphore_implementation { /// This handle is used to interact with semaphores created by the driver implementation. #[repr(transparent)] pub struct SemaphoreHandle(SemaphorePtr); + +unsafe impl Send for SemaphoreHandle {} +unsafe impl Sync for SemaphoreHandle {} + impl SemaphoreHandle { /// Creates a new semaphore instance. /// @@ -446,8 +450,6 @@ impl Drop for SemaphoreHandle { } } -unsafe impl Send for SemaphoreHandle {} - #[cfg(feature = "ipc-implementations")] mod implementation { use alloc::boxed::Box; diff --git a/esp-radio/CHANGELOG.md b/esp-radio/CHANGELOG.md index 65a48f8c323..54fc3ac2783 100644 --- a/esp-radio/CHANGELOG.md +++ b/esp-radio/CHANGELOG.md @@ -19,6 +19,69 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Removed +## [v1.0.0-beta.2] - 2026-09-16 + +- Fixed S31 builds (#6341) + +## [v1.0.0-beta.1] - 2026-09-15 + +### Added + +- ESP32-S31 Wi-Fi and 802.15.4. (#6296) +- Wi-Fi 6 support for ESP32-C5 (#6283) +- HIL test `esp_now_survives_controller_drop` to verify Wi-Fi reference counting across controller drop and ESP-NOW teardown. (#6281) +- Wi-Fi: Implemented `xarxa-driver` for the Wi-Fi `Interface`. (#6249) +- `sta_disconnected_pm` and `espnow_max_encrypt_num` to `ControllerConfig` (#6144) +- bt-hci-transport 0.1.0 implementation (#6030) +- `PhyMode`, `RateConfig` (#5884) +- Wifi: `esp_radio::wifi::ConnectionError` (#5872) + +### Changed + +- `WifiError::Failed` has been renamed to `WifiError::Other`. (#6309) +- `ESP_NOW_MAX_DATA_LEN` is now `ESP_NOW_MAX_DATA_LEN_V1` and `ESP_NOW_MAX_DATA_LEN_V2` (#6285) +- `WifiController::esp_now()` and `WifiController::sniffer()` return instances that no longer borrow the controller. Wi-Fi stays initialized until the instance is dropped. (#6281) +- `EspNow`, `EspNowManager`, `EspNowSender`, `EspNowReceiver`, and `Sniffer` no longer carry a lifetime parameter. (#6281) +- Updated Wi-Fi and BLE blobs to ESP-IDF `6.1-255-g4dbfecac7e3`. (#6271) +- BLE: the BLE HCI implementation is now less wasteful about copying data. (#6257) +- Enabling the `coex` feature without both `wifi` and `ble` now fails with a clear error instead of hard to decrypt compiler errors (and an easy to miss warning) (#6159) +- `StationConfig` and `AccessPointConfig` now take authentication via `AuthenticationMethodConfig` instead of separate `auth_method` and `password` fields. (#6146) +- Added a dedicated `Password` type. Oversized passwords are rejected instead of truncated. (#6146) +- `Ssid` is constructed via `TryFrom`; oversized SSIDs are rejected instead of truncated. (#6146) +- `sta_disconnected_pm` now defaults to `CONFIG_ESP_WIFI_STA_DISCONNECTED_PM_ENABLE`, previously it was always `false`. (#6144) +- esp-radio can now be built with opt-level "z" (#5911) +- Replaced `EspNow::set_rate` / `EspNowManager::set_rate` with `set_peer_rate(peer_address, RateConfig)` (#5884) +- Wifi: `WifiController::connect_async` now returns `Result` (#5872) +- Wifi: `WifiError::Disconnected` no longer carries the AP info. (#5872) +- Update `bt-hci` to version 0.9 (#5821) +- updated defmt to 1.1 (#5752) +- `esp_radio::wifi::new()` is now `esp_radio::wifi::WifiController::new()`. (#5605) +- `ConnectedStationInfo` renamed to `sta::ConnectedInfo` and moved to the `sta` module. (#5605) +- `DisconnectedStationInfo` renamed to `sta::DisconnectedInfo` and moved to the `sta` module. (#5605) +- `AccessPointStationConnectedInfo` renamed to `ap::ConnectedInfo` and moved to the `ap` module. (#5605) +- `AccessPointStationDisconnectedInfo` renamed to `ap::DisconnectedInfo` and moved to the `ap` module. (#5605) +- `AccessPointStationEventInfo` renamed to `ap::EventInfo` and moved to the `ap` module. (#5605) +- `AccessPointConfig::max_connections` and `AccessPointConfig::dtim_period` setters are now gated behind the `unstable` feature. (#5605) + +### Fixed + +- Unknown or unmapped Wi-Fi driver error codes no longer panic in `WifiError::from_error_code`. They now map to `WifiError::Other`, and only truly unrecognised codes log a warning. (#6309) +- BLE: BTDM devices no longer block when sending BLE packets through HCI (#6257) +- `WifiController::disconnect_async` can now abort an in-progress connection attempt instead of returning `NotConnected`. (#6254) +- fixed a possible deadlock during Wi-Fi initialization/deinitialization (#6222) +- IEEE 802.15.4 documentation: coexistence with BLE is supported, coexistence with Wi‑Fi remains unsupported. (#6159) +- 802.15.4 - unconditionally raise the pending bit in all ACKs so that SED children are not missing frames (#6090) +- Power down the modem power domain and gate the modem clocks when the last radio driver is deinitialized. (#6074) +- Gate the 802.15.4 modem clocks (including `clk_coex_en` on ESP32-C6) when the driver is dropped. (#6074) +- ESP32-C2 dropping and re-creating WifiController left the radio inoperational (#6074) +- The default BLE default TX power on ESP32-C3/S3 is now correctly set to +9dBm (#6036) +- `WifiPhyRate` enum values (#5884) +- Enable clocks for security engine for esp32h2. (#5852) +- WifiController set_config only updates AP and STA config on changes (#5849) +- Wi-Fi PHY enable/disable now toggles Wi-Fi RX state on combo modules, so restoring the combo-module PHY init no longer breaks Wi-Fi connectivity (#5776) +- ESP-NOW/sniffer `RxControlInfo` RSSI and noise floor values by sign-extending raw 8-bit signed bitfields. (#5687) +- Read the 802.15.4 AR (ack-request) bit and frame-version from the correct FCF octet. They were read one octet too high, misclassifying ack-required frames and breaking ACK handling for fragmented frames. (#5650) + ## [v1.0.0-beta.0] - 2026-06-03 ### Added @@ -481,4 +544,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 [v0.17.0]: https://github.com/esp-rs/esp-hal/compare/esp-radio-v0.16.0...esp-radio-v0.17.0 [v0.18.0]: https://github.com/esp-rs/esp-hal/compare/esp-radio-v0.17.0...esp-radio-v0.18.0 [v1.0.0-beta.0]: https://github.com/esp-rs/esp-hal/compare/esp-radio-v0.18.0...esp-radio-v1.0.0-beta.0 -[Unreleased]: https://github.com/esp-rs/esp-hal/compare/esp-radio-v1.0.0-beta.0...HEAD +[v1.0.0-beta.1]: https://github.com/esp-rs/esp-hal/compare/esp-radio-v1.0.0-beta.0...esp-radio-v1.0.0-beta.1 +[v1.0.0-beta.2]: https://github.com/esp-rs/esp-hal/compare/esp-radio-v1.0.0-beta.1...esp-radio-v1.0.0-beta.2 +[Unreleased]: https://github.com/esp-rs/esp-hal/compare/esp-radio-v1.0.0-beta.2...HEAD diff --git a/esp-radio/Cargo.toml b/esp-radio/Cargo.toml index 838f1a497de..98ed557be7c 100644 --- a/esp-radio/Cargo.toml +++ b/esp-radio/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "esp-radio" -version = "1.0.0-beta.0" +version = "1.0.0-beta.2" edition = "2024" rust-version = "1.95.0" description = "A driver for the radio peripherals found in Espressif microcontrollers for and bare-metal Rust" @@ -33,9 +33,12 @@ check-configs = [ { features = ["esp-hal/rt", "defmt"] }, { features = ["esp-hal/rt", "defmt"], env = { ESP_RADIO_CONFIG_DUMP_PACKETS = "true" } }, { features = ["esp-hal/rt", "wifi"], if = 'wifi_driver_supported' }, + { features = ["esp-hal/rt", "wifi"], env = { ESP_RADIO_CONFIG_WIFI_NAN_SYNC_ENABLE = "true" }, if = 'wifi_driver_supported && wifi_has_nan' }, + { features = ["esp-hal/rt", "wifi"], env = { ESP_RADIO_CONFIG_WIFI_FTM_ENABLE = "true" }, if = 'wifi_driver_supported && wifi_has_ftm' }, # feature(c_variadic) requires nightly compiler, but we can't configure the toolchain here. Only check xtensa chips, where the compiler has nightly features enabled. { features = ["esp-hal/unstable", "esp-hal/rt", "wifi", "print-logs-from-driver", "unstable"], if = 'wifi_driver_supported && xtensa' }, { features = ["esp-hal/unstable", "esp-hal/rt", "unstable", "defmt", "wifi", "wifi-eap", "esp-now", "sniffer"], if = 'wifi_driver_supported' }, + { features = ["esp-hal/unstable", "esp-hal/rt", "unstable", "wifi", "wifi-eap", "esp-now", "sniffer"], env = { ESP_RADIO_CONFIG_WIFI_SOFTAP_SUPPORT = "false" }, if = 'wifi_driver_supported' }, { features = ["esp-hal/unstable", "esp-hal/rt", "unstable", "ble"], if = 'bt_driver_supported' }, { features = ["esp-hal/unstable", "esp-hal/rt", "unstable", "ieee802154"], if = 'ieee802154_driver_supported' }, { features = ["esp-hal/unstable", "esp-hal/rt", "unstable", "defmt", "wifi", "wifi-eap", "esp-now", "sniffer", "ble", "coex"], if = 'wifi_driver_supported && bt_driver_supported' }, @@ -46,6 +49,8 @@ clippy-configs = [ { features = ["esp-hal/unstable", "esp-hal/rt", "wifi", "wifi-eap", "unstable"], if = 'wifi_driver_supported', append = [ { features = ["ble"], if = 'bt_driver_supported' }, ] }, + # `ieee802154` cannot be combined with `wifi`, so it needs a config of its own. + { features = ["esp-hal/unstable", "esp-hal/rt", "unstable", "ieee802154"], if = 'ieee802154_driver_supported' }, ] [lib] @@ -53,24 +58,24 @@ bench = false test = false [dependencies] -esp-hal = { version = "~1.2.0-rc.0", path = "../esp-hal", default-features = false } +esp-hal = { version = "~1.2.0", path = "../esp-hal", default-features = false } portable-atomic = { version = "1.11", default-features = false } enumset = { version = "1.1", default-features = false, optional = true } # ⚠️ Unstable dependencies -esp-radio-rtos-driver = { version = "0.3.0", path = "../esp-radio-rtos-driver" } +esp-radio-rtos-driver = { version = "0.4.2", path = "../esp-radio-rtos-driver" } instability = "0.3.12" # Unstable dependencies that are not (strictly) part of the public API allocator-api2 = { version = "0.3.0", default-features = false, features = ["alloc"] } docsplay = { version = "0.1", default-features = false } document-features = "0.2" -esp-alloc = { version = "0.10.0", path = "../esp-alloc", optional = true, default-features = false } +esp-alloc = { version = "0.11.0", path = "../esp-alloc", optional = true, default-features = false } esp-config = { version = "0.8.0", path = "../esp-config" } -esp-metadata-generated = { version = "0.5.0", path = "../esp-metadata-generated" } +esp-metadata-generated = { version = "0.6.0", path = "../esp-metadata-generated" } esp-rom-sys = { version = "=0.1.5", path = "../esp-rom-sys" } esp-sync = { version = "0.3.0", path = "../esp-sync" } -esp-phy = { version = "0.2.0", path = "../esp-phy/" } +esp-phy = { version = "0.3.0", path = "../esp-phy/" } num-derive = "0.4.2" num-traits = { version = "0.2.19", default-features = false } portable_atomic_enum = { version = "0.3.1", features = ["portable-atomic"] } @@ -78,28 +83,31 @@ procmacros = { version = "0.23.0", package = "esp-hal-procmacros", path = "../es xtensa-lx-rt = { version = "0.23.0", path = "../xtensa-lx-rt", optional = true } byte = { version = "0.2.7", optional = true } ieee802154 = { version = "0.6.1", optional = true } -heapless = "0.9" embassy-sync = "0.8" # Make sure these are aligned with esp-phy's dependencies, too! -esp-wifi-sys-esp32 = { version = "0.2.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "2ea8e3e" } -esp-wifi-sys-esp32c2 = { version = "0.2.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "2ea8e3e" } -esp-wifi-sys-esp32c3 = { version = "0.2.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "2ea8e3e" } -esp-wifi-sys-esp32c5 = { version = "0.2.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "2ea8e3e" } -esp-wifi-sys-esp32c6 = { version = "0.2.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "2ea8e3e" } -esp-wifi-sys-esp32c61 = { version = "0.2.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "2ea8e3e" } -esp-wifi-sys-esp32h2 = { version = "0.2.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "2ea8e3e" } -esp-wifi-sys-esp32s2 = { version = "0.2.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "2ea8e3e" } -esp-wifi-sys-esp32s3 = { version = "0.2.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "2ea8e3e" } - -esp32 = { version = "0.41", features = ["critical-section"], optional = true } -esp32c2 = { version = "0.30", features = ["critical-section"], optional = true } -esp32c3 = { version = "0.33", features = ["critical-section"], optional = true } -esp32c5 = { version = "0.3", features = ["critical-section"], optional = true } -esp32c6 = { version = "0.24", features = ["critical-section"], optional = true } -esp32c61 = { version = "0.4", features = ["critical-section"], optional = true } -esp32h2 = { version = "0.20", features = ["critical-section"], optional = true } -esp32s2 = { version = "0.32", features = ["critical-section"], optional = true } -esp32s3 = { version = "0.36", features = ["critical-section"], optional = true } +esp-wifi-sys-esp32 = { version = "0.3.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "5afc3a3" } +esp-wifi-sys-esp32c2 = { version = "0.3.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "5afc3a3" } +esp-wifi-sys-esp32c3 = { version = "0.3.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "5afc3a3" } +esp-wifi-sys-esp32c5 = { version = "0.3.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "5afc3a3" } +esp-wifi-sys-esp32c6 = { version = "0.3.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "5afc3a3" } +esp-wifi-sys-esp32c61 = { version = "0.3.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "5afc3a3" } +esp-wifi-sys-esp32h2 = { version = "0.3.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "5afc3a3" } +esp-wifi-sys-esp32h4 = { version = "0.3.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "5afc3a3" } +esp-wifi-sys-esp32s2 = { version = "0.3.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "5afc3a3" } +esp-wifi-sys-esp32s3 = { version = "0.3.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "5afc3a3" } +esp-wifi-sys-esp32s31 = { version = "0.3.0", optional = true, git = "https://github.com/esp-rs/esp-wifi-sys.git", rev = "5afc3a3" } + +esp32 = { version = "0.42", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32c2 = { version = "0.31", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32c3 = { version = "0.34", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32c5 = { version = "0.4", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32c6 = { version = "0.25", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32c61 = { version = "0.5", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32h2 = { version = "0.21", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32h4 = { version = "0.1", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32s2 = { version = "0.33", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32s3 = { version = "0.37", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32s31 = { version = "0.3", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } # Optional dependencies enabling ecosystem features embedded-io-06 = { package = "embedded-io", version = "0.6", default-features = false, optional = true } @@ -107,6 +115,7 @@ embedded-io-async-06 = { package = "embedded-io-async", version = "0.6", default embedded-io-07 = { package = "embedded-io", version = "0.7", default-features = false, optional = true } embedded-io-async-07 = { package = "embedded-io-async", version = "0.7", default-features = false, optional = true } embassy-net-driver-02 = { package = "embassy-net-driver", version = "0.2.0", optional = true } +xarxa-driver = { version = "0.1.0", features = ["async"], optional = true } bt-hci = { version = "0.9.0", optional = true } bt-hci-transport = { version = "0.1.0", optional = true } @@ -116,10 +125,10 @@ log-04 = { package = "log", version = "0.4.27", optional = true } [build-dependencies] esp-config = { version = "0.8.0", path = "../esp-config", features = ["build"] } -esp-metadata-generated = { version = "0.5.0", path = "../esp-metadata-generated", features = ["build-script"] } +esp-metadata-generated = { version = "0.6.0", path = "../esp-metadata-generated", features = ["build-script"] } [dev-dependencies] -esp-rtos = { version = "0.3.0", path = "../esp-rtos" } +esp-rtos = { version = "0.4.0", path = "../esp-rtos" } [features] default = ["esp-alloc"] @@ -155,8 +164,10 @@ print-logs-from-driver = [ "esp-wifi-sys-esp32c6?/sys-logs", "esp-wifi-sys-esp32c61?/sys-logs", "esp-wifi-sys-esp32h2?/sys-logs", + "esp-wifi-sys-esp32h4?/sys-logs", "esp-wifi-sys-esp32s2?/sys-logs", "esp-wifi-sys-esp32s3?/sys-logs", + "esp-wifi-sys-esp32s31?/sys-logs", ] #! ### Chip selection @@ -241,6 +252,17 @@ esp32h2 = [ "esp-metadata-generated/esp32h2", ] ## +esp32h4 = [ + "dep:esp32h4", + "esp-hal/esp32h4", + "esp-alloc?/esp32h4", + "esp-rtos/esp32h4", + "esp-radio-rtos-driver/esp32h4", + "esp-phy/esp32h4", + "dep:esp-wifi-sys-esp32h4", + "esp-metadata-generated/esp32h4", +] +## esp32s2 = [ "dep:esp32s2", "esp-hal/esp32s2", @@ -264,12 +286,36 @@ esp32s3 = [ "esp-metadata-generated/esp32s3", "xtensa-lx-rt/float-save-restore", ] +## +esp32s31 = [ + "dep:esp32s31", + "esp-hal/esp32s31", + "esp-alloc?/esp32s31", + "esp-rtos/esp32s31", + "esp-radio-rtos-driver/esp32s31", + "esp-phy/esp32s31", + "dep:esp-wifi-sys-esp32s31", + "esp-metadata-generated/esp32s31", +] #! ### Wireless Feature Flags #DOC_IF has("wifi_driver_supported") ## Enable Wi-Fi support. -wifi = ["dep:enumset", "dep:embassy-net-driver-02"] +wifi = [ + "dep:enumset", + "dep:embassy-net-driver-02", + "dep:xarxa-driver", + "esp-wifi-sys-esp32?/wifi", + "esp-wifi-sys-esp32c2?/wifi", + "esp-wifi-sys-esp32c3?/wifi", + "esp-wifi-sys-esp32c5?/wifi", + "esp-wifi-sys-esp32c6?/wifi", + "esp-wifi-sys-esp32c61?/wifi", + "esp-wifi-sys-esp32s2?/wifi", + "esp-wifi-sys-esp32s3?/wifi", + "esp-wifi-sys-esp32s31?/wifi", +] ## Enable Wi-Fi Enterprise Authentication Protocol (EAP) support. ## @@ -291,7 +337,23 @@ sniffer = ["wifi", "__has_unstable_feature_enabled"] ## Enable BLE support. ## ## ⚠️ This feature is considered unstable. -ble = ["esp-hal/__bluetooth", "dep:bt-hci", "dep:bt-hci-transport", "__has_unstable_feature_enabled"] +ble = [ + "esp-hal/__bluetooth", + "dep:bt-hci", + "dep:bt-hci-transport", + "dep:enumset", + "__has_unstable_feature_enabled", + "esp-wifi-sys-esp32?/bt", + "esp-wifi-sys-esp32c2?/bt", + "esp-wifi-sys-esp32c3?/bt", + "esp-wifi-sys-esp32c5?/bt", + "esp-wifi-sys-esp32c6?/bt", + "esp-wifi-sys-esp32c61?/bt", + "esp-wifi-sys-esp32h2?/bt", + "esp-wifi-sys-esp32h4?/bt", + "esp-wifi-sys-esp32s3?/bt", + "esp-wifi-sys-esp32s31?/bt", +] #DOC_ENDIF #DOC_IF has("bt_driver_supported") && has("wifi_driver_supported") @@ -315,7 +377,16 @@ csi = ["__has_unstable_feature_enabled"] ## Cannot be used together with Wi-Fi. ## ## ⚠️ This feature is considered unstable. -ieee802154 = ["dep:byte", "dep:ieee802154", "__has_unstable_feature_enabled"] +ieee802154 = [ + "dep:byte", + "dep:ieee802154", + "__has_unstable_feature_enabled", + "esp-wifi-sys-esp32c5?/ieee802154", + "esp-wifi-sys-esp32c6?/ieee802154", + "esp-wifi-sys-esp32h2?/ieee802154", + "esp-wifi-sys-esp32h4?/ieee802154", + "esp-wifi-sys-esp32s31?/ieee802154", +] #DOC_ENDIF #! ### Ecosystem Feature Flags @@ -328,10 +399,14 @@ log-04 = [ "esp-wifi-sys-esp32?/log", "esp-wifi-sys-esp32c2?/log", "esp-wifi-sys-esp32c3?/log", + "esp-wifi-sys-esp32c5?/log", "esp-wifi-sys-esp32c6?/log", + "esp-wifi-sys-esp32c61?/log", "esp-wifi-sys-esp32h2?/log", + "esp-wifi-sys-esp32h4?/log", "esp-wifi-sys-esp32s2?/log", "esp-wifi-sys-esp32s3?/log", + "esp-wifi-sys-esp32s31?/log", "esp-phy/log-04", ] @@ -344,15 +419,19 @@ defmt = [ "esp-wifi-sys-esp32?/defmt", "esp-wifi-sys-esp32c2?/defmt", "esp-wifi-sys-esp32c3?/defmt", + "esp-wifi-sys-esp32c5?/defmt", "esp-wifi-sys-esp32c6?/defmt", + "esp-wifi-sys-esp32c61?/defmt", "esp-wifi-sys-esp32h2?/defmt", + "esp-wifi-sys-esp32h4?/defmt", "esp-wifi-sys-esp32s2?/defmt", "esp-wifi-sys-esp32s3?/defmt", + "esp-wifi-sys-esp32s31?/defmt", "enumset/defmt", - "heapless/defmt", "esp-sync/defmt", "esp-phy/defmt", "ieee802154?/defmt", + "xarxa-driver?/defmt", ] #! ### Unstable APIs diff --git a/esp-radio/esp_config.yml b/esp-radio/esp_config.yml index 62e61b4d5f8..428f57a5e00 100644 --- a/esp-radio/esp_config.yml +++ b/esp-radio/esp_config.yml @@ -37,3 +37,43 @@ options: constraints: - type: validator: non_negative_integer + + - name: wifi_softap_support + description: "Wi-Fi access point support. Mirrors ESP-IDF's `CONFIG_ESP_WIFI_SOFTAP_SUPPORT`. + When disabled, the access point parts of the Wi-Fi driver are replaced by stubs, which saves + about 30 KB of flash, and the access point API (`Config::AccessPoint`, + `Config::AccessPointStation`, `Interface::access_point`, ESP-NOW's access point interface, ...) + is not available." + default: + - value: true + + - name: wifi_nan_sync_enable + description: "Link the Wi-Fi Aware: Synchronization (NAN-Sync) code of the Wi-Fi driver. + Mirrors ESP-IDF's `CONFIG_ESP_WIFI_NAN_SYNC_ENABLE`. esp-radio doesn't provide a NAN API, + so this is only useful when using the driver's NAN functions directly. + When disabled, the NAN code is replaced by stubs, which saves a significant amount of flash." + default: + - value: false + active: "wifi_has_nan" + + - name: wifi_ftm_enable + description: "Enable Fine Timing Measurement (FTM) for calculating Wi-Fi Round-Trip-Time (RTT). + Mirrors ESP-IDF's `CONFIG_ESP_WIFI_FTM_ENABLE`. esp-radio doesn't provide an FTM API, + so this is only useful when using the driver's FTM functions directly." + default: + - value: false + active: "wifi_has_ftm" + + - name: wifi_ftm_initiator_support + description: "FTM Initiator support. Only used when `wifi_ftm_enable` is set. + Mirrors ESP-IDF's `CONFIG_ESP_WIFI_FTM_INITIATOR_SUPPORT`." + default: + - value: true + active: "wifi_has_ftm" + + - name: wifi_ftm_responder_support + description: "FTM Responder support. Only used when `wifi_ftm_enable` is set. + Mirrors ESP-IDF's `CONFIG_ESP_WIFI_FTM_RESPONDER_SUPPORT`." + default: + - value: true + active: "wifi_has_ftm" diff --git a/esp-radio/ld/esp32h4_provides.x b/esp-radio/ld/esp32h4_provides.x new file mode 100644 index 00000000000..69763022aee --- /dev/null +++ b/esp-radio/ld/esp32h4_provides.x @@ -0,0 +1,43 @@ +EXTERN( __esp_radio_strdup ); +EXTERN( __ESP_RADIO_G_WIFI_OSI_FUNCS ); +EXTERN( __ESP_RADIO_G_WIFI_FEATURE_CAPS ); +EXTERN( __ESP_RADIO_WIFI_EVENT ); +EXTERN( __esp_radio_gettimeofday ); +EXTERN( __esp_radio_esp_fill_random ); +EXTERN( __esp_radio_strrchr ); + + +EXTERN( __esp_radio_putchar ); +EXTERN( __esp_radio_putchar ); +EXTERN( __esp_radio_fwrite ); +EXTERN( __esp_radio_fopen ); +EXTERN( __esp_radio_fgets ); +EXTERN( __esp_radio_fclose ); +EXTERN( __esp_radio_esp_timer_get_time ); +EXTERN( __esp_radio_esp_event_post ); +EXTERN( __esp_radio_vTaskDelay ); +EXTERN( __esp_radio_puts ); +EXTERN( __esp_radio_sleep ); +EXTERN( __esp_radio_usleep ); + +PROVIDE( strdup = __esp_radio_strdup ); +PROVIDE( g_wifi_osi_funcs = __ESP_RADIO_G_WIFI_OSI_FUNCS ); +PROVIDE( g_wifi_feature_caps = __ESP_RADIO_G_WIFI_FEATURE_CAPS ); +PROVIDE( WIFI_EVENT = __ESP_RADIO_WIFI_EVENT ); +PROVIDE( gettimeofday = __esp_radio_gettimeofday ); +PROVIDE( esp_fill_random = __esp_radio_esp_fill_random ); +PROVIDE( strrchr = __esp_radio_strrchr ); + + +PROVIDE( putchar = __esp_radio_putchar ); +PROVIDE( _putchar = __esp_radio_putchar ); +PROVIDE( fwrite = __esp_radio_fwrite ); +PROVIDE( fopen = __esp_radio_fopen ); +PROVIDE( fgets = __esp_radio_fgets ); +PROVIDE( fclose = __esp_radio_fclose ); +PROVIDE( esp_timer_get_time = __esp_radio_esp_timer_get_time ); +PROVIDE( esp_event_post = __esp_radio_esp_event_post ); +PROVIDE( vTaskDelay = __esp_radio_vTaskDelay ); +PROVIDE( puts = __esp_radio_puts ); +PROVIDE( sleep = __esp_radio_sleep ); +PROVIDE( usleep = __esp_radio_usleep ); diff --git a/esp-radio/ld/esp32s31_provides.x b/esp-radio/ld/esp32s31_provides.x new file mode 100644 index 00000000000..7d298087033 --- /dev/null +++ b/esp-radio/ld/esp32s31_provides.x @@ -0,0 +1,53 @@ +EXTERN( __esp_radio_strdup ); +EXTERN( __ESP_RADIO_G_WIFI_OSI_FUNCS ); +EXTERN( __ESP_RADIO_G_WIFI_FEATURE_CAPS ); +EXTERN( __ESP_RADIO_WIFI_EVENT ); +EXTERN( __esp_radio_gettimeofday ); +EXTERN( __esp_radio_esp_fill_random ); +EXTERN( __esp_radio_strrchr ); + + +EXTERN( __esp_radio_putchar ); +EXTERN( __esp_radio_putchar ); +EXTERN( __esp_radio_fwrite ); +EXTERN( __esp_radio_fopen ); +EXTERN( __esp_radio_fgets ); +EXTERN( __esp_radio_fclose ); +EXTERN( __esp_radio_esp_timer_get_time ); +EXTERN( __esp_radio_esp_event_post ); +EXTERN( __esp_radio_vTaskDelay ); +EXTERN( __esp_radio_puts ); +EXTERN( __esp_radio_sleep ); +EXTERN( __esp_radio_usleep ); + +PROVIDE( strdup = __esp_radio_strdup ); +PROVIDE( g_wifi_osi_funcs = __ESP_RADIO_G_WIFI_OSI_FUNCS ); +PROVIDE( g_wifi_feature_caps = __ESP_RADIO_G_WIFI_FEATURE_CAPS ); +PROVIDE( WIFI_EVENT = __ESP_RADIO_WIFI_EVENT ); +PROVIDE( gettimeofday = __esp_radio_gettimeofday ); +PROVIDE( esp_fill_random = __esp_radio_esp_fill_random ); +PROVIDE( strrchr = __esp_radio_strrchr ); + + +PROVIDE( putchar = __esp_radio_putchar ); +PROVIDE( _putchar = __esp_radio_putchar ); +PROVIDE( fwrite = __esp_radio_fwrite ); +PROVIDE( fopen = __esp_radio_fopen ); +PROVIDE( fgets = __esp_radio_fgets ); +PROVIDE( fclose = __esp_radio_fclose ); +PROVIDE( esp_timer_get_time = __esp_radio_esp_timer_get_time ); +PROVIDE( esp_event_post = __esp_radio_esp_event_post ); +PROVIDE( vTaskDelay = __esp_radio_vTaskDelay ); +PROVIDE( puts = __esp_radio_puts ); +PROVIDE( sleep = __esp_radio_sleep ); +PROVIDE( usleep = __esp_radio_usleep ); + +#IF wifi +EXTERN( __ESP_RADIO_G_LOG_LEVEL ); +EXTERN( __esp_radio_sleep ); +EXTERN( __esp_radio_usleep ); + +PROVIDE( g_log_level = __ESP_RADIO_G_LOG_LEVEL ); +PROVIDE( sleep = __esp_radio_sleep ); +PROVIDE( usleep = __esp_radio_usleep ); +#ENDIF diff --git a/esp-radio/src/ble/btdm.rs b/esp-radio/src/ble/btdm.rs deleted file mode 100644 index 291acf4caf3..00000000000 --- a/esp-radio/src/ble/btdm.rs +++ /dev/null @@ -1,441 +0,0 @@ -use alloc::boxed::Box; -use core::ptr::{NonNull, addr_of, addr_of_mut}; - -use esp_phy::PhyInitGuard; -use esp_sync::RawMutex; -use portable_atomic::{AtomicBool, Ordering}; - -use super::{Config, ReceivedPacket}; -use crate::{ - ble::{ - HCI_OUT_COLLECTOR, - HciOutCollector, - btdm::ble_os_adapter_chip_specific::{G_OSI_FUNCS, osi_funcs_s}, - }, - compat::common::str_from_c, - hal::ram, - sys::{c_types::*, include::*}, -}; - -#[cfg_attr(esp32c3, path = "os_adapter_esp32c3_s3.rs")] -#[cfg_attr(esp32s3, path = "os_adapter_esp32c3_s3.rs")] -#[cfg_attr(esp32, path = "os_adapter_esp32.rs")] -pub(crate) mod ble_os_adapter_chip_specific; - -static PACKET_SENT: AtomicBool = AtomicBool::new(true); - -#[repr(C)] -struct VhciHostCallbacks { - // callback used to notify that the host can - // send packet to controller - notify_host_send_available: extern "C" fn(), - // callback used to notify that the - // controller has a packet to send to - // the host - notify_host_recv: extern "C" fn(*mut u8, u16) -> i32, -} - -unsafe extern "C" { - fn btdm_osi_funcs_register(osi_funcs: *const osi_funcs_s) -> i32; - fn btdm_controller_get_compile_version() -> *const c_char; - - #[cfg(any(esp32c3, esp32s3))] - fn btdm_controller_init(config_opts: *const esp_bt_controller_config_t) -> i32; - - #[cfg(esp32)] - fn btdm_controller_init( - config_mask: u32, - config_opts: *const esp_bt_controller_config_t, - ) -> i32; - - fn btdm_controller_enable(mode: esp_bt_mode_t); - - fn API_vhci_host_check_send_available() -> bool; - fn API_vhci_host_send_packet(data: *const u8, len: u16); - fn API_vhci_host_register_callback(vhci_host_callbac: *const VhciHostCallbacks) -> i32; - - #[cfg(not(esp32))] - fn coex_pti_v2(); -} - -static VHCI_HOST_CALLBACK: VhciHostCallbacks = VhciHostCallbacks { - notify_host_send_available, - notify_host_recv, -}; - -extern "C" fn notify_host_send_available() { - trace!("notify_host_send_available"); - - PACKET_SENT.store(true, Ordering::Relaxed); -} - -extern "C" fn notify_host_recv(data: *mut u8, len: u16) -> i32 { - trace!("notify_host_recv {:?} {}", data, len); - - let data = unsafe { core::slice::from_raw_parts(data, len as usize) }; - - let packet = ReceivedPacket { - data: Box::from(data), - }; - - super::BT_STATE.with(|state| state.rx_queue.push_back(packet)); - - super::dump_packet_info(data); - - crate::ble::controller::hci_read_data_available(); - - 0 -} - -// This is fine, we're only accessing it inside a critical section (protected by INTERRUPT_LOCK). -static mut G_INTER_FLAGS: heapless::Vec = heapless::Vec::new(); - -static INTERRUPT_LOCK: RawMutex = RawMutex::new(); - -#[ram] -unsafe extern "C" fn interrupt_enable() { - #[allow(static_mut_refs)] - unsafe { - let flags = unwrap!( - G_INTER_FLAGS.pop(), - "interrupt_enable called without prior interrupt_disable" - ); - trace!("interrupt_enable {:?}", flags); - INTERRUPT_LOCK.release(flags); - } -} - -#[ram] -unsafe extern "C" fn interrupt_disable() { - trace!("interrupt_disable"); - #[allow(static_mut_refs)] - unsafe { - let flags = INTERRUPT_LOCK.acquire(); - unwrap!( - G_INTER_FLAGS.push(flags), - "interrupt_disable was called too many times" - ); - trace!("interrupt_disable {:?}", flags); - } -} - -#[ram] -unsafe extern "C" fn task_yield() { - crate::preempt::yield_task(); -} - -unsafe extern "C" fn task_yield_from_isr() { - // This is not called because we never set xHigherPriorityTaskWoken = true in the `_from_isr` - // functions. This should be revisited if a scheduler needs it. - crate::preempt::yield_task_from_isr(); -} - -unsafe extern "C" fn mutex_create() -> *const () { - todo!(); -} - -unsafe extern "C" fn mutex_delete(_mutex: *const ()) { - todo!(); -} - -unsafe extern "C" fn mutex_lock(_mutex: *const ()) -> i32 { - todo!(); -} - -unsafe extern "C" fn mutex_unlock(_mutex: *const ()) -> i32 { - todo!(); -} - -unsafe extern "C" fn task_create( - func: *mut crate::sys::c_types::c_void, - name_ptr: *const c_char, - stack_depth: u32, - param: *mut crate::sys::c_types::c_void, - prio: u32, - handle: *mut crate::sys::c_types::c_void, - core_id: u32, -) -> i32 { - let name = unsafe { str_from_c(name_ptr) }; - trace!( - "task_create {:?} {:?} {} {} {:?} {} {:?} {}", - func, name_ptr, name, stack_depth, param, prio, handle, core_id - ); - - unsafe { - let task_func = core::mem::transmute::< - *mut crate::sys::c_types::c_void, - extern "C" fn(*mut crate::sys::c_types::c_void), - >(func); - - let task = crate::preempt::task_create( - name, - task_func, - param, - prio, - if core_id < 2 { Some(core_id) } else { None }, - stack_depth as usize, - ); - *(handle as *mut usize) = task.as_ptr() as usize; - } - - 1 -} - -unsafe extern "C" fn task_delete(task: *mut ()) { - trace!("task delete called for {:?}", task); - - unsafe { - crate::preempt::schedule_task_deletion(NonNull::new(task)); - } -} - -#[cfg(esp32)] -#[ram] -unsafe extern "C" fn cause_sw_intr_to_core(_core: i32, _intr_no: i32) -> i32 { - trace!("cause_sw_intr_to_core {} {}", _core, _intr_no); - unsafe { xtensa_lx_rt::xtensa_lx::interrupt::set(1 << _intr_no) }; - 0 -} - -#[allow(unused)] -#[ram] -unsafe extern "C" fn srand(seed: u32) { - debug!("!!!! unimplemented srand {}", seed); -} - -#[allow(unused)] -#[ram] -unsafe extern "C" fn rand() -> i32 { - trace!("rand"); - unsafe { crate::common_adapter::random() as i32 } -} - -#[ram] -unsafe extern "C" fn btdm_lpcycles_2_hus(_cycles: u32, _error_corr: u32) -> u32 { - todo!(); -} - -#[ram] -unsafe extern "C" fn btdm_hus_2_lpcycles(us: u32) -> u32 { - const RTC_CLK_CAL_FRACT: u32 = 19; - let g_btdm_lpcycle_us_frac = RTC_CLK_CAL_FRACT; - let g_btdm_lpcycle_us = 2 << (g_btdm_lpcycle_us_frac); - - // Converts a duration in half us into a number of low power clock cycles. - let cycles: u64 = ((us as u64) << g_btdm_lpcycle_us_frac) / (g_btdm_lpcycle_us as u64); - trace!("btdm_hus_2_lpcycles {} {}", us, cycles); - - cycles as u32 -} - -unsafe extern "C" fn btdm_sleep_check_duration(_slot_cnt: i32) -> i32 { - todo!(); -} - -unsafe extern "C" fn btdm_sleep_enter_phase1(_lpcycles: i32) { - todo!(); -} - -unsafe extern "C" fn btdm_sleep_enter_phase2() { - todo!(); -} - -unsafe extern "C" fn btdm_sleep_exit_phase1() { - todo!(); -} - -unsafe extern "C" fn btdm_sleep_exit_phase2() { - todo!(); -} - -unsafe extern "C" fn btdm_sleep_exit_phase3() { - todo!(); -} - -unsafe extern "C" fn coex_schm_status_bit_set(_typ: i32, status: i32) { - trace!("coex_schm_status_bit_set {} {}", _typ, status); - #[cfg(feature = "coex")] - unsafe { - crate::sys::include::coex_schm_status_bit_set(_typ as u32, status as u32) - }; -} - -unsafe extern "C" fn coex_schm_status_bit_clear(_typ: i32, status: i32) { - trace!("coex_schm_status_bit_clear {} {}", _typ, status); - #[cfg(feature = "coex")] - unsafe { - crate::sys::include::coex_schm_status_bit_clear(_typ as u32, status as u32) - }; -} - -#[ram] -unsafe extern "C" fn read_efuse_mac(mac: *const ()) -> i32 { - unsafe { crate::common_adapter::read_mac(mac as *mut _, 2) } -} - -#[cfg(esp32)] -unsafe extern "C" fn set_isr13(n: i32, handler: unsafe extern "C" fn(), arg: *const ()) -> i32 { - unsafe { ble_os_adapter_chip_specific::set_isr(n, handler, arg) } -} - -#[cfg(esp32)] -unsafe extern "C" fn interrupt_l3_disable() { - // info!("unimplemented interrupt_l3_disable"); -} - -#[cfg(esp32)] -unsafe extern "C" fn interrupt_l3_restore() { - // info!("unimplemented interrupt_l3_restore"); -} - -#[cfg(esp32)] -unsafe extern "C" fn custom_queue_create( - _len: u32, - _item_size: u32, -) -> *mut crate::sys::c_types::c_void { - todo!(); -} - -pub(crate) fn ble_init(config: &Config) -> PhyInitGuard<'static> { - let phy_init_guard; - unsafe { - (*addr_of_mut!(HCI_OUT_COLLECTOR)).write(HciOutCollector::new()); - // turn on logging - #[allow(static_mut_refs)] - #[cfg(feature = "print-logs-from-driver")] - { - unsafe extern "C" { - static mut g_bt_plf_log_level: u32; - } - - debug!("g_bt_plf_log_level = {}", g_bt_plf_log_level); - g_bt_plf_log_level = 10; - } - - // esp32_bt_controller_init - ble_os_adapter_chip_specific::btdm_controller_mem_init(); - - let mut cfg = ble_os_adapter_chip_specific::create_ble_config(config); - - let res = btdm_osi_funcs_register(addr_of!(G_OSI_FUNCS)); - assert!(res == 0, "btdm_osi_funcs_register returned {}", res); - - #[cfg(feature = "coex")] - { - let res = crate::wifi::coex_init(); - assert!(res == 0, "coex_init failed"); - } - - let version = btdm_controller_get_compile_version(); - let version_str = str_from_c(version); - debug!("BT controller compile version {}", version_str); - - ble_os_adapter_chip_specific::bt_periph_module_enable(); - - ble_os_adapter_chip_specific::disable_sleep_mode(); - - #[cfg(any(esp32c3, esp32s3))] - let res = btdm_controller_init(&mut cfg as *mut esp_bt_controller_config_t); - - #[cfg(esp32)] - let res = btdm_controller_init( - (1 << 3) | (1 << 4), - &mut cfg as *mut esp_bt_controller_config_t, - ); // see btdm_config_mask_load for mask - - assert!(res == 0, "btdm_controller_init returned {}", res); - - debug!("The btdm_controller_init was initialized"); - - #[cfg(feature = "coex")] - crate::sys::include::coex_enable(); - - phy_init_guard = esp_phy::enable_phy(); - - cfg_select! { - esp32 => { - unsafe extern "C" { - fn btdm_rf_bb_init_phase2(); - } - - btdm_rf_bb_init_phase2(); - coex_bt_high_prio(); - } - _ => { - coex_pti_v2(); - } - } - - #[cfg(feature = "coex")] - coex_enable(); - - btdm_controller_enable(esp_bt_mode_t_ESP_BT_MODE_BLE); - - API_vhci_host_register_callback(&VHCI_HOST_CALLBACK); - } - - // At some point the "High-speed ADC" entropy source became available. - unsafe { esp_hal::rng::TrngSource::increase_entropy_source_counter() }; - phy_init_guard -} - -pub(crate) fn ble_deinit() { - esp_hal::rng::TrngSource::decrease_entropy_source_counter(unsafe { - esp_hal::Internal::conjure() - }); - - unsafe extern "C" { - fn btdm_controller_deinit(); - } - - unsafe { - btdm_controller_deinit(); - } - // Disabling the PHY happens automatically, when the BLEController gets dropped. -} -/// Sends HCI data to the BLE controller. -#[instability::unstable] -pub fn send_hci(data: &[u8]) { - let hci_out = unsafe { (*addr_of_mut!(HCI_OUT_COLLECTOR)).assume_init_mut() }; - hci_out.push(data); - - if hci_out.is_ready() { - let packet = hci_out.packet(); - - unsafe { - loop { - let can_send = API_vhci_host_check_send_available(); - - if !can_send { - trace!("can_send is false"); - continue; - } - - PACKET_SENT.store(false, Ordering::Relaxed); - - #[cfg(all(esp32, feature = "coex"))] - ble_os_adapter_chip_specific::async_wakeup_request( - ble_os_adapter_chip_specific::BTDM_ASYNC_WAKEUP_REQ_HCI, - ); - - API_vhci_host_send_packet(packet.as_ptr(), packet.len() as u16); - - #[cfg(all(esp32, feature = "coex"))] - ble_os_adapter_chip_specific::async_wakeup_request_end( - ble_os_adapter_chip_specific::BTDM_ASYNC_WAKEUP_REQ_HCI, - ); - - trace!("sent vhci host packet"); - - super::dump_packet_info(packet); - - break; - } - - // make sure the packet buffer doesn't get touched until sent - while !PACKET_SENT.load(Ordering::Relaxed) {} - } - - hci_out.reset(); - } -} diff --git a/esp-radio/src/ble/btdm/mod.rs b/esp-radio/src/ble/btdm/mod.rs new file mode 100644 index 00000000000..155c98e52bf --- /dev/null +++ b/esp-radio/src/ble/btdm/mod.rs @@ -0,0 +1,577 @@ +use alloc::boxed::Box; +use core::{ptr::NonNull, task::Poll}; + +use esp_phy::PhyInitGuard; +use portable_atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; + +use super::{Config, ReceivedPacket}; +#[cfg(feature = "coex")] +use crate::sys::include; +use crate::{ + asynch::AtomicWaker, + compat::common::str_from_c, + hal::ram, + sys::{c_types::*, include::*}, +}; + +#[cfg_attr(esp32c3, path = "os_adapter_esp32c3_s3.rs")] +#[cfg_attr(esp32s3, path = "os_adapter_esp32c3_s3.rs")] +#[cfg_attr(esp32, path = "os_adapter_esp32.rs")] +pub(crate) mod chip_specific; + +use chip_specific::{G_OSI_FUNCS, osi_funcs_s}; + +pub(crate) unsafe extern "C" fn malloc_internal(size: u32) -> *mut crate::sys::c_types::c_void { + unsafe { crate::compat::malloc::malloc_internal(size as usize).cast() } +} + +static PACKET_IN_FLIGHT: AtomicBool = AtomicBool::new(false); +static PACKET_SENT_WAKER: AtomicWaker = AtomicWaker::new(); + +#[repr(C)] +struct VhciHostCallbacks { + // callback used to notify that the host can + // send packet to controller + notify_host_send_available: extern "C" fn(), + // callback used to notify that the + // controller has a packet to send to + // the host + notify_host_recv: extern "C" fn(*mut u8, u16) -> i32, +} + +unsafe extern "C" { + fn btdm_osi_funcs_register(osi_funcs: *const osi_funcs_s) -> i32; + fn btdm_controller_get_compile_version() -> *const c_char; + + fn btdm_controller_init( + #[cfg(esp32)] config_mask: u32, + config_opts: *mut esp_bt_controller_config_t, + ) -> i32; + + fn btdm_controller_enable(mode: esp_bt_mode_t); + fn btdm_controller_deinit(); + + fn API_vhci_host_check_send_available() -> bool; + fn API_vhci_host_send_packet(data: *const u8, len: u16); + fn API_vhci_host_register_callback(vhci_host_callbac: *const VhciHostCallbacks) -> i32; + + #[cfg(esp32)] + fn btdm_rf_bb_init_phase2(); + + #[cfg(not(esp32))] + fn coex_pti_v2(); +} + +static VHCI_HOST_CALLBACK: VhciHostCallbacks = VhciHostCallbacks { + notify_host_send_available, + notify_host_recv, +}; + +extern "C" fn notify_host_send_available() { + trace!("notify_host_send_available"); + + PACKET_IN_FLIGHT.store(false, Ordering::Release); + PACKET_SENT_WAKER.wake(); +} + +extern "C" fn notify_host_recv(data: *mut u8, len: u16) -> i32 { + trace!("notify_host_recv {:?} {}", data, len); + + let data = unsafe { core::slice::from_raw_parts(data, len as usize) }; + + let packet = ReceivedPacket { + data: Box::from(data), + }; + + super::BT_STATE.with(|state| state.rx_queue.push_back(packet)); + + super::dump_packet_info(data); + + crate::ble::controller::hci_read_data_available(); + + 0 +} + +static CRITICAL_NEST: AtomicU32 = AtomicU32::new(0); +static CRITICAL_TOKEN: AtomicU32 = AtomicU32::new(0); + +#[ram] +unsafe extern "C" fn interrupt_enable() { + trace!("interrupt_enable"); + if CRITICAL_NEST.fetch_sub(1, Ordering::Release) == 1 { + let last = CRITICAL_TOKEN.load(Ordering::Relaxed); + + unsafe { + super::ESP_RADIO_LOCK.release(esp_sync::RestoreState::new(last)); + } + } +} + +#[ram] +unsafe extern "C" fn interrupt_disable() { + trace!("interrupt_disable"); + let last = CRITICAL_NEST.fetch_add(1, Ordering::Release); + if last == 0 { + let token = unsafe { super::ESP_RADIO_LOCK.acquire().inner() }; + CRITICAL_TOKEN.store(token, Ordering::Relaxed); + } +} + +#[ram] +unsafe extern "C" fn task_yield() { + crate::preempt::yield_task(); +} + +unsafe extern "C" fn task_yield_from_isr() { + // This is not called because we never set xHigherPriorityTaskWoken = true in the `_from_isr` + // functions. This should be revisited if a scheduler needs it. + crate::preempt::yield_task_from_isr(); +} + +unsafe extern "C" fn mutex_create() -> *const () { + todo!(); +} + +unsafe extern "C" fn mutex_delete(_mutex: *const ()) { + todo!(); +} + +unsafe extern "C" fn mutex_lock(_mutex: *const ()) -> i32 { + todo!(); +} + +unsafe extern "C" fn mutex_unlock(_mutex: *const ()) -> i32 { + todo!(); +} + +unsafe extern "C" fn task_create( + func: *mut c_void, + name_ptr: *const c_char, + stack_depth: u32, + param: *mut c_void, + prio: u32, + handle: *mut c_void, + core_id: u32, +) -> i32 { + let name = unsafe { str_from_c(name_ptr) }; + trace!( + "task_create {:?} {:?} {} {} {:?} {} {:?} {}", + func, name_ptr, name, stack_depth, param, prio, handle, core_id + ); + + unsafe { + let task_func = core::mem::transmute::<*mut c_void, extern "C" fn(*mut c_void)>(func); + + let task = crate::preempt::task_create( + name, + task_func, + param, + prio, + if core_id < 2 { Some(core_id) } else { None }, + stack_depth as usize, + ); + *(handle as *mut usize) = task.as_ptr() as usize; + } + + 1 +} + +unsafe extern "C" fn task_delete(task: *mut ()) { + trace!("task delete called for {:?}", task); + + unsafe { + crate::preempt::schedule_task_deletion(NonNull::new(task)); + } +} + +#[cfg(esp32)] +#[ram] +unsafe extern "C" fn cause_sw_intr_to_core(_core: i32, _intr_no: i32) -> i32 { + trace!("cause_sw_intr_to_core {} {}", _core, _intr_no); + unsafe { xtensa_lx_rt::xtensa_lx::interrupt::set(1 << _intr_no) }; + 0 +} + +#[allow(unused)] +#[ram] +unsafe extern "C" fn srand(seed: u32) { + debug!("!!!! unimplemented srand {}", seed); +} + +#[allow(unused)] +#[ram] +unsafe extern "C" fn rand() -> i32 { + trace!("rand"); + unsafe { crate::common_adapter::random() as i32 } +} + +const LP_CYCLE_US_FRAC: u32 = 19; +static LP_CYCLE_US: AtomicU32 = AtomicU32::new(1 << LP_CYCLE_US_FRAC); + +unsafe extern "C" { + fn btdm_lpclk_select_src(sel: u32) -> bool; + fn btdm_lpclk_set_div(div: u32) -> bool; + #[cfg(not(esp32))] + fn btdm_sleep_clock_sync() -> u8; + fn btdm_controller_enable_sleep(enable: bool); + fn btdm_wakeup_request(); + fn btdm_in_wakeup_requesting_set(set: bool); + fn btdm_power_state_active() -> bool; + + #[cfg(feature = "coex")] + fn coex_update_lpclk_interval(); +} + +fn program_btdm_lpclk() { + let params = super::lp_clk::btdm(); + LP_CYCLE_US.store(params.lpcycle_us, Ordering::Relaxed); + unsafe { + let selected = btdm_lpclk_select_src(params.select); + let divided = btdm_lpclk_set_div(params.divider); + assert!(selected && divided, "btdm_lpclk_select_src/set_div failed"); + #[cfg(feature = "coex")] + coex_update_lpclk_interval(); + } +} + +#[ram] +unsafe extern "C" fn btdm_lpcycles_2_hus(cycles: u32, error_corr: u32) -> u32 { + let lpcycle_us = LP_CYCLE_US.load(Ordering::Relaxed).max(1); + cfg_select! { + esp32 => { + let _ = error_corr; + let us = u64::from(lpcycle_us) * u64::from(cycles); + ((us + (1 << (LP_CYCLE_US_FRAC - 1))) >> LP_CYCLE_US_FRAC) as u32 + } + _ => { + let error_corr = error_corr as *mut u32; + let mut local = if error_corr.is_null() { + 0 + } else { + unsafe { u64::from(*error_corr) } + }; + let mut res = u64::from(lpcycle_us) * u64::from(cycles) * 2; + local += res; + res = local >> LP_CYCLE_US_FRAC; + local -= res << LP_CYCLE_US_FRAC; + if !error_corr.is_null() { + unsafe { *error_corr = local as u32 }; + } + res as u32 + } + } +} + +#[ram] +unsafe extern "C" fn btdm_hus_2_lpcycles(us: u32) -> u32 { + let lpcycle_us = u64::from(LP_CYCLE_US.load(Ordering::Relaxed).max(1)); + let cycles = (u64::from(us) << LP_CYCLE_US_FRAC) / lpcycle_us; + cfg_select! { + esp32 => cycles as u32, + _ => (cycles >> 1) as u32, + } +} + +#[ram] +unsafe extern "C" fn btdm_sleep_check_duration(slot_cnt: i32) -> i32 { + if !super::modem_sleep_enabled() { + return 0; + } + + let (min_sleep, wake_delay) = cfg_select! { + esp32 => (12, 4), + _ => (24, 8), + }; + let slot_cnt = slot_cnt as *mut i32; + let slots = unsafe { *slot_cnt }; + if slots < min_sleep { + return 0; + } + unsafe { *slot_cnt = slots - wake_delay }; + 1 +} + +/// When the chip must be awake again, in microseconds since boot. Zero while the controller does +/// not sleep. +static CHIP_WAKE_AT_US: AtomicU64 = AtomicU64::new(0); + +#[ram] +unsafe extern "C" fn btdm_sleep_enter_phase1(lpcycles: i32) { + if !super::modem_sleep_enabled() { + return; + } + + // ESP-IDF `btdm_sleep_enter_phase1_wrapper`. The chip must wake before the controller does, + // with a margin for the clock drift and for the wake of the chip. + const MIN_UNCERTAINTY_US: u32 = 1800; + let lp_time = unsafe { btdm_lpcycles_2_hus(lpcycles as u32, 0) }; + // The C3 and S3 count in half microseconds. + let us_to_sleep = cfg_select! { + esp32 => lp_time, + _ => lp_time >> 1, + }; + let uncertainty = cfg_select! { + esp32 => us_to_sleep >> 11, + _ => { + // When either the controller sleep clock or the RTC wakeup timer runs + // on an RC oscillator, allow a 7% drift margin. + if super::lp_clk::source_is_rc(esp_hal::clock::ll::ble_lp_clk_root_source) + || super::lp_clk::source_is_rc(esp_hal::clock::ll::rtc_slow_clk_root_source) + { + const RC_DRIFT_PERCENT: u64 = 7; + (u64::from(us_to_sleep) * RC_DRIFT_PERCENT / 100) as u32 + } else { + us_to_sleep >> 11 + } + } + }; + let uncertainty = uncertainty.max(MIN_UNCERTAINTY_US); + let now = esp_hal::time::Instant::now() + .duration_since_epoch() + .as_micros(); + let wake_at = now + u64::from(us_to_sleep.saturating_sub(uncertainty)); + CHIP_WAKE_AT_US.store(wake_at.max(1), Ordering::Relaxed); +} + +/// Returns how long the chip can sleep before the controller wakes. +/// +/// Returns zero when the chip must not sleep. +pub(super) fn time_until_controller_wakes() -> esp_hal::time::Duration { + let wake_at = CHIP_WAKE_AT_US.load(Ordering::Relaxed); + let now = esp_hal::time::Instant::now() + .duration_since_epoch() + .as_micros(); + esp_hal::time::Duration::from_micros(wake_at.saturating_sub(now)) +} + +unsafe extern "C" fn btdm_sleep_enter_phase2() { + if super::modem_sleep_enabled() { + super::modem_phy_release(); + } +} + +unsafe extern "C" fn btdm_sleep_exit_phase1() {} + +unsafe extern "C" fn btdm_sleep_exit_phase2() {} + +unsafe extern "C" fn btdm_sleep_exit_phase3() { + if !super::modem_sleep_enabled() { + return; + } + CHIP_WAKE_AT_US.store(0, Ordering::Relaxed); + let phy_restored = super::modem_phy_acquire(); + cfg_select! { + // The RF can be off since the last baseband initialization. + esp32 => { + if phy_restored { + unsafe { btdm_rf_bb_init_phase2() }; + } + } + _ => { + let _ = phy_restored; + if super::lp_clk::source_is_rc(esp_hal::clock::ll::ble_lp_clk_root_source) { + LP_CYCLE_US.store(super::lp_clk::btdm_lpcycle_us(), Ordering::Relaxed); + } + unsafe { while btdm_sleep_clock_sync() != 0 {} } + } + } +} + +fn wake_controller_for_hci() { + if !super::modem_sleep_enabled() { + return; + } + // `btdm_in_wakeup_requesting_set(true)` takes a lock, and only + // `btdm_in_wakeup_requesting_set(false)` releases it. Do not nest the calls. + unsafe { + btdm_in_wakeup_requesting_set(true); + if !btdm_power_state_active() { + btdm_wakeup_request(); + } + } +} + +/// Wakes the controller for a coex scheduler event. +/// +/// Returns `true` if the controller sleeps. The controller then handles the event after it wakes. +unsafe extern "C" fn coex_bt_wakeup_request() -> bool { + trace!("coex_bt_wakeup_request"); + + let wake = super::modem_sleep_enabled() && unsafe { !btdm_power_state_active() }; + if wake { + unsafe { btdm_wakeup_request() }; + } + wake +} + +unsafe extern "C" fn coex_bt_wakeup_request_end() { + trace!("coex_bt_wakeup_request_end"); + // Nothing to release: `coex_bt_wakeup_request` does not take the wakeup-requesting lock. +} + +fn end_controller_hci_wake() { + if !super::modem_sleep_enabled() { + return; + } + unsafe { btdm_in_wakeup_requesting_set(false) }; +} + +/// Returns whether the controller has not yet taken the last HCI packet. +/// +/// The send path requests a controller wake, and the controller takes the PHY again only later. +/// Until then, the PHY reference shows a sleeping controller. +pub(super) fn hci_packet_in_flight() -> bool { + PACKET_IN_FLIGHT.load(Ordering::Acquire) +} + +#[ram] +unsafe extern "C" fn read_efuse_mac(mac: *const ()) -> i32 { + unsafe { crate::common_adapter::read_mac(mac as *mut _, 2) } +} + +pub(crate) fn ble_init(config: &Config) -> PhyInitGuard<'static> { + super::set_modem_sleep(config.modem_sleep()); + super::lp_clk::request(); + program_btdm_lpclk(); + + let phy_init_guard; + unsafe { + // turn on logging + #[allow(static_mut_refs)] + #[cfg(feature = "print-logs-from-driver")] + { + unsafe extern "C" { + static mut g_bt_plf_log_level: u32; + } + + debug!("g_bt_plf_log_level = {}", g_bt_plf_log_level); + g_bt_plf_log_level = 10; + } + + // esp32_bt_controller_init + chip_specific::btdm_controller_mem_init(); + + let mut cfg = chip_specific::create_ble_config(config); + + let res = btdm_osi_funcs_register(&G_OSI_FUNCS); + assert!(res == 0, "btdm_osi_funcs_register returned {}", res); + + #[cfg(feature = "coex")] + { + let res = crate::wifi::coex_init(); + assert!(res == 0, "coex_init failed"); + } + + let version = btdm_controller_get_compile_version(); + debug!("BT controller compile version {}", str_from_c(version)); + + chip_specific::bt_periph_module_enable(); + + chip_specific::disable_sleep_mode(); + + let res = btdm_controller_init( + #[cfg(esp32)] + { + // see btdm_config_mask_load for mask + // const BTDM_CFG_BT_DATA_RELEASE: u32 = 1 << 0; + // const BTDM_CFG_HCI_UART: u32 = 1 << 1; + // const BTDM_CFG_CONTROLLER_RUN_APP_CPU: u32 = 1 << 2; + const BTDM_CFG_SCAN_DUPLICATE_OPTIONS: u32 = 1 << 3; + const BTDM_CFG_SEND_ADV_RESERVED_SIZE: u32 = 1 << 4; + // const BTDM_CFG_BLE_FULL_SCAN_SUPPORTED: u32 = 1 << 5; + BTDM_CFG_SCAN_DUPLICATE_OPTIONS | BTDM_CFG_SEND_ADV_RESERVED_SIZE + }, + &mut cfg, + ); + assert!(res == 0, "btdm_controller_init returned {}", res); + + #[cfg(feature = "coex")] + include::coex_enable(); + + phy_init_guard = esp_phy::enable_phy(); + + cfg_select! { + esp32 => { + btdm_rf_bb_init_phase2(); + coex_bt_high_prio(); + } + _ => { + coex_pti_v2(); + } + } + + btdm_controller_enable(esp_bt_mode_t_ESP_BT_MODE_BLE); + + if config.modem_sleep() { + btdm_controller_enable_sleep(true); + } + + API_vhci_host_register_callback(&VHCI_HOST_CALLBACK); + } + + if config.modem_sleep() && super::lp_clk::light_sleep_supported() { + super::lp_clk::claim_wake_source(); + } + + // At some point the "High-speed ADC" entropy source became available. + unsafe { esp_hal::rng::TrngSource::increase_entropy_source_counter() }; + phy_init_guard +} + +pub(crate) fn ble_deinit() { + super::lp_clk::release_wake_source(); + super::modem_phy_acquire(); + super::set_modem_sleep(false); + + esp_hal::rng::TrngSource::decrease_entropy_source_counter(unsafe { + esp_hal::Internal::conjure() + }); + + unsafe { + btdm_controller_deinit(); + } + + super::lp_clk::release(); + // Disabling the PHY happens automatically, when the BLEController gets dropped. +} + +pub(crate) fn send(data: &[u8]) { + // make sure the packet buffer doesn't get touched until sent + while PACKET_IN_FLIGHT.load(Ordering::Acquire) {} + while unsafe { !API_vhci_host_check_send_available() } { + trace!("can_send is false"); + } + + send_packet(data) +} + +pub(crate) async fn send_async(data: &[u8]) { + // make sure the packet buffer doesn't get touched until sent + core::future::poll_fn(|cx| { + PACKET_SENT_WAKER.register(cx.waker()); + if PACKET_IN_FLIGHT.load(Ordering::Acquire) + || unsafe { !API_vhci_host_check_send_available() } + { + Poll::Pending + } else { + Poll::Ready(()) + } + }) + .await; + + send_packet(data) +} + +fn send_packet(packet: &[u8]) { + unsafe { + PACKET_IN_FLIGHT.store(true, Ordering::Relaxed); + + wake_controller_for_hci(); + API_vhci_host_send_packet(packet.as_ptr(), packet.len() as u16); + end_controller_hci_wake(); + } + + trace!("sent vhci host packet"); + + super::dump_packet_info(packet); +} diff --git a/esp-radio/src/ble/os_adapter_esp32.rs b/esp-radio/src/ble/btdm/os_adapter_esp32.rs similarity index 79% rename from esp-radio/src/ble/os_adapter_esp32.rs rename to esp-radio/src/ble/btdm/os_adapter_esp32.rs index 13a0b356761..247df020b33 100644 --- a/esp-radio/src/ble/os_adapter_esp32.rs +++ b/esp-radio/src/ble/btdm/os_adapter_esp32.rs @@ -2,20 +2,12 @@ use core::ptr::addr_of_mut; use procmacros::BuilderLite; -use super::*; use crate::{ ble::InvalidConfigError, common_adapter::*, hal::{interrupt::Priority, peripherals::BT}, interrupt_dispatch::Handler, - sys::include::{ - esp_bt_controller_config_t, - esp_bt_mode_t, - esp_bt_mode_t_ESP_BT_MODE_BLE, - esp_bt_mode_t_ESP_BT_MODE_BTDM, - esp_bt_mode_t_ESP_BT_MODE_CLASSIC_BT, - esp_bt_mode_t_ESP_BT_MODE_IDLE, - }, + sys::{c_types::*, include::*}, }; static ISR_INTERRUPT_5: Handler = Handler::new(); @@ -83,15 +75,15 @@ pub(super) struct osi_funcs_s { coex_bb_reset_lock: Option u32>, coex_bb_reset_unlock: Option, coex_schm_register_btdm_callback: Option i32>, - coex_schm_status_bit_clear: Option, - coex_schm_status_bit_set: Option, + coex_schm_status_bit_clear: Option, + coex_schm_status_bit_set: Option, coex_schm_interval_get: Option u32>, coex_schm_curr_period_get: Option u8>, coex_schm_curr_phase_get: Option *mut c_void>, coex_wifi_channel_get: Option i32>, coex_register_wifi_channel_change_callback: Option i32>, - set_isr13: Option i32>, + set_isr_l3: Option i32>, interrupt_l3_disable: Option, interrupt_l3_restore: Option, custom_queue_create: Option *mut c_void>, @@ -104,46 +96,46 @@ pub(super) static G_OSI_FUNCS: osi_funcs_s = osi_funcs_s { version: 0x00010005, set_isr: Some(set_isr), ints_on: Some(ints_on), - interrupt_disable: Some(interrupt_disable), - interrupt_restore: Some(interrupt_enable), - task_yield: Some(task_yield), - task_yield_from_isr: Some(task_yield_from_isr), + interrupt_disable: Some(super::interrupt_disable), + interrupt_restore: Some(super::interrupt_enable), + task_yield: Some(super::task_yield), + task_yield_from_isr: Some(super::task_yield_from_isr), semphr_create: Some(semphr_create), semphr_delete: Some(semphr_delete), semphr_take_from_isr: Some(semphr_take_from_isr), semphr_give_from_isr: Some(semphr_give_from_isr), semphr_take: Some(semphr_take), semphr_give: Some(semphr_give), - mutex_create: Some(mutex_create), - mutex_delete: Some(mutex_delete), - mutex_lock: Some(mutex_lock), - mutex_unlock: Some(mutex_unlock), + mutex_create: Some(super::mutex_create), + mutex_delete: Some(super::mutex_delete), + mutex_lock: Some(super::mutex_lock), + mutex_unlock: Some(super::mutex_unlock), queue_create: Some(queue_create), queue_delete: Some(queue_delete), queue_send: Some(queue_send), queue_send_from_isr: Some(queue_send_from_isr), queue_recv: Some(queue_recv), queue_recv_from_isr: Some(queue_recv_from_isr), - task_create: Some(task_create), - task_delete: Some(task_delete), + task_create: Some(super::task_create), + task_delete: Some(super::task_delete), is_in_isr: Some(is_in_isr), - cause_sw_intr_to_core: Some(cause_sw_intr_to_core), + cause_sw_intr_to_core: Some(super::cause_sw_intr_to_core), malloc: Some(crate::ble::malloc), - malloc_internal: Some(crate::ble::malloc_internal), + malloc_internal: Some(super::malloc_internal), free: Some(crate::ble::free), - read_efuse_mac: Some(read_efuse_mac), - srand: Some(crate::ble::btdm::srand), - rand: Some(crate::ble::btdm::rand), - btdm_lpcycles_2_hus: Some(btdm_lpcycles_2_hus), - btdm_hus_2_lpcycles: Some(btdm_hus_2_lpcycles), - btdm_sleep_check_duration: Some(btdm_sleep_check_duration), - btdm_sleep_enter_phase1: Some(btdm_sleep_enter_phase1), - btdm_sleep_enter_phase2: Some(btdm_sleep_enter_phase2), - btdm_sleep_exit_phase1: Some(btdm_sleep_exit_phase1), - btdm_sleep_exit_phase2: Some(btdm_sleep_exit_phase2), - btdm_sleep_exit_phase3: Some(btdm_sleep_exit_phase3), - coex_bt_wakeup_request: Some(coex_bt_wakeup_request), - coex_bt_wakeup_request_end: Some(coex_bt_wakeup_request_end), + read_efuse_mac: Some(super::read_efuse_mac), + srand: Some(super::srand), + rand: Some(super::rand), + btdm_lpcycles_2_hus: Some(super::btdm_lpcycles_2_hus), + btdm_hus_2_lpcycles: Some(super::btdm_hus_2_lpcycles), + btdm_sleep_check_duration: Some(super::btdm_sleep_check_duration), + btdm_sleep_enter_phase1: Some(super::btdm_sleep_enter_phase1), + btdm_sleep_enter_phase2: Some(super::btdm_sleep_enter_phase2), + btdm_sleep_exit_phase1: Some(super::btdm_sleep_exit_phase1), + btdm_sleep_exit_phase2: Some(super::btdm_sleep_exit_phase2), + btdm_sleep_exit_phase3: Some(super::btdm_sleep_exit_phase3), + coex_bt_wakeup_request: Some(super::coex_bt_wakeup_request), + coex_bt_wakeup_request_end: Some(super::coex_bt_wakeup_request_end), coex_bt_request: Some(coex_bt_request), coex_bt_release: Some(coex_bt_release), coex_register_bt_cb: Some(coex_register_bt_cb), @@ -157,7 +149,7 @@ pub(super) static G_OSI_FUNCS: osi_funcs_s = osi_funcs_s { coex_schm_curr_phase_get: Some(coex_schm_curr_phase_get), coex_wifi_channel_get: Some(coex_wifi_channel_get), coex_register_wifi_channel_change_callback: Some(coex_register_wifi_channel_change_callback), - set_isr13: Some(set_isr13), + set_isr_l3: Some(set_isr_l3), interrupt_l3_disable: Some(interrupt_l3_disable), interrupt_l3_restore: Some(interrupt_l3_restore), custom_queue_create: Some(custom_queue_create), @@ -166,6 +158,23 @@ pub(super) static G_OSI_FUNCS: osi_funcs_s = osi_funcs_s { magic: 0xfadebead, }; +unsafe extern "C" fn set_isr_l3(n: i32, handler: unsafe extern "C" fn(), arg: *const ()) -> i32 { + trace!("set_isr_l3 called {} {:?} {:?}", n, handler, arg); + unsafe { set_isr(n, handler, arg) } +} + +unsafe extern "C" fn interrupt_l3_disable() { + unsafe { super::interrupt_disable() } +} + +unsafe extern "C" fn interrupt_l3_restore() { + unsafe { super::interrupt_enable() } +} + +unsafe extern "C" fn custom_queue_create(_len: u32, _item_size: u32) -> *mut c_void { + todo!(); +} + extern "C" fn patch_apply() { trace!("patch apply"); @@ -188,7 +197,7 @@ extern "C" fn coex_version_get_wrapper(major: *mut u32, minor: *mut u32, patch: patch: 0, }; if coex_version_get_value(&mut version) == 0 { - info!( + debug!( "COEX Version {}.{}.{}", version.major, version.minor, version.patch ); @@ -273,6 +282,14 @@ static BTDM_DRAM_AVAILABLE_REGION: [btdm_dram_available_region_t; 7] = [ #[derive(BuilderLite, Clone, Copy, Eq, PartialEq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub struct Config { + /// Enables controller modem sleep. + /// + /// The low-power clock source comes from the clock tree (`BLE_LP_CLK`). + /// While the controller sleeps, the chip can also enter automatic light + /// sleep, but only when `BLE_LP_CLK` runs from a 32 kHz crystal. Set this + /// before the controller starts. The default is off. + modem_sleep: bool, + /// The priority of the RTOS task. task_priority: u8, @@ -321,6 +338,7 @@ pub struct Config { impl Default for Config { fn default() -> Self { Self { + modem_sleep: false, task_priority: crate::preempt::max_task_priority() .saturating_sub(2) .min(255) as u8, @@ -458,41 +476,19 @@ pub(crate) fn disable_sleep_mode() { } const BTDM_MODEM_SLEEP_MODE_NONE: u8 = 0; + const BTDM_MODEM_SLEEP_MODE_ORIG: u8 = 1; + + let mode = if crate::ble::modem_sleep_enabled() { + BTDM_MODEM_SLEEP_MODE_ORIG + } else { + BTDM_MODEM_SLEEP_MODE_NONE + }; unsafe { - btdm_controller_set_sleep_mode(BTDM_MODEM_SLEEP_MODE_NONE); + btdm_controller_set_sleep_mode(mode); } } -pub(crate) unsafe extern "C" fn coex_bt_wakeup_request() -> bool { - trace!("coex_bt_wakeup_request"); - - // This should really be - // ```rust,norun - // #[cfg(feature = "coex")] - // return async_wakeup_request(BTDM_ASYNC_WAKEUP_REQ_COEX); - // #[cfg(not(feature = "coex"))] - // true - // ``` - // - // But doing the right thing here keeps BT from working. - // In a similar scenario this function isn't called in ESP-IDF. - true -} - -pub(crate) unsafe extern "C" fn coex_bt_wakeup_request_end() { - trace!("coex_bt_wakeup_request_end"); - - // This should really be - // ```rust,norun - // #[cfg(feature = "coex")] - // async_wakeup_request_end(BTDM_ASYNC_WAKEUP_REQ_COEX); - // ``` - // - // But doing the right thing here keeps BT from working. - // In a similar scenario this function isn't called in ESP-IDF. -} - extern_coex_fns! { fn coex_bt_request(event: u32, latency: u32, duration: u32) -> i32; fn coex_bt_release(event: u32) -> i32; @@ -503,6 +499,8 @@ extern_coex_fns! { } coex_fns! { + fn coex_schm_status_bit_set(typ: u32, status: u32); + fn coex_schm_status_bit_clear(typ: u32, status: u32); fn coex_schm_interval_get() -> u32; fn coex_schm_curr_period_get() -> u8; fn coex_schm_curr_phase_get() -> *mut c_void; @@ -570,96 +568,6 @@ pub(crate) unsafe extern "C" fn ints_on(mask: u32) { } } -#[cfg(feature = "coex")] -pub(crate) const BTDM_ASYNC_WAKEUP_REQ_HCI: i32 = 0; - -#[cfg(feature = "coex")] -pub(crate) const BTDM_ASYNC_WAKEUP_REQ_COEX: i32 = 1; - -// const BTDM_ASYNC_WAKEUP_REQMAX: i32 = 2; - -/// ************************************************************************** -/// Name: async_wakeup_request -/// -/// Description: -/// Request the BLE Controller to wakeup -/// -/// Input Parameters: -/// event - the event that triggered the wakeup -/// -/// Returned Value: -/// true if request lock is needed, false otherwise -/// -/// ************************************************************************* -#[cfg(feature = "coex")] -pub(crate) fn async_wakeup_request(event: i32) -> bool { - trace!("async_wakeup_request {}", event); - - unsafe extern "C" { - fn btdm_in_wakeup_requesting_set(set: bool); - - fn btdm_power_state_active() -> bool; - - fn btdm_wakeup_request(); - } - - match event { - e if e == BTDM_ASYNC_WAKEUP_REQ_HCI => { - unsafe { - btdm_in_wakeup_requesting_set(true); - } - false - } - e if e == BTDM_ASYNC_WAKEUP_REQ_COEX => { - unsafe { - btdm_in_wakeup_requesting_set(true); - } - - if !unsafe { btdm_power_state_active() } { - unsafe { - btdm_wakeup_request(); - } - true - } else { - false - } - } - _ => false, - } -} - -/// ************************************************************************** -/// Name: async_wakeup_request_end -/// -/// Description: -/// Finish a wakeup request -/// -/// Input Parameters: -/// event - the event that triggered the wakeup -/// -/// Returned Value: -/// true if request lock is needed, false otherwise -/// -/// ************************************************************************* -#[cfg(feature = "coex")] -pub(crate) fn async_wakeup_request_end(event: i32) { - trace!("async_wakeup_request_end {}", event); - - let request_lock = match event { - e if e == BTDM_ASYNC_WAKEUP_REQ_HCI => true, - e if e == BTDM_ASYNC_WAKEUP_REQ_COEX => false, - _ => return, - }; - - unsafe extern "C" { - fn btdm_in_wakeup_requesting_set(set: bool); - } - - if request_lock { - unsafe { btdm_in_wakeup_requesting_set(false) }; - } -} - #[allow(non_snake_case)] #[unsafe(no_mangle)] #[crate::hal::ram] diff --git a/esp-radio/src/ble/os_adapter_esp32c3_s3.rs b/esp-radio/src/ble/btdm/os_adapter_esp32c3_s3.rs similarity index 89% rename from esp-radio/src/ble/os_adapter_esp32c3_s3.rs rename to esp-radio/src/ble/btdm/os_adapter_esp32c3_s3.rs index 618aed3f129..5b8c9d3f7a6 100644 --- a/esp-radio/src/ble/os_adapter_esp32c3_s3.rs +++ b/esp-radio/src/ble/btdm/os_adapter_esp32c3_s3.rs @@ -1,6 +1,5 @@ use procmacros::BuilderLite; -use super::*; #[cfg(multi_core)] use crate::hal::system::Cpu; use crate::{ @@ -8,6 +7,7 @@ use crate::{ common_adapter::*, hal::{interrupt::Priority, peripherals::BT}, interrupt_dispatch::Handler, + sys::{c_types::*, include::*}, }; static ISR_INTERRUPT_5: Handler = Handler::new(); @@ -73,8 +73,8 @@ pub(super) struct osi_funcs_s { coex_wifi_sleep_set: Option, coex_core_ble_conn_dyn_prio_get: Option i32>, coex_schm_register_btdm_callback: Option i32>, - coex_schm_status_bit_set: Option, - coex_schm_status_bit_clear: Option, + coex_schm_status_bit_set: Option, + coex_schm_status_bit_clear: Option, coex_schm_interval_get: Option u32>, coex_schm_curr_period_get: Option u8>, coex_schm_curr_phase_get: Option *mut c_void>, @@ -83,9 +83,10 @@ pub(super) struct osi_funcs_s { esp_hw_power_down: Option, esp_hw_power_up: Option, ets_backup_dma_copy: Option, + malloc_retention: Option *mut c_void>, ets_delay_us: Option, btdm_rom_table_ready: Option, - coex_bt_wakeup_request: Option, + coex_bt_wakeup_request: Option bool>, coex_bt_wakeup_request_end: Option, get_time_us: Option u64>, assert: Option, @@ -93,48 +94,48 @@ pub(super) struct osi_funcs_s { pub(super) static G_OSI_FUNCS: osi_funcs_s = osi_funcs_s { magic: 0xfadebead, - version: 0x0001000A, + version: 0x0001000B, interrupt_alloc: Some(interrupt_set), interrupt_free: Some(interrupt_clear), interrupt_handler_set: Some(interrupt_handler_set), - interrupt_disable: Some(interrupt_disable), - interrupt_restore: Some(interrupt_enable), - task_yield: Some(task_yield), - task_yield_from_isr: Some(task_yield_from_isr), + interrupt_disable: Some(super::interrupt_disable), + interrupt_restore: Some(super::interrupt_enable), + task_yield: Some(super::task_yield), + task_yield_from_isr: Some(super::task_yield_from_isr), semphr_create: Some(semphr_create), semphr_delete: Some(semphr_delete), semphr_take_from_isr: Some(semphr_take_from_isr), semphr_give_from_isr: Some(semphr_give_from_isr), semphr_take: Some(semphr_take), semphr_give: Some(semphr_give), - mutex_create: Some(mutex_create), - mutex_delete: Some(mutex_delete), - mutex_lock: Some(mutex_lock), - mutex_unlock: Some(mutex_unlock), + mutex_create: Some(super::mutex_create), + mutex_delete: Some(super::mutex_delete), + mutex_lock: Some(super::mutex_lock), + mutex_unlock: Some(super::mutex_unlock), queue_create: Some(queue_create), queue_delete: Some(queue_delete), queue_send: Some(queue_send), queue_send_from_isr: Some(queue_send_from_isr), queue_recv: Some(queue_recv), queue_recv_from_isr: Some(queue_recv_from_isr), - task_create: Some(task_create), - task_delete: Some(task_delete), + task_create: Some(super::task_create), + task_delete: Some(super::task_delete), is_in_isr: Some(is_in_isr), cause_sw_intr_to_core: None, malloc: Some(crate::ble::malloc), - malloc_internal: Some(crate::ble::malloc_internal), + malloc_internal: Some(super::malloc_internal), free: Some(crate::ble::free), - read_efuse_mac: Some(read_efuse_mac), - srand: Some(crate::ble::btdm::srand), - rand: Some(crate::ble::btdm::rand), - btdm_lpcycles_2_hus: Some(btdm_lpcycles_2_hus), - btdm_hus_2_lpcycles: Some(btdm_hus_2_lpcycles), - btdm_sleep_check_duration: Some(btdm_sleep_check_duration), - btdm_sleep_enter_phase1: Some(btdm_sleep_enter_phase1), - btdm_sleep_enter_phase2: Some(btdm_sleep_enter_phase2), - btdm_sleep_exit_phase1: Some(btdm_sleep_exit_phase1), - btdm_sleep_exit_phase2: Some(btdm_sleep_exit_phase2), - btdm_sleep_exit_phase3: Some(btdm_sleep_exit_phase3), + read_efuse_mac: Some(super::read_efuse_mac), + srand: Some(super::srand), + rand: Some(super::rand), + btdm_lpcycles_2_hus: Some(super::btdm_lpcycles_2_hus), + btdm_hus_2_lpcycles: Some(super::btdm_hus_2_lpcycles), + btdm_sleep_check_duration: Some(super::btdm_sleep_check_duration), + btdm_sleep_enter_phase1: Some(super::btdm_sleep_enter_phase1), + btdm_sleep_enter_phase2: Some(super::btdm_sleep_enter_phase2), + btdm_sleep_exit_phase1: Some(super::btdm_sleep_exit_phase1), + btdm_sleep_exit_phase2: Some(super::btdm_sleep_exit_phase2), + btdm_sleep_exit_phase3: Some(super::btdm_sleep_exit_phase3), coex_wifi_sleep_set: Some(coex_wifi_sleep_set), coex_core_ble_conn_dyn_prio_get: Some(coex_core_ble_conn_dyn_prio_get), coex_schm_register_btdm_callback: Some(coex_schm_register_btdm_callback), @@ -148,14 +149,21 @@ pub(super) static G_OSI_FUNCS: osi_funcs_s = osi_funcs_s { esp_hw_power_down: Some(esp_hw_power_down), esp_hw_power_up: Some(esp_hw_power_up), ets_backup_dma_copy: Some(ets_backup_dma_copy), + malloc_retention: Some(malloc_retention), ets_delay_us: Some(ets_delay_us_wrapper), btdm_rom_table_ready: Some(btdm_rom_table_ready_wrapper), - coex_bt_wakeup_request: Some(coex_bt_wakeup_request), - coex_bt_wakeup_request_end: Some(coex_bt_wakeup_request_end), + coex_bt_wakeup_request: Some(super::coex_bt_wakeup_request), + coex_bt_wakeup_request_end: Some(super::coex_bt_wakeup_request_end), get_time_us: Some(get_time_us_wrapper), assert: Some(assert_wrapper), }; +pub(crate) unsafe extern "C" fn malloc_retention(size: u32) -> *mut crate::sys::c_types::c_void { + // IDF uses heap_caps_malloc(size, MALLOC_CAP_RETENTION). We have no retention + // heap, so fall back to the same internal allocator as malloc_internal. + unsafe { crate::compat::malloc::malloc_internal(size as usize).cast() } +} + extern "C" fn get_time_us_wrapper() -> u64 { // Get time in microseconds since boot crate::preempt::now() @@ -170,6 +178,8 @@ extern_coex_fns! { } coex_fns! { + fn coex_schm_status_bit_set(typ: u32, status: u32); + fn coex_schm_status_bit_clear(typ: u32, status: u32); fn coex_schm_interval_get() -> u32; fn coex_schm_curr_period_get() -> u8; fn coex_schm_curr_phase_get() -> *mut c_void; @@ -187,30 +197,6 @@ extern "C" fn coex_schm_register_btdm_callback(_callback: *mut c_void) -> i32 { } } -extern "C" fn coex_bt_wakeup_request() { - trace!("coex_bt_wakeup_request"); - - unsafe extern "C" { - fn btdm_wakeup_request(); - } - - unsafe { - btdm_wakeup_request(); - } -} - -extern "C" fn coex_bt_wakeup_request_end() { - trace!("coex_bt_wakeup_request_end"); - - unsafe extern "C" { - fn btdm_in_wakeup_requesting_set(set: bool); - } - - unsafe { - btdm_in_wakeup_requesting_set(false); - } -} - extern "C" fn ets_delay_us_wrapper(us: u32) { unsafe extern "C" { fn ets_delay_us(us: u32); @@ -354,6 +340,13 @@ pub enum CcaMode { #[derive(BuilderLite, Clone, Copy, Eq, PartialEq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub struct Config { + /// Enables controller modem sleep. + /// + /// The low-power clock source comes from the clock tree (`BLE_LP_CLK`). + /// While the controller sleeps, the chip can also enter automatic light + /// sleep. Set this before the controller starts. The default is off. + modem_sleep: bool, + /// The priority of the RTOS task. task_priority: u8, @@ -456,6 +449,7 @@ pub struct Config { impl Default for Config { fn default() -> Self { Self { + modem_sleep: false, task_priority: crate::preempt::max_task_priority() .saturating_sub(2) .min(255) as u8, @@ -521,7 +515,7 @@ pub(crate) fn create_ble_config(config: &Config) -> esp_bt_controller_config_t { bluetooth_mode: esp_bt_mode_t_ESP_BT_MODE_BLE as _, ble_max_act: config.max_connections, - sleep_mode: 0, + sleep_mode: u8::from(config.modem_sleep), sleep_clock: 0, ble_st_acl_tx_buf_nb: 0, ble_hw_cca_check: 0, diff --git a/esp-radio/src/ble/btdm2/mod.rs b/esp-radio/src/ble/btdm2/mod.rs new file mode 100644 index 00000000000..354871144cd --- /dev/null +++ b/esp-radio/src/ble/btdm2/mod.rs @@ -0,0 +1,1613 @@ +//! IDF `porting_btdm` controller (nested BLE/BR-EDR/BTDM config + `esp_*` VHCI). +//! +//! Distinct from the original BTDM OSI / `API_vhci_host_*` path used on +//! ESP32/C3/S3 (`bt_controller = "btdm"`). +//! +//! The second half of this file is the `wr_btdm_osal_*` OSAL the blob calls +//! back into. Objects are heap-allocated (IDF's `BTDM_MEMPOOL_ALLOC` path is +//! not used) and, as with IDF's `BTDM_OSAL_USE_ESP_TIMER`, one tick is one +//! millisecond. + +use core::{ + mem::{size_of, transmute}, + ptr::NonNull, + sync::atomic::{AtomicU8, AtomicU16, AtomicU32, Ordering}, +}; + +use esp_phy::PhyInitGuard; + +use super::{Config, ReceivedPacket, in_isr}; +use crate::{ + compat::{ + self, + common::str_from_c, + mutex, + queue::{ + queue_create, + queue_delete, + queue_messages_waiting, + queue_receive, + queue_remove, + queue_send_to_back, + queue_send_to_front, + queue_try_receive_from_isr, + queue_try_send_to_back_from_isr, + queue_try_send_to_front_from_isr, + }, + semaphore, + }, + drop_guard::DropGuard, + hal::{ram, system::Cpu}, + sys::{ + c_types::{c_char, c_void}, + include::*, + }, + time::{blob_ticks_to_micros, blob_ticks_to_millis, millis_to_blob_ticks}, +}; + +#[cfg_attr(esp32h4, path = "os_adapter_esp32h4.rs")] +#[cfg_attr(esp32s31, path = "os_adapter_esp32s31.rs")] +pub(crate) mod chip_specific; + +const EXT_FUNC_VERSION: u32 = 0x20250819; +const EXT_FUNC_MAGIC: u32 = 0xA5A5A5A5; +const ACL_DATA_MBUF_LEADINGSPACE: usize = 4; + +static CONTROLLER_STATUS: AtomicU32 = + AtomicU32::new(esp_bt_controller_status_t_ESP_BT_CONTROLLER_STATUS_IDLE); + +/// Out-parameter of `r_ble_ll_get_npl_element_info`: how many OSAL elements of +/// each kind the controller needs. IDF pre-allocates a pool per kind; we +/// allocate on demand, so only `evt_count` is of any use to us. +#[derive(Default)] +#[repr(C)] +struct OsalElemNum { + evt_count: u16, + evtq_count: u16, + co_count: u16, + sem_count: u16, + mutex_count: u16, +} + +#[repr(C)] +struct ExtFuncsT { + ext_version: u32, + malloc: Option *mut c_void>, + free: Option, + osi_assert: Option, + os_random: Option u32>, + ecc_gen_key_pair: Option i32>, + ecc_gen_dh_key: Option i32>, + esp_reset_rpa_moudle: Option, + ecc_aes_cmac: Option i32>, + magic: u32, +} + +static EXT_FUNCS: ExtFuncsT = ExtFuncsT { + ext_version: EXT_FUNC_VERSION, + malloc: Some(wr_btdm_osal_malloc), + free: Some(wr_btdm_osal_free), + osi_assert: Some(osi_assert), + os_random: Some(os_random), + ecc_gen_key_pair: Some(ecc_gen_key_pair), + ecc_gen_dh_key: Some(ecc_gen_dh_key), + esp_reset_rpa_moudle: Some(reset_rpa), + ecc_aes_cmac: Some(ecc_aes_cmac), + magic: EXT_FUNC_MAGIC, +}; + +/// Chained memory buffer used by the NimBLE-style controller. +#[repr(C)] +struct OsMbuf { + om_data: *const u8, + om_flags: u8, + om_pkthdr_len: u8, + om_len: u16, + om_omp: *const c_void, + next: *const OsMbuf, +} + +unsafe extern "C" { + fn r_btdm_task_init(cfg: *mut esp_btdm_controller_config_t) -> i32; + fn r_btdm_task_deinit(); + fn r_btdm_task_enable() -> i32; + fn r_btdm_task_disable(); + fn r_btdm_hal_rtc_freq_set(freq: u64); + fn r_esp_ble_change_rtc_freq(freq: u32); + + fn esp_register_ext_funcs(funcs: *const ExtFuncsT) -> i32; + fn esp_unregister_ext_funcs(); + fn esp_ble_register_bb_funcs() -> i32; + fn esp_ble_unregister_bb_funcs() -> i32; + fn r_ble_controller_init(cfg: *mut esp_bt_controller_config_t__bindgen_ty_1) -> i32; + fn r_ble_controller_deinit() -> i32; + fn r_esp_ble_msys_init( + msys_size1: u16, + msys_size2: u16, + msys_cnt1: u16, + msys_cnt2: u16, + from_heap: u8, + ) -> i32; + fn r_esp_ble_msys_deinit(); + fn r_esp_ble_ll_set_public_addr(addr: *const u8); + fn r_ble_ll_get_npl_element_info( + cfg: *mut esp_bt_controller_config_t__bindgen_ty_1, + elem: *mut OsalElemNum, + ) -> i32; + fn r_base_stack_initEnv() -> i32; + fn r_base_stack_deinitEnv() -> i32; + fn r_base_stack_enable() -> i32; + fn r_base_stack_disable(); + fn r_conn_stack_initEnv() -> i32; + fn r_conn_stack_deinitEnv(); + fn r_conn_stack_enable() -> i32; + fn r_conn_stack_disable(); + fn bt_bb_v2_init_cmplx(value: u8); + fn coex_pti_v2(); + fn bt_bb_get_tx_pwr_table(length: *mut u8) -> *const i8; + + fn r_ble_hci_trans_cfg_hs( + evt: Option i32>, + evt_arg: *const c_void, + acl_cb: Option i32>, + acl_arg: *const c_void, + ); + fn r_ble_hci_trans_buf_free(buf: *const u8); + fn r_ble_hci_trans_hs_acl_tx(om: *mut OsMbuf) -> i32; + fn r_os_msys_get_pkthdr(dsize: u16, user_hdr_len: u16) -> *mut OsMbuf; + fn r_os_mbuf_append(om: *mut OsMbuf, src: *const u8, len: u16) -> i32; + fn r_os_mbuf_free_chain(om: *mut OsMbuf) -> i32; + + fn r_btdm_hci_trans_buf_alloc(typ: u8, conn_handle: u16) -> *mut HciDriverPacket; + fn r_btdm_hci_trans_buf_free(pkt: *mut HciDriverPacket); + fn r_btdm_hci_trans_rx(pkt: *mut HciDriverPacket) -> i32; + fn r_btdm_hci_trans_register_tx(tx_func: *const c_void, async_: bool) -> i32; + + // IDF `UC_BT_CTRL_CONN_FC_ENABLE` is hardcoded on. The BLE stack + // calls these accessors after a connection; without `env_init` the + // env pointer stays NULL and `r_sym_bt_E5PSb5NmRdfYVGFUOLdR` load- + // faults at offset 1. + fn r_btdm_hci_fc_env_init() -> i32; + fn r_btdm_hci_fc_env_deinit(); + fn r_btdm_hci_fc_enable() -> i32; + fn r_btdm_hci_fc_disable(); +} + +/// IDF `hci_driver_packet_t` (`STAILQ_ENTRY` is one next pointer). +#[repr(C)] +struct HciDriverPacket { + next: *mut HciDriverPacket, + data: *mut u8, + length: u16, + flags: u8, + type_: u8, +} + +const HCI_DRIVER_TYPE_CMD: u8 = 0x01; + +unsafe extern "C" fn osi_assert(ln: u32, fn_name: *const c_void, param1: u32, param2: u32) { + unsafe { + let name = crate::compat::common::str_from_c(fn_name.cast()); + panic!("BLE assert {}:{} 0x{:x} 0x{:x}", name, ln, param1, param2); + } +} + +unsafe extern "C" fn os_random() -> u32 { + unsafe { crate::common_adapter::random() as u32 } +} + +unsafe extern "C" fn reset_rpa() { + crate::radio_clocks::clocks_ll::reset_rpa(); +} + +unsafe extern "C" fn ecc_gen_key_pair(_pub: *mut u8, _priv: *mut u8) -> i32 { + -1 +} + +unsafe extern "C" fn ecc_gen_dh_key( + _x: *const u8, + _y: *const u8, + _priv: *const u8, + _out: *mut u8, +) -> i32 { + -1 +} + +unsafe extern "C" fn ecc_aes_cmac( + _key: *const u8, + _input: *const u8, + _len: usize, + _out: *mut u8, +) -> i32 { + -1 +} + +fn controller_status() -> u32 { + CONTROLLER_STATUS.load(Ordering::Relaxed) +} + +fn set_controller_status(status: u32) { + CONTROLLER_STATUS.store(status, Ordering::Relaxed); +} + +/// Number of entries to size the event queue for, following IDF's +/// `esp_bt_controller_init` seed of `3 + 100` plus the `+10` workaround in +/// `ble_osal_elem_calc`. +fn eventq_depth(cfg: *mut esp_bt_controller_config_t) -> u16 { + let mut elem = OsalElemNum::default(); + // On failure `elem` stays zeroed, leaving us with IDF's seed. + unsafe { r_ble_ll_get_npl_element_info(&raw mut (*cfg).ble, &mut elem) }; + elem.evt_count.saturating_add(113) +} + +fn ble_stack_init(cfg: *mut esp_bt_controller_config_t) -> i32 { + unsafe { + let res = esp_register_ext_funcs(&raw const EXT_FUNCS); + if res != 0 { + warn!("esp_register_ext_funcs failed {}", res); + return res; + } + + // C6 IDF sets this to `s_bt_lpclk_freq` for MAIN_XTAL (100 kHz). + // porting_btdm's S31 stub still hardcodes 32000; the HW divider we + // program is 100 kHz. Advertising enable busy-waits on cputime. + (*cfg).ble.rtc_freq = lpclk_hz(); + + let res = esp_ble_register_bb_funcs(); + if res != 0 { + warn!("esp_ble_register_bb_funcs failed {}", res); + return res; + } + + let res = r_ble_controller_init(&raw mut (*cfg).ble); + if res != 0 { + warn!("r_ble_controller_init failed {}", res); + return res; + } + + r_esp_ble_change_rtc_freq(lpclk_hz() as u32); + + let res = r_esp_ble_msys_init( + CONFIG_BT_LE_MSYS_1_BLOCK_SIZE as u16, + CONFIG_BT_LE_MSYS_2_BLOCK_SIZE as u16, + CONFIG_BT_LE_MSYS_1_BLOCK_COUNT as u16, + CONFIG_BT_LE_MSYS_2_BLOCK_COUNT as u16, + CONFIG_BT_LE_MSYS_BUF_FROM_HEAP as u8, + ); + if res != 0 { + warn!("r_esp_ble_msys_init failed {}", res); + return res; + } + + let mut mac = [0u8; 6]; + crate::common_adapter::read_mac(mac.as_mut_ptr(), 2); + mac.reverse(); + r_esp_ble_ll_set_public_addr(mac.as_ptr()); + + let res = r_base_stack_initEnv(); + if res != 0 { + warn!("r_base_stack_initEnv failed {}", res); + return res; + } + + let res = r_conn_stack_initEnv(); + if res != 0 { + warn!("r_conn_stack_initEnv failed {}", res); + return res; + } + } + 0 +} + +fn ble_stack_deinit() { + unsafe { + r_conn_stack_deinitEnv(); + let _ = r_base_stack_deinitEnv(); + r_esp_ble_msys_deinit(); + let _ = r_ble_controller_deinit(); + let _ = esp_ble_unregister_bb_funcs(); + esp_unregister_ext_funcs(); + } +} + +fn ble_stack_enable() -> i32 { + unsafe { + let res = r_base_stack_enable(); + if res != 0 { + return res; + } + // `r_conn_stack_enable` in this blob is a 2-byte `c.jr ra` that + // never writes a0, so the "return value" is leftover register + // garbage (we saw 8). Connection setup is done in initEnv. + let _ = r_conn_stack_enable(); + 0 + } +} + +fn ble_stack_disable() { + unsafe { + r_conn_stack_disable(); + r_base_stack_disable(); + } +} + +fn bt_controller_deinit() { + set_controller_status(esp_bt_controller_status_t_ESP_BT_CONTROLLER_STATUS_IDLE); + unsafe { + // `r_ble_controller_init` registers the two coex callbacks, but + // `r_ble_controller_deinit` frees their environment without + // unregistering them. The next `coex_enable` / `coex_disable` from + // Wi-Fi would run them against a NULL environment. + #[cfg(feature = "coex")] + { + coex_register_ble_cb(0, core::ptr::null_mut()); + coex_register_ble_cb(1, core::ptr::null_mut()); + } + + r_ble_hci_trans_cfg_hs(None, core::ptr::null(), None, core::ptr::null()); + ble_stack_deinit(); + r_btdm_hci_fc_env_deinit(); + r_btdm_task_deinit(); + crate::radio_clocks::clocks_ll::enable_bt(false); + } +} + +fn esp_bt_controller_init(cfg: *mut esp_bt_controller_config_t) -> esp_err_t { + if cfg.is_null() { + return ESP_ERR_INVALID_ARG as _; + } + if controller_status() != esp_bt_controller_status_t_ESP_BT_CONTROLLER_STATUS_IDLE { + return ESP_ERR_INVALID_STATE as _; + } + + unsafe { + if (*cfg).btdm.bluetooth_mode == esp_bt_mode_t_ESP_BT_MODE_IDLE as u8 { + return ESP_ERR_INVALID_ARG as _; + } + + EVENTQ_DEPTH.store(eventq_depth(cfg), Ordering::Relaxed); + + crate::radio_clocks::clocks_ll::enable_bt(true); + + let res = r_btdm_task_init(&raw mut (*cfg).btdm); + if res != 0 { + warn!("r_btdm_task_init failed {}", res); + bt_controller_deinit(); + return ESP_FAIL as _; + } + + btdm_lp_init(); + + // IDF `esp_bt_controller_init`: after `r_btdm_task_init` / + // `btdm_lp_init`, before `ble_stack_init`. + let res = r_btdm_hci_fc_env_init(); + if res != 0 { + warn!("r_btdm_hci_fc_env_init failed {}", res); + bt_controller_deinit(); + return ESP_FAIL as _; + } + + bt_bb_v2_init_cmplx(1); + coex_pti_v2(); + // Same ROM pointer 802.15.4 TX needs on S31. A null/stale + // `coex_pti_tab_ptr` leaves the BB waiting for a PTI grant. + #[cfg(soc_has_wifi)] + { + unsafe extern "C" { + static mut coex_pti_tab_ptr: u32; + static coex_pti_tab: u8; + } + (&raw mut coex_pti_tab_ptr).write_volatile(&raw const coex_pti_tab as u32); + } + + let res = ble_stack_init(cfg); + if res != 0 { + bt_controller_deinit(); + return ESP_FAIL as _; + } + + // IDF `hci_transport_init` registers this during init so + // `r_ble_hci_trans_ll_evt_tx` has a host callback before enable. + r_ble_hci_trans_cfg_hs( + Some(ble_hs_hci_rx_evt), + core::ptr::null(), + Some(ble_hs_rx_data), + core::ptr::null(), + ); + // IDF also registers the BTDM-common TX path so dual-mode / + // controller-originated packets reach the host. The blob returns + // the previous callback pointer (often a ROM address), not an + // error code. + let _prev = r_btdm_hci_trans_register_tx(btdm_hci_controller_tx as *const c_void, false); + } + + set_controller_status(esp_bt_controller_status_t_ESP_BT_CONTROLLER_STATUS_INITED); + 0 +} + +fn esp_bt_controller_deinit() -> esp_err_t { + if controller_status() != esp_bt_controller_status_t_ESP_BT_CONTROLLER_STATUS_INITED { + return ESP_ERR_INVALID_STATE as _; + } + bt_controller_deinit(); + 0 +} + +fn esp_bt_controller_enable(_mode: esp_bt_mode_t) -> esp_err_t { + if controller_status() != esp_bt_controller_status_t_ESP_BT_CONTROLLER_STATUS_INITED { + return ESP_ERR_INVALID_STATE as _; + } + + unsafe { bt_bb_v2_init_cmplx(1) }; + + let res = ble_stack_enable(); + if res != 0 { + warn!("ble_stack_enable failed {}", res); + return ESP_FAIL as _; + } + let ble_stack = DropGuard::new((), |_| ble_stack_disable()); + + let res = unsafe { r_btdm_hci_fc_enable() }; + if res != 0 { + warn!("r_btdm_hci_fc_enable failed {}", res); + return ESP_FAIL as _; + } + let hci_fc = DropGuard::new((), |_| unsafe { r_btdm_hci_fc_disable() }); + + let res = unsafe { r_btdm_task_enable() }; + if res != 0 { + warn!("r_btdm_task_enable failed {}", res); + return ESP_FAIL as _; + } + + hci_fc.defuse(); + ble_stack.defuse(); + + set_controller_status(esp_bt_controller_status_t_ESP_BT_CONTROLLER_STATUS_ENABLED); + 0 +} + +fn esp_bt_controller_disable() -> esp_err_t { + if controller_status() != esp_bt_controller_status_t_ESP_BT_CONTROLLER_STATUS_ENABLED { + return ESP_ERR_INVALID_STATE as _; + } + + unsafe { + r_ble_hci_trans_cfg_hs(None, core::ptr::null(), None, core::ptr::null()); + r_btdm_task_disable(); + r_btdm_hci_fc_disable(); + ble_stack_disable(); + } + set_controller_status(esp_bt_controller_status_t_ESP_BT_CONTROLLER_STATUS_INITED); + 0 +} + +#[unsafe(no_mangle)] +extern "C" fn e_btdm_lp_modem_clock_set(enable: bool) { + trace!("e_btdm_lp_modem_clock_set {:?}", enable); + // crate::radio_clocks::clocks_ll::enable_bt_clocks(enable); +} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_assert(file: *const c_void, line: i32, p0: i32, p1: i32, _ty: u8) { + unsafe { + let name = crate::compat::common::str_from_c(file.cast()); + panic!("BLE assert {}:{} 0x{:x} 0x{:x}", name, line, p0, p1); + } +} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_log_set_flags(_p0: u8) {} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_log_reset_flags(_p0: u8) {} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_log_internal_x0(_p0: u32) {} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_log_internal_x1(_p0: u32, _p1: u32) {} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_log_internal_x2(_p0: u32, _p1: u32, _p2: u32) {} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_log_internal_x3(_p0: u32, _p1: u32, _p2: u32, _p3: u32) {} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_log_internal_hex(_p0: u32, _p1: u32, _p2: u32) {} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_log_raw_export(_p0: u16, _p1: u32, _p2: u32) {} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_external_bb_get_tx_pwr_table(length: *mut u8, _modem_cfg: u8) -> *const i8 { + unsafe { bt_bb_get_tx_pwr_table(length) } +} + +// The controller's view of coexistence, mirroring IDF `btdm_coex.c`. Without +// the `coex` feature these keep the values IDF returns with +// `CONFIG_SW_COEXIST_ENABLE` off. + +// Declared `extern` in IDF `btdm_coex.c` rather than in a coex header, so +// esp-wifi-sys does not generate bindings for them. +#[cfg(feature = "coex")] +unsafe extern "C" { + fn coex_register_ble_cb(ty: u8, func: *mut c_void) -> i32; + fn coex_ble_idle_time_inform(start_offset: u32, duration: u32); +} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_coex_schm_status_bit_set(_ty: u32, _status: u32) { + #[cfg(feature = "coex")] + unsafe { + coex_schm_status_bit_set(_ty, _status) + }; +} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_coex_schm_status_bit_clear(_ty: u32, _status: u32) { + #[cfg(feature = "coex")] + unsafe { + coex_schm_status_bit_clear(_ty, _status) + }; +} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_coex_schm_register_btdm_callback(_cb: *mut c_void) -> i32 { + cfg_select! { + feature = "coex" => unsafe { + coex_schm_register_callback(coex_schm_callback_type_t_COEX_SCHM_CALLBACK_TYPE_BT, _cb) + }, + _ => 0, + } +} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_coex_schm_interval_get() -> u32 { + cfg_select! { + feature = "coex" => unsafe { coex_schm_interval_get() }, + _ => 0, + } +} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_coex_schm_curr_period_get() -> u8 { + cfg_select! { + // Before a scheme is running the scheduler has no period to report. + // Clamp to the one-period value IDF uses with coex off rather than + // handing the controller a zero it may divide by. + feature = "coex" => unsafe { coex_schm_curr_period_get().max(1) }, + _ => 1, + } +} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_coex_schm_curr_phase_get() -> *mut c_void { + cfg_select! { + feature = "coex" => unsafe { coex_schm_curr_phase_get() }, + _ => core::ptr::null_mut(), + } +} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_coex_register_wifi_channel_change_callback( + _cb: coex_wifi_channel_change_cb_t, +) -> i32 { + cfg_select! { + feature = "coex" => unsafe { coex_register_wifi_channel_change_callback(_cb) }, + _ => -1, + } +} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_coex_wifi_channel_get(_primary: *mut u8, _secondary: *mut u8) -> i32 { + cfg_select! { + feature = "coex" => unsafe { coex_wifi_channel_get(_primary, _secondary) }, + _ => -1, + } +} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_coex_version_get(_major: *mut u32, _minor: *mut u32, _path: *mut u32) -> i32 { + // IDF reports success here while leaving the out-parameters untouched: its + // `coex_version_get_value` call is `#if 0`-ed out pending a coexist + // submodule update. Query it for real rather than reporting success over + // whatever the controller left on its stack. + cfg_select! { + feature = "coex" => unsafe { + let mut version = coex_version_t { + major: 0, + minor: 0, + patch: 0, + }; + let res = coex_version_get_value(&mut version); + if res == 0 { + _major.write(version.major.into()); + _minor.write(version.minor.into()); + _path.write(version.patch.into()); + } + res + }, + _ => -1, + } +} + +// The ISO hooks stay stubbed: IDF gates them on `CONFIG_BT_LE_ISO_SUPPORT`, +// which esp-radio does not offer. + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_coex_iso_start(_info: *mut c_void) -> i32 { + 0 +} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_coex_iso_stop(_handle: u16) -> i32 { + 0 +} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_coex_iso_protect_frame_thres_get() -> u16 { + 0 +} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_coex_iso_start_int_handle(_handle: u16, _duration: u32) {} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_coex_iso_end_int_handle(_handle: u16, _duration: u32) {} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_coex_ble_idle_time_inform(_start_offset: u32, _duration: u32) { + cfg_select! { + feature = "coex" => unsafe { coex_ble_idle_time_inform(_start_offset, _duration) }, + _ => {} + } +} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_coex_register_ble_cb(_ty: u32, _func: *mut c_void) -> i32 { + cfg_select! { + feature = "coex" => unsafe { coex_register_ble_cb(_ty as u8, _func) }, + _ => 0, + } +} + +/// Hands a complete HCI packet, indicator byte first, to the host reader. +fn queue_rx_packet(header: &[u8], payload: &[u8]) { + let mut data = alloc::vec::Vec::with_capacity(header.len() + payload.len()); + data.extend_from_slice(header); + data.extend_from_slice(payload); + + super::dump_packet_info(&data); + super::BT_STATE.with(|state| { + state.rx_queue.push_back(ReceivedPacket { + data: data.into_boxed_slice(), + }); + }); + crate::ble::controller::hci_read_data_available(); +} + +extern "C" fn btdm_hci_controller_tx(pkt: *mut HciDriverPacket) -> i32 { + let Some(pkt) = (unsafe { pkt.as_mut() }) else { + return -1; + }; + queue_rx_packet(&[pkt.type_], unsafe { + core::slice::from_raw_parts(pkt.data, pkt.length as usize) + }); + unsafe { r_btdm_hci_trans_buf_free(core::ptr::from_mut(pkt)) }; + 0 +} + +unsafe extern "C" fn ble_hs_hci_rx_evt(cmd: *const u8, _arg: *const c_void) -> i32 { + let event = unsafe { *cmd }; + let len = unsafe { *cmd.add(1) }; + queue_rx_packet(&[0x04, event, len], unsafe { + core::slice::from_raw_parts(cmd.add(2), len as usize) + }); + unsafe { r_ble_hci_trans_buf_free(cmd) }; + 0 +} + +unsafe extern "C" fn ble_hs_rx_data(om: *const OsMbuf, _arg: *const c_void) -> i32 { + queue_rx_packet(&[0x02], unsafe { + core::slice::from_raw_parts((*om).om_data, (*om).om_len as usize) + }); + unsafe { r_os_mbuf_free_chain(om.cast_mut()) }; + 0 +} + +fn send_hci_packet(packet: &[u8]) { + const DATA_TYPE_COMMAND: u8 = 1; + const DATA_TYPE_ACL: u8 = 2; + + super::dump_packet_info(packet); + + unsafe { + if packet[0] == DATA_TYPE_COMMAND { + // IDF VHCI uses the BTDM-common packet path, not NimBLE + // `r_ble_hci_trans_hs_cmd_tx`. + let pkt = r_btdm_hci_trans_buf_alloc(HCI_DRIVER_TYPE_CMD, 0); + if pkt.is_null() { + warn!("r_btdm_hci_trans_buf_alloc failed"); + return; + } + (*pkt).type_ = HCI_DRIVER_TYPE_CMD; + (*pkt).length = (packet.len() - 1) as u16; + core::ptr::copy_nonoverlapping(packet.as_ptr().add(1), (*pkt).data, packet.len() - 1); + let res = r_btdm_hci_trans_rx(pkt); + if res != 0 { + warn!("r_btdm_hci_trans_rx returned {}", res); + } + } else if packet[0] == DATA_TYPE_ACL { + let om = r_os_msys_get_pkthdr(packet.len() as u16, ACL_DATA_MBUF_LEADINGSPACE as u16); + if om.is_null() { + warn!("r_os_msys_get_pkthdr failed"); + return; + } + let res = r_os_mbuf_append(om, packet.as_ptr().add(1), (packet.len() - 1) as u16); + if res != 0 { + panic!("r_os_mbuf_append returned {}", res); + } + *((*om).om_data as *mut u8).add(1) = 0; + let res = r_ble_hci_trans_hs_acl_tx(om); + if res != 0 { + panic!("r_ble_hci_trans_hs_acl_tx returned {}", res); + } + } + } +} + +fn lpclk_hz() -> u64 { + u64::from(super::lp_clk::frequency_hz()) +} + +#[ram] +unsafe extern "C" fn btdm_lp_sleep_cb(_enable_tick: u32, _arg: *mut c_void) { + // The callbacks are registered during controller init. IDF guards them with `s_bt_active` so + // that the PHY stays up until the controller is enabled. + if controller_status() != esp_bt_controller_status_t_ESP_BT_CONTROLLER_STATUS_ENABLED { + return; + } + super::modem_phy_release(); +} + +#[ram] +unsafe extern "C" fn btdm_lp_wake_up_cb(arg: *mut c_void) { + // The controller passes its `btdm_lp_wakeup_params_t`. Bit 31 tells it that the BLE timer + // ended the light sleep. + const BT_WAKEUP: u32 = 1 << 31; + let params = arg.cast::(); + super::modem_phy_acquire(); + if !params.is_null() { + let by_bt = cfg_select! { + sleep_driver_supported => { + esp_hal::rtc_cntl::wakeup_cause().contains(esp_hal::rtc_cntl::WakeupSource::Bt) + } + _ => false, + }; + unsafe { + let value = params.read_volatile(); + params.write_volatile(if by_bt { + value | BT_WAKEUP + } else { + value & !BT_WAKEUP + }); + } + } +} + +/// Returns whether the controller refuses a light sleep, because its next event is too close. +#[cfg(sleep_driver_supported)] +pub(super) fn controller_skips_light_sleep() -> bool { + unsafe extern "C" { + fn r_btdm_sleep_should_skip_light_sleep_check() -> bool; + } + unsafe { r_btdm_sleep_should_skip_light_sleep_check() } +} + +/// IDF `btdm_lp_init`. Runs after `r_btdm_task_init`, before `ble_stack_init`. +/// +/// `r_btdm_task_init` initializes the hardware environment that holds the low-power clock +/// frequency, so the frequency has to be set after it. +unsafe fn btdm_lp_init() { + unsafe extern "C" { + fn r_btdm_sleep_set_sleep_cb( + sleep_cb: unsafe extern "C" fn(u32, *mut c_void), + wakeup_cb: unsafe extern "C" fn(*mut c_void), + sleep_arg: *mut c_void, + wakeup_arg: *mut c_void, + us_to_enabled: u32, + ); + } + + // IDF `BTDM_RTC_DELAY_US_LIGHT_SLEEP`: how long the controller needs to enable the PHY, when + // the chip can light-sleep while the controller sleeps. + const RTC_DELAY_US_LIGHT_SLEEP: u32 = 1800; + + unsafe { + if super::modem_sleep_enabled() { + r_btdm_sleep_set_sleep_cb( + btdm_lp_sleep_cb, + btdm_lp_wake_up_cb, + core::ptr::null_mut(), + core::ptr::null_mut(), + RTC_DELAY_US_LIGHT_SLEEP, + ); + } + + r_btdm_hal_rtc_freq_set(lpclk_hz()); + } +} + +pub(crate) fn ble_init(config: &Config) -> PhyInitGuard<'static> { + super::set_modem_sleep(config.modem_sleep()); + super::lp_clk::request(); + chip_specific::btdm_controller_mem_init(); + + let mut cfg = chip_specific::create_ble_config(config); + + #[cfg(feature = "coex")] + unsafe { + let res = crate::wifi::coex_init(); + assert!(res == 0, "coex_init failed"); + } + + chip_specific::bt_periph_module_enable(); + chip_specific::disable_sleep_mode(); + + let phy_init_guard = esp_phy::enable_phy(); + + let res = esp_bt_controller_init(&mut cfg); + assert!(res == 0, "esp_bt_controller_init returned {}", res); + + #[cfg(feature = "coex")] + unsafe { + crate::sys::include::coex_enable(); + } + + let res = esp_bt_controller_enable(esp_bt_mode_t_ESP_BT_MODE_BLE); + assert!(res == 0, "esp_bt_controller_enable returned {}", res); + + if config.modem_sleep() { + super::lp_clk::claim_wake_source(); + } + + #[cfg(rng_trng_supported)] + unsafe { + esp_hal::rng::TrngSource::increase_entropy_source_counter() + }; + + phy_init_guard +} + +pub(crate) fn ble_deinit() { + super::lp_clk::release_wake_source(); + super::modem_phy_acquire(); + super::set_modem_sleep(false); + + #[cfg(rng_trng_supported)] + esp_hal::rng::TrngSource::decrease_entropy_source_counter(unsafe { + esp_hal::Internal::conjure() + }); + + let _ = esp_bt_controller_disable(); + let _ = esp_bt_controller_deinit(); + + super::lp_clk::release(); +} + +pub(crate) fn send(data: &[u8]) { + send_hci_packet(data) +} + +pub(crate) async fn send_async(data: &[u8]) { + send_hci_packet(data) +} + +// ------------------------------------------------------------------------- +// OSAL (wr_btdm_osal_*) +// +// Event queues are local. CompatQueue's blocking receive sleeps inside +// NonReentrantMutex (IRQs off); on S31 the SWI yield is lost and the next +// schedule_wakeup panics because the task is already Sleeping. +// ------------------------------------------------------------------------- + +const BTDM_OSAL_OK: i32 = 0; +const BTDM_OSAL_INVALID_PARM: i32 = 3; +const BTDM_OSAL_TIMEOUT: i32 = 6; + +static EVENTQ_DEPTH: AtomicU16 = AtomicU16::new(16); +static CRITICAL_NEST: AtomicU8 = AtomicU8::new(0); +static CRITICAL_TOKEN: AtomicU32 = AtomicU32::new(0); + +#[repr(C)] +#[derive(Default, Clone, Copy)] +struct BtdmOsalPtr { + pub ptr: *mut c_void, +} + +type EventFn = unsafe extern "C" fn(*mut BtdmOsalPtr); + +struct Event { + queued: bool, + fn_ptr: Option, + arg: *mut c_void, +} + +struct Callout { + timer: ets_timer, + evq: *mut BtdmOsalPtr, + ev: BtdmOsalPtr, + expiry_ms: u32, +} + +#[inline(always)] +fn event_inner(ev: *mut BtdmOsalPtr) -> &'static mut Event { + let ev = unwrap!(unsafe { ev.as_ref() }, "event is null"); + unwrap!( + unsafe { ev.ptr.cast::().as_mut() }, + "event inner is null" + ) +} + +fn alloc() -> *mut T { + unsafe { crate::compat::malloc::calloc(1, size_of::()).cast() } +} + +fn free_ptr(ptr: *mut c_void) { + unsafe { crate::compat::malloc::free(ptr.cast()) } +} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_osal_eventq_init(evq: *mut BtdmOsalPtr) { + trace!("wr_btdm_osal_eventq_init {:?}", evq); + let evq = unwrap!(unsafe { evq.as_mut() }, "eventq is null"); + if !evq.ptr.is_null() { + return; + } + + evq.ptr = queue_create( + EVENTQ_DEPTH.load(Ordering::Relaxed) as i32, + size_of::<*mut BtdmOsalPtr>() as i32, + ); +} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_osal_eventq_deinit(evq: *mut BtdmOsalPtr) { + trace!("wr_btdm_osal_eventq_deinit {:?}", evq); + let evq = unwrap!(unsafe { evq.as_mut() }, "eventq is null"); + queue_delete(evq.ptr) +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn wr_btdm_osal_eventq_get(evq: *mut BtdmOsalPtr, tmo: u32) -> *mut BtdmOsalPtr { + trace!("wr_btdm_osal_eventq_get {:?} {}", evq, tmo); + let evq = unwrap!(unsafe { evq.as_mut() }, "eventq is null"); + + let mut ev = core::ptr::null_mut::(); + let received = if in_isr() { + if tmo != 0 { + return core::ptr::null_mut(); + } + queue_try_receive_from_isr(evq.ptr, (&raw mut ev).cast(), core::ptr::null_mut()) + } else { + queue_receive(evq.ptr, (&raw mut ev).cast(), blob_ticks_to_micros(tmo)) + }; + + if received != 0 + && let Some(inner) = unsafe { (*ev).ptr.cast::().as_mut() } + { + inner.queued = false; + } + + ev +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn wr_btdm_osal_eventq_put(evq: *mut BtdmOsalPtr, ev: *mut BtdmOsalPtr) { + trace!("wr_btdm_osal_eventq_put {:?} {:?}", evq, ev); + let evq = unwrap!(unsafe { evq.as_mut() }, "eventq is null"); + + let ret = if in_isr() { + queue_try_send_to_back_from_isr(evq.ptr, (&raw const ev).cast(), core::ptr::null_mut()) + } else { + queue_send_to_back(evq.ptr, (&raw const ev).cast(), OSI_FUNCS_TIME_BLOCKING) + }; + + assert_ne!(ret, 0); +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn wr_btdm_osal_eventq_put_to_front(evq: *mut BtdmOsalPtr, ev: *mut BtdmOsalPtr) { + trace!("wr_btdm_osal_eventq_put_to_front {:?} {:?}", evq, ev); + let evq = unwrap!(unsafe { evq.as_mut() }, "eventq is null"); + + let ret = if in_isr() { + queue_try_send_to_front_from_isr(evq.ptr, (&raw const ev).cast(), core::ptr::null_mut()) + } else { + queue_send_to_front(evq.ptr, (&raw const ev).cast(), OSI_FUNCS_TIME_BLOCKING) + }; + + assert_ne!(ret, 0); +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn wr_btdm_osal_eventq_remove(evq: *mut BtdmOsalPtr, ev: *mut BtdmOsalPtr) { + trace!("wr_btdm_osal_eventq_remove {:?} {:?}", evq, ev); + let evq = unwrap!(unsafe { evq.as_mut() }, "eventq is null"); + let inner = event_inner(ev); + + if inner.queued { + queue_remove(evq.ptr, (&raw const ev).cast()); + inner.queued = false; + } +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn wr_btdm_osal_eventq_is_empty(evq: *mut BtdmOsalPtr) -> bool { + let evq = unwrap!(unsafe { evq.as_mut() }, "eventq is null"); + queue_messages_waiting(evq.ptr) == 0 +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn wr_btdm_osal_event_run(ev: *mut BtdmOsalPtr) { + trace!("wr_btdm_osal_event_run {:?}", ev); + if let Some(func) = event_inner(ev).fn_ptr { + trace!("calling event handler {:#x}", func as usize); + unsafe { func(ev) }; + } +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn wr_btdm_osal_event_init( + ev: *mut BtdmOsalPtr, + func: Option, + arg: *mut c_void, +) { + let func_p = func.map(|f| f as usize).unwrap_or(0); + trace!("creating event with handler {:#x}", func_p); + let ev = unwrap!(unsafe { ev.as_mut() }, "event is null"); + if ev.ptr.is_null() { + ev.ptr = alloc::().cast(); + } + let inner = unwrap!( + unsafe { ev.ptr.cast::().as_mut() }, + "event alloc failed" + ); + *inner = Event { + queued: false, + fn_ptr: func, + arg, + }; +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn wr_btdm_osal_event_deinit(ev: *mut BtdmOsalPtr) { + trace!("wr_btdm_osal_event_deinit {:?}", ev); + let ev = unwrap!(unsafe { ev.as_mut() }, "event is null"); + if !ev.ptr.is_null() { + free_ptr(ev.ptr); + ev.ptr = core::ptr::null_mut(); + } +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn wr_btdm_osal_event_reset(ev: *mut BtdmOsalPtr) { + trace!("wr_btdm_osal_event_reset {:?}", ev); + let ev = unwrap!(unsafe { ev.as_ref() }, "event is null"); + if let Some(inner) = unsafe { ev.ptr.cast::().as_mut() } { + inner.queued = false; + } +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn wr_btdm_osal_event_is_queued(ev: *mut BtdmOsalPtr) -> bool { + trace!("wr_btdm_osal_event_is_queued {:?}", ev); + event_inner(ev).queued +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn wr_btdm_osal_event_get_arg(ev: *mut BtdmOsalPtr) -> *mut c_void { + trace!("wr_btdm_osal_event_get_arg {:?}", ev); + event_inner(ev).arg +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn wr_btdm_osal_event_set_arg(ev: *mut BtdmOsalPtr, arg: *mut c_void) { + trace!("wr_btdm_osal_event_set_arg {:?} {:?}", ev, arg); + event_inner(ev).arg = arg; +} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_osal_mutex_init(mu: *mut BtdmOsalPtr) -> i32 { + trace!("wr_btdm_osal_mutex_init {:?}", mu); + let mu = unwrap!(unsafe { mu.as_mut() }, "mutex is null"); + if mu.ptr.is_null() { + mu.ptr = mutex::mutex_create(true); + } + if mu.ptr.is_null() { + BTDM_OSAL_INVALID_PARM + } else { + BTDM_OSAL_OK + } +} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_osal_mutex_deinit(mu: *mut BtdmOsalPtr) -> i32 { + trace!("wr_btdm_osal_mutex_deinit {:?}", mu); + let mu = unwrap!(unsafe { mu.as_mut() }, "mutex is null"); + if mu.ptr.is_null() { + return BTDM_OSAL_INVALID_PARM; + } + mutex::mutex_delete(mu.ptr); + mu.ptr = core::ptr::null_mut(); + BTDM_OSAL_OK +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn wr_btdm_osal_mutex_pend(mu: *mut BtdmOsalPtr, timeout: u32) -> i32 { + trace!("wr_btdm_osal_mutex_pend {:?} {}", mu, timeout); + let mu = unwrap!(unsafe { mu.as_ref() }, "mutex is null"); + if mu.ptr.is_null() || in_isr() { + return BTDM_OSAL_INVALID_PARM; + } + + if mutex::mutex_lock_with_timeout(mu.ptr, blob_ticks_to_micros(timeout)) != 0 { + BTDM_OSAL_OK + } else { + BTDM_OSAL_TIMEOUT + } +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn wr_btdm_osal_mutex_release(mu: *mut BtdmOsalPtr) -> i32 { + trace!("wr_btdm_osal_mutex_release {:?}", mu); + let mu = unwrap!(unsafe { mu.as_ref() }, "mutex is null"); + if mu.ptr.is_null() || in_isr() { + return BTDM_OSAL_INVALID_PARM; + } + if mutex::mutex_unlock(mu.ptr) != 0 { + BTDM_OSAL_OK + } else { + BTDM_OSAL_TIMEOUT + } +} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_osal_sem_init(sem: *mut BtdmOsalPtr, tokens: u16) -> i32 { + trace!("wr_btdm_osal_sem_init {:?} {:?}", sem, tokens); + let sem = unwrap!(unsafe { sem.as_mut() }, "sem is null"); + if sem.ptr.is_null() { + sem.ptr = semaphore::sem_create(128, tokens as u32); + } + if sem.ptr.is_null() { + BTDM_OSAL_INVALID_PARM + } else { + BTDM_OSAL_OK + } +} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_osal_sem_deinit(sem: *mut BtdmOsalPtr) -> i32 { + trace!("wr_btdm_osal_sem_deinit {:?}", sem); + let sem = unwrap!(unsafe { sem.as_mut() }, "sem is null"); + if sem.ptr.is_null() { + return BTDM_OSAL_INVALID_PARM; + } + semaphore::sem_delete(sem.ptr); + sem.ptr = core::ptr::null_mut(); + BTDM_OSAL_OK +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn wr_btdm_osal_sem_pend(sem: *mut BtdmOsalPtr, timeout: u32) -> i32 { + trace!("wr_btdm_osal_sem_pend {:?} {}", sem, timeout); + let sem = unwrap!(unsafe { sem.as_ref() }, "sem is null"); + if sem.ptr.is_null() { + return BTDM_OSAL_INVALID_PARM; + } + + let taken = if in_isr() { + if timeout != 0 { + return BTDM_OSAL_INVALID_PARM; + } + + semaphore::sem_try_take_from_isr(sem.ptr, core::ptr::null_mut()) + } else { + semaphore::sem_take(sem.ptr, blob_ticks_to_micros(timeout)) + }; + if taken != 0 { + BTDM_OSAL_OK + } else { + BTDM_OSAL_TIMEOUT + } +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn wr_btdm_osal_sem_release(sem: *mut BtdmOsalPtr) -> i32 { + trace!("wr_btdm_osal_sem_release {:?}", sem); + let sem = unwrap!(unsafe { sem.as_ref() }, "sem is null"); + if sem.ptr.is_null() { + return BTDM_OSAL_INVALID_PARM; + } + let given = if in_isr() { + semaphore::sem_try_give_from_isr(sem.ptr, core::ptr::null_mut()) + } else { + semaphore::sem_give(sem.ptr) + }; + if given != 0 { + BTDM_OSAL_OK + } else { + BTDM_OSAL_TIMEOUT + } +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn wr_btdm_osal_sem_get_count(sem: *mut BtdmOsalPtr) -> u16 { + trace!("wr_btdm_osal_sem_get_count {:?}", sem); + let Some(sem) = (unsafe { sem.as_ref() }) else { + return 0; + }; + if sem.ptr.is_null() { + return 0; + } + semaphore::sem_count(sem.ptr) as u16 +} + +#[inline(always)] +fn callout_inner(co: *mut BtdmOsalPtr) -> &'static mut Callout { + let co = unwrap!(unsafe { co.as_ref() }, "callout is null"); + unwrap!( + unsafe { co.ptr.cast::().as_mut() }, + "callout inner is null" + ) +} + +unsafe extern "C" fn callout_timer_cb(arg: *mut c_void) { + trace!("callout_timer_cb {:#x}", arg as usize); + let callout = arg.cast::(); + let callout = unwrap!(unsafe { callout.as_mut() }, "callout is null"); + if !callout.evq.is_null() { + wr_btdm_osal_eventq_put(callout.evq, &raw mut callout.ev); + } else { + wr_btdm_osal_event_run(&raw mut callout.ev); + } +} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_osal_callout_init( + co: *mut BtdmOsalPtr, + evq: *mut BtdmOsalPtr, + ev_cb: Option, + ev_arg: *mut c_void, +) -> i32 { + trace!( + "wr_btdm_osal_callout_init co={:#x} evq={:#x}", + co as usize, evq as usize + ); + let co = unwrap!(unsafe { co.as_mut() }, "callout is null"); + if co.ptr.is_null() { + let callout = alloc::(); + if callout.is_null() { + return -1; + } + unsafe { + (*callout).ev.ptr = core::ptr::null_mut(); + compat::timer_compat::compat_timer_setfn( + &raw mut (*callout).timer, + callout_timer_cb, + callout.cast(), + ); + } + co.ptr = callout.cast(); + } + + let callout = co.ptr.cast::(); + unsafe { + (*callout).evq = evq; + wr_btdm_osal_event_init(&raw mut (*callout).ev, ev_cb, ev_arg); + } + + 0 +} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_osal_callout_deinit(co: *mut BtdmOsalPtr) { + trace!("wr_btdm_osal_callout_deinit co={:#x}", co as usize); + let co = unwrap!(unsafe { co.as_mut() }, "callout is null"); + if co.ptr.is_null() { + return; + } + let callout = co.ptr.cast::(); + let timer = unsafe { &raw mut (*callout).timer }; + unsafe { + compat::timer_compat::compat_timer_disarm(timer); + compat::timer_compat::compat_timer_done(timer); + wr_btdm_osal_event_deinit(&raw mut (*callout).ev); + free_ptr(callout.cast()); + } + co.ptr = core::ptr::null_mut(); +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn wr_btdm_osal_callout_reset(co: *mut BtdmOsalPtr, ticks: u32) -> i32 { + trace!( + "wr_btdm_osal_callout_reset co={:#x} ticks={}", + co as usize, ticks + ); + let callout = callout_inner(co); + compat::timer_compat::compat_timer_disarm(&raw mut callout.timer); + if !callout.evq.is_null() { + wr_btdm_osal_eventq_remove(callout.evq, &raw mut callout.ev); + } + let millis = blob_ticks_to_millis(ticks.max(1)); + callout.expiry_ms = wr_btdm_osal_time_get().wrapping_add(millis); + compat::timer_compat::compat_timer_arm(&raw mut callout.timer, millis, false); + BTDM_OSAL_OK +} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_osal_callout_mem_reset(co: *mut BtdmOsalPtr) { + trace!("wr_btdm_osal_callout_mem_reset co={:#x}", co as usize); + let callout = callout_inner(co); + wr_btdm_osal_event_reset(&raw mut callout.ev); +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn wr_btdm_osal_callout_stop(co: *mut BtdmOsalPtr) { + trace!("wr_btdm_osal_callout_stop co={:#x}", co as usize); + let Some(co) = (unsafe { co.as_ref() }) else { + return; + }; + let Some(callout) = (unsafe { co.ptr.cast::().as_mut() }) else { + return; + }; + compat::timer_compat::compat_timer_disarm(&raw mut callout.timer); + if !callout.evq.is_null() { + wr_btdm_osal_eventq_remove(callout.evq, &raw mut callout.ev); + } +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn wr_btdm_osal_callout_is_active(co: *mut BtdmOsalPtr) -> bool { + trace!("wr_btdm_osal_callout_is_active co={:#x}", co as usize); + let callout = callout_inner(co); + compat::timer_compat::compat_timer_is_active(&raw mut callout.timer) +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn wr_btdm_osal_callout_get_ticks(co: *mut BtdmOsalPtr) -> u32 { + trace!("wr_btdm_osal_callout_get_ticks co={:#x}", co as usize); + let callout = callout_inner(co); + callout.expiry_ms +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn wr_btdm_osal_callout_remaining_ticks(co: *mut BtdmOsalPtr, now: u32) -> u32 { + trace!( + "wr_btdm_osal_callout_remaining_ticks co={:#x} now={}", + co as usize, now + ); + let callout = callout_inner(co); + if !compat::timer_compat::compat_timer_is_active(&raw mut callout.timer) { + return 0; + } + callout.expiry_ms.saturating_sub(now) +} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_osal_callout_set_arg(co: *mut BtdmOsalPtr, arg: *mut c_void) { + trace!( + "wr_btdm_osal_callout_set_arg co={:#x} arg={:#x}", + co as usize, arg as usize + ); + let callout = callout_inner(co); + wr_btdm_osal_event_set_arg(&raw mut callout.ev, arg); +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn wr_btdm_osal_time_get() -> u32 { + crate::hal::time::Instant::now() + .duration_since_epoch() + .as_millis() as u32 +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn wr_btdm_osal_time_ms_to_ticks(ms: u32, out_ticks: *mut u32) -> i32 { + unsafe { *out_ticks = millis_to_blob_ticks(ms) }; + BTDM_OSAL_OK +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn wr_btdm_osal_time_ticks_to_ms(ticks: u32, out_ms: *mut u32) -> i32 { + unsafe { *out_ms = blob_ticks_to_millis(ticks) }; + BTDM_OSAL_OK +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn wr_btdm_osal_time_ms_to_ticks32(ms: u32) -> u32 { + millis_to_blob_ticks(ms) +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn wr_btdm_osal_time_ticks_to_ms32(ticks: u32) -> u32 { + blob_ticks_to_millis(ticks) +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn wr_btdm_osal_get_time_forever() -> u32 { + OSI_FUNCS_TIME_BLOCKING +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn wr_btdm_osal_hw_enter_critical() -> u32 { + // We count calls because in at least one place, the blob doesn't pass the returned number back + // to `exit_critical`. + let last = CRITICAL_NEST.fetch_add(1, Ordering::Release); + if last == 0 { + let token = unsafe { crate::ble::ESP_RADIO_LOCK.acquire().inner() }; + CRITICAL_TOKEN.store(token, Ordering::Relaxed); + } + 0 +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn wr_btdm_osal_hw_exit_critical(_ctx: u32) { + if CRITICAL_NEST.fetch_sub(1, Ordering::Release) == 1 { + let last = CRITICAL_TOKEN.load(Ordering::Relaxed); + + unsafe { + crate::ble::ESP_RADIO_LOCK.release(esp_sync::RestoreState::new(last)); + } + } +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn wr_btdm_osal_hw_is_in_critical() -> u8 { + CRITICAL_NEST.load(Ordering::Acquire) +} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_osal_task_create( + fn_ptr: *mut c_void, + name: *const c_char, + stack_size: u32, + arg: *mut c_void, + priority: u32, + task_handle: *mut *mut c_void, + core_id: u32, +) -> i32 { + let name_str = unsafe { str_from_c(name) }; + unsafe { + let task_func = transmute::<*mut c_void, extern "C" fn(*mut c_void)>(fn_ptr); + // Sleeping waits (usleep) let embassy main run even at the blob + // priority. Ready yield-loops at prio 29 starve main. + let task = crate::preempt::task_create( + name_str, + task_func, + arg, + priority.min(crate::preempt::max_task_priority()), + if core_id < Cpu::COUNT as u32 { + Some(core_id) + } else { + None + }, + stack_size as usize, + ); + if !task_handle.is_null() { + *task_handle = task.as_ptr().cast(); + } + } + BTDM_OSAL_OK +} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_osal_task_delete(task_handle: *mut c_void) { + unsafe { + crate::preempt::schedule_task_deletion(NonNull::new(task_handle.cast::<()>())); + } +} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_osal_intr_alloc( + src: i32, + _flags: i32, + fn_ptr: Option, + arg: *mut c_void, + _handle: *mut *mut c_void, +) -> i32 { + let Some(func) = fn_ptr else { + return BTDM_OSAL_INVALID_PARM; + }; + unsafe { chip_specific::osal_intr_alloc(src as u32, func, arg) } +} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_osal_intr_free(_handle: *mut c_void) -> i32 { + 0 +} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_osal_malloc(size: u32, _flags: u32) -> *mut c_void { + unsafe { crate::compat::malloc::malloc(size as usize).cast() } +} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_osal_free(ptr: *mut c_void) { + if !ptr.is_null() { + unsafe { crate::compat::malloc::free(ptr.cast()) }; + } +} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_osal_mmgmt_block_malloc(size: u32) -> *mut c_void { + let raw = wr_btdm_osal_malloc(size.saturating_add(4), 0) as *mut u32; + if raw.is_null() { + return core::ptr::null_mut(); + } + unsafe { + *raw = (5 << 29) | ((size + 4) >> 2); + raw.add(1).cast() + } +} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_osal_mmgmt_block_free(ptr: *mut c_void) { + if ptr.is_null() { + return; + } + wr_btdm_osal_free(unsafe { (ptr as *mut u32).sub(1) }.cast()); +} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_osal_mmgmt_block_copy(dst: *mut c_void, src: *const c_void, size: u16) { + unsafe extern "C" { + fn r_ble_lll_mmgmt_block_copy(dst: *mut c_void, src: *mut c_void, size: u16); + } + unsafe { r_ble_lll_mmgmt_block_copy(dst, src.cast_mut(), size) }; +} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_osal_read_efuse_mac(mac: *mut u8) -> i32 { + unsafe { crate::common_adapter::read_mac(mac, 2) } +} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_osal_srand(_seed: u32) {} + +#[unsafe(no_mangle)] +extern "C" fn wr_btdm_osal_rand() -> i32 { + unsafe { crate::common_adapter::random() as i32 } +} diff --git a/esp-radio/src/ble/btdm2/os_adapter_esp32h4.rs b/esp-radio/src/ble/btdm2/os_adapter_esp32h4.rs new file mode 100644 index 00000000000..066178fc23b --- /dev/null +++ b/esp-radio/src/ble/btdm2/os_adapter_esp32h4.rs @@ -0,0 +1,339 @@ +use procmacros::BuilderLite; + +use super::*; +use crate::{ + ble::InvalidConfigError, + hal::{ + interrupt::{self, Priority}, + peripherals::Interrupt, + ram, + system::Cpu, + }, + interrupt_dispatch::Handler, + sys::{c_types::c_void, include::esp_bt_controller_config_t}, +}; + +static ISR_INTERRUPT_MAC: Handler = Handler::new(); +static ISR_INTERRUPT_MAC_INT1: Handler = Handler::new(); +static ISR_INTERRUPT_BB: Handler = Handler::new(); +static ISR_INTERRUPT_BB_NMI: Handler = Handler::new(); +static ISR_INTERRUPT_LP_TIMER: Handler = Handler::new(); +static ISR_INTERRUPT_LP_RTC_BLE_TIMER: Handler = Handler::new(); +static ISR_INTERRUPT_BLE_TIMER: Handler = Handler::new(); +static ISR_INTERRUPT_BLE_SEC: Handler = Handler::new(); + +/// The interrupts the controller may ask for, each with the slot holding its +/// handler and the trampoline that dispatches from that slot. +const BLE_INTERRUPTS: &[(Interrupt, &Handler)] = &[ + (Interrupt::BT_MAC, &ISR_INTERRUPT_MAC), + (Interrupt::BT_MAC_INT1, &ISR_INTERRUPT_MAC_INT1), + (Interrupt::BT_BB, &ISR_INTERRUPT_BB), + (Interrupt::BT_BB_NMI, &ISR_INTERRUPT_BB_NMI), + (Interrupt::LP_TIMER, &ISR_INTERRUPT_LP_TIMER), + (Interrupt::LP_RTC_BLE_TIMER, &ISR_INTERRUPT_LP_RTC_BLE_TIMER), + (Interrupt::BLE_TIMER, &ISR_INTERRUPT_BLE_TIMER), + (Interrupt::BLE_SEC, &ISR_INTERRUPT_BLE_SEC), +]; + +/// Antenna Selection +#[derive(Default, Clone, Copy, Eq, PartialEq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum Antenna { + /// Use Antenna 0 + #[default] + Antenna0 = 0, + /// Use Antenna 1 + Antenna1 = 1, +} + +/// Transmission Power Level +#[derive(Default, Clone, Copy, Eq, PartialEq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum TxPower { + /// -15 dBm + N15, + /// -12 dBm + N12, + /// -9 dBm + N9, + /// -6 dBm + N6, + /// -3 dBm + N3, + /// 0 dBm + N0, + /// 3 dBm + P3, + /// 6 dBm + P6, + /// 9 dBm + #[default] + P9, + /// 12 dBm + P12, + /// 15 dBm + P15, + /// 18 dBm + P18, + /// 20 dBm + P20, +} + +impl TxPower { + fn dbm(self) -> i8 { + match self { + Self::N15 => -15, + Self::N12 => -12, + Self::N9 => -9, + Self::N6 => -6, + Self::N3 => -3, + Self::N0 => 0, + Self::P3 => 3, + Self::P6 => 6, + Self::P9 => 9, + Self::P12 => 12, + Self::P15 => 15, + Self::P18 => 18, + Self::P20 => 20, + } + } +} + +/// Bluetooth controller configuration. +#[derive(BuilderLite, Clone, Copy, Eq, PartialEq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub struct Config { + /// Enables controller modem sleep. + /// + /// The low-power clock source comes from the clock tree (`BLE_LP_CLK`). + /// While the controller sleeps, the chip can also enter automatic light + /// sleep. Set this before the controller starts. The default is off. + modem_sleep: bool, + + /// The priority of the RTOS task. + task_priority: u8, + /// The stack size of the RTOS task. + task_stack_size: u16, + /// The CPU core on which the BLE controller task should run. + task_cpu: Cpu, + /// The maximum number of simultaneous connections. + max_connections: u8, + /// Enable QA test mode. + qa_test_mode: bool, + /// Default TX antenna. + default_tx_antenna: Antenna, + /// Default RX antenna. + default_rx_antenna: Antenna, + /// Default TX power. + default_tx_power: TxPower, + /// Coexistence: limit on MAX Tx/Rx time for coded-PHY connection. + limit_time_for_coded_phy_connection: bool, +} + +impl Default for Config { + fn default() -> Self { + Self { + modem_sleep: false, + task_priority: crate::preempt::max_task_priority() + .saturating_sub(2) + .min(255) as u8, + task_stack_size: CONFIG_BT_CTRL_TASK_STACK_SIZE as u16, + task_cpu: Cpu::ProCpu, + max_connections: DEFAULT_BT_LE_MAX_CONNECTIONS as u8, + qa_test_mode: false, + default_tx_antenna: Antenna::default(), + default_rx_antenna: Antenna::default(), + default_tx_power: TxPower::default(), + limit_time_for_coded_phy_connection: false, + } + } +} + +impl Config { + pub(crate) fn validate(&self) -> Result<(), InvalidConfigError> { + crate::ble::validate_range!( + self, + task_priority, + 0, + crate::preempt::max_task_priority().min(255) as u8 + ); + crate::ble::validate_range!(self, max_connections, 1, 10); + Ok(()) + } +} + +pub(crate) fn create_ble_config(config: &Config) -> esp_bt_controller_config_t { + // BLE-only defaults from IDF `BT_CONTROLLER_INIT_CONFIG_DEFAULT`. + let ble = esp_bt_controller_config_t__bindgen_ty_1 { + config_version: BLE_CONFIG_VERSION, + ble_ll_resolv_list_size: CONFIG_BT_LE_LL_RESOLV_LIST_SIZE as u16, + ble_hci_evt_hi_buf_count: DEFAULT_BT_LE_HCI_EVT_HI_BUF_COUNT as u16, + ble_hci_evt_lo_buf_count: DEFAULT_BT_LE_HCI_EVT_LO_BUF_COUNT as u16, + ble_ll_sync_list_cnt: DEFAULT_BT_LE_MAX_PERIODIC_ADVERTISER_LIST as u8, + ble_ll_sync_cnt: DEFAULT_BT_LE_MAX_PERIODIC_SYNCS as u8, + ble_ll_rsp_dup_list_count: CONFIG_BT_LE_LL_DUP_SCAN_LIST_COUNT as u16, + ble_ll_adv_dup_list_count: CONFIG_BT_LE_LL_DUP_SCAN_LIST_COUNT as u16, + ble_ll_tx_pwr_dbm: config.default_tx_power.dbm() as u8, + rtc_freq: super::super::lp_clk::frequency_hz() as u64, + ble_ll_sca: CONFIG_BT_LE_LL_SCA as _, + ble_ll_scan_phy_number: BLE_LL_SCAN_PHY_NUMBER_N as u8, + ble_ll_conn_def_auth_pyld_tmo: BLE_LL_CONN_DEF_AUTH_PYLD_TMO_N as u16, + ble_ll_jitter_usecs: BLE_LL_JITTER_USECS_N as u8, + ble_ll_sched_max_adv_pdu_usecs: BLE_LL_SCHED_MAX_ADV_PDU_USECS_N as u16, + ble_ll_sched_direct_adv_max_usecs: BLE_LL_SCHED_DIRECT_ADV_MAX_USECS_N as u16, + ble_ll_sched_adv_max_usecs: BLE_LL_SCHED_ADV_MAX_USECS_N as u16, + ble_scan_rsp_data_max_len: DEFAULT_BT_LE_SCAN_RSP_DATA_MAX_LEN_N as u16, + ble_ll_cfg_num_hci_cmd_pkts: BLE_LL_CFG_NUM_HCI_CMD_PKTS_N as u8, + ble_ll_ctrl_proc_timeout_ms: BLE_LL_CTRL_PROC_TIMEOUT_MS_N, + nimble_max_connections: config.max_connections as u16, + ble_whitelist_size: DEFAULT_BT_NIMBLE_WHITELIST_SIZE as u8, + ble_acl_buf_size: DEFAULT_BT_LE_ACL_BUF_SIZE as u16, + ble_acl_buf_count: DEFAULT_BT_LE_ACL_BUF_COUNT as u16, + ble_hci_evt_buf_size: DEFAULT_BT_LE_HCI_EVT_BUF_SIZE as u16, + ble_multi_adv_instances: DEFAULT_BT_LE_MAX_EXT_ADV_INSTANCES as u16, + ble_ext_adv_max_size: DEFAULT_BT_LE_EXT_ADV_MAX_SIZE as u16, + controller_task_stack_size: config.task_stack_size, + controller_task_prio: config.task_priority, + controller_run_cpu: config.task_cpu as u8, + enable_qa_test: config.qa_test_mode as u8, + enable_bqb_test: 0, + enable_tx_cca: DEFAULT_BT_LE_TX_CCA_ENABLED as u8, + cca_rssi_thresh: (256 - DEFAULT_BT_LE_CCA_RSSI_THRESH) as u8, + sleep_en: u8::from(config.modem_sleep), + coex_phy_coded_tx_rx_time_limit: if cfg!(feature = "coex") { + config.limit_time_for_coded_phy_connection as u8 + } else { + DEFAULT_BT_LE_COEX_PHY_CODED_TX_RX_TLIM_EFF as u8 + }, + dis_scan_backoff: 0, + ble_scan_classify_filter_enable: 1, + cca_drop_mode: 0, + cca_low_tx_pwr: 0, + main_xtal_freq: CONFIG_XTAL_FREQ as u8, + ignore_wl_for_direct_adv: 0, + enable_pcl: 0, + csa2_select: 1, + enable_csr: 0, + backoff_rssi: -100, + iso_enabled: DEFAULT_BT_LE_ISO_ENABLED != 0, + iso_bqb_test: false, + iso_fra_unseg: DEFAULT_BT_LE_ISO_FRA_UNSEG != 0, + iso_nsfc_en: DEFAULT_BT_LE_ISO_NSFC_EN != 0, + iso_nsfc_num: DEFAULT_BT_LE_ISO_NSFC_NUM as u8, + iso_buf_count: DEFAULT_BT_LE_ISO_BUF_COUNT as u8, + iso_buf_size: DEFAULT_BT_LE_ISO_BUF_SIZE as u16, + iso_big_count: DEFAULT_BT_LE_ISO_BIG as u8, + iso_bis_count: DEFAULT_BT_LE_ISO_BIS as u16, + iso_bis_per_big: DEFAULT_BT_LE_ISO_BIS_PER_BIG as u8, + iso_cig_count: DEFAULT_BT_LE_ISO_CIG as u8, + iso_cis_count: DEFAULT_BT_LE_ISO_CIS as u16, + iso_cis_per_cig: DEFAULT_BT_LE_ISO_CIS_PER_CIG as u8, + config_magic: BLE_CONFIG_MAGIC, + }; + + let btdm = esp_btdm_controller_config_t { + version: BTDM_CONFIG_VERSION, + task_stack_size: config.task_stack_size, + task_prio: config.task_priority, + task_run_cpu: config.task_cpu as u8, + hci_cmd_num: CONFIG_BT_CTRL_HCI_CMD_NUM as u8, + hci_conn_num: config.max_connections, + sleep_en: u8::from(config.modem_sleep), + version_num: 0, + bluetooth_mode: esp_bt_mode_t_ESP_BT_MODE_BLE as u8, + magic: BTDM_CONFIG_MAGIC_VALUE, + }; + + esp_bt_controller_config_t { ble, btdm } +} + +pub(crate) fn btdm_controller_mem_init() {} + +pub(crate) fn bt_periph_module_enable() { + crate::radio_clocks::clocks_ll::enable_bt(true); +} + +pub(crate) fn disable_sleep_mode() {} + +pub(super) unsafe fn osal_intr_alloc( + source: u32, + func: unsafe extern "C" fn(*mut c_void), + arg: *mut c_void, +) -> i32 { + trace!( + "btdm osal_intr_alloc source={} fn={:?} arg={:?}", + source, func, arg + ); + + // The blob passes IDF interrupt source numbers, which are the PAC's + // `Interrupt` discriminants. + let entry = u8::try_from(source) + .ok() + .and_then(|source| Interrupt::try_from(source).ok()) + .and_then(|source| BLE_INTERRUPTS.iter().find(|(int, _)| *int == source)); + + let Some(&(int, slot)) = entry else { + panic!("Unsupported BLE interrupt source {}", source); + }; + + slot.set(func as *const c_void, arg); + + interrupt::enable(int, Priority::Priority3); + 0 +} + +pub(crate) fn shutdown_ble_isr() { + for &(int, _) in BLE_INTERRUPTS { + for core in Cpu::all() { + interrupt::disable(core, int); + } + } +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn BT_MAC() { + ISR_INTERRUPT_MAC.dispatch(); +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn BT_BB() { + ISR_INTERRUPT_BB.dispatch(); +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn BT_BB_NMI() { + ISR_INTERRUPT_BB_NMI.dispatch(); +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn LP_TIMER() { + ISR_INTERRUPT_LP_TIMER.dispatch(); +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn LP_RTC_BLE_TIMER() { + ISR_INTERRUPT_LP_RTC_BLE_TIMER.dispatch(); +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn BLE_TIMER() { + ISR_INTERRUPT_BLE_TIMER.dispatch(); +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn BLE_SEC() { + ISR_INTERRUPT_BLE_SEC.dispatch(); +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn BT_MAC_INT1() { + ISR_INTERRUPT_MAC_INT1.dispatch(); +} diff --git a/esp-radio/src/ble/btdm2/os_adapter_esp32s31.rs b/esp-radio/src/ble/btdm2/os_adapter_esp32s31.rs new file mode 100644 index 00000000000..e4c810f252d --- /dev/null +++ b/esp-radio/src/ble/btdm2/os_adapter_esp32s31.rs @@ -0,0 +1,335 @@ +use procmacros::BuilderLite; + +use super::*; +use crate::{ + ble::InvalidConfigError, + hal::{ + interrupt::{self, Priority}, + peripherals::Interrupt, + ram, + system::Cpu, + }, + interrupt_dispatch::Handler, + sys::{c_types::c_void, include::esp_bt_controller_config_t}, +}; + +static ISR_INTERRUPT_MAC: Handler = Handler::new(); +static ISR_INTERRUPT_MAC_INT1: Handler = Handler::new(); +static ISR_INTERRUPT_BB: Handler = Handler::new(); +static ISR_INTERRUPT_BB_NMI: Handler = Handler::new(); +static ISR_INTERRUPT_LP_TIMER: Handler = Handler::new(); +static ISR_INTERRUPT_BLE_TIMER: Handler = Handler::new(); +static ISR_INTERRUPT_BLE_SEC: Handler = Handler::new(); + +/// The interrupts the controller may ask for, each with the slot holding its +/// handler and the trampoline that dispatches from that slot. +const BLE_INTERRUPTS: &[(Interrupt, &Handler)] = &[ + (Interrupt::MODEM_BT_MAC, &ISR_INTERRUPT_MAC), + (Interrupt::MODEM_BT_MAC_INT1, &ISR_INTERRUPT_MAC_INT1), + (Interrupt::MODEM_BT_BB, &ISR_INTERRUPT_BB), + (Interrupt::MODEM_BT_BB_NMI, &ISR_INTERRUPT_BB_NMI), + (Interrupt::MODEM_LP_TIMER, &ISR_INTERRUPT_LP_TIMER), + (Interrupt::MODEM_BLE_TIMER, &ISR_INTERRUPT_BLE_TIMER), + (Interrupt::MODEM_BLE_SEC, &ISR_INTERRUPT_BLE_SEC), +]; + +/// Antenna Selection +#[derive(Default, Clone, Copy, Eq, PartialEq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum Antenna { + /// Use Antenna 0 + #[default] + Antenna0 = 0, + /// Use Antenna 1 + Antenna1 = 1, +} + +/// Transmission Power Level +#[derive(Default, Clone, Copy, Eq, PartialEq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub enum TxPower { + /// -15 dBm + N15, + /// -12 dBm + N12, + /// -9 dBm + N9, + /// -6 dBm + N6, + /// -3 dBm + N3, + /// 0 dBm + N0, + /// 3 dBm + P3, + /// 6 dBm + P6, + /// 9 dBm + #[default] + P9, + /// 12 dBm + P12, + /// 15 dBm + P15, + /// 18 dBm + P18, + /// 20 dBm + P20, +} + +impl TxPower { + fn dbm(self) -> i8 { + match self { + Self::N15 => -15, + Self::N12 => -12, + Self::N9 => -9, + Self::N6 => -6, + Self::N3 => -3, + Self::N0 => 0, + Self::P3 => 3, + Self::P6 => 6, + Self::P9 => 9, + Self::P12 => 12, + Self::P15 => 15, + Self::P18 => 18, + Self::P20 => 20, + } + } +} + +/// Bluetooth controller configuration. +#[derive(BuilderLite, Clone, Copy, Eq, PartialEq)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub struct Config { + /// Enables controller modem sleep. + /// + /// The low-power clock source comes from the clock tree (`BLE_LP_CLK`). + /// While the controller sleeps, the chip can also enter automatic light + /// sleep. Set this before the controller starts. The default is off. + modem_sleep: bool, + + /// The priority of the RTOS task. + task_priority: u8, + /// The stack size of the RTOS task. + task_stack_size: u16, + /// The CPU core on which the BLE controller task should run. + task_cpu: Cpu, + /// The maximum number of simultaneous connections. + max_connections: u8, + /// Enable QA test mode. + qa_test_mode: bool, + /// Default TX antenna. + default_tx_antenna: Antenna, + /// Default RX antenna. + default_rx_antenna: Antenna, + /// Default TX power. + default_tx_power: TxPower, + /// Coexistence: limit on MAX Tx/Rx time for coded-PHY connection. + limit_time_for_coded_phy_connection: bool, +} + +impl Default for Config { + fn default() -> Self { + Self { + modem_sleep: false, + task_priority: crate::preempt::max_task_priority() + .saturating_sub(2) + .min(255) as u8, + task_stack_size: CONFIG_BT_CTRL_TASK_STACK_SIZE as u16, + task_cpu: Cpu::ProCpu, + max_connections: DEFAULT_BT_LE_MAX_CONNECTIONS as u8, + qa_test_mode: false, + default_tx_antenna: Antenna::default(), + default_rx_antenna: Antenna::default(), + default_tx_power: TxPower::default(), + limit_time_for_coded_phy_connection: false, + } + } +} + +impl Config { + pub(crate) fn validate(&self) -> Result<(), InvalidConfigError> { + crate::ble::validate_range!( + self, + task_priority, + 0, + crate::preempt::max_task_priority().min(255) as u8 + ); + crate::ble::validate_range!(self, max_connections, 1, 10); + Ok(()) + } +} + +pub(crate) fn create_ble_config(config: &Config) -> esp_bt_controller_config_t { + // BLE-only defaults from IDF `BT_CONTROLLER_INIT_CONFIG_DEFAULT`. + let ble = esp_bt_controller_config_t__bindgen_ty_1 { + config_version: BLE_CONFIG_VERSION, + ble_ll_resolv_list_size: CONFIG_BT_LE_LL_RESOLV_LIST_SIZE as u16, + ble_hci_evt_hi_buf_count: DEFAULT_BT_LE_HCI_EVT_HI_BUF_COUNT as u16, + ble_hci_evt_lo_buf_count: DEFAULT_BT_LE_HCI_EVT_LO_BUF_COUNT as u16, + ble_ll_sync_list_cnt: DEFAULT_BT_LE_MAX_PERIODIC_ADVERTISER_LIST as u8, + ble_ll_sync_cnt: DEFAULT_BT_LE_MAX_PERIODIC_SYNCS as u8, + ble_ll_rsp_dup_list_count: CONFIG_BT_LE_LL_DUP_SCAN_LIST_COUNT as u16, + ble_ll_adv_dup_list_count: CONFIG_BT_LE_LL_DUP_SCAN_LIST_COUNT as u16, + ble_ll_tx_pwr_dbm: config.default_tx_power.dbm() as u8, + rtc_freq: super::super::lp_clk::frequency_hz() as u64, + ble_ll_sca: CONFIG_BT_LE_LL_SCA as _, + ble_ll_scan_phy_number: BLE_LL_SCAN_PHY_NUMBER_N as u8, + ble_ll_conn_def_auth_pyld_tmo: BLE_LL_CONN_DEF_AUTH_PYLD_TMO_N as u16, + ble_ll_jitter_usecs: BLE_LL_JITTER_USECS_N as u8, + ble_ll_sched_max_adv_pdu_usecs: BLE_LL_SCHED_MAX_ADV_PDU_USECS_N as u16, + ble_ll_sched_direct_adv_max_usecs: BLE_LL_SCHED_DIRECT_ADV_MAX_USECS_N as u16, + ble_ll_sched_adv_max_usecs: BLE_LL_SCHED_ADV_MAX_USECS_N as u16, + ble_scan_rsp_data_max_len: DEFAULT_BT_LE_SCAN_RSP_DATA_MAX_LEN_N as u16, + ble_ll_cfg_num_hci_cmd_pkts: BLE_LL_CFG_NUM_HCI_CMD_PKTS_N as u8, + ble_ll_ctrl_proc_timeout_ms: BLE_LL_CTRL_PROC_TIMEOUT_MS_N, + nimble_max_connections: config.max_connections as u16, + ble_whitelist_size: DEFAULT_BT_NIMBLE_WHITELIST_SIZE as u8, + ble_acl_buf_size: DEFAULT_BT_LE_ACL_BUF_SIZE as u16, + ble_acl_buf_count: DEFAULT_BT_LE_ACL_BUF_COUNT as u16, + ble_hci_evt_buf_size: DEFAULT_BT_LE_HCI_EVT_BUF_SIZE as u16, + ble_multi_adv_instances: DEFAULT_BT_LE_MAX_EXT_ADV_INSTANCES as u16, + ble_ext_adv_max_size: DEFAULT_BT_LE_EXT_ADV_MAX_SIZE as u16, + controller_task_stack_size: config.task_stack_size, + controller_task_prio: config.task_priority, + controller_run_cpu: config.task_cpu as u8, + enable_qa_test: config.qa_test_mode as u8, + enable_bqb_test: 0, + enable_tx_cca: DEFAULT_BT_LE_TX_CCA_ENABLED as u8, + cca_rssi_thresh: (256 - DEFAULT_BT_LE_CCA_RSSI_THRESH) as u8, + sleep_en: u8::from(config.modem_sleep), + coex_phy_coded_tx_rx_time_limit: if cfg!(feature = "coex") { + config.limit_time_for_coded_phy_connection as u8 + } else { + DEFAULT_BT_LE_COEX_PHY_CODED_TX_RX_TLIM_EFF as u8 + }, + dis_scan_backoff: 0, + ble_scan_classify_filter_enable: 1, + cca_drop_mode: 0, + cca_low_tx_pwr: 0, + main_xtal_freq: CONFIG_XTAL_FREQ as u8, + ignore_wl_for_direct_adv: 0, + enable_pcl: 0, + csa2_select: 1, + enable_csr: 0, + backoff_rssi: -100, + iso_enabled: DEFAULT_BT_LE_ISO_ENABLED != 0, + iso_bqb_test: false, + iso_fra_unseg: DEFAULT_BT_LE_ISO_FRA_UNSEG != 0, + iso_nsfc_en: DEFAULT_BT_LE_ISO_NSFC_EN != 0, + iso_nsfc_num: DEFAULT_BT_LE_ISO_NSFC_NUM as u8, + iso_buf_count: DEFAULT_BT_LE_ISO_BUF_COUNT as u8, + iso_buf_size: DEFAULT_BT_LE_ISO_BUF_SIZE as u16, + iso_big_count: DEFAULT_BT_LE_ISO_BIG as u8, + iso_bis_count: DEFAULT_BT_LE_ISO_BIS as u16, + iso_bis_per_big: DEFAULT_BT_LE_ISO_BIS_PER_BIG as u8, + iso_cig_count: DEFAULT_BT_LE_ISO_CIG as u8, + iso_cis_count: DEFAULT_BT_LE_ISO_CIS as u16, + iso_cis_per_cig: DEFAULT_BT_LE_ISO_CIS_PER_CIG as u8, + config_magic: BLE_CONFIG_MAGIC, + }; + + let btdm = esp_btdm_controller_config_t { + version: BTDM_CONFIG_VERSION, + task_stack_size: config.task_stack_size, + task_prio: config.task_priority, + task_run_cpu: config.task_cpu as u8, + hci_cmd_num: CONFIG_BT_CTRL_HCI_CMD_NUM as u8, + hci_conn_num: config.max_connections, + sleep_en: u8::from(config.modem_sleep), + version_num: 0, + bluetooth_mode: esp_bt_mode_t_ESP_BT_MODE_BLE as u8, + magic: BTDM_CONFIG_MAGIC_VALUE, + }; + + esp_bt_controller_config_t { + ble, + bredr: unsafe { core::mem::zeroed() }, + btdm, + } +} + +pub(crate) fn btdm_controller_mem_init() {} + +pub(crate) fn bt_periph_module_enable() { + crate::radio_clocks::clocks_ll::enable_bt(true); +} + +pub(crate) fn disable_sleep_mode() {} + +pub(super) unsafe fn osal_intr_alloc( + source: u32, + func: unsafe extern "C" fn(*mut c_void), + arg: *mut c_void, +) -> i32 { + trace!( + "btdm osal_intr_alloc source={} fn={:?} arg={:?}", + source, func, arg + ); + + // The blob passes IDF interrupt source numbers, which are the PAC's + // `Interrupt` discriminants. + let entry = u8::try_from(source) + .ok() + .and_then(|source| Interrupt::try_from(source).ok()) + .and_then(|source| BLE_INTERRUPTS.iter().find(|(int, _)| *int == source)); + + let Some(&(int, slot)) = entry else { + panic!("Unsupported BLE interrupt source {}", source); + }; + + slot.set(func as *const c_void, arg); + + interrupt::enable(int, Priority::Priority3); + 0 +} + +pub(crate) fn shutdown_ble_isr() { + for &(int, _) in BLE_INTERRUPTS { + for core in Cpu::all() { + interrupt::disable(core, int); + } + } +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn MODEM_BT_MAC() { + ISR_INTERRUPT_MAC.dispatch(); +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn MODEM_BT_BB() { + ISR_INTERRUPT_BB.dispatch(); +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn MODEM_BT_BB_NMI() { + ISR_INTERRUPT_BB_NMI.dispatch(); +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn MODEM_LP_TIMER() { + ISR_INTERRUPT_LP_TIMER.dispatch(); +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn MODEM_BLE_TIMER() { + ISR_INTERRUPT_BLE_TIMER.dispatch(); +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn MODEM_BLE_SEC() { + ISR_INTERRUPT_BLE_SEC.dispatch(); +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn MODEM_BT_MAC_INT1() { + ISR_INTERRUPT_MAC_INT1.dispatch(); +} diff --git a/esp-radio/src/ble/controller/mod.rs b/esp-radio/src/ble/controller/mod.rs index 25ba7ee7fa9..f65ca9fc8f2 100644 --- a/esp-radio/src/ble/controller/mod.rs +++ b/esp-radio/src/ble/controller/mod.rs @@ -1,4 +1,5 @@ //! BLE controller +use alloc::boxed::Box; use core::{future::Future, task::Poll}; use bt_hci::{ @@ -10,12 +11,25 @@ use bt_hci::{ }; use bt_hci_transport::{PacketKind, PacketToController, PacketToHost}; use docsplay::Display; +use embassy_sync::mutex::Mutex; use esp_phy::PhyInitGuard; +use esp_sync::RawMutex; use crate::{ RadioRefGuard, asynch::AtomicWaker, - ble::{Config, InvalidConfigError, have_hci_read_data, read_hci, read_next, send_hci}, + ble::{ + Config, + HciOutCollector, + InvalidConfigError, + MAX_HCI_ACL_PACKET_LEN, + MAX_HCI_CMD_PACKET_LEN, + have_hci_packet, + have_hci_read_data, + read_hci, + read_next, + take_next, + }, }; #[derive(Display, Debug, Copy, Clone, Eq, PartialEq, Hash)] @@ -41,6 +55,9 @@ pub struct BleConnector<'d> { _phy_init_guard: PhyInitGuard<'d>, _device: crate::hal::peripherals::BT<'d>, _guard: RadioRefGuard, + /// The `Transport` implementations write through a shared reference, so they need the mutex to + /// get at the writer. + hci_writer: Mutex, } impl Drop for BleConnector<'_> { @@ -56,7 +73,13 @@ impl<'d> BleConnector<'d> { device: crate::hal::peripherals::BT<'d>, config: Config, ) -> Result, BleInitError> { - let _guard = RadioRefGuard::new(); + // With modem sleep, the claimed `Bt` wakeup source refuses the sleeps that are not safe. + // The driver claims it only where light sleep works with the controller. + let _guard = if config.modem_sleep() && crate::ble::lp_clk::light_sleep_supported() { + RadioRefGuard::without_wake_lock() + } else { + RadioRefGuard::new() + }; config.validate()?; @@ -64,13 +87,17 @@ impl<'d> BleConnector<'d> { _phy_init_guard: crate::ble::ble_init(&config), _device: device, _guard, + hci_writer: Mutex::new(HciOutCollector::new()), }) } /// Read the next HCI packet from the BLE controller. + /// + /// Returns the length of the packet, or 0 if no packet is available. If the packet is longer + /// than `buf`, the packet is dropped and an error is returned. #[instability::unstable] pub fn next(&mut self, buf: &mut [u8]) -> Result { - Ok(read_next(buf)) + read_next(buf) } /// Read from HCI. @@ -96,20 +123,25 @@ impl<'d> BleConnector<'d> { return Ok(0); } - if !have_hci_read_data() { - HciReadyEventFuture.await; - } + HciAnyDataReadyEventFuture.await; self.read(buf) } /// Write to HCI. + /// + /// Returns the number of bytes written, which is at most one packet. #[instability::unstable] pub fn write(&mut self, buf: &[u8]) -> Result { - for b in buf { - send_hci(&[*b]); - } - Ok(buf.len()) + Ok(self.hci_writer.get_mut().write(buf)) + } + + /// Write to HCI asynchronously. + /// + /// Returns the number of bytes written, which is at most one packet. + #[instability::unstable] + pub async fn write_async(&mut self, buf: &[u8]) -> Result { + Ok(self.hci_writer.get_mut().write_async(buf).await) } } @@ -192,8 +224,7 @@ impl embedded_io_async_06::Read for BleConnector<'_> { impl embedded_io_async_06::Write for BleConnector<'_> { async fn write(&mut self, buf: &[u8]) -> Result { - send_hci(buf); - Ok(buf.len()) + self.write_async(buf).await } async fn flush(&mut self) -> Result<(), BleConnectorError> { @@ -210,8 +241,7 @@ impl embedded_io_async_07::Read for BleConnector<'_> { impl embedded_io_async_07::Write for BleConnector<'_> { async fn write(&mut self, buf: &[u8]) -> Result { - send_hci(buf); - Ok(buf.len()) + self.write_async(buf).await } async fn flush(&mut self) -> Result<(), BleConnectorError> { @@ -226,10 +256,10 @@ impl From for BleConnectorError { } } -#[must_use = "futures do nothing unless you `.await` or poll them"] -pub(crate) struct HciReadyEventFuture; +/// Completes once any HCI data is available, including a part-read packet. +pub(crate) struct HciAnyDataReadyEventFuture; -impl core::future::Future for HciReadyEventFuture { +impl core::future::Future for HciAnyDataReadyEventFuture { type Output = (); fn poll( @@ -246,28 +276,23 @@ impl core::future::Future for HciReadyEventFuture { } } -/// The largest HCI packet, including the packet type indicator byte. -const MAX_HCI_PACKET_LEN: usize = 259; - -/// The HCI output of the BLE controller. -/// -/// The transport implementations use this zero-sized writer to serialize packets directly into the -/// controller. -struct HciWriter; +/// Completes once the receive queue holds a complete packet. +pub(crate) struct HciPacketReadyEventFuture; -impl embedded_io_07::ErrorType for HciWriter { - type Error = BleConnectorError; -} +impl core::future::Future for HciPacketReadyEventFuture { + type Output = (); -impl embedded_io_async_07::Write for HciWriter { - async fn write(&mut self, buf: &[u8]) -> Result { - send_hci(buf); - Ok(buf.len()) - } + fn poll( + self: core::pin::Pin<&mut Self>, + cx: &mut core::task::Context<'_>, + ) -> Poll { + HCI_WAKER.register(cx.waker()); - async fn flush(&mut self) -> Result<(), Self::Error> { - // nothing to do - Ok(()) + if have_hci_packet() { + Poll::Ready(()) + } else { + Poll::Pending + } } } @@ -287,15 +312,42 @@ fn parse_hci(data: &[u8]) -> Result, BleConnectorErro } } -/// Waits for a packet from the controller, then reads it into `rx`. +/// Checks that the collector can send a packet, before any byte of it gets to the collector. /// -/// Returns the length of the packet. -async fn next_packet(rx: &mut [u8]) -> usize { - if !have_hci_read_data() { - HciReadyEventFuture.await; - } +/// `indicator` is the HCI packet type indicator, and `size` is the size of the packet without it. +/// +/// The collector sends only command and ACL packets, and only up to its buffer size. It cannot +/// drop a packet as a whole, so it would read the rest of such a packet as new packets. +fn check_outgoing_packet(indicator: u8, size: usize) -> Result<(), BleConnectorError> { + const COMMAND: u8 = 1; + const ACL_DATA: u8 = 2; + + let max_len = match indicator { + COMMAND => MAX_HCI_CMD_PACKET_LEN, + ACL_DATA => MAX_HCI_ACL_PACKET_LEN, + _ => 0, + }; + let len = size.saturating_add(1); + if len > max_len { + warn!( + "[hci] dropping outgoing packet of type {} and {} bytes, which cannot be sent", + indicator, len + ); + return Err(BleConnectorError::Unknown); + } + + Ok(()) +} - read_next(rx) +/// Waits for a packet from the controller, then removes it from the receive queue. +async fn next_packet() -> Box<[u8]> { + loop { + HciPacketReadyEventFuture.await; + + if let Some(packet) = take_next() { + return packet; + } + } } impl bt_hci::transport::Transport for BleConnector<'_> { @@ -305,14 +357,28 @@ impl bt_hci::transport::Transport for BleConnector<'_> { // Safety: we only return a reference to x once, if parsing is successful. let rx = unsafe { &mut *core::ptr::slice_from_raw_parts_mut(rx.as_mut_ptr(), rx.len()) }; - let len = next_packet(rx).await; + // `ControllerToHostPacket` borrows `rx`, so the packet has to be copied there. + let len = loop { + HciPacketReadyEventFuture.await; + match read_next(rx) { + Ok(0) => {} // A different reader took the packet first: wait again. + Ok(len) => break len, + // The packet is longer than `rx`, and `read_next` dropped it. Do not return an + // error: hosts stop their receive loop on a read error, so one packet that + // does not fit would stop all BLE traffic. + Err(_) => {} + } + }; parse_hci(&rx[..len]) } /// Write a complete HCI packet from the tx buffer async fn write(&self, val: &T) -> Result<(), Self::Error> { + check_outgoing_packet(T::KIND as u8, val.size())?; + + let mut writer = self.hci_writer.lock().await; bt_hci::transport::WithIndicator::new(val) - .write_hci_async(HciWriter) + .write_hci_async(&mut *writer) .await } } @@ -320,20 +386,38 @@ impl bt_hci::transport::Transport for BleConnector<'_> { impl bt_hci_transport::Transport for BleConnector<'_> { /// Read a complete HCI packet into the rx buffer async fn read<'a, P: PacketToHost<'a>>(&self, rx: &'a mut [u8]) -> Result { - // `P::read_hci` deserializes from a reader into `rx`, so the packet must be read into a - // buffer other than `rx`. - let mut packet = [0; MAX_HCI_PACKET_LEN]; - let len = next_packet(&mut packet).await; + // `P::read_hci` deserializes from a reader into `rx`, so the packet must be read from a + // buffer other than `rx`. The queued packet itself is that buffer. + let packet = next_packet().await; - let mut reader = &packet[..len]; + let mut reader = &packet[..]; let kind = PacketKind::read(&mut reader)?; - Ok(P::read_hci(kind, &mut reader, rx)?) + let parsed = P::read_hci(kind, &mut reader, rx)?; + + // `P::read_hci` reads only the length that the packet header gives, so bytes after it + // stay in `reader`. A data packet must fill its frame exactly: extra bytes show that the + // frame is malformed. Event packets are not checked, which is the same as in the + // `bt_hci::transport::Transport` implementation above + // (`ControllerToHostPacket::from_hci_bytes_complete`). + if kind != PacketKind::Event && !reader.is_empty() { + warn!( + "[hci] dropping {:?} packet with {} unexpected trailing bytes", + kind, + reader.len() + ); + return Err(BleConnectorError::Unknown); + } + + Ok(parsed) } /// Write a complete HCI packet from the tx buffer async fn write(&self, tx: &P) -> Result<(), Self::Error> { + check_outgoing_packet(P::KIND as u8, tx.size())?; + + let mut writer = self.hci_writer.lock().await; bt_hci_transport::WithIndicator::new(tx) - .write_hci_async(HciWriter) + .write_hci_async(&mut *writer) .await } } diff --git a/esp-radio/src/ble/lp_clk.rs b/esp-radio/src/ble/lp_clk.rs new file mode 100644 index 00000000000..cef4cb740de --- /dev/null +++ b/esp-radio/src/ble/lp_clk.rs @@ -0,0 +1,186 @@ +//! BLE low-power clock, read from the clock tree. +//! +//! The tree reports the divided output frequency. + +#[cfg(bt_controller = "btdm")] +use esp_hal::clock::ll::BleLpClkConfig; +use esp_hal::clock::ll::{self, ClockSource}; +#[cfg(sleep_driver_supported)] +use { + enumset::EnumSet, + esp_hal::rtc_cntl::{WakeupSource, sleep::WrappedSleepConfig}, + portable_atomic::{AtomicU32, Ordering}, +}; + +/// Sleep clock accuracy (in ppm) reported to the BLE controller when `BLE_LP_CLK` runs from an RC +/// oscillator (see `ble_rtc_clk_init()` in `bt.c`). +#[cfg(bt_controller = "npl")] +pub(crate) const RC_SCA_PPM: u16 = 3000; + +/// BTDM blob parameters for the selected low-power clock. +#[cfg(bt_controller = "btdm")] +pub(crate) struct BtdmLpClk { + /// Value for `btdm_lpclk_select_src`. Crystal is 0. RTC slow is 2. + pub select: u32, + /// Value for `btdm_lpclk_set_div`. + pub divider: u32, + /// Microseconds per low-power cycle, in Q19 format. + pub lpcycle_us: u32, +} + +#[cfg(bt_controller = "btdm")] +fn selected() -> BleLpClkConfig { + ll::ClockTree::with(|clocks| clocks.ble_lp_clk()).expect("BLE_LP_CLK is not configured") +} + +/// Turns the BLE low-power clock on for as long as the controller runs. +/// +/// The controller wakes from sleep on this clock, so it must keep running even while the +/// controller is asleep. +pub(crate) fn request() { + ll::ClockTree::with(ll::request_ble_lp_clk); +} + +/// Releases the request taken by [`request`]. +pub(crate) fn release() { + ll::ClockTree::with(ll::release_ble_lp_clk); +} + +/// Returns whether the chip can light-sleep while the controller sleeps. +/// +/// ESP32 needs a 32 kHz crystal for it, because it cannot light-sleep with the main crystal as the +/// controller clock. +pub(crate) fn light_sleep_supported() -> bool { + cfg_select! { + not(sleep_driver_supported) => false, + esp32 => ll::ClockTree::with(ll::ble_lp_clk_root_source) != Some(ClockSource::XtalClk), + _ => true, + } +} + +/// The source that `BLE_LP_CLK` runs on, as the bits of an [`EnumSet`]. +#[cfg(sleep_driver_supported)] +static WAKE_CLOCK: AtomicU32 = AtomicU32::new(0); + +/// Claims the `Bt` wakeup source, so that the chip can sleep while the controller sleeps. +/// +/// Call this only with modem sleep on, after the controller is enabled, and only when +/// [`light_sleep_supported`] returns `true`. Otherwise the radio wake lock stays. +pub(crate) fn claim_wake_source() { + #[cfg(sleep_driver_supported)] + { + let root = ll::ClockTree::with(ll::ble_lp_clk_root_source); + WAKE_CLOCK.store( + root.map_or(0, |source| EnumSet::only(source).as_u32()), + Ordering::Relaxed, + ); + WakeupSource::Bt.enable_with_hooks(Some(sleep_entry), None); + } +} + +/// Releases the claim taken by [`claim_wake_source`]. +/// +/// Call this before the controller is disabled. +pub(crate) fn release_wake_source() { + #[cfg(sleep_driver_supported)] + WakeupSource::Bt.disable(); +} + +#[cfg(sleep_driver_supported)] +fn sleep_entry(config: &mut WrappedSleepConfig<'_>) { + // The controller does not survive a deep sleep, so it needs no clock through one. + if config.is_deep_sleep() { + return; + } + + // The controller holds the PHY while it is awake, and it then runs on clocks that light sleep + // stops. + let awake = !super::MODEM_PHY_OFF.load(Ordering::Relaxed); + #[cfg(bt_controller = "btdm")] + let awake = awake || super::porting::hci_packet_in_flight(); + if awake { + config.reject_sleep(); + return; + } + + cfg_select! { + bt_controller = "btdm" => { + // The controller wakes on its own timer, but the chip must be awake before it does. + let remaining = super::porting::time_until_controller_wakes(); + if remaining.as_micros() == 0 { + config.reject_sleep(); + return; + } + config.limit_sleep(remaining); + } + // The BLE timer wakes the chip through the `Bt` source. The controller refuses the sleep + // when its next event is too close. + not(esp32c2) => { + if super::porting::controller_skips_light_sleep() { + config.reject_sleep(); + return; + } + } + // The BLE timer wakes the chip through the `Bt` source. + _ => {} + } + + for source in EnumSet::::from_u32_truncated(WAKE_CLOCK.load(Ordering::Relaxed)) { + config.keep_clock_running(source); + } +} + +/// Returns whether the clock node's root source is an internal RC oscillator. +#[cfg(not(bt_controller = "btdm2"))] +pub(crate) fn source_is_rc(f: fn(&mut ll::ClockTree) -> Option) -> bool { + matches!( + ll::ClockTree::with(f), + Some(ClockSource::RcSlowClk | ClockSource::RcFastClk) + ) +} + +/// Returns the BLE low-power clock frequency, in hertz. +#[cfg(not(bt_controller = "btdm"))] +pub(crate) fn frequency_hz() -> u32 { + ll::ble_lp_clk_frequency() +} + +/// Returns the microseconds per low-power cycle. +#[cfg(bt_controller = "btdm")] +pub(crate) fn btdm_lpcycle_us() -> u32 { + let hz = ll::ble_lp_clk_frequency().max(1); + ((1_000_000u64 << 19) / u64::from(hz)) as u32 +} + +/// Returns the BTDM blob clock-select parameters for the configured source. +#[cfg(bt_controller = "btdm")] +pub(crate) fn btdm() -> BtdmLpClk { + // ESP32 only supports the main crystal or an external 32 kHz crystal/oscillator as the BLE + // sleep clock (see `btdm_low_power_mode_init()` in `esp32/bt.c`). + #[cfg(esp32)] + if source_is_rc(ll::ble_lp_clk_root_source) { + panic!("RC clocks cannot be selected as the BLE low-power clock"); + } + + let config = selected(); + let lpcycle_us = btdm_lpcycle_us(); + + let (select, divider) = match config { + BleLpClkConfig::Xtal => { + let ratio = ll::xtal_clk_frequency() / ll::ble_lp_xtal_clk_frequency(); + // The ESP32 blob takes the divider field, which is one less than the ratio. + let divider = cfg_select! { + esp32 => ratio - 1, + _ => ratio, + }; + (0, divider) + } + BleLpClkConfig::RtcSlow => (2, 0), + }; + + BtdmLpClk { + select, + divider, + lpcycle_us, + } +} diff --git a/esp-radio/src/ble/mod.rs b/esp-radio/src/ble/mod.rs index b3a7fd3d892..328d0ce66e6 100644 --- a/esp-radio/src/ble/mod.rs +++ b/esp-radio/src/ble/mod.rs @@ -1,20 +1,24 @@ //! Bluetooth Low Energy HCI interface -#[cfg(bt_controller = "btdm")] -pub(crate) mod btdm; +mod lp_clk; -#[cfg(all(bt_controller = "npl", not(feature = "ble-host-npl")))] -pub(crate) mod npl; +#[cfg(not(all(bt_controller = "npl", feature = "ble-host-npl")))] +#[cfg_attr(bt_controller = "btdm", path = "btdm/mod.rs")] +#[cfg_attr(bt_controller = "npl", path = "npl/mod.rs")] +#[cfg_attr(bt_controller = "btdm2", path = "btdm2/mod.rs")] +pub(crate) mod porting; /// BLE NPL (NimBLE Porting Layer) for external C-based BLE host integration. #[cfg(all(bt_controller = "npl", feature = "ble-host-npl"))] +#[path = "npl/mod.rs"] pub mod npl; +#[cfg(all(bt_controller = "npl", feature = "ble-host-npl"))] +use npl as porting; -use alloc::{boxed::Box, collections::vec_deque::VecDeque, vec::Vec}; -use core::mem::MaybeUninit; +use alloc::{boxed::Box, collections::vec_deque::VecDeque}; -pub(crate) use ble::{ble_deinit, ble_init, send_hci}; use docsplay::Display; use esp_sync::NonReentrantMutex; +pub(crate) use porting::{ble_deinit, ble_init}; /// An error that is returned when the configuration is invalid. #[derive(Display, Debug, Clone, Copy, PartialEq, Eq, Hash)] @@ -25,43 +29,87 @@ pub struct InvalidConfigError; impl core::error::Error for InvalidConfigError {} // Expose chip-specific configuration types -pub use ble::ble_os_adapter_chip_specific::*; +pub use porting::chip_specific::*; -#[cfg(bt_controller = "btdm")] -use self::btdm as ble; -#[cfg(bt_controller = "npl")] -use self::npl as ble; +pub(crate) static ESP_RADIO_LOCK: esp_sync::RawMutex = esp_sync::RawMutex::new(); + +/// Returns whether the caller runs in an interrupt handler. +/// +/// The controller calls some of the OS glue from its interrupt handlers. Those calls must not +/// block, so they use the try-variant of the operation. +#[cfg(any(bt_controller = "npl", bt_controller = "btdm2"))] +pub(crate) fn in_isr() -> bool { + !crate::hal::interrupt::RunLevel::current().is_thread() +} + +static MODEM_SLEEP: portable_atomic::AtomicBool = portable_atomic::AtomicBool::new(false); +static MODEM_PHY_OFF: portable_atomic::AtomicBool = portable_atomic::AtomicBool::new(false); + +pub(crate) fn set_modem_sleep(enabled: bool) { + MODEM_SLEEP.store(enabled, portable_atomic::Ordering::Relaxed); +} + +#[allow(dead_code, reason = "The ESP32 BTDM adapter reads this flag")] +pub(crate) fn modem_sleep_enabled() -> bool { + MODEM_SLEEP.load(portable_atomic::Ordering::Relaxed) +} + +/// Drops the extra PHY reference taken around controller sleep. +/// +/// The controller's [`esp_phy::PhyInitGuard`] stays alive. This pairs with +/// [`modem_phy_acquire`]. +pub(crate) fn modem_phy_release() { + if !MODEM_PHY_OFF.swap(true, portable_atomic::Ordering::SeqCst) { + esp_phy::disable_phy(); + } +} + +/// Restores the PHY reference if sleep left it off. +/// +/// Returns `true` if the reference was restored. +pub(crate) fn modem_phy_acquire() -> bool { + let restore = MODEM_PHY_OFF.swap(false, portable_atomic::Ordering::SeqCst); + if restore { + core::mem::forget(esp_phy::enable_phy()); + } + restore +} unstable_module! { pub mod controller; } +// btdm2 registers its own `wr_btdm_osal_malloc` / `wr_btdm_osal_free` wrappers. The NPL +// controller allocates from internal RAM only, see `malloc_internal`. #[cfg(bt_controller = "btdm")] pub(crate) unsafe extern "C" fn malloc(size: u32) -> *mut crate::sys::c_types::c_void { unsafe { crate::compat::malloc::malloc(size as usize).cast() } } -#[cfg(any(bt_controller = "btdm", bt_controller = "npl"))] +// The BTDM controller has its own `malloc_internal` in `btdm/mod.rs`; the NPL controller takes +// its memory from internal RAM through this one. +#[cfg(bt_controller = "npl")] pub(crate) unsafe extern "C" fn malloc_internal(size: u32) -> *mut crate::sys::c_types::c_void { unsafe { crate::compat::malloc::malloc_internal(size as usize).cast() } } +#[cfg(not(bt_controller = "btdm2"))] pub(crate) unsafe extern "C" fn free(ptr: *mut crate::sys::c_types::c_void) { unsafe { crate::compat::malloc::free(ptr.cast()) } } struct BleState { pub rx_queue: VecDeque, - pub hci_read_data: Vec, + /// The packet that the byte-stream reader is part-way through, and the number of bytes the + /// host already took from it. + pub partial_read: Option<(Box<[u8]>, usize)>, } static BT_STATE: NonReentrantMutex = NonReentrantMutex::new(BleState { rx_queue: VecDeque::new(), - hci_read_data: Vec::new(), + partial_read: None, }); -static mut HCI_OUT_COLLECTOR: MaybeUninit = MaybeUninit::uninit(); - #[derive(PartialEq, Debug)] enum HciOutType { Unknown, @@ -69,17 +117,40 @@ enum HciOutType { Command, } -struct HciOutCollector { - data: [u8; 256], +/// The largest HCI command packet: indicator (1) + header (3) + parameters (up to 255). +pub(crate) const MAX_HCI_CMD_PACKET_LEN: usize = 1 + 3 + 255; + +/// The largest outgoing HCI ACL data packet that this connector supports: indicator (1) + header +/// (4) + data (up to 255). +/// +/// `trouble-host` splits outgoing ACL data at the size that the controller reports (`LE Read +/// Buffer Size`). `Transport::write` rejects ACL packets with more than 255 data bytes. +pub(crate) const MAX_HCI_ACL_PACKET_LEN: usize = 1 + 4 + 255; + +/// The largest outgoing HCI packet that this connector supports, including the packet type +/// indicator byte. +const MAX_HCI_PACKET_LEN: usize = if MAX_HCI_ACL_PACKET_LEN > MAX_HCI_CMD_PACKET_LEN { + MAX_HCI_ACL_PACKET_LEN +} else { + MAX_HCI_CMD_PACKET_LEN +}; + +/// Reassembles whole HCI packets out of the byte stream that the host writes. +/// +/// The byte-stream write APIs put no constraint on where the caller splits a packet, and one +/// write can hold several packets. The collector takes only the bytes that the packet in progress +/// still needs, so that it never runs past a packet boundary. +pub(crate) struct HciOutCollector { + data: [u8; MAX_HCI_PACKET_LEN], index: usize, ready: bool, kind: HciOutType, } impl HciOutCollector { - fn new() -> HciOutCollector { + pub(crate) const fn new() -> HciOutCollector { HciOutCollector { - data: [0u8; 256], + data: [0u8; MAX_HCI_PACKET_LEN], index: 0, ready: false, kind: HciOutType::Unknown, @@ -90,30 +161,83 @@ impl HciOutCollector { self.ready } - fn push(&mut self, data: &[u8]) { - self.data[self.index..(self.index + data.len())].copy_from_slice(data); - self.index += data.len(); + /// The length of the header, including the packet type indicator byte. + /// + /// The kind is unknown until the indicator byte arrives, so ask for that byte on its own + /// first. + fn header_len(&self) -> usize { + match self.kind { + HciOutType::Unknown => 1, + HciOutType::Command => 4, + HciOutType::Acl => 5, + } + } + + /// The length of the packet in progress, or `None` while its header is incomplete. + fn packet_len(&self) -> Option { + if self.index < self.header_len() { + return None; + } + + match self.kind { + HciOutType::Unknown => None, + HciOutType::Command => Some(self.data[3] as usize + 4), + HciOutType::Acl => Some(u16::from_le_bytes([self.data[3], self.data[4]]) as usize + 5), + } + } + + /// Copies bytes from `data` until the packet buffer holds `upto` bytes. + /// + /// Returns the number of bytes copied. + fn fill_to(&mut self, data: &[u8], upto: usize) -> usize { + let take = usize::min(data.len(), upto - self.index); + self.data[self.index..][..take].copy_from_slice(&data[..take]); + self.index += take; + take + } + + /// Copies as much of `data` as the packet in progress needs, and returns how much it took. + /// + /// Bytes that belong to the next packet stay in `data`. The caller must send and reset the + /// collector once [`Self::is_ready`] holds, before it offers those bytes again. + fn push(&mut self, data: &[u8]) -> usize { + if data.is_empty() { + return 0; + } - if self.kind == HciOutType::Unknown { - self.kind = match self.data[0] { + if self.index == 0 { + self.kind = match data[0] { 1 => HciOutType::Command, 2 => HciOutType::Acl, - _ => HciOutType::Unknown, + indicator => { + warn!( + "Dropping HCI byte with unknown packet type indicator {}", + indicator + ); + return 1; + } }; } - if !self.ready { - if self.kind == HciOutType::Command && self.index >= 4 { - if self.index == self.data[3] as usize + 4 { - self.ready = true; - } - } else if self.kind == HciOutType::Acl - && self.index >= 5 - && self.index == (self.data[3] as usize) + ((self.data[4] as usize) << 8) + 5 - { - self.ready = true; + // The packet length lives in the header, so complete the header before asking for the + // rest of the packet. + let mut taken = 0; + if self.packet_len().is_none() { + taken += self.fill_to(data, self.header_len()); + } + + if let Some(total) = self.packet_len() { + if total > self.data.len() { + warn!("Dropping HCI packet of {} bytes, which is too long", total); + self.reset(); + return taken; } + + taken += self.fill_to(&data[taken..], total); + self.ready = self.index == total; } + + taken } fn reset(&mut self) { @@ -125,6 +249,43 @@ impl HciOutCollector { fn packet(&self) -> &[u8] { &self.data[0..self.index] } + + pub(crate) fn write(&mut self, buf: &[u8]) -> usize { + let taken = self.push(buf); + + if self.is_ready() { + porting::send(self.packet()); + self.reset(); + } + + taken + } + + pub(crate) async fn write_async(&mut self, buf: &[u8]) -> usize { + let taken = self.push(buf); + + if self.is_ready() { + porting::send_async(self.packet()).await; + self.reset(); + } + + taken + } +} + +impl embedded_io_07::ErrorType for HciOutCollector { + type Error = controller::BleConnectorError; +} + +impl embedded_io_async_07::Write for HciOutCollector { + async fn write(&mut self, buf: &[u8]) -> Result { + Ok(self.write_async(buf).await) + } + + async fn flush(&mut self) -> Result<(), Self::Error> { + // nothing to do + Ok(()) + } } #[derive(Debug, Clone, PartialEq, Eq, Hash)] @@ -146,38 +307,73 @@ impl defmt::Format for ReceivedPacket { pub(crate) fn clear_bt_state() { BT_STATE.with(|state| { state.rx_queue.clear(); - state.hci_read_data.clear(); + state.partial_read = None; }); } /// Checks if there is any HCI data available to read. #[instability::unstable] pub fn have_hci_read_data() -> bool { - BT_STATE.with(|state| !state.rx_queue.is_empty() || !state.hci_read_data.is_empty()) + BT_STATE.with(|state| !state.rx_queue.is_empty() || state.partial_read.is_some()) } -pub(crate) fn read_next(data: &mut [u8]) -> usize { - if let Some(packet) = BT_STATE.with(|state| state.rx_queue.pop_front()) { - data[..packet.data.len()].copy_from_slice(&packet.data[..packet.data.len()]); - packet.data.len() - } else { - 0 - } +/// Checks if the receive queue holds a complete packet. +pub(crate) fn have_hci_packet() -> bool { + BT_STATE.with(|state| !state.rx_queue.is_empty()) +} + +/// Removes the next packet from the receive queue, without copying it. +pub(crate) fn take_next() -> Option> { + BT_STATE.with(|state| state.rx_queue.pop_front().map(|packet| packet.data)) +} + +/// Removes the next packet from the receive queue, and copies it into `data`. +/// +/// Returns the length of the packet, or 0 if the queue is empty. If the packet is longer than +/// `data`, the packet is dropped and an error is returned: the caller can then read the next +/// packet. +pub(crate) fn read_next(data: &mut [u8]) -> Result { + let Some(packet) = take_next() else { + return Ok(0); + }; + + let Some(dst) = data.get_mut(..packet.len()) else { + warn!( + "[hci] dropping received packet of {} bytes, which is longer than the {}-byte buffer", + packet.len(), + data.len() + ); + return Err(controller::BleConnectorError::Unknown); + }; + + dst.copy_from_slice(&packet); + Ok(packet.len()) } /// Reads the next HCI packet from the BLE controller. #[instability::unstable] pub fn read_hci(data: &mut [u8]) -> usize { BT_STATE.with(|state| { - if state.hci_read_data.is_empty() + if state.partial_read.is_none() && let Some(packet) = state.rx_queue.pop_front() { - state.hci_read_data.extend_from_slice(&packet.data); + state.partial_read = Some((packet.data, 0)); + } + + let Some((packet, read)) = state.partial_read.as_mut() else { + return 0; + }; + + let remaining = &packet[*read..]; + let l = usize::min(remaining.len(), data.len()); + data[..l].copy_from_slice(&remaining[..l]); + *read += l; + + let drained = *read == packet.len(); + if drained { + state.partial_read = None; } - let l = usize::min(state.hci_read_data.len(), data.len()); - data[..l].copy_from_slice(&state.hci_read_data[..l]); - state.hci_read_data.drain(..l); l }) } diff --git a/esp-radio/src/ble/npl.rs b/esp-radio/src/ble/npl/mod.rs similarity index 70% rename from esp-radio/src/ble/npl.rs rename to esp-radio/src/ble/npl/mod.rs index 4e026d3c126..a82305cbbd1 100644 --- a/esp-radio/src/ble/npl.rs +++ b/esp-radio/src/ble/npl/mod.rs @@ -1,15 +1,11 @@ -use alloc::boxed::Box; -use core::{ - mem::transmute, - ptr::{NonNull, addr_of, addr_of_mut}, -}; +use alloc::vec::Vec; +use core::{mem::transmute, ptr::NonNull}; -use esp_hal::time::Instant; use esp_phy::PhyInitGuard; use esp_radio_rtos_driver::current_task; use esp_radio_rtos_driver::semaphore::{SemaphoreHandle, SemaphorePtr}; -use super::*; +use super::{Config, ReceivedPacket, in_isr}; use crate::{ compat::{ self, OSI_FUNCS_TIME_BLOCKING, @@ -18,6 +14,7 @@ use crate::{ queue, semaphore::{sem_create, sem_delete, sem_give, sem_take}, }, + hal::time::Instant, sys::{c_types::*, include::*}, time::{blob_ticks_to_micros, blob_ticks_to_millis, millis_to_blob_ticks}, }; @@ -27,25 +24,11 @@ use crate::{ #[cfg_attr(esp32c6, path = "os_adapter_esp32c6.rs")] #[cfg_attr(esp32c61, path = "os_adapter_esp32c61.rs")] #[cfg_attr(esp32h2, path = "os_adapter_esp32h2.rs")] -pub(crate) mod ble_os_adapter_chip_specific; +pub(crate) mod chip_specific; +mod os_mempool; const EVENT_QUEUE_SIZE: usize = 16; -const TIME_FOREVER: u32 = crate::compat::OSI_FUNCS_TIME_BLOCKING; - -#[cfg(esp32c2)] -const OS_MSYS_1_BLOCK_COUNT: i32 = 24; -#[cfg(esp32c2)] -const SYSINIT_MSYS_1_MEMPOOL_SIZE: usize = 768; -#[cfg(esp32c2)] -const SYSINIT_MSYS_1_MEMBLOCK_SIZE: i32 = 128; -#[cfg(esp32c2)] -const OS_MSYS_2_BLOCK_COUNT: i32 = 24; -#[cfg(esp32c2)] -const SYSINIT_MSYS_2_MEMPOOL_SIZE: usize = 1920; -#[cfg(esp32c2)] -const SYSINIT_MSYS_2_MEMBLOCK_SIZE: i32 = 320; - const BLE_HCI_TRANS_BUF_CMD: i32 = 3; // ACL_DATA_MBUF_LEADINGSPCAE: The leadingspace in user info header for ACL data @@ -68,50 +51,30 @@ struct Event { queued: bool, } -#[cfg(esp32c2)] -type OsMembufT = u32; - /// Memory pool #[repr(C)] pub(crate) struct OsMempool { /// Size of the memory blocks, in bytes. - mp_block_size: u32, + pub(crate) mp_block_size: u32, /// The number of memory blocks. - mp_num_blocks: u16, + pub(crate) mp_num_blocks: u16, /// The number of free blocks left - mp_num_free: u16, + pub(crate) mp_num_free: u16, /// The lowest number of free blocks seen - mp_min_free: u16, + pub(crate) mp_min_free: u16, /// Bitmap of OS_MEMPOOL_F_[...] values. - mp_flags: u8, + pub(crate) mp_flags: u8, /// Address of memory buffer used by pool - mp_membuf_addr: u32, + pub(crate) mp_membuf_addr: u32, // STAILQ_ENTRY(os_mempool) mp_list; - next: *const OsMempool, + pub(crate) next: *const OsMempool, // SLIST_HEAD(,os_memblock); - first: *const c_void, + pub(crate) first: *const c_void, /// Name for memory block - name: *const u8, -} - -#[cfg(esp32c2)] -impl OsMempool { - const fn zeroed() -> Self { - Self { - mp_block_size: 0, - mp_num_blocks: 0, - mp_num_free: 0, - mp_min_free: 0, - mp_flags: 0, - mp_membuf_addr: 0, - next: core::ptr::null(), - first: core::ptr::null(), - name: core::ptr::null(), - } - } + pub(crate) name: *const u8, } /// A mbuf pool from which to allocate mbufs. This contains a pointer to the os @@ -131,17 +94,6 @@ pub(crate) struct OsMbufPool { next: *const OsMbufPool, } -#[cfg(esp32c2)] -impl OsMbufPool { - const fn zeroed() -> Self { - Self { - omp_databuf_len: 0, - omp_pool: core::ptr::null(), - next: core::ptr::null(), - } - } -} - /// Chained memory buffer. #[repr(C)] pub struct OsMbuf { @@ -164,28 +116,74 @@ pub struct OsMbuf { om_databuf: u32, } -#[cfg(esp32c2)] -pub(crate) static mut OS_MSYS_INIT_1_DATA: *mut OsMembufT = core::ptr::null_mut(); -#[cfg(esp32c2)] -pub(crate) static mut OS_MSYS_INIT_1_MBUF_POOL: OsMbufPool = OsMbufPool::zeroed(); -#[cfg(esp32c2)] -pub(crate) static mut OS_MSYS_INIT_1_MEMPOOL: OsMempool = OsMempool::zeroed(); - -#[cfg(esp32c2)] -pub(crate) static mut OS_MSYS_INIT_2_DATA: *mut OsMembufT = core::ptr::null_mut(); -#[cfg(esp32c2)] -pub(crate) static mut OS_MSYS_INIT_2_MBUF_POOL: OsMbufPool = OsMbufPool::zeroed(); -#[cfg(esp32c2)] -pub(crate) static mut OS_MSYS_INIT_2_MEMPOOL: OsMempool = OsMempool::zeroed(); - unsafe extern "C" { + cfg_select! { + esp32c2 => { + fn ble_controller_init(cfg: *const esp_bt_controller_config_t) -> i32; + fn ble_controller_deinit() -> i32; + fn ble_controller_enable(mode: u8) -> i32; + fn ble_controller_disable(); + fn ble_get_npl_element_info( + cfg: *const esp_bt_controller_config_t, + npl_info: *const BleNplCountInfoT, + ) -> i32; + fn esp_ble_ll_set_public_addr(addr: *const u8); + } + _ => { + fn esp_ble_register_bb_funcs() -> i32; + fn r_ble_controller_disable() -> i32; + fn r_ble_controller_deinit() -> i32; + fn r_ble_controller_init(cfg: *const esp_bt_controller_config_t) -> i32; + fn r_ble_controller_enable(mode: u8) -> i32; + fn r_ble_get_npl_element_info( + cfg: *const esp_bt_controller_config_t, + npl_info: *const BleNplCountInfoT, + ) -> i32; + fn r_esp_ble_ll_set_public_addr(addr: *const u8); + fn scan_stack_initEnv() -> i32; + fn scan_stack_deinitEnv(); + + fn r_esp_ble_msys_init( + msys_size1: u16, + msys_size2: u16, + msys_cnt1: u16, + msys_cnt2: u16, + from_heap: u8, + ) -> i32; + + fn base_stack_initEnv() -> i32; + fn conn_stack_initEnv() -> i32; + fn adv_stack_initEnv() -> i32; + fn extAdv_stack_initEnv() -> i32; + fn sync_stack_initEnv() -> i32; + + fn base_stack_enable() -> i32; + fn adv_stack_enable() -> i32; + fn extAdv_stack_enable() -> i32; + fn scan_stack_enable() -> i32; + fn sync_stack_enable() -> i32; + + fn base_stack_deinitEnv() -> i32; + fn conn_stack_deinitEnv() -> i32; + fn adv_stack_deinitEnv() -> i32; + fn extAdv_stack_deinitEnv() -> i32; + fn sync_stack_deinitEnv() -> i32; + + fn base_stack_disable() -> i32; + fn adv_stack_disable() -> i32; + fn extAdv_stack_disable() -> i32; + fn scan_stack_disable() -> i32; + fn sync_stack_disable() -> i32; + } + } + // Sends ACL data from host to controller. // // om The ACL data packet to send. // // 0 on success; // A BLE_ERR_[...] error code on failure. - pub(crate) fn r_ble_hci_trans_hs_acl_tx(om: *const OsMbuf) -> i32; + fn r_ble_hci_trans_hs_acl_tx(om: *const OsMbuf) -> i32; // Sends an HCI command from the host to the controller. // @@ -194,52 +192,13 @@ unsafe extern "C" { // // 0 on success; // A BLE_ERR_[...] error code on failure. - pub(crate) fn r_ble_hci_trans_hs_cmd_tx(cmd: *const u8) -> i32; - - #[cfg(esp32c2)] - pub(crate) fn ble_controller_init(cfg: *const esp_bt_controller_config_t) -> i32; - - #[cfg(not(esp32c2))] - pub(crate) fn r_ble_controller_disable() -> i32; - - #[cfg(not(esp32c2))] - pub(crate) fn r_ble_controller_deinit() -> i32; - - #[cfg(esp32c2)] - pub(crate) fn ble_controller_deinit() -> i32; - - #[cfg(not(esp32c2))] - pub(crate) fn r_ble_controller_init(cfg: *const esp_bt_controller_config_t) -> i32; - - #[cfg(esp32c2)] - pub(crate) fn ble_controller_enable(mode: u8) -> i32; - - #[cfg(not(esp32c2))] - pub(crate) fn r_ble_controller_enable(mode: u8) -> i32; - - pub(crate) fn esp_unregister_ext_funcs(); - - pub(crate) fn esp_register_ext_funcs(funcs: *const ExtFuncsT) -> i32; + fn r_ble_hci_trans_hs_cmd_tx(cmd: *const u8) -> i32; + fn esp_unregister_ext_funcs(); + fn esp_register_ext_funcs(funcs: *const ExtFuncsT) -> i32; + fn esp_register_npl_funcs(funcs: *const npl_funcs_t) -> i32; + fn esp_unregister_npl_funcs(); - pub(crate) fn esp_register_npl_funcs(funcs: *const npl_funcs_t) -> i32; - - pub(crate) fn esp_unregister_npl_funcs(); - - #[cfg(esp32c2)] - pub(crate) fn ble_get_npl_element_info( - cfg: *const esp_bt_controller_config_t, - npl_info: *const BleNplCountInfoT, - ) -> i32; - - #[cfg(not(esp32c2))] - pub(crate) fn r_ble_get_npl_element_info( - cfg: *const esp_bt_controller_config_t, - npl_info: *const BleNplCountInfoT, - ) -> i32; - - pub(crate) fn bt_bb_v2_init_cmplx(value: u8); - - pub(crate) fn r_ble_hci_trans_cfg_hs( + fn r_ble_hci_trans_cfg_hs( // ble_hci_trans_rx_cmd_fn evt: Option i32>, evt_arg: *const c_void, @@ -248,48 +207,82 @@ unsafe extern "C" { acl_arg: *const c_void, ); - #[cfg(esp32c2)] - pub(crate) fn esp_ble_ll_set_public_addr(addr: *const u8); + #[cfg(feature = "coex")] + fn ble_osi_coex_funcs_register(coex_funcs: *const OsiCoexFuncsT) -> i32; - #[cfg(not(esp32c2))] - pub(crate) fn r_esp_ble_ll_set_public_addr(addr: *const u8); + fn r_os_msys_get_pkthdr(dsize: u16, user_hdr_len: u16) -> *mut OsMbuf; + fn r_os_mbuf_append(om: *mut OsMbuf, src: *const u8, len: u16) -> i32; + fn r_os_mbuf_free_chain(om: *mut OsMbuf) -> i32; + fn r_ble_hci_trans_init(m: u8); + fn r_ble_hci_trans_buf_alloc(typ: i32) -> *const u8; + fn r_ble_hci_trans_buf_free(buf: *const u8); + fn coex_pti_v2(); +} - #[cfg(esp32c2)] - pub(crate) fn r_mem_init_mbuf_pool( - mem: *const c_void, - mempool: *const OsMempool, - mbuf_pool: *const OsMbufPool, - num_blocks: i32, - block_size: i32, - name: *const u8, - ) -> i32; +#[cfg(not(esp32c2))] +fn ble_controller_init(cfg: *const esp_bt_controller_config_t) -> i32 { + unsafe { + let res = esp_ble_register_bb_funcs(); + assert!(res == 0, "esp_ble_register_bb_funcs returned {}", res); - #[cfg(esp32c2)] - pub(crate) fn r_os_msys_reset(); + let res = r_ble_controller_init(cfg); + assert!(res == 0, "ble_controller_init returned {}", res); - #[cfg(esp32c2)] - pub(crate) fn r_os_msys_register(mbuf_pool: *const OsMbufPool) -> i32; + let res = base_stack_initEnv(); + assert!(res == 0, "base_stack_initEnv returned {}", res); - #[allow(unused)] - pub(crate) fn ble_osi_coex_funcs_register(coex_funcs: *const OsiCoexFuncsT) -> i32; + let res = adv_stack_initEnv(); + assert!(res == 0, "adv_stack_initEnv returned {}", res); - pub(crate) fn r_os_msys_get_pkthdr(dsize: u16, user_hdr_len: u16) -> *mut OsMbuf; + let res = extAdv_stack_initEnv(); + assert!(res == 0, "extAdv_stack_initEnv returned {}", res); - pub(crate) fn r_os_mbuf_append(om: *mut OsMbuf, src: *const u8, len: u16) -> i32; + let res = scan_stack_initEnv(); + assert!(res == 0, "scan_stack_initEnv returned {}", res); - pub(crate) fn r_os_mbuf_free_chain(om: *mut OsMbuf) -> i32; + let res = conn_stack_initEnv(); + assert!(res == 0, "conn_stack_initEnv returned {}", res); - pub(crate) fn r_ble_hci_trans_buf_alloc(typ: i32) -> *const u8; + let res = sync_stack_initEnv(); + assert!(res == 0, "sync_stack_initEnv returned {}", res); - pub(crate) fn r_ble_hci_trans_buf_free(buf: *const u8); + let res = r_esp_ble_msys_init(256, 320, 12, 24, 1); + assert!(res == 0, "esp_ble_msys_init returned {}", res); - pub(crate) fn coex_pti_v2(); + let res = base_stack_enable(); + assert!(res == 0, "base_stack_enable returned {}", res); - #[cfg(not(esp32c2))] - pub(crate) fn scan_stack_initEnv() -> i32; + let res = adv_stack_enable(); + assert!(res == 0, "adv_stack_enable returned {}", res); - #[cfg(not(esp32c2))] - pub(crate) fn scan_stack_deinitEnv(); + let res = extAdv_stack_enable(); + assert!(res == 0, "extAdv_stack_enable returned {}", res); + + let res = scan_stack_enable(); + assert!(res == 0, "scan_stack_enable returned {}", res); + + let res = sync_stack_enable(); + assert!(res == 0, "sync_stack_enable returned {}", res); + } + 0 +} + +#[cfg(not(esp32c2))] +fn ble_controller_deinit() -> i32 { + unsafe { + sync_stack_disable(); + scan_stack_disable(); + extAdv_stack_disable(); + adv_stack_disable(); + base_stack_disable(); + conn_stack_deinitEnv(); + sync_stack_deinitEnv(); + scan_stack_deinitEnv(); + extAdv_stack_deinitEnv(); + adv_stack_deinitEnv(); + base_stack_deinitEnv(); + r_ble_controller_deinit() + } } #[repr(C)] @@ -354,7 +347,7 @@ static G_OSI_FUNCS: ExtFuncsT = ExtFuncsT { 0x20250825 }, - esp_intr_alloc: Some(self::ble_os_adapter_chip_specific::esp_intr_alloc), + esp_intr_alloc: Some(chip_specific::esp_intr_alloc), esp_intr_free: Some(esp_intr_free), malloc: Some(crate::ble::malloc_internal), free: Some(crate::ble::free), @@ -377,9 +370,9 @@ static G_OSI_FUNCS: ExtFuncsT = ExtFuncsT { ecc_gen_key_pair: Some(ecc_gen_key_pair), ecc_gen_dh_key: Some(ecc_gen_dh_key), #[cfg(any(esp32c6, esp32h2))] - esp_reset_modem: Some(self::ble_os_adapter_chip_specific::reset_modem), + esp_reset_modem: Some(chip_specific::reset_modem), #[cfg(esp32c2)] - esp_reset_rpa_moudle: Some(self::ble_os_adapter_chip_specific::esp_reset_rpa_moudle), + esp_reset_rpa_moudle: Some(chip_specific::esp_reset_rpa_moudle), #[cfg(esp32c2)] esp_bt_track_pll_cap: None, magic: 0xA5A5A5A5, @@ -439,10 +432,8 @@ unsafe extern "C" fn task_delete(task: *mut c_void) { } unsafe extern "C" fn osi_assert(ln: u32, fn_name: *const c_void, param1: u32, param2: u32) { - unsafe { - let name_str = str_from_c(fn_name as _); - panic!("ASSERT {}:{} {} {}", name_str, ln, param1, param2); - } + let name_str = unsafe { str_from_c(fn_name as _) }; + panic!("ASSERT {}:{} {} {}", name_str, ln, param1, param2); } unsafe extern "C" fn esp_intr_free(_ret_handle: *mut *mut c_void) -> i32 { @@ -538,9 +529,11 @@ pub(crate) struct npl_funcs_t { p_ble_npl_hw_exit_critical: Option, p_ble_npl_get_time_forever: Option u32>, p_ble_npl_hw_is_in_critical: Option u8>, + p_ble_npl_eventq_put_to_front: + Option, } -static mut G_NPL_FUNCS: npl_funcs_t = npl_funcs_t { +static G_NPL_FUNCS: npl_funcs_t = npl_funcs_t { p_ble_npl_os_started: Some(ble_npl_os_started), p_ble_npl_get_current_task_id: Some(ble_npl_get_current_task_id), p_ble_npl_eventq_init: Some(ble_npl_eventq_init), @@ -585,9 +578,11 @@ static mut G_NPL_FUNCS: npl_funcs_t = npl_funcs_t { p_ble_npl_hw_exit_critical: Some(ble_npl_hw_exit_critical), p_ble_npl_get_time_forever: Some(ble_npl_get_time_forever), p_ble_npl_hw_is_in_critical: Some(ble_npl_hw_is_in_critical), + p_ble_npl_eventq_put_to_front: Some(ble_npl_eventq_put_to_front), }; #[repr(C)] +#[cfg(feature = "coex")] /// Contains pointers to functions used for BLE coexistence with Wi-Fi. pub(crate) struct OsiCoexFuncsT { magic: u32, @@ -599,7 +594,7 @@ pub(crate) struct OsiCoexFuncsT { coex_schm_status_bit_clear: Option, } -#[allow(unused)] +#[cfg(feature = "coex")] static G_COEX_FUNCS: OsiCoexFuncsT = OsiCoexFuncsT { magic: 0xFADEBEAD, version: 0x00010006, @@ -619,14 +614,11 @@ unsafe extern "C" fn coex_core_ble_conn_dyn_prio_get(_low: *mut bool, _high: *mu todo!() } -#[allow(unused)] -unsafe extern "C" fn coex_schm_status_bit_set(_type: u32, _status: u32) { - trace!("coex_schm_status_bit_set is an empty stub"); -} - -#[allow(unused)] -unsafe extern "C" fn coex_schm_status_bit_clear(_type: u32, _status: u32) { - trace!("coex_schm_status_bit_clear is an empty stub"); +coex_fns! { + #[allow(unused)] + fn coex_schm_status_bit_set(typ: u32, status: u32); + #[allow(unused)] + fn coex_schm_status_bit_clear(typ: u32, status: u32); } unsafe extern "C" fn ble_npl_hw_is_in_critical() -> u8 { @@ -634,8 +626,7 @@ unsafe extern "C" fn ble_npl_hw_is_in_critical() -> u8 { } unsafe extern "C" fn ble_npl_get_time_forever() -> u32 { - trace!("ble_npl_get_time_forever"); - TIME_FOREVER + OSI_FUNCS_TIME_BLOCKING } #[cfg_attr(feature = "ble-host-npl", unsafe(no_mangle))] @@ -643,14 +634,14 @@ unsafe extern "C" fn ble_npl_hw_exit_critical(mask: u32) { trace!("ble_npl_hw_exit_critical {}", mask); unsafe { let token = esp_sync::RestoreState::new(mask); - crate::ESP_RADIO_LOCK.release(token); + super::ESP_RADIO_LOCK.release(token); } } #[cfg_attr(feature = "ble-host-npl", unsafe(no_mangle))] unsafe extern "C" fn ble_npl_hw_enter_critical() -> u32 { trace!("ble_npl_hw_enter_critical"); - unsafe { crate::ESP_RADIO_LOCK.acquire().inner() } + unsafe { super::ESP_RADIO_LOCK.acquire().inner() } } unsafe extern "C" fn ble_npl_hw_set_isr(_no: i32, _mask: u32) { @@ -855,7 +846,7 @@ unsafe extern "C" fn ble_npl_sem_pend( }; let mut ticks_ms = 0; - unsafe { ble_npl_time_ticks_to_ms(time, addr_of_mut!(ticks_ms)) }; + unsafe { ble_npl_time_ticks_to_ms(time, &raw mut ticks_ms) }; let ticks_us = ticks_ms * 1_000; if sem_take(semaphore, ticks_us) == 1 { @@ -1101,6 +1092,19 @@ unsafe extern "C" fn ble_npl_eventq_remove( unsafe extern "C" fn ble_npl_eventq_put(queue: *mut ble_npl_eventq, event: *const ble_npl_event) { trace!("ble_npl_eventq_put {:?} {:?}", queue, event); + unsafe { eventq_insert(queue, event, false) } +} + +unsafe extern "C" fn ble_npl_eventq_put_to_front( + queue: *mut ble_npl_eventq, + event: *const ble_npl_event, +) { + trace!("ble_npl_eventq_put_to_front {:?} {:?}", queue, event); + + unsafe { eventq_insert(queue, event, true) } +} + +unsafe fn eventq_insert(queue: *mut ble_npl_eventq, event: *const ble_npl_event, front: bool) { let evt = unsafe { (*event).dummy } as *mut Event; assert!(!evt.is_null()); @@ -1114,13 +1118,29 @@ unsafe extern "C" fn ble_npl_eventq_put(queue: *mut ble_npl_eventq, event: *cons } let wrapper = unwrap!(unsafe { queue.as_mut() }, "queue wrapper is null"); - + let handle = wrapper.dummy as _; // Store the pointer to the ble_npl_event in the queue - this is what we'll need to dequeue. - queue::queue_send_to_back( - wrapper.dummy as _, - (&raw const event).cast(), - OSI_FUNCS_TIME_BLOCKING, - ); + let item = (&raw const event).cast(); + + let sent = if in_isr() { + if front { + queue::queue_try_send_to_front_from_isr(handle, item, core::ptr::null_mut()) + } else { + queue::queue_try_send_to_back_from_isr(handle, item, core::ptr::null_mut()) + } + } else if front { + queue::queue_send_to_front(handle, item, OSI_FUNCS_TIME_BLOCKING) + } else { + queue::queue_send_to_back(handle, item, OSI_FUNCS_TIME_BLOCKING) + }; + + if sent == 0 { + // The queue is full. Mark the event unqueued so that the controller can post it again. + trace!("Event queue is full, event dropped"); + unsafe { + (*evt).queued = false; + } + } } #[cfg_attr(feature = "ble-host-npl", unsafe(no_mangle))] @@ -1132,13 +1152,18 @@ unsafe extern "C" fn ble_npl_eventq_get( let mut evt = core::ptr::null_mut::(); let wrapper = unwrap!(unsafe { queue.as_mut() }, "queue wrapper is null"); + let item = (&raw mut evt).cast(); - if queue::queue_receive( - wrapper.dummy as _, - (&raw mut evt).cast(), - blob_ticks_to_micros(timeout), - ) == 1 - { + let received = if in_isr() { + if timeout != 0 { + return core::ptr::null(); + } + queue::queue_try_receive_from_isr(wrapper.dummy as _, item, core::ptr::null_mut()) + } else { + queue::queue_receive(wrapper.dummy as _, item, blob_ticks_to_micros(timeout)) + }; + + if received != 0 { trace!("got {:x}", evt as usize); unsafe { let evt = (*evt).dummy as *mut Event; @@ -1159,10 +1184,10 @@ unsafe extern "C" fn ble_npl_eventq_dflt_get() -> *mut ble_npl_eventq { unsafe { if !DEFAULT_EVENTQ_INITIALIZED { - ble_npl_eventq_init(addr_of_mut!(DEFAULT_EVENTQ)); + ble_npl_eventq_init(&raw mut DEFAULT_EVENTQ); DEFAULT_EVENTQ_INITIALIZED = true; } - addr_of_mut!(DEFAULT_EVENTQ) + &raw mut DEFAULT_EVENTQ } } @@ -1215,11 +1240,11 @@ unsafe extern "C" fn ble_npl_callout_init( crate::compat::malloc::calloc_internal(1, core::mem::size_of::()) as *mut Callout; (*new_callout).eventq = eventq; - ble_npl_event_init(addr_of_mut!((*new_callout).events), func, args); + ble_npl_event_init(&raw mut (*new_callout).events, func, args); (*callout).dummy = new_callout as i32; crate::compat::timer_compat::compat_timer_setfn( - addr_of_mut!((*new_callout).timer_handle), + &raw mut (*new_callout).timer_handle, callout_timer_callback_wrapper, callout as *mut c_void, ); @@ -1235,9 +1260,9 @@ unsafe extern "C" fn callout_timer_callback_wrapper(arg: *mut c_void) { unsafe { if !(*co).eventq.is_null() { - ble_npl_eventq_put((*co).eventq.cast_mut(), addr_of!((*co).events)); + ble_npl_eventq_put((*co).eventq.cast_mut(), &raw const (*co).events); } else { - ble_npl_event_run(addr_of!((*co).events)); + ble_npl_event_run(&raw const (*co).events); } } } @@ -1286,11 +1311,109 @@ pub(crate) struct BleNplCountInfoT { mutex_count: u16, } +unsafe extern "C" { + fn r_ble_rtc_wake_up_state_clr(); + #[cfg(not(esp32c2))] + fn r_ble_lll_sleep_should_skip_light_sleep_check() -> bool; +} + +/// Returns whether the controller refuses a light sleep, because its next event is too close. +#[cfg(not(esp32c2))] +pub(super) fn controller_skips_light_sleep() -> bool { + unsafe { r_ble_lll_sleep_should_skip_light_sleep_check() } +} + +#[crate::hal::ram] +unsafe extern "C" fn controller_sleep_cb(_enable_tick: u32, _arg: *mut c_void) { + unsafe { r_ble_rtc_wake_up_state_clr() }; + super::modem_phy_release(); +} + +#[crate::hal::ram] +unsafe extern "C" fn controller_wakeup_cb(arg: *mut c_void) { + unsafe { + #[cfg(not(esp32c2))] + r_ble_rtc_wake_up_state_clr(); + + // ESP-IDF: `controller_wakeup_cb()` and `bt_wakeup_params_t` in `bt.c`. + // Bits 0..20 hold `rtc_freq`, bit 31 tells the controller that the BLE timer ended the + // light sleep. + const BT_WAKEUP: u32 = 1 << 31; + const RTC_FREQ_MASK: u32 = 0xfffff; + let params = arg.cast::(); + if !params.is_null() { + let by_bt = + esp_hal::rtc_cntl::wakeup_cause().contains(esp_hal::rtc_cntl::WakeupSource::Bt); + let mut value = params.read_volatile(); + if by_bt { + value |= BT_WAKEUP; + } else { + value &= !BT_WAKEUP; + } + if super::lp_clk::source_is_rc(esp_hal::clock::ll::ble_lp_clk_root_source) { + let freq = super::lp_clk::frequency_hz(); + value = (value & !RTC_FREQ_MASK) | (freq & RTC_FREQ_MASK); + } + params.write_volatile(value); + } + } + super::modem_phy_acquire(); +} + +fn register_modem_sleep() { + unsafe extern "C" { + #[cfg(not(esp32c2))] + fn r_ble_lll_sleep_set_sleep_cb( + sleep_cb: unsafe extern "C" fn(u32, *mut c_void), + wakeup_cb: unsafe extern "C" fn(*mut c_void), + sleep_arg: *mut c_void, + wakeup_arg: *mut c_void, + us_to_enabled: u32, + ); + #[cfg(esp32c2)] + fn r_ble_lll_rfmgmt_set_sleep_cb( + sleep_cb: unsafe extern "C" fn(u32, *mut c_void), + wakeup_cb: unsafe extern "C" fn(*mut c_void), + sleep_arg: *mut c_void, + wakeup_arg: *mut c_void, + us_to_enabled: u32, + ); + } + + // ESP-IDF PHY enable delay. C2 adds `BLE_RTC_DELAY_US` (1800) to 500. The others use the + // light-sleep delay, because the chip can light-sleep while the controller sleeps. + let delay_us = cfg_select! { + esp32c2 => 2_300, + esp32c5 => 2_500, + any(esp32c6, esp32c61) => 3_200, + esp32h2 => 5_100, + }; + + unsafe { + cfg_select! { + esp32c2 => r_ble_lll_rfmgmt_set_sleep_cb( + controller_sleep_cb, + controller_wakeup_cb, + core::ptr::null_mut(), + core::ptr::null_mut(), + delay_us, + ), + _ => r_ble_lll_sleep_set_sleep_cb( + controller_sleep_cb, + controller_wakeup_cb, + core::ptr::null_mut(), + core::ptr::null_mut(), + delay_us, + ), + } + } +} + pub(crate) fn ble_init(config: &Config) -> PhyInitGuard<'static> { + super::set_modem_sleep(config.modem_sleep()); + let phy_init_guard; unsafe { - (*addr_of_mut!(HCI_OUT_COLLECTOR)).write(HciOutCollector::new()); - // turn on logging #[allow(static_mut_refs)] #[cfg(all(feature = "print-logs-from-driver", esp32c2))] @@ -1303,9 +1426,11 @@ pub(crate) fn ble_init(config: &Config) -> PhyInitGuard<'static> { g_ble_plf_log_level = 10; } - self::ble_os_adapter_chip_specific::ble_rtc_clk_init(); + self::chip_specific::ble_rtc_clk_init(); - let cfg = ble_os_adapter_chip_specific::create_ble_config(config); + super::lp_clk::request(); + + let cfg = chip_specific::create_ble_config(config); let res = esp_register_ext_funcs(&G_OSI_FUNCS as *const ExtFuncsT); assert!(res == 0, "esp_register_ext_funcs returned {}", res); @@ -1326,13 +1451,14 @@ pub(crate) fn ble_init(config: &Config) -> PhyInitGuard<'static> { assert!(res == 0, "coex_init failed"); } - ble_os_adapter_chip_specific::bt_periph_module_enable(); + chip_specific::bt_periph_module_enable(); - ble_os_adapter_chip_specific::disable_sleep_mode(); + chip_specific::disable_sleep_mode(); - let res = esp_register_npl_funcs(core::ptr::addr_of!(G_NPL_FUNCS)); + let res = esp_register_npl_funcs(&G_NPL_FUNCS); assert!(res == 0, "esp_register_npl_funcs returned {}", res); + // not really using here ... remove it? let npl_info = BleNplCountInfoT { evt_count: 0, evtq_count: 0, @@ -1340,120 +1466,35 @@ pub(crate) fn ble_init(config: &Config) -> PhyInitGuard<'static> { sem_count: 0, mutex_count: 0, }; - #[cfg(esp32c2)] - let res = ble_get_npl_element_info( - &cfg as *const esp_bt_controller_config_t, - &npl_info as *const BleNplCountInfoT, - ); - #[cfg(not(esp32c2))] - let res = r_ble_get_npl_element_info( - &cfg as *const esp_bt_controller_config_t, - &npl_info as *const BleNplCountInfoT, - ); - assert!(res == 0, "ble_get_npl_element_info returned {}", res); - // not really using npl_info here ... remove it? + let res = cfg_select! { + esp32c2 => ble_get_npl_element_info(&cfg, &npl_info), + _ => r_ble_get_npl_element_info(&cfg, &npl_info), + }; + assert!(res == 0, "ble_get_npl_element_info returned {}", res); + // Initialize the global memory pool #[cfg(esp32c2)] - { - // Initialize the global memory pool - let ret = os_msys_buf_alloc(); - assert!(ret, "os_msys_buf_alloc failed"); - - os_msys_init(); - } + chip_specific::os_msys_init(); phy_init_guard = esp_phy::enable_phy(); - // init bb - bt_bb_v2_init_cmplx(1); + // init bb - unless the IEEE 802.15.4 driver, which shares it, already did + crate::btbb_enable(); coex_pti_v2(); #[cfg(feature = "coex")] { - let rc = ble_osi_coex_funcs_register(&G_COEX_FUNCS as *const OsiCoexFuncsT); + let rc = ble_osi_coex_funcs_register(&G_COEX_FUNCS); assert!(rc == 0, "ble_osi_coex_funcs_register returned {}", rc); } - #[cfg(not(esp32c2))] - { - unsafe extern "C" { - fn esp_ble_register_bb_funcs() -> i32; - } - let res = esp_ble_register_bb_funcs(); - assert!(res == 0, "esp_ble_register_bb_funcs returned {}", res); - } - - #[cfg(esp32c2)] - let res = ble_controller_init(&cfg as *const esp_bt_controller_config_t); - #[cfg(not(esp32c2))] - let res = r_ble_controller_init(&cfg as *const esp_bt_controller_config_t); - + let res = ble_controller_init(&cfg); assert!(res == 0, "ble_controller_init returned {}", res); - #[cfg(not(esp32c2))] - { - unsafe extern "C" { - fn r_esp_ble_msys_init( - msys_size1: u16, - msys_size2: u16, - msys_cnt1: u16, - msys_cnt2: u16, - from_heap: u8, - ) -> i32; - - fn base_stack_initEnv() -> i32; - fn conn_stack_initEnv() -> i32; - fn adv_stack_initEnv() -> i32; - fn extAdv_stack_initEnv() -> i32; - fn sync_stack_initEnv() -> i32; - - fn base_stack_enable() -> i32; - fn adv_stack_enable() -> i32; - fn extAdv_stack_enable() -> i32; - fn scan_stack_enable() -> i32; - fn sync_stack_enable() -> i32; - } - - let res = base_stack_initEnv(); - assert!(res == 0, "base_stack_initEnv returned {}", res); - - let res = adv_stack_initEnv(); - assert!(res == 0, "adv_stack_initEnv returned {}", res); - - let res = extAdv_stack_initEnv(); - assert!(res == 0, "extAdv_stack_initEnv returned {}", res); - - #[cfg(not(esp32c2))] - { - let res = scan_stack_initEnv(); - assert!(res == 0, "scan_stack_initEnv returned {}", res); - } - - let res = conn_stack_initEnv(); - assert!(res == 0, "conn_stack_initEnv returned {}", res); - - let res = sync_stack_initEnv(); - assert!(res == 0, "sync_stack_initEnv returned {}", res); - - let res = r_esp_ble_msys_init(256, 320, 12, 24, 1); - assert!(res == 0, "esp_ble_msys_init returned {}", res); - - let res = base_stack_enable(); - assert!(res == 0, "base_stack_enable returned {}", res); - - let res = adv_stack_enable(); - assert!(res == 0, "adv_stack_enable returned {}", res); - - let res = extAdv_stack_enable(); - assert!(res == 0, "extAdv_stack_enable returned {}", res); - - let res = scan_stack_enable(); - assert!(res == 0, "scan_stack_enable returned {}", res); - - let res = sync_stack_enable(); - assert!(res == 0, "sync_stack_enable returned {}", res); + if config.modem_sleep() { + register_modem_sleep(); } #[cfg(feature = "coex")] @@ -1463,14 +1504,11 @@ pub(crate) fn ble_init(config: &Config) -> PhyInitGuard<'static> { crate::common_adapter::read_mac(mac.as_mut_ptr(), 2); mac.reverse(); - #[cfg(esp32c2)] - esp_ble_ll_set_public_addr(&mac as *const u8); - #[cfg(not(esp32c2))] - r_esp_ble_ll_set_public_addr(&mac as *const u8); + cfg_select! { + esp32c2 => esp_ble_ll_set_public_addr(mac.as_ptr()), + _ => r_esp_ble_ll_set_public_addr(mac.as_ptr()), + }; - unsafe extern "C" { - fn r_ble_hci_trans_init(m: u8); - } r_ble_hci_trans_init(0); r_ble_hci_trans_cfg_hs( @@ -1480,13 +1518,18 @@ pub(crate) fn ble_init(config: &Config) -> PhyInitGuard<'static> { core::ptr::null(), ); - #[cfg(esp32c2)] - let res = ble_controller_enable(1); // 1 = BLE - #[cfg(not(esp32c2))] - let res = r_ble_controller_enable(1); // 1 = BLE + const BLE: u8 = 1; + let res = cfg_select! { + esp32c2 => ble_controller_enable(BLE), + _ => r_ble_controller_enable(BLE), + }; assert!(res == 0, "ble_controller_enable returned {}", res); } + if config.modem_sleep() { + super::lp_clk::claim_wake_source(); + } + // At some point the "High-speed ADC" entropy source became available. #[cfg(rng_trng_supported)] unsafe { @@ -1498,156 +1541,37 @@ pub(crate) fn ble_init(config: &Config) -> PhyInitGuard<'static> { } pub(crate) fn ble_deinit() { + super::lp_clk::release_wake_source(); + super::modem_phy_acquire(); + super::set_modem_sleep(false); + #[cfg(rng_trng_supported)] esp_hal::rng::TrngSource::decrease_entropy_source_counter(unsafe { esp_hal::Internal::conjure() }); - #[cfg(not(esp32c2))] - unsafe extern "C" { - fn base_stack_deinitEnv() -> i32; - fn conn_stack_deinitEnv() -> i32; - fn adv_stack_deinitEnv() -> i32; - fn extAdv_stack_deinitEnv() -> i32; - fn sync_stack_deinitEnv() -> i32; - - fn base_stack_disable() -> i32; - fn adv_stack_disable() -> i32; - fn extAdv_stack_disable() -> i32; - fn scan_stack_disable() -> i32; - fn sync_stack_disable() -> i32; - } - - #[cfg(esp32c2)] - unsafe extern "C" { - fn ble_controller_disable(); - } - unsafe { // HCI deinit - npl::r_ble_hci_trans_cfg_hs(None, core::ptr::null(), None, core::ptr::null()); - - #[cfg(not(esp32c2))] - { - npl::r_ble_controller_disable(); - sync_stack_disable(); - scan_stack_disable(); - extAdv_stack_disable(); - adv_stack_disable(); - base_stack_disable(); - conn_stack_deinitEnv(); - sync_stack_deinitEnv(); - scan_stack_deinitEnv(); - extAdv_stack_deinitEnv(); - adv_stack_deinitEnv(); - base_stack_deinitEnv(); - } + r_ble_hci_trans_cfg_hs(None, core::ptr::null(), None, core::ptr::null()); - #[cfg(esp32c2)] - { - ble_controller_disable(); - } - - #[cfg(not(esp32c2))] - let res = npl::r_ble_controller_deinit(); - - #[cfg(esp32c2)] - let res = npl::ble_controller_deinit(); + cfg_select! { + esp32c2 => ble_controller_disable(), + _ => r_ble_controller_disable(), + }; + let res = ble_controller_deinit(); assert!(res == 0, "ble_controller_deinit returned {}", res); #[cfg(esp32c2)] - os_msys_buf_free(); + chip_specific::os_msys_buf_free(); - npl::esp_unregister_npl_funcs(); - - npl::esp_unregister_ext_funcs(); + esp_unregister_npl_funcs(); + esp_unregister_ext_funcs(); } -} -// -#[cfg(esp32c2)] -fn os_msys_buf_alloc() -> bool { - unsafe { - OS_MSYS_INIT_1_DATA = crate::compat::malloc::calloc_internal( - 1, - core::mem::size_of::() * SYSINIT_MSYS_1_MEMPOOL_SIZE, - ) as *mut u32; - OS_MSYS_INIT_2_DATA = crate::compat::malloc::calloc_internal( - 1, - core::mem::size_of::() * SYSINIT_MSYS_2_MEMPOOL_SIZE, - ) as *mut u32; - - if OS_MSYS_INIT_1_DATA.is_null() || OS_MSYS_INIT_2_DATA.is_null() { - os_msys_buf_free(); - return false; - } + crate::btbb_disable(); - true - } -} - -// -#[cfg(esp32c2)] -fn os_msys_buf_free() { - unsafe { - // No C2 ROM revision exposes `os_mempool_unregister`, so drop every registered pool before - // releasing the memory it points at. - r_os_msys_reset(); - - if !OS_MSYS_INIT_1_DATA.is_null() { - crate::compat::malloc::free(OS_MSYS_INIT_1_DATA.cast()); - OS_MSYS_INIT_1_DATA = core::ptr::null_mut(); - } - if !OS_MSYS_INIT_2_DATA.is_null() { - crate::compat::malloc::free(OS_MSYS_INIT_2_DATA.cast()); - OS_MSYS_INIT_2_DATA = core::ptr::null_mut(); - } - } -} - -#[cfg(esp32c2)] -fn os_msys_init() { - static MSYS1: &[u8] = b"msys_1\0"; - static MSYS2: &[u8] = b"msys_2\0"; - - unsafe { - r_os_msys_reset(); - - let rc = r_mem_init_mbuf_pool( - OS_MSYS_INIT_1_DATA as *const c_void, - addr_of!(OS_MSYS_INIT_1_MEMPOOL), - addr_of!(OS_MSYS_INIT_1_MBUF_POOL), - OS_MSYS_1_BLOCK_COUNT, - SYSINIT_MSYS_1_MEMBLOCK_SIZE, - MSYS1 as *const _ as *const u8, - ); - if rc != 0 { - panic!("r_mem_init_mbuf_pool failed"); - } - - let rc = r_os_msys_register(addr_of!(OS_MSYS_INIT_1_MBUF_POOL)); - if rc != 0 { - panic!("r_os_msys_register failed"); - } - - let rc = r_mem_init_mbuf_pool( - OS_MSYS_INIT_2_DATA as *const c_void, - addr_of!(OS_MSYS_INIT_2_MEMPOOL), - addr_of!(OS_MSYS_INIT_2_MBUF_POOL), - OS_MSYS_2_BLOCK_COUNT, - SYSINIT_MSYS_2_MEMBLOCK_SIZE, - MSYS2 as *const _ as *const u8, - ); - if rc != 0 { - panic!("r_mem_init_mbuf_pool failed"); - } - - let rc = r_os_msys_register(addr_of!(OS_MSYS_INIT_2_MBUF_POOL)); - if rc != 0 { - panic!("r_os_msys_register failed"); - } - } + super::lp_clk::release(); } unsafe extern "C" fn ble_hs_hci_rx_evt(cmd: *const u8, arg: *const c_void) -> i32 { @@ -1660,19 +1584,18 @@ unsafe extern "C" fn ble_hs_hci_rx_evt(cmd: *const u8, arg: *const c_void) -> i3 let payload = unsafe { core::slice::from_raw_parts(cmd.offset(2), len) }; trace!("$ pld = {:?}", payload); - super::BT_STATE.with(|state| { - let mut data = [0u8; 256]; + let mut data = Vec::with_capacity(len + 3); + data.push(0x04); // this is an event + data.push(event); + data.push(len as u8); + data.extend_from_slice(payload); - data[0] = 0x04; // this is an event - data[1] = event; - data[2] = len as u8; - data[3..][..len].copy_from_slice(payload); + super::dump_packet_info(&data); + super::BT_STATE.with(|state| { state.rx_queue.push_back(ReceivedPacket { - data: Box::from(&data[..len + 3]), + data: data.into_boxed_slice(), }); - - dump_packet_info(&data[..(len + 3)]); }); unsafe { @@ -1691,17 +1614,16 @@ unsafe extern "C" fn ble_hs_rx_data(om: *const OsMbuf, arg: *const c_void) -> i3 let len = unsafe { (*om).om_len }; let data_slice = unsafe { core::slice::from_raw_parts(data_ptr, len as usize) }; - super::BT_STATE.with(|state| { - let mut data = [0u8; 256]; + let mut data = Vec::with_capacity(data_slice.len() + 1); + data.push(0x02); // ACL + data.extend_from_slice(data_slice); - data[0] = 0x02; // ACL - data[1..][..data_slice.len()].copy_from_slice(data_slice); + super::dump_packet_info(&data); + super::BT_STATE.with(|state| { state.rx_queue.push_back(ReceivedPacket { - data: Box::from(&data[..data_slice.len() + 1]), + data: data.into_boxed_slice(), }); - - super::dump_packet_info(&data[..(len + 1) as usize]); }); unsafe { @@ -1713,64 +1635,66 @@ unsafe extern "C" fn ble_hs_rx_data(om: *const OsMbuf, arg: *const c_void) -> i3 0 } -/// Sends HCI data to the Bluetooth controller. -#[instability::unstable] +pub(crate) fn send(data: &[u8]) { + send_packet(data) +} + +/// Sends an HCI packet (H4 indicator byte first) to the controller. +/// +/// Used by the external NPL based host (e.g. `esp-nimble-host`) to forward its HCI traffic. +/// +/// Fork-only: upstream keeps HCI sending crate-private (`send`); esp-nimble-host needs it public. +#[cfg(feature = "ble-host-npl")] pub fn send_hci(data: &[u8]) { - let hci_out = unsafe { (*addr_of_mut!(HCI_OUT_COLLECTOR)).assume_init_mut() }; - hci_out.push(data); + send_packet(data) +} - if hci_out.is_ready() { - let packet = hci_out.packet(); +pub(crate) async fn send_async(data: &[u8]) { + send_packet(data) +} - unsafe { - const DATA_TYPE_COMMAND: u8 = 1; - const DATA_TYPE_ACL: u8 = 2; - - dump_packet_info(packet); - - super::BT_STATE.with(|_state| { - if packet[0] == DATA_TYPE_COMMAND { - let cmd = r_ble_hci_trans_buf_alloc(BLE_HCI_TRANS_BUF_CMD) as *mut u8; - - if cmd.is_null() { - error!("Unable to get HCI transport buffer"); - return; - } - - let cmd = core::slice::from_raw_parts_mut(cmd, packet.len() - 1); - - cmd.copy_from_slice(&packet[1..]); - - let res = r_ble_hci_trans_hs_cmd_tx(cmd.as_ptr()); - - if res != 0 { - warn!("ble_hci_trans_hs_cmd_tx res == {}", res); - } - } else if packet[0] == DATA_TYPE_ACL { - let om = r_os_msys_get_pkthdr( - packet.len() as u16, - ACL_DATA_MBUF_LEADINGSPACE as u16, - ); - - let res = - r_os_mbuf_append(om, packet.as_ptr().offset(1), (packet.len() - 1) as u16); - if res != 0 { - panic!("r_os_mbuf_append returned {}", res); - } - - // this modification of the ACL data packet makes it getting sent and - // received by the other side - *((*om).om_data as *mut u8).offset(1) = 0; - - let res = r_ble_hci_trans_hs_acl_tx(om); - if res != 0 { - panic!("ble_hci_trans_hs_acl_tx returned {}", res); - } - trace!("ACL tx done"); - } - }); - } +fn send_packet(packet: &[u8]) { + const DATA_TYPE_COMMAND: u8 = 1; + const DATA_TYPE_ACL: u8 = 2; - hci_out.reset(); + super::dump_packet_info(packet); + + unsafe { + if packet[0] == DATA_TYPE_COMMAND { + let cmd = r_ble_hci_trans_buf_alloc(BLE_HCI_TRANS_BUF_CMD) as *mut u8; + + if cmd.is_null() { + error!("Unable to get HCI transport buffer"); + return; + } + + // don't send the TYPE + let cmd = core::slice::from_raw_parts_mut(cmd, packet.len() - 1); + + cmd.copy_from_slice(&packet[1..]); + + let res = r_ble_hci_trans_hs_cmd_tx(cmd.as_ptr()); + + if res != 0 { + warn!("ble_hci_trans_hs_cmd_tx res == {}", res); + } + } else if packet[0] == DATA_TYPE_ACL { + let om = r_os_msys_get_pkthdr(packet.len() as u16, ACL_DATA_MBUF_LEADINGSPACE as u16); + + let res = r_os_mbuf_append(om, packet.as_ptr().offset(1), (packet.len() - 1) as u16); + assert!(res == 0, "r_os_mbuf_append returned {}", res); + + // this modification of the ACL data packet makes it getting sent and + // received by the other side + *((*om).om_data as *mut u8).offset(1) = 0; + + let res = r_ble_hci_trans_hs_acl_tx(om); + if res != 0 { + panic!("ble_hci_trans_hs_acl_tx returned {}", res); + } + trace!("ACL tx done"); + } else { + warn!("Unknown packet kind {} dropped", packet[0]); + } } } diff --git a/esp-radio/src/ble/os_adapter_esp32c2.rs b/esp-radio/src/ble/npl/os_adapter_esp32c2.rs similarity index 71% rename from esp-radio/src/ble/os_adapter_esp32c2.rs rename to esp-radio/src/ble/npl/os_adapter_esp32c2.rs index cec01cb141e..2e0178b7a04 100644 --- a/esp-radio/src/ble/os_adapter_esp32c2.rs +++ b/esp-radio/src/ble/npl/os_adapter_esp32c2.rs @@ -2,7 +2,7 @@ use procmacros::BuilderLite; use super::*; use crate::{ - ble::InvalidConfigError, + ble::{InvalidConfigError, lp_clk}, hal::{interrupt, peripherals::BT}, interrupt_dispatch::Handler, sys::include::esp_bt_controller_config_t, @@ -99,6 +99,13 @@ impl TxPower { #[derive(BuilderLite, Clone, Copy, Eq, PartialEq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub struct Config { + /// Enables controller modem sleep. + /// + /// The low-power clock source comes from the clock tree (`BLE_LP_CLK`). + /// While the controller sleeps, the chip can also enter automatic light + /// sleep. Set this before the controller starts. The default is off. + modem_sleep: bool, + /// The priority of the RTOS task. task_priority: u8, @@ -212,6 +219,7 @@ pub struct Config { impl Default for Config { fn default() -> Self { Self { + modem_sleep: false, task_priority: crate::preempt::max_task_priority() .saturating_sub(2) .min(255) as u8, @@ -270,7 +278,7 @@ impl Config { pub(crate) fn create_ble_config(config: &Config) -> esp_bt_controller_config_t { let main_xtal_freq = esp_hal::clock::xtal_clock().as_mhz() as u8; - let rtc_freq = if main_xtal_freq == 26 { 40000 } else { 32000 }; + let rtc_freq = u64::from(lp_clk::frequency_hz()); // keep them aligned with BT_CONTROLLER_INIT_CONFIG_DEFAULT in ESP-IDF // ideally _some_ of these values should be configurable @@ -285,7 +293,12 @@ pub(crate) fn create_ble_config(config: &Config) -> esp_bt_controller_config_t { ble_ll_adv_dup_list_count: config.ll_adv_dup_list_count, ble_ll_tx_pwr_dbm: config.default_tx_power.dbm() as u8, rtc_freq, - ble_ll_sca: CONFIG_BT_LE_LL_SCA as _, + // ESP-IDF: `ble_rtc_clk_init()` in `bt.c`. + ble_ll_sca: if lp_clk::source_is_rc(esp_hal::clock::ll::ble_lp_clk_root_source) { + lp_clk::RC_SCA_PPM as _ + } else { + CONFIG_BT_LE_LL_SCA as _ + }, ble_ll_scan_phy_number: if CONFIG_BT_LE_LL_CFG_FEAT_LE_CODED_PHY != 0 { 2 } else { @@ -320,7 +333,7 @@ pub(crate) fn create_ble_config(config: &Config) -> esp_bt_controller_config_t { ble_hci_uart_uart_parity: 0, enable_tx_cca: config.cca as u8, cca_rssi_thresh: (256 - config.cca_threshold as u32) as u8, - sleep_en: 0, // CONFIG_BT_LE_SLEEP_ENABLE unset + sleep_en: u8::from(config.modem_sleep), coex_phy_coded_tx_rx_time_limit: CONFIG_BT_LE_COEX_PHY_CODED_TX_RX_TLIM_EFF as _, dis_scan_backoff: config.dis_scan_backoff as u8, ble_scan_classify_filter_enable: 0, @@ -384,12 +397,11 @@ pub(super) unsafe extern "C" fn esp_reset_rpa_moudle() { crate::radio_clocks::clocks_ll::reset_rpa(); } -// Provide the symbol for < eco4 to make the linker happy +// The controller library reads and writes this variable. The ROM of ESP32-C2 < eco4 does not +// supply it. #[unsafe(no_mangle)] -unsafe fn g_ble_lll_rfmgmt_env_p() -> *mut c_void { - // prevent "undefined symbol: g_ble_lll_rfmgmt_env_p" for ESP32-C2 < eco4 - unreachable!() -} +#[allow(non_upper_case_globals)] +static mut g_ble_lll_rfmgmt_env_p: *mut c_void = core::ptr::null_mut(); pub(crate) fn shutdown_ble_isr() { unsafe { @@ -409,3 +421,138 @@ extern "C" fn LP_TIMER() { extern "C" fn BT_MAC() { ISR_INTERRUPT_4.dispatch(); } + +const OS_MSYS_1_BLOCK_COUNT: i32 = 24; +const SYSINIT_MSYS_1_MEMPOOL_SIZE: usize = 768; +const SYSINIT_MSYS_1_MEMBLOCK_SIZE: i32 = 128; +const OS_MSYS_2_BLOCK_COUNT: i32 = 24; +const SYSINIT_MSYS_2_MEMPOOL_SIZE: usize = 1920; +const SYSINIT_MSYS_2_MEMBLOCK_SIZE: i32 = 320; + +impl OsMempool { + const fn zeroed() -> Self { + Self { + mp_block_size: 0, + mp_num_blocks: 0, + mp_num_free: 0, + mp_min_free: 0, + mp_flags: 0, + mp_membuf_addr: 0, + next: core::ptr::null(), + first: core::ptr::null(), + name: core::ptr::null(), + } + } +} + +unsafe extern "C" { + fn r_mem_init_mbuf_pool( + mem: *mut c_void, + mempool: *mut OsMempool, + mbuf_pool: *mut OsMbufPool, + num_blocks: i32, + block_size: i32, + name: *const u8, + ) -> i32; + fn r_os_msys_reset(); + fn r_os_msys_register(mbuf_pool: *const OsMbufPool) -> i32; +} + +impl OsMbufPool { + const fn zeroed() -> Self { + Self { + omp_databuf_len: 0, + omp_pool: core::ptr::null(), + next: core::ptr::null(), + } + } +} + +type OsMembufT = u32; + +pub(crate) static mut OS_MSYS_INIT_1_DATA: *mut OsMembufT = core::ptr::null_mut(); +pub(crate) static mut OS_MSYS_INIT_1_MBUF_POOL: OsMbufPool = OsMbufPool::zeroed(); +pub(crate) static mut OS_MSYS_INIT_1_MEMPOOL: OsMempool = OsMempool::zeroed(); + +pub(crate) static mut OS_MSYS_INIT_2_DATA: *mut OsMembufT = core::ptr::null_mut(); +pub(crate) static mut OS_MSYS_INIT_2_MBUF_POOL: OsMbufPool = OsMbufPool::zeroed(); +pub(crate) static mut OS_MSYS_INIT_2_MEMPOOL: OsMempool = OsMempool::zeroed(); + +// +fn os_msys_buf_alloc() -> bool { + use core::mem::size_of; + + use crate::compat::malloc::calloc_internal; + + unsafe { + OS_MSYS_INIT_1_DATA = + calloc_internal(SYSINIT_MSYS_1_MEMPOOL_SIZE as u32, size_of::()).cast(); + OS_MSYS_INIT_2_DATA = + calloc_internal(SYSINIT_MSYS_2_MEMPOOL_SIZE as u32, size_of::()).cast(); + + if OS_MSYS_INIT_1_DATA.is_null() || OS_MSYS_INIT_2_DATA.is_null() { + os_msys_buf_free(); + return false; + } + + true + } +} + +// +pub(super) fn os_msys_buf_free() { + use crate::compat::malloc::free; + + unsafe { + // No C2 ROM revision exposes `os_mempool_unregister`, so drop every registered pool before + // releasing the memory it points at. + r_os_msys_reset(); + + if !OS_MSYS_INIT_1_DATA.is_null() { + free(OS_MSYS_INIT_1_DATA.cast()); + OS_MSYS_INIT_1_DATA = core::ptr::null_mut(); + } + if !OS_MSYS_INIT_2_DATA.is_null() { + free(OS_MSYS_INIT_2_DATA.cast()); + OS_MSYS_INIT_2_DATA = core::ptr::null_mut(); + } + } +} + +pub(super) fn os_msys_init() { + static MSYS1: &[u8] = b"msys_1\0"; + static MSYS2: &[u8] = b"msys_2\0"; + + unsafe { + let ret = os_msys_buf_alloc(); + assert!(ret, "os_msys_buf_alloc failed"); + + r_os_msys_reset(); + + let rc = r_mem_init_mbuf_pool( + OS_MSYS_INIT_1_DATA.cast(), + &raw mut OS_MSYS_INIT_1_MEMPOOL, + &raw mut OS_MSYS_INIT_1_MBUF_POOL, + OS_MSYS_1_BLOCK_COUNT, + SYSINIT_MSYS_1_MEMBLOCK_SIZE, + MSYS1.as_ptr(), + ); + assert!(rc == 0, "r_mem_init_mbuf_pool failed"); + + let rc = r_os_msys_register(&raw const OS_MSYS_INIT_1_MBUF_POOL); + assert!(rc == 0, "r_os_msys_register failed"); + + let rc = r_mem_init_mbuf_pool( + OS_MSYS_INIT_2_DATA.cast(), + &raw mut OS_MSYS_INIT_2_MEMPOOL, + &raw mut OS_MSYS_INIT_2_MBUF_POOL, + OS_MSYS_2_BLOCK_COUNT, + SYSINIT_MSYS_2_MEMBLOCK_SIZE, + MSYS2.as_ptr(), + ); + assert!(rc == 0, "r_mem_init_mbuf_pool failed"); + + let rc = r_os_msys_register(&raw const OS_MSYS_INIT_2_MBUF_POOL); + assert!(rc == 0, "r_os_msys_register failed"); + } +} diff --git a/esp-radio/src/ble/os_adapter_esp32c5.rs b/esp-radio/src/ble/npl/os_adapter_esp32c5.rs similarity index 93% rename from esp-radio/src/ble/os_adapter_esp32c5.rs rename to esp-radio/src/ble/npl/os_adapter_esp32c5.rs index 6961006348d..ec5ba3ee827 100644 --- a/esp-radio/src/ble/os_adapter_esp32c5.rs +++ b/esp-radio/src/ble/npl/os_adapter_esp32c5.rs @@ -2,7 +2,7 @@ use procmacros::BuilderLite; use super::*; use crate::{ - ble::InvalidConfigError, + ble::{InvalidConfigError, lp_clk}, hal::{interrupt, peripherals::BT}, interrupt_dispatch::Handler, sys::include::esp_bt_controller_config_t, @@ -87,6 +87,13 @@ impl TxPower { #[derive(BuilderLite, Clone, Copy, Eq, PartialEq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub struct Config { + /// Enables controller modem sleep. + /// + /// The low-power clock source comes from the clock tree (`BLE_LP_CLK`). + /// While the controller sleeps, the chip can also enter automatic light + /// sleep. Set this before the controller starts. The default is off. + modem_sleep: bool, + /// The priority of the RTOS task. task_priority: u8, @@ -206,6 +213,7 @@ pub struct Config { impl Default for Config { fn default() -> Self { Self { + modem_sleep: false, task_priority: crate::preempt::max_task_priority() .saturating_sub(2) .min(255) as u8, @@ -276,8 +284,13 @@ pub(crate) fn create_ble_config(config: &Config) -> esp_bt_controller_config_t { ble_ll_rsp_dup_list_count: config.ll_rsp_dup_list_count, ble_ll_adv_dup_list_count: config.ll_adv_dup_list_count, ble_ll_tx_pwr_dbm: config.default_tx_power.dbm() as u8, - rtc_freq: 32768, - ble_ll_sca: 60, + rtc_freq: u64::from(lp_clk::frequency_hz()), + // ESP-IDF: `ble_rtc_clk_init()` in `bt.c`. + ble_ll_sca: if lp_clk::source_is_rc(esp_hal::clock::ll::ble_lp_clk_root_source) { + lp_clk::RC_SCA_PPM + } else { + 60 + }, ble_ll_scan_phy_number: 2, ble_ll_conn_def_auth_pyld_tmo: 3000, ble_ll_jitter_usecs: 16, @@ -301,7 +314,7 @@ pub(crate) fn create_ble_config(config: &Config) -> esp_bt_controller_config_t { enable_bqb_test: config.bqb_test as u8, enable_tx_cca: config.cca as u8, cca_rssi_thresh: (256 - config.cca_threshold as u32) as u8, - sleep_en: 0, + sleep_en: u8::from(config.modem_sleep), coex_phy_coded_tx_rx_time_limit: 0, dis_scan_backoff: config.dis_scan_backoff as u8, ble_scan_classify_filter_enable: 1, @@ -332,12 +345,15 @@ pub(crate) fn create_ble_config(config: &Config) -> esp_bt_controller_config_t { slv_fst_rx_lat_en: 0, dl_itvl_phy_sync_en: 0, scan_allow_adi_filter: 0, + // BT_CONTROLLER_INIT_CONFIG_DEFAULT: both stay 0 unless ADV_FAST_TX is set. + enhanced_mem_resv: 0, + rxbuf_reserved: 0, config_magic: CONFIG_MAGIC, } } pub(crate) fn bt_periph_module_enable() { - crate::radio_clocks::clocks_ll::enable_bt(true); + crate::radio_clocks::enable_bt(true); } pub(crate) fn disable_sleep_mode() { diff --git a/esp-radio/src/ble/os_adapter_esp32c6.rs b/esp-radio/src/ble/npl/os_adapter_esp32c6.rs similarity index 88% rename from esp-radio/src/ble/os_adapter_esp32c6.rs rename to esp-radio/src/ble/npl/os_adapter_esp32c6.rs index 855134a83d7..fdcaf54cb82 100644 --- a/esp-radio/src/ble/os_adapter_esp32c6.rs +++ b/esp-radio/src/ble/npl/os_adapter_esp32c6.rs @@ -2,7 +2,7 @@ use procmacros::BuilderLite; use super::*; use crate::{ - ble::InvalidConfigError, + ble::{InvalidConfigError, lp_clk}, hal::{interrupt, peripherals::BT}, interrupt_dispatch::Handler, sys::include::esp_bt_controller_config_t, @@ -87,6 +87,13 @@ impl TxPower { #[derive(BuilderLite, Clone, Copy, Eq, PartialEq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub struct Config { + /// Enables controller modem sleep. + /// + /// The low-power clock source comes from the clock tree (`BLE_LP_CLK`). + /// While the controller sleeps, the chip can also enter automatic light + /// sleep. Set this before the controller starts. The default is off. + modem_sleep: bool, + /// The priority of the RTOS task. task_priority: u8, @@ -206,6 +213,7 @@ pub struct Config { impl Default for Config { fn default() -> Self { Self { + modem_sleep: false, task_priority: crate::preempt::max_task_priority() .saturating_sub(2) .min(255) as u8, @@ -276,8 +284,13 @@ pub(crate) fn create_ble_config(config: &Config) -> esp_bt_controller_config_t { ble_ll_rsp_dup_list_count: config.ll_rsp_dup_list_count, ble_ll_adv_dup_list_count: config.ll_adv_dup_list_count, ble_ll_tx_pwr_dbm: config.default_tx_power.dbm() as u8, - rtc_freq: 32000, - ble_ll_sca: 60, + rtc_freq: u64::from(lp_clk::frequency_hz()), + // ESP-IDF: `ble_rtc_clk_init()` in `bt.c`. + ble_ll_sca: if lp_clk::source_is_rc(esp_hal::clock::ll::ble_lp_clk_root_source) { + lp_clk::RC_SCA_PPM + } else { + 60 + }, ble_ll_scan_phy_number: 2, ble_ll_conn_def_auth_pyld_tmo: 3000, ble_ll_jitter_usecs: 16, @@ -301,7 +314,7 @@ pub(crate) fn create_ble_config(config: &Config) -> esp_bt_controller_config_t { enable_bqb_test: config.bqb_test as u8, enable_tx_cca: config.cca as u8, cca_rssi_thresh: (256 - config.cca_threshold as u32) as u8, - sleep_en: 0, + sleep_en: u8::from(config.modem_sleep), coex_phy_coded_tx_rx_time_limit: 0, dis_scan_backoff: config.dis_scan_backoff as u8, ble_scan_classify_filter_enable: 1, @@ -333,12 +346,15 @@ pub(crate) fn create_ble_config(config: &Config) -> esp_bt_controller_config_t { slv_fst_rx_lat_en: 0, dl_itvl_phy_sync_en: 0, scan_allow_adi_filter: 0, + // BT_CONTROLLER_INIT_CONFIG_DEFAULT: both stay 0 unless ADV_FAST_TX is set. + enhanced_mem_resv: 0, + rxbuf_reserved: 0, config_magic: CONFIG_MAGIC, } } pub(crate) fn bt_periph_module_enable() { - crate::radio_clocks::clocks_ll::enable_bt(true); + crate::radio_clocks::enable_bt(true); } pub(crate) fn disable_sleep_mode() { @@ -365,6 +381,15 @@ pub(super) unsafe extern "C" fn esp_intr_alloc( 7 => unsafe { ISR_INTERRUPT_7.set(handler, arg); BT::steal().enable_lp_timer_interrupt(interrupt::Priority::Priority1); + // `r_hal_timer_init` pulses `TASKS_STOP`, `TASKS_CLEAR`, and `TASKS_START` on the BLE + // RTC timer back-to-back before allocating this interrupt, and + // `r_ble_controller_enable` pulses `TASKS_START` again + // (`r_hal_timer_task_start`) right after `r_hal_timer_init` returns. Wait + // for `TASKS_STOP` / `TASKS_CLEAR` to cross into the `BLE_LP_CLK` domain + // before `r_hal_timer_task_start` runs, otherwise `TASKS_STOP` overrides both + // `TASKS_START` strobes and the timer stays stopped at 0. + let cycle_us = 1_000_000u32.div_ceil(lp_clk::frequency_hz()); + esp_hal::rom::ets_delay_us(cycle_us * 2); }, _ => panic!("Unexpected interrupt source {}", source), } diff --git a/esp-radio/src/ble/os_adapter_esp32c61.rs b/esp-radio/src/ble/npl/os_adapter_esp32c61.rs similarity index 93% rename from esp-radio/src/ble/os_adapter_esp32c61.rs rename to esp-radio/src/ble/npl/os_adapter_esp32c61.rs index 6961006348d..7178921a3cd 100644 --- a/esp-radio/src/ble/os_adapter_esp32c61.rs +++ b/esp-radio/src/ble/npl/os_adapter_esp32c61.rs @@ -2,7 +2,7 @@ use procmacros::BuilderLite; use super::*; use crate::{ - ble::InvalidConfigError, + ble::{InvalidConfigError, lp_clk}, hal::{interrupt, peripherals::BT}, interrupt_dispatch::Handler, sys::include::esp_bt_controller_config_t, @@ -87,6 +87,13 @@ impl TxPower { #[derive(BuilderLite, Clone, Copy, Eq, PartialEq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub struct Config { + /// Enables controller modem sleep. + /// + /// The low-power clock source comes from the clock tree (`BLE_LP_CLK`). + /// While the controller sleeps, the chip can also enter automatic light + /// sleep. Set this before the controller starts. The default is off. + modem_sleep: bool, + /// The priority of the RTOS task. task_priority: u8, @@ -206,6 +213,7 @@ pub struct Config { impl Default for Config { fn default() -> Self { Self { + modem_sleep: false, task_priority: crate::preempt::max_task_priority() .saturating_sub(2) .min(255) as u8, @@ -276,8 +284,13 @@ pub(crate) fn create_ble_config(config: &Config) -> esp_bt_controller_config_t { ble_ll_rsp_dup_list_count: config.ll_rsp_dup_list_count, ble_ll_adv_dup_list_count: config.ll_adv_dup_list_count, ble_ll_tx_pwr_dbm: config.default_tx_power.dbm() as u8, - rtc_freq: 32768, - ble_ll_sca: 60, + rtc_freq: u64::from(lp_clk::frequency_hz()), + // ESP-IDF: `ble_rtc_clk_init()` in `bt.c`. + ble_ll_sca: if lp_clk::source_is_rc(esp_hal::clock::ll::ble_lp_clk_root_source) { + lp_clk::RC_SCA_PPM + } else { + 60 + }, ble_ll_scan_phy_number: 2, ble_ll_conn_def_auth_pyld_tmo: 3000, ble_ll_jitter_usecs: 16, @@ -301,7 +314,7 @@ pub(crate) fn create_ble_config(config: &Config) -> esp_bt_controller_config_t { enable_bqb_test: config.bqb_test as u8, enable_tx_cca: config.cca as u8, cca_rssi_thresh: (256 - config.cca_threshold as u32) as u8, - sleep_en: 0, + sleep_en: u8::from(config.modem_sleep), coex_phy_coded_tx_rx_time_limit: 0, dis_scan_backoff: config.dis_scan_backoff as u8, ble_scan_classify_filter_enable: 1, @@ -332,6 +345,9 @@ pub(crate) fn create_ble_config(config: &Config) -> esp_bt_controller_config_t { slv_fst_rx_lat_en: 0, dl_itvl_phy_sync_en: 0, scan_allow_adi_filter: 0, + // BT_CONTROLLER_INIT_CONFIG_DEFAULT: both stay 0 unless ADV_FAST_TX is set. + enhanced_mem_resv: 0, + rxbuf_reserved: 0, config_magic: CONFIG_MAGIC, } } diff --git a/esp-radio/src/ble/os_adapter_esp32h2.rs b/esp-radio/src/ble/npl/os_adapter_esp32h2.rs similarity index 93% rename from esp-radio/src/ble/os_adapter_esp32h2.rs rename to esp-radio/src/ble/npl/os_adapter_esp32h2.rs index 24541819629..7dbb26414d6 100644 --- a/esp-radio/src/ble/os_adapter_esp32h2.rs +++ b/esp-radio/src/ble/npl/os_adapter_esp32h2.rs @@ -2,7 +2,7 @@ use procmacros::BuilderLite; use super::*; use crate::{ - ble::InvalidConfigError, + ble::{InvalidConfigError, lp_clk}, hal::{interrupt, peripherals::BT}, interrupt_dispatch::Handler, sys::include::esp_bt_controller_config_t, @@ -99,6 +99,13 @@ impl TxPower { #[derive(BuilderLite, Clone, Copy, Eq, PartialEq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub struct Config { + /// Enables controller modem sleep. + /// + /// The low-power clock source comes from the clock tree (`BLE_LP_CLK`). + /// While the controller sleeps, the chip can also enter automatic light + /// sleep. Set this before the controller starts. The default is off. + modem_sleep: bool, + /// The priority of the RTOS task. task_priority: u8, @@ -218,6 +225,7 @@ pub struct Config { impl Default for Config { fn default() -> Self { Self { + modem_sleep: false, task_priority: crate::preempt::max_task_priority() .saturating_sub(2) .min(255) as u8, @@ -286,8 +294,13 @@ pub(crate) fn create_ble_config(config: &Config) -> esp_bt_controller_config_t { ble_ll_rsp_dup_list_count: config.ll_rsp_dup_list_count, ble_ll_adv_dup_list_count: config.ll_adv_dup_list_count, ble_ll_tx_pwr_dbm: config.default_tx_power.dbm() as u8, - rtc_freq: 32000, - ble_ll_sca: CONFIG_BT_LE_LL_SCA as _, + rtc_freq: u64::from(lp_clk::frequency_hz()), + // ESP-IDF: `ble_rtc_clk_init()` in `bt.c`. + ble_ll_sca: if lp_clk::source_is_rc(esp_hal::clock::ll::ble_lp_clk_root_source) { + lp_clk::RC_SCA_PPM as _ + } else { + CONFIG_BT_LE_LL_SCA as _ + }, ble_ll_scan_phy_number: if CONFIG_BT_LE_LL_CFG_FEAT_LE_CODED_PHY != 0 { 2 } else { @@ -315,7 +328,7 @@ pub(crate) fn create_ble_config(config: &Config) -> esp_bt_controller_config_t { enable_bqb_test: config.bqb_test as u8, enable_tx_cca: config.cca as u8, cca_rssi_thresh: (256 - config.cca_threshold as u32) as u8, - sleep_en: 0, + sleep_en: u8::from(config.modem_sleep), coex_phy_coded_tx_rx_time_limit: CONFIG_BT_LE_COEX_PHY_CODED_TX_RX_TLIM_EFF as _, dis_scan_backoff: config.dis_scan_backoff as u8, ble_scan_classify_filter_enable: 1, @@ -347,6 +360,9 @@ pub(crate) fn create_ble_config(config: &Config) -> esp_bt_controller_config_t { slv_fst_rx_lat_en: 0, dl_itvl_phy_sync_en: 0, scan_allow_adi_filter: 0, + // BT_CONTROLLER_INIT_CONFIG_DEFAULT: both stay 0 unless ADV_FAST_TX is set. + enhanced_mem_resv: 0, + rxbuf_reserved: 0, config_magic: CONFIG_MAGIC, } } diff --git a/esp-radio/src/ble/npl/os_mempool.rs b/esp-radio/src/ble/npl/os_mempool.rs new file mode 100644 index 00000000000..822fc63042c --- /dev/null +++ b/esp-radio/src/ble/npl/os_mempool.rs @@ -0,0 +1,381 @@ +//! NimBLE `os_mempool` implementation. +//! +//! Port of IDF `components/bt/porting/mem/os_mempool.c` without +//! poison/guard/runtime-alloc. The BLE blob calls these unprefixed symbols. +//! +//! On C2, ROM provides `r_os_mempool_*` and `g_os_mempool_list`. This module +//! exports the unprefixed names against a private list, so ROM msys +//! (`r_os_msys_*`) and blob calls to `os_mempool_*` do not share a list. + +use core::ptr; + +use super::OsMempool; + +const OS_OK: i32 = 0; +const OS_INVALID_PARM: i32 = 3; +const OS_MEM_NOT_ALIGNED: i32 = 4; +const OS_ALIGNMENT: usize = 4; +const OS_MEMPOOL_F_EXT: u8 = 1; +const OS_MEMPOOL_F_FRAG: u8 = 8; +const OS_MEMPOOL_F_COMBINATION: u8 = 128; + +type OsMempoolPutFn = + unsafe extern "C" fn(mpe: *mut OsMempoolExt, data: *mut u8, arg: *mut u8) -> i32; +type OsMempoolGetFn = unsafe extern "C" fn(mpe: *mut OsMempoolExt, arg: *mut u8) -> *mut u8; + +#[repr(C)] +pub(crate) struct OsMempoolExt { + mp: OsMempool, + put_cb: Option, + put_arg: *mut u8, + get_cb: Option, + get_arg: *mut u8, +} + +#[repr(C)] +struct OsMemblock { + next: *mut OsMemblock, +} + +static mut G_OS_MEMPOOL_LIST: *mut OsMempool = ptr::null_mut(); + +fn true_block_size(block_size: u32) -> usize { + (block_size as usize + OS_ALIGNMENT - 1) & !(OS_ALIGNMENT - 1) +} + +// IDF compares the name *pointer* (re-init of the same pool), not the string. +unsafe fn list_contains_name(name: *const u8) -> *mut OsMempool { + let mut cur = unsafe { G_OS_MEMPOOL_LIST }; + while !cur.is_null() { + if unsafe { (*cur).name } == name { + return cur; + } + cur = unsafe { (*cur).next.cast_mut() }; + } + ptr::null_mut() +} + +unsafe fn list_insert_tail(mp: *mut OsMempool) { + unsafe { (*mp).next = ptr::null() }; + let mut cur = unsafe { G_OS_MEMPOOL_LIST }; + if cur.is_null() { + unsafe { G_OS_MEMPOOL_LIST = mp }; + return; + } + loop { + let next = unsafe { (*cur).next }; + if next.is_null() { + unsafe { (*cur).next = mp }; + break; + } + cur = next.cast_mut(); + } +} + +unsafe fn chain_blocks(mp: *mut OsMempool, membuf: *mut u8, blocks: u16) { + if blocks == 0 { + unsafe { (*mp).first = ptr::null() }; + return; + } + + let stride = true_block_size(unsafe { (*mp).mp_block_size }); + unsafe { (*mp).first = membuf.cast() }; + let mut block = membuf.cast::(); + for i in 1..blocks { + let next = unsafe { membuf.add(i as usize * stride) }.cast::(); + unsafe { (*block).next = next }; + block = next; + } + unsafe { (*block).next = ptr::null_mut() }; +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn os_mempool_init_internal( + mp: *mut OsMempool, + blocks: u16, + block_size: u32, + membuf: *mut u8, + name: *const u8, + flags: u8, +) -> i32 { + if mp.is_null() || block_size == 0 { + return OS_INVALID_PARM; + } + if membuf.is_null() && blocks != 0 { + return OS_INVALID_PARM; + } + if !membuf.is_null() && !(membuf as usize).is_multiple_of(OS_ALIGNMENT) { + return OS_MEM_NOT_ALIGNED; + } + + unsafe { + (*mp).mp_block_size = block_size; + (*mp).mp_num_free = blocks; + (*mp).mp_min_free = blocks; + (*mp).mp_flags = flags; + (*mp).mp_num_blocks = blocks; + (*mp).mp_membuf_addr = membuf as u32; + (*mp).name = name; + chain_blocks(mp, membuf, blocks); + + let existing = list_contains_name(name); + if !existing.is_null() { + let _ = os_mempool_unregister(existing); + } + list_insert_tail(mp); + } + OS_OK +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn os_mempool_init( + mp: *mut OsMempool, + blocks: u16, + block_size: u32, + membuf: *mut u8, + name: *const u8, +) -> i32 { + unsafe { os_mempool_init_internal(mp, blocks, block_size, membuf, name, 0) } +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn os_mempool_ext_init( + mpe: *mut OsMempoolExt, + blocks: u16, + block_size: u32, + membuf: *mut u8, + name: *const u8, +) -> i32 { + if mpe.is_null() { + return OS_INVALID_PARM; + } + let rc = unsafe { + os_mempool_init_internal( + ptr::addr_of_mut!((*mpe).mp), + blocks, + block_size, + membuf, + name, + OS_MEMPOOL_F_EXT, + ) + }; + if rc != 0 { + return rc; + } + unsafe { + (*mpe).put_cb = None; + (*mpe).put_arg = ptr::null_mut(); + (*mpe).get_cb = None; + (*mpe).get_arg = ptr::null_mut(); + } + OS_OK +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn os_ext_mempool_register_cb( + mpe: *mut OsMempoolExt, + put_cb: Option, + put_arg: *mut u8, + get_cb: Option, + get_arg: *mut u8, +) { + if mpe.is_null() { + return; + } + unsafe { + (*mpe).put_cb = put_cb; + (*mpe).put_arg = put_arg; + (*mpe).get_cb = get_cb; + (*mpe).get_arg = get_arg; + } +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn os_mempool_unregister(mp: *mut OsMempool) -> i32 { + if mp.is_null() { + return OS_INVALID_PARM; + } + + let mut prev: *mut OsMempool = ptr::null_mut(); + let mut cur = unsafe { G_OS_MEMPOOL_LIST }; + while !cur.is_null() { + if cur == mp { + let next = unsafe { (*cur).next }; + if prev.is_null() { + unsafe { G_OS_MEMPOOL_LIST = next.cast_mut() }; + } else { + unsafe { (*prev).next = next }; + } + unsafe { (*mp).next = ptr::null() }; + return OS_OK; + } + prev = cur; + cur = unsafe { (*cur).next.cast_mut() }; + } + OS_INVALID_PARM +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn os_mempool_clear(mp: *mut OsMempool) -> i32 { + if mp.is_null() { + return OS_INVALID_PARM; + } + unsafe { + (*mp).mp_num_free = (*mp).mp_num_blocks; + (*mp).mp_min_free = (*mp).mp_num_blocks; + chain_blocks(mp, (*mp).mp_membuf_addr as *mut u8, (*mp).mp_num_blocks); + } + OS_OK +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn os_mempool_flags_set(mp: *mut OsMempool, flags: u8) { + if !mp.is_null() { + unsafe { (*mp).mp_flags |= flags }; + } +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn os_memblock_from(mp: *const OsMempool, block: *const u8) -> i32 { + if mp.is_null() || block.is_null() { + return 0; + } + let start = unsafe { (*mp).mp_membuf_addr } as usize; + let stride = true_block_size(unsafe { (*mp).mp_block_size }); + let end = start + unsafe { (*mp).mp_num_blocks } as usize * stride; + let addr = block as usize; + if addr < start || addr >= end { + return 0; + } + if unsafe { (*mp).mp_flags } & OS_MEMPOOL_F_COMBINATION == 0 + && !(addr - start).is_multiple_of(stride) + { + return 0; + } + 1 +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn os_mempool_ext_clear(mpe: *mut OsMempoolExt) -> i32 { + if mpe.is_null() { + return OS_INVALID_PARM; + } + unsafe { + (*mpe).put_cb = None; + (*mpe).put_arg = ptr::null_mut(); + (*mpe).get_cb = None; + (*mpe).get_arg = ptr::null_mut(); + let rc = os_mempool_clear(ptr::addr_of_mut!((*mpe).mp)); + (*mpe).mp.mp_flags = 0; + rc + } +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn os_mempool_is_sane(mp: *const OsMempool) -> bool { + if mp.is_null() { + return false; + } + let mut block = unsafe { (*mp).first }; + while !block.is_null() { + if unsafe { os_memblock_from(mp, block.cast()) } == 0 { + return false; + } + block = unsafe { (*block.cast::()).next.cast() }; + } + true +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn os_mempool_module_init() {} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn os_memblock_get(mp: *mut OsMempool) -> *mut u8 { + if mp.is_null() { + return ptr::null_mut(); + } + + if unsafe { (*mp).mp_flags } & OS_MEMPOOL_F_EXT != 0 { + let mpe = mp.cast::(); + if let Some(cb) = unsafe { (*mpe).get_cb } { + return unsafe { cb(mpe, (*mpe).get_arg) }; + } + } + + let token = unsafe { crate::ble::ESP_RADIO_LOCK.acquire() }; + let block = unsafe { + if (*mp).mp_num_free == 0 { + ptr::null_mut() + } else { + let block = (*mp).first.cast_mut(); + (*mp).first = (*block.cast::()).next.cast(); + // Hand out the block without the free-list link in its first word: + // `ble_npl_event_init` reads a non-zero first word as an + // initialised event and would run the stale link as its callback. + (*block.cast::()).next = ptr::null_mut(); + (*mp).mp_num_free -= 1; + if (*mp).mp_min_free > (*mp).mp_num_free { + (*mp).mp_min_free = (*mp).mp_num_free; + } + block.cast() + } + }; + unsafe { crate::ble::ESP_RADIO_LOCK.release(token) }; + block +} + +unsafe fn memblock_put_from_cb(mp: *mut OsMempool, block_addr: *mut u8) -> i32 { + if unsafe { (*mp).mp_flags } & OS_MEMPOOL_F_FRAG == 0 + && unsafe { os_memblock_from(mp, block_addr) } == 0 + { + return OS_INVALID_PARM; + } + + let token = unsafe { crate::ble::ESP_RADIO_LOCK.acquire() }; + let rc = unsafe { + let mut cur = (*mp).first.cast::(); + let mut dup = false; + while !cur.is_null() { + if cur.cast::() == block_addr { + dup = true; + break; + } + cur = (*cur).next; + } + if dup || (*mp).mp_num_free >= (*mp).mp_num_blocks { + OS_INVALID_PARM + } else { + let block = block_addr.cast::(); + (*block).next = (*mp).first.cast_mut().cast(); + (*mp).first = block.cast(); + (*mp).mp_num_free += 1; + OS_OK + } + }; + unsafe { crate::ble::ESP_RADIO_LOCK.release(token) }; + rc +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn os_memblock_put(mp: *mut OsMempool, block_addr: *mut u8) -> i32 { + if mp.is_null() || block_addr.is_null() { + return OS_INVALID_PARM; + } + + if unsafe { (*mp).mp_flags } & OS_MEMPOOL_F_EXT != 0 { + let mpe = mp.cast::(); + if let Some(cb) = unsafe { (*mpe).put_cb } { + return unsafe { cb(mpe, block_addr, (*mpe).put_arg) }; + } + } + + unsafe { memblock_put_from_cb(mp, block_addr) } +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn os_memblock_put_from_cb(mp: *mut OsMempool, block_addr: *mut u8) -> i32 { + if mp.is_null() || block_addr.is_null() { + return OS_INVALID_PARM; + } + unsafe { memblock_put_from_cb(mp, block_addr) } +} diff --git a/esp-radio/src/common_adapter.rs b/esp-radio/src/common_adapter.rs index eb488100b40..61ced47f3fa 100644 --- a/esp-radio/src/common_adapter.rs +++ b/esp-radio/src/common_adapter.rs @@ -11,7 +11,10 @@ use crate::{ }; #[ram] -#[cfg(any(feature = "coex", all(feature = "ble", bt_controller = "btdm")))] +#[cfg(any( + feature = "coex", + all(feature = "ble", any(bt_controller = "btdm", bt_controller = "btdm2")) +))] pub(crate) unsafe extern "C" fn is_in_isr() -> i32 { !hal::interrupt::RunLevel::current().is_thread() as i32 } @@ -346,7 +349,7 @@ pub(crate) fn enable_wifi_power_domain() { const BTBB_RST: u32 = 1 << 3; // Bluetooth Baseband const BTMAC_RST: u32 = 1 << 4; // deprecated const RW_BTMAC_RST: u32 = 1 << 9; // Bluetooth MAC - const RW_BTMAC_REG_RST: u32 = 1 << 11; // Bluetooth MAC Regsiters + const RW_BTMAC_REG_RST: u32 = 1 << 11; // Bluetooth MAC Registers const BTBB_REG_RST: u32 = 1 << 13; // Bluetooth Baseband Registers const MODEM_RESET_FIELD_WHEN_PU: u32 = WIFIBB_RST diff --git a/esp-radio/src/compat/atomic.rs b/esp-radio/src/compat/atomic.rs new file mode 100644 index 00000000000..a85e07a8ec8 --- /dev/null +++ b/esp-radio/src/compat/atomic.rs @@ -0,0 +1,113 @@ +//! GCC/LLVM libatomic helpers for targets without hardware CAS. +//! +//! `wpa_supplicant` uses C11 atomics (`eloop.c`). rustc's `compiler_builtins` +//! does not export `__atomic_*` on `riscv32imc` or `xtensa-esp32s2`. +//! Implemented with [`portable_atomic`]. + +use portable_atomic::{AtomicU8, AtomicU16, AtomicU32, Ordering}; + +fn ordering(order: i32) -> Ordering { + match order { + 0 => Ordering::Relaxed, + 1 | 2 => Ordering::Acquire, + 3 => Ordering::Release, + 4 => Ordering::AcqRel, + _ => Ordering::SeqCst, + } +} + +fn failure_ordering(order: i32) -> Ordering { + match order { + 0 => Ordering::Relaxed, + 1 | 2 => Ordering::Acquire, + _ => Ordering::SeqCst, + } +} + +macro_rules! libatomic { + ($ty:ty, $atomic:ty, $cas:ident, $xchg:ident, $add:ident, $sub:ident, $load:ident, $store:ident) => { + /// GCC 6-operand CAS; `weak` selects `compare_exchange_weak`. + #[unsafe(no_mangle)] + pub unsafe extern "C" fn $cas( + dst: *mut $ty, + expected: *mut $ty, + desired: $ty, + weak: bool, + success: i32, + failure: i32, + ) -> bool { + let atomic = unsafe { <$atomic>::from_ptr(dst) }; + let exp = unsafe { core::ptr::read(expected) }; + let success = ordering(success); + let failure = failure_ordering(failure); + let result = if weak { + atomic.compare_exchange_weak(exp, desired, success, failure) + } else { + atomic.compare_exchange(exp, desired, success, failure) + }; + match result { + Ok(_) => true, + Err(current) => { + unsafe { core::ptr::write(expected, current) }; + false + } + } + } + + #[unsafe(no_mangle)] + pub unsafe extern "C" fn $xchg(dst: *mut $ty, val: $ty, order: i32) -> $ty { + unsafe { <$atomic>::from_ptr(dst) }.swap(val, ordering(order)) + } + + #[unsafe(no_mangle)] + pub unsafe extern "C" fn $add(dst: *mut $ty, val: $ty, order: i32) -> $ty { + unsafe { <$atomic>::from_ptr(dst) }.fetch_add(val, ordering(order)) + } + + #[unsafe(no_mangle)] + pub unsafe extern "C" fn $sub(dst: *mut $ty, val: $ty, order: i32) -> $ty { + unsafe { <$atomic>::from_ptr(dst) }.fetch_sub(val, ordering(order)) + } + + #[unsafe(no_mangle)] + pub unsafe extern "C" fn $load(src: *const $ty, order: i32) -> $ty { + unsafe { <$atomic>::from_ptr(src.cast_mut()) }.load(ordering(order)) + } + + #[unsafe(no_mangle)] + pub unsafe extern "C" fn $store(dst: *mut $ty, val: $ty, order: i32) { + unsafe { <$atomic>::from_ptr(dst) }.store(val, ordering(order)) + } + }; +} + +libatomic!( + u8, + AtomicU8, + __atomic_compare_exchange_1, + __atomic_exchange_1, + __atomic_fetch_add_1, + __atomic_fetch_sub_1, + __atomic_load_1, + __atomic_store_1 +); +libatomic!( + u16, + AtomicU16, + __atomic_compare_exchange_2, + __atomic_exchange_2, + __atomic_fetch_add_2, + __atomic_fetch_sub_2, + __atomic_load_2, + __atomic_store_2 +); +libatomic!( + u32, + AtomicU32, + __atomic_compare_exchange_4, + __atomic_exchange_4, + __atomic_fetch_add_4, + __atomic_fetch_sub_4, + __atomic_load_4, + __atomic_store_4 +); diff --git a/esp-radio/src/compat/mod.rs b/esp-radio/src/compat/mod.rs index a129fb9c794..a6510165892 100644 --- a/esp-radio/src/compat/mod.rs +++ b/esp-radio/src/compat/mod.rs @@ -1,5 +1,9 @@ #![allow(dead_code)] +/// C11 `__atomic_*` helpers where the target has no hardware CAS (RISC-V IMC, ESP32-S2). +#[cfg(any(all(target_arch = "riscv32", not(target_feature = "a")), esp32s2))] +pub mod atomic; + pub mod common; pub mod malloc; pub mod misc; @@ -7,7 +11,10 @@ pub mod mutex; pub mod queue; pub mod semaphore; -#[cfg(any(feature = "wifi", all(feature = "ble", bt_controller = "npl")))] +#[cfg(any( + feature = "wifi", + all(feature = "ble", any(bt_controller = "npl", bt_controller = "btdm2")) +))] pub mod timer_compat; pub(crate) const OSI_FUNCS_TIME_BLOCKING: u32 = u32::MAX; diff --git a/esp-radio/src/compat/mutex.rs b/esp-radio/src/compat/mutex.rs index 7dd00671083..e57ba6ad6b2 100644 --- a/esp-radio/src/compat/mutex.rs +++ b/esp-radio/src/compat/mutex.rs @@ -1,6 +1,7 @@ use esp_radio_rtos_driver::semaphore::SemaphoreKind; use crate::{ + compat::OSI_FUNCS_TIME_BLOCKING, preempt::semaphore::{SemaphoreHandle, SemaphorePtr}, sys::c_types::c_void, }; @@ -28,11 +29,29 @@ pub(crate) fn mutex_delete(mutex: *mut c_void) { } pub(crate) fn mutex_lock(mutex: *mut c_void) -> i32 { + mutex_lock_with_timeout(mutex, OSI_FUNCS_TIME_BLOCKING) +} + +pub(crate) fn mutex_lock_with_timeout(mutex: *mut c_void, tick: u32) -> i32 { + let ptr = unwrap!(SemaphorePtr::new(mutex.cast()), "mutex is null"); + + let handle = unsafe { SemaphoreHandle::ref_from_ptr(&ptr) }; + // Assuming `tick` is in microseconds + let timeout = if tick == OSI_FUNCS_TIME_BLOCKING { + None + } else { + Some(tick) + }; + + handle.take(timeout) as i32 +} + +pub(crate) fn mutex_try_lock(mutex: *mut c_void) -> bool { let ptr = unwrap!(SemaphorePtr::new(mutex.cast()), "mutex is null"); let handle = unsafe { SemaphoreHandle::ref_from_ptr(&ptr) }; - handle.take(None) as i32 + handle.try_take() } pub(crate) fn mutex_unlock(mutex: *mut c_void) -> i32 { diff --git a/esp-radio/src/compat/queue.rs b/esp-radio/src/compat/queue.rs index c00ab2ed82b..31d7b602474 100644 --- a/esp-radio/src/compat/queue.rs +++ b/esp-radio/src/compat/queue.rs @@ -17,7 +17,7 @@ pub(crate) fn queue_create(queue_len: c_int, item_size: c_int) -> *mut c_void { } pub(crate) fn queue_delete(queue: *mut c_void) { - trace!("delete_queue {:?}", queue); + trace!("queue_delete {:?}", queue); let ptr = unwrap!(QueuePtr::new(queue.cast()), "queue is null"); @@ -27,7 +27,7 @@ pub(crate) fn queue_delete(queue: *mut c_void) { pub(crate) fn queue_send_to_back(queue: *mut c_void, item: *const c_void, tick: u32) -> i32 { trace!( - "queue_send queue {:?} item {:x} tick {}", + "queue_send_to_back queue {:?} item {:#x} tick {}", queue, item as usize, tick ); @@ -50,7 +50,7 @@ pub(crate) fn queue_try_send_to_back_from_isr( higher_priority_task_waken: *mut bool, ) -> i32 { trace!( - "queue_try_send_to_back_from_isr queue {:?} item {:x}", + "queue_try_send_to_back_from_isr queue {:?} item {:#x}", queue, item as usize ); @@ -63,10 +63,29 @@ pub(crate) fn queue_try_send_to_back_from_isr( } } +pub(crate) fn queue_try_send_to_front_from_isr( + queue: *mut c_void, + item: *const c_void, + higher_priority_task_waken: *mut bool, +) -> i32 { + trace!( + "queue_try_send_to_front_from_isr queue {:?} item {:#x}", + queue, item as usize + ); + + let ptr = unwrap!(QueuePtr::new(queue.cast()), "queue is null"); + + let handle = unsafe { QueueHandle::ref_from_ptr(&ptr) }; + + unsafe { + handle.try_send_to_front_from_isr(item.cast(), higher_priority_task_waken.as_mut()) as i32 + } +} + pub(crate) fn queue_send_to_front(queue: *mut c_void, item: *const c_void, tick: u32) -> i32 { trace!( - "queue_send_to_front {:?} item {:?} tick {}", - queue, item, tick + "queue_send_to_front {:?} item {:#x} tick {}", + queue, item as usize, tick ); let ptr = unwrap!(QueuePtr::new(queue.cast()), "queue is null"); @@ -82,7 +101,10 @@ pub(crate) fn queue_send_to_front(queue: *mut c_void, item: *const c_void, tick: } pub(crate) fn queue_receive(queue: *mut c_void, item: *mut c_void, tick: u32) -> i32 { - trace!("queue_recv {:?} item {:?} tick {}", queue, item, tick); + trace!( + "queue_receive {:?} item {:#x} tick {}", + queue, item as usize, tick + ); let ptr = unwrap!(QueuePtr::new(queue.cast()), "queue is null"); @@ -102,7 +124,10 @@ pub(crate) fn queue_try_receive_from_isr( item: *mut c_void, higher_priority_task_waken: *mut bool, ) -> i32 { - trace!("queue_try_recv_from_isr {:?} item {:?}", queue, item); + trace!( + "queue_try_receive_from_isr {:?} item {:#x}", + queue, item as usize + ); let ptr = unwrap!(QueuePtr::new(queue.cast()), "queue is null"); @@ -112,7 +137,7 @@ pub(crate) fn queue_try_receive_from_isr( } pub(crate) fn queue_remove(queue: *mut c_void, item: *const c_void) { - trace!("queue_remove queue {:?} item {:x}", queue, item as usize); + trace!("queue_remove queue {:?} item {:#x}", queue, item as usize); let ptr = unwrap!(QueuePtr::new(queue.cast()), "queue is null"); @@ -122,7 +147,7 @@ pub(crate) fn queue_remove(queue: *mut c_void, item: *const c_void) { } pub(crate) fn queue_messages_waiting(queue: *mut c_void) -> u32 { - trace!("queue_msg_waiting {:?}", queue); + trace!("queue_messages_waiting {:?}", queue); let ptr = unwrap!(QueuePtr::new(queue.cast()), "queue is null"); diff --git a/esp-radio/src/compat/semaphore.rs b/esp-radio/src/compat/semaphore.rs index 948f33bd7e3..a16861de6aa 100644 --- a/esp-radio/src/compat/semaphore.rs +++ b/esp-radio/src/compat/semaphore.rs @@ -70,3 +70,9 @@ pub(crate) fn sem_give_from_isr(semphr: *mut c_void, _higher_prio_task_waken: *m handle.give() as i32 } + +pub(crate) fn sem_count(semphr: *mut c_void) -> u32 { + let ptr = unwrap!(SemaphorePtr::new(semphr.cast()), "semphr is null"); + let handle = unsafe { SemaphoreHandle::ref_from_ptr(&ptr) }; + handle.current_count() +} diff --git a/esp-radio/src/compiler_rt_abi.rs b/esp-radio/src/compiler_rt_abi.rs new file mode 100644 index 00000000000..f62e87ea89c --- /dev/null +++ b/esp-radio/src/compiler_rt_abi.rs @@ -0,0 +1,37 @@ +//! Integer builtins the Wi-Fi/BLE blobs call, defined here so that +//! `compiler_builtins` is never asked for them. +//! +//! `riscv32imafc-unknown-none-elf` is a hard-float (`ilp32f`) target, and so +//! is every object in the blobs. Rust, however, ships `compiler_builtins` +//! with `optimized-compiler-builtins` enabled, which builds compiler-rt's C +//! routines through cc-rs, and cc-rs passes `-mabi=ilp32` for every non-Linux +//! `riscv32` target regardless of the `f` in the triple +//! (). 36 objects in the +//! shipped rlib are soft-float as a result, and pulling one in fails the link +//! with "cannot link object files with different floating-point ABI". +//! +//! Defining the symbols here means lld resolves them before it reaches those +//! archive members. Plain Rust cannot hit this - LLVM inlines `ctpop` and +//! `bswap` for this target - so only the GCC-built blobs need it, which is why +//! this lives in esp-radio and not in esp-hal. It can go once a Rust release +//! ships a `compiler_builtins` built by a fixed cc-rs. + +#[unsafe(no_mangle)] +extern "C" fn __popcountsi2(x: u32) -> i32 { + x.count_ones() as i32 +} + +#[unsafe(no_mangle)] +extern "C" fn __popcountdi2(x: u64) -> i32 { + x.count_ones() as i32 +} + +#[unsafe(no_mangle)] +extern "C" fn __bswapsi2(x: u32) -> u32 { + x.swap_bytes() +} + +#[unsafe(no_mangle)] +extern "C" fn __bswapdi2(x: u64) -> u64 { + x.swap_bytes() +} diff --git a/esp-radio/src/drop_guard.rs b/esp-radio/src/drop_guard.rs new file mode 100644 index 00000000000..695ed0b3ed0 --- /dev/null +++ b/esp-radio/src/drop_guard.rs @@ -0,0 +1,59 @@ +use core::{ + mem::ManuallyDrop, + ops::{Deref, DerefMut}, +}; + +pub(crate) struct DropGuard { + inner: ManuallyDrop, + on_drop: ManuallyDrop, +} + +impl DropGuard { + pub(crate) fn new(inner: I, on_drop: F) -> Self { + Self { + inner: ManuallyDrop::new(inner), + on_drop: ManuallyDrop::new(on_drop), + } + } + + pub(crate) fn defuse(self) { + core::mem::forget(self); + } +} + +impl Drop for DropGuard { + fn drop(&mut self) { + let inner = unsafe { ManuallyDrop::take(&mut self.inner) }; + let on_drop = unsafe { ManuallyDrop::take(&mut self.on_drop) }; + (on_drop)(inner) + } +} + +impl core::fmt::Debug for DropGuard { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("DropGuard") + .field("inner", &*self.inner) + .finish_non_exhaustive() + } +} + +#[cfg(feature = "defmt")] +impl defmt::Format for DropGuard { + fn format(&self, f: defmt::Formatter<'_>) { + defmt::write!(f, "DropGuard {{ inner: {}, .. }}", &*self.inner) + } +} + +impl Deref for DropGuard { + type Target = I; + + fn deref(&self) -> &I { + &self.inner + } +} + +impl DerefMut for DropGuard { + fn deref_mut(&mut self) -> &mut I { + &mut self.inner + } +} diff --git a/esp-radio/src/esp_now/mod.rs b/esp-radio/src/esp_now/mod.rs index 1dd70356dda..dc2c51c927a 100644 --- a/esp-radio/src/esp_now/mod.rs +++ b/esp-radio/src/esp_now/mod.rs @@ -27,13 +27,16 @@ use crate::wifi::csi::CsiConfig; use crate::{ asynch::AtomicWaker, sys::include::*, - wifi::{RxControlInfo, WifiError}, + wifi::{RxControlInfo, WifiError, WifiRefGuard}, }; const RECEIVE_QUEUE_SIZE: usize = 10; -/// Maximum payload length -pub const ESP_NOW_MAX_DATA_LEN: usize = 250; +/// Maximum ESP-NOW v1.0 payload length. +pub const ESP_NOW_MAX_DATA_LEN_V1: usize = crate::sys::include::ESP_NOW_MAX_DATA_LEN as _; + +/// Maximum ESP-NOW v2.0 payload length. +pub const ESP_NOW_MAX_DATA_LEN_V2: usize = crate::sys::include::ESP_NOW_MAX_DATA_LEN_V2 as _; /// Broadcast address pub const BROADCAST_ADDRESS: [u8; 6] = [0xffu8, 0xffu8, 0xffu8, 0xffu8, 0xffu8, 0xffu8]; @@ -334,6 +337,7 @@ impl Debug for ReceivedData { #[instability::unstable] pub enum EspNowWifiInterface { /// Use the access point interface + #[cfg(wifi_softap_support)] AccessPoint, /// Use the station interface Station, @@ -342,6 +346,7 @@ pub enum EspNowWifiInterface { impl EspNowWifiInterface { fn as_wifi_interface(&self) -> wifi_interface_t { match self { + #[cfg(wifi_softap_support)] EspNowWifiInterface::AccessPoint => wifi_interface_t_WIFI_IF_AP, EspNowWifiInterface::Station => wifi_interface_t_WIFI_IF_STA, } @@ -350,6 +355,7 @@ impl EspNowWifiInterface { fn from_wifi_interface(interface: wifi_interface_t) -> Self { #[allow(non_upper_case_globals)] match interface { + #[cfg(wifi_softap_support)] wifi_interface_t_WIFI_IF_AP => EspNowWifiInterface::AccessPoint, wifi_interface_t_WIFI_IF_STA => EspNowWifiInterface::Station, wifi_interface_t_WIFI_IF_NAN => panic!("NAN is unsupported"), @@ -402,11 +408,11 @@ pub struct RateConfig { #[derive(Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[instability::unstable] -pub struct EspNowManager<'d> { - _rc: EspNowRc<'d>, +pub struct EspNowManager { + _rc: EspNowRc, } -impl EspNowManager<'_> { +impl EspNowManager { /// Set primary Wi-Fi channel. /// When using ESP-NOW with an access point or station, /// the device cannot switch channels after connecting to Wi-Fi. @@ -417,6 +423,10 @@ impl EspNowManager<'_> { } /// Get the version of ESP-NOW. + /// + /// ESP-NOW supports two versions: v1.0 and v2.0. v1.0 and v2.0 are capable of talking to each + /// other, but v1.0 devices may truncate or discard v2.0 messages that exceed the v1.0 maximum + /// data length ([`ESP_NOW_MAX_DATA_LEN_V1`]). #[instability::unstable] pub fn version(&self) -> Result { let mut version = 0u32; @@ -610,11 +620,11 @@ impl EspNowManager<'_> { #[derive(Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[instability::unstable] -pub struct EspNowSender<'d> { - _rc: EspNowRc<'d>, +pub struct EspNowSender { + _rc: EspNowRc, } -impl EspNowSender<'_> { +impl EspNowSender { /// Send data to peer /// /// The peer needs to be added to the peer list first. @@ -644,7 +654,7 @@ impl EspNowSender<'_> { /// invoked. #[must_use] #[instability::unstable] -pub struct SendWaiter<'s>(PhantomData<&'s mut EspNowSender<'s>>); +pub struct SendWaiter<'s>(PhantomData<&'s mut EspNowSender>); impl SendWaiter<'_> { /// Wait for the previous sending to complete, i.e. the send callback is @@ -677,11 +687,11 @@ impl Drop for SendWaiter<'_> { #[derive(Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[instability::unstable] -pub struct EspNowReceiver<'d> { - _rc: EspNowRc<'d>, +pub struct EspNowReceiver { + _rc: EspNowRc, } -impl EspNowReceiver<'_> { +impl EspNowReceiver { /// Receives data from the ESP-NOW queue. #[instability::unstable] pub fn receive(&self) -> Option { @@ -692,24 +702,24 @@ impl EspNowReceiver<'_> { /// The reference counter for properly deinit espnow after all parts are /// dropped. #[derive(Debug)] -struct EspNowRc<'d> { +struct EspNowRc { rc: &'static AtomicU8, - inner: PhantomData>, + _wifi_guard: WifiRefGuard, } #[cfg(feature = "defmt")] -impl defmt::Format for EspNowRc<'_> { +impl defmt::Format for EspNowRc { fn format(&self, f: defmt::Formatter<'_>) { defmt::write!( f, - "EspNowRc {{ rc: {}, inner: ... }}", + "EspNowRc {{ rc: {}, _wifi_guard: ... }}", self.rc.load(Ordering::Relaxed) ); } } -impl EspNowRc<'_> { - fn new() -> Self { +impl EspNowRc { + fn new(wifi_guard: WifiRefGuard) -> Self { static ESP_NOW_RC: AtomicU8 = AtomicU8::new(0); assert!( ESP_NOW_RC.fetch_add(1, Ordering::AcqRel) == 0, @@ -718,22 +728,22 @@ impl EspNowRc<'_> { Self { rc: &ESP_NOW_RC, - inner: PhantomData, + _wifi_guard: wifi_guard, } } } -impl Clone for EspNowRc<'_> { +impl Clone for EspNowRc { fn clone(&self) -> Self { self.rc.fetch_add(1, Ordering::Release); Self { rc: self.rc, - inner: PhantomData, + _wifi_guard: self._wifi_guard.clone(), } } } -impl Drop for EspNowRc<'_> { +impl Drop for EspNowRc { fn drop(&mut self) { if self.rc.fetch_sub(1, Ordering::AcqRel) == 1 { unsafe { @@ -758,16 +768,15 @@ impl Drop for EspNowRc<'_> { #[derive(Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[instability::unstable] -pub struct EspNow<'d> { - manager: EspNowManager<'d>, - sender: EspNowSender<'d>, - receiver: EspNowReceiver<'d>, - _phantom: PhantomData<&'d ()>, +pub struct EspNow { + manager: EspNowManager, + sender: EspNowSender, + receiver: EspNowReceiver, } -impl<'d> EspNow<'d> { - pub(crate) fn new_internal() -> EspNow<'d> { - let espnow_rc = EspNowRc::new(); +impl EspNow { + pub(crate) fn new_internal(guard: WifiRefGuard) -> EspNow { + let espnow_rc = EspNowRc::new(guard); let esp_now = EspNow { manager: EspNowManager { _rc: espnow_rc.clone(), @@ -776,7 +785,6 @@ impl<'d> EspNow<'d> { _rc: espnow_rc.clone(), }, receiver: EspNowReceiver { _rc: espnow_rc }, - _phantom: PhantomData, }; check_error_expect!({ esp_now_init() }, "esp-now-init failed"); @@ -805,7 +813,7 @@ impl<'d> EspNow<'d> { /// Splits the `EspNow` instance into its manager, sender, and receiver /// components. #[instability::unstable] - pub fn split(self) -> (EspNowManager<'d>, EspNowSender<'d>, EspNowReceiver<'d>) { + pub fn split(self) -> (EspNowManager, EspNowSender, EspNowReceiver) { (self.manager, self.sender, self.receiver) } @@ -971,7 +979,7 @@ unsafe extern "C" fn rcv_cb( }); } -impl EspNowReceiver<'_> { +impl EspNowReceiver { /// This function takes mutable reference to self because the /// implementation of `ReceiveFuture` is not logically thread /// safe. @@ -981,7 +989,7 @@ impl EspNowReceiver<'_> { } } -impl EspNowSender<'_> { +impl EspNowSender { /// Sends data asynchronously to a peer (using its MAC) using ESP-NOW. #[instability::unstable] pub fn send_async<'s, 'r>( @@ -998,7 +1006,7 @@ impl EspNowSender<'_> { } } -impl EspNow<'_> { +impl EspNow { /// This function takes mutable reference to self because the /// implementation of `ReceiveFuture` is not logically thread /// safe. @@ -1024,7 +1032,7 @@ impl EspNow<'_> { #[must_use = "futures do nothing unless you `.await` or poll them"] #[instability::unstable] pub struct SendFuture<'s, 'r> { - _sender: PhantomData<&'s mut EspNowSender<'s>>, + _sender: PhantomData<&'s mut EspNowSender>, addr: &'r [u8; 6], data: &'r [u8], sent: bool, @@ -1062,7 +1070,7 @@ impl core::future::Future for SendFuture<'_, '_> { /// the rest of them unwakable. #[must_use = "futures do nothing unless you `.await` or poll them"] #[instability::unstable] -pub struct ReceiveFuture<'r>(PhantomData<&'r mut EspNowReceiver<'r>>); +pub struct ReceiveFuture<'r>(PhantomData<&'r mut EspNowReceiver>); impl core::future::Future for ReceiveFuture<'_> { type Output = ReceivedData; diff --git a/esp-radio/src/ieee802154/frame.rs b/esp-radio/src/ieee802154/frame.rs index 4910c27c75a..53260b6396a 100644 --- a/esp-radio/src/ieee802154/frame.rs +++ b/esp-radio/src/ieee802154/frame.rs @@ -47,15 +47,13 @@ pub struct ReceivedFrame { } pub(crate) fn frame_is_ack_required(frame: &[u8]) -> bool { - if frame.len() <= FRAME_AR_OFFSET { - return false; - } - (frame[FRAME_AR_OFFSET] & FRAME_AR_BIT) != 0 + frame + .get(FRAME_AR_OFFSET) + .is_some_and(|fcf| fcf & FRAME_AR_BIT != 0) } pub(crate) fn frame_get_version(frame: &[u8]) -> u8 { - if frame.len() <= FRAME_VERSION_OFFSET { - return 0; - } - frame[FRAME_VERSION_OFFSET] & FRAME_VERSION_MASK + frame + .get(FRAME_VERSION_OFFSET) + .map_or(0, |fcf| fcf & FRAME_VERSION_MASK) } diff --git a/esp-radio/src/ieee802154/mod.rs b/esp-radio/src/ieee802154/mod.rs index 2317990fd09..47897d9b6c6 100644 --- a/esp-radio/src/ieee802154/mod.rs +++ b/esp-radio/src/ieee802154/mod.rs @@ -111,6 +111,8 @@ impl Default for Config { pub struct Ieee802154<'a> { _align: u32, transmit_buffer: [u8; FRAME_SIZE], + // Before the PHY guards, so that it drops first. + _entropy_source_guard: EntropySourceGuard, _phy_clock_guard: PhyClockGuard<'a>, _phy_init_guard: PhyInitGuard<'a>, // Fields drop in declaration order: this guard must stay last so the PHY @@ -125,10 +127,12 @@ impl<'a> Ieee802154<'a> { /// NOTE: Coexistence with Wi-Fi is currently not supported. #[instability::unstable] pub fn new(radio: IEEE802154<'a>) -> Self { - let (_phy_clock_guard, _phy_init_guard, _radio_clock_guard) = esp_ieee802154_enable(radio); + let (_entropy_source_guard, _phy_clock_guard, _phy_init_guard, _radio_clock_guard) = + esp_ieee802154_enable(radio); Self { _align: 0, transmit_buffer: [0u8; FRAME_SIZE], + _entropy_source_guard, _phy_clock_guard, _phy_init_guard, _radio_clock_guard, @@ -146,7 +150,7 @@ impl<'a> Ieee802154<'a> { set_rx_when_idle(cfg.rx_when_idle); set_tx_power(cfg.txpower); set_channel(cfg.channel); - set_cca_theshold(cfg.cca_threshold); + set_cca_threshold(cfg.cca_threshold); set_cca_mode(cfg.cca_mode); if let Some(pan_id) = cfg.pan_id { diff --git a/esp-radio/src/ieee802154/pib.rs b/esp-radio/src/ieee802154/pib.rs index 87c2a5da78c..faea16ada45 100644 --- a/esp-radio/src/ieee802154/pib.rs +++ b/esp-radio/src/ieee802154/pib.rs @@ -171,7 +171,7 @@ pub(crate) fn ieee802154_pib_set_extended_address( PIB.with(|pib| pib.ext_addr[index as usize] = address) } -pub(crate) fn ieee802154_pib_set_cca_theshold(cca_threshold: i8) { +pub(crate) fn ieee802154_pib_set_cca_threshold(cca_threshold: i8) { PIB.with(|pib| pib.cca_threshold = cca_threshold) } @@ -215,6 +215,8 @@ fn ieee802154_set_multipan_hal(pib: &Pib) { } // https://github.com/espressif/esp-idf/blob/v5.3/components/ieee802154/driver/esp_ieee802154_pib.c#L48 +// TODO: revisit how we get these values. Newer IDF reads the power table from the PHY blob +// (`bt_bb_get_tx_pwr_table`): https://github.com/espressif/esp-idf/blob/v6.1/components/ieee802154/driver/esp_ieee802154_pib.c#L76-L101 fn ieee802154_txpower_convert(txpower: i8) -> u8 { cfg_select! { esp32h2 => { @@ -223,13 +225,18 @@ fn ieee802154_txpower_convert(txpower: i8) -> u8 { const IEEE802154_TXPOWER_VALUE_MIN: i8 = -24; const IEEE802154_TXPOWER_INDEX_MIN: i8 = 0; } - any(esp32c6, esp32c5) => { + esp32h4 => { + // https://github.com/espressif/esp-idf/blob/5d36094661/components/esp_hal_ieee802154/esp32h4/include/hal/ieee802154_ll.h + const IEEE802154_TXPOWER_VALUE_MAX: i8 = 10; + const IEEE802154_TXPOWER_VALUE_MIN: i8 = -14; + const IEEE802154_TXPOWER_INDEX_MIN: i8 = 0; + } + _ => { // https://github.com/espressif/esp-idf/blob/v5.3/components/hal/esp32c6/include/hal/ieee802154_ll.h const IEEE802154_TXPOWER_VALUE_MAX: i8 = 20; const IEEE802154_TXPOWER_VALUE_MIN: i8 = -15; const IEEE802154_TXPOWER_INDEX_MIN: i8 = 3; } - _ => {} } if txpower >= IEEE802154_TXPOWER_VALUE_MAX { 15 diff --git a/esp-radio/src/ieee802154/raw.rs b/esp-radio/src/ieee802154/raw.rs index c8fff1c5860..09c18e5cc20 100644 --- a/esp-radio/src/ieee802154/raw.rs +++ b/esp-radio/src/ieee802154/raw.rs @@ -16,7 +16,7 @@ use super::{ pib::*, }; use crate::{ - radio_clocks::{clocks_ll::enable_ieee802154, deinit_radio_clocks, init_radio_clocks}, + radio_clocks::enable_ieee802154, sys::include::{ ieee802154_coex_event_t, ieee802154_coex_event_t_IEEE802154_IDLE, @@ -25,8 +25,6 @@ use crate::{ }, }; -const PHY_ENABLE_VERSION_PRINT: u8 = 1; - /// ACK receive timeout in microseconds (200ms), matching the C driver's /// `receive_ack_timeout_timer_start(200000)`. const ACK_TIMEOUT_US: u32 = 200_000; @@ -62,8 +60,6 @@ static STATE: NonReentrantMutex = NonReentrantMutex::new(IeeeState { }); unsafe extern "C" { - fn bt_bb_v2_init_cmplx(print_version: u8); // from libbtbb.a - fn bt_bb_set_zb_tx_on_delay(time: u16); // from libbtbb.a fn esp_coex_ieee802154_ack_pti_set(event: ieee802154_coex_event_t); // from ??? @@ -104,8 +100,9 @@ pub struct RawReceived { pub channel: u8, } -/// Gates off the 802.15.4 modem clocks and de-initializes the radio clocks -/// when dropped. +/// Releases what [`esp_ieee802154_enable`] took, in reverse order, when dropped: gates off the +/// 802.15.4 modem clocks, and lets go of the BT baseband and of the modem power domain - which +/// stay up for as long as another radio (BLE) holds them. /// /// Must be dropped only after the PHY guards: PHY teardown still requires the /// modem clocks. @@ -116,32 +113,71 @@ pub(crate) struct RadioClockGuard; impl Drop for RadioClockGuard { fn drop(&mut self) { enable_ieee802154(false); - deinit_radio_clocks(); + crate::btbb_disable(); + crate::release_modem_domain(); + } +} + +/// Counts the radio as a TRNG entropy source while the PHY is enabled. +/// +/// Must be dropped before the PHY guards: the count must fall before the entropy source is +/// disabled. +#[derive(Debug)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub(crate) struct EntropySourceGuard; + +impl EntropySourceGuard { + fn new() -> Self { + // The PHY enables the high-speed ADC that feeds the RNG. + #[cfg(rng_trng_supported)] + unsafe { + esp_hal::rng::TrngSource::increase_entropy_source_counter() + }; + Self + } +} + +impl Drop for EntropySourceGuard { + fn drop(&mut self) { + #[cfg(rng_trng_supported)] + esp_hal::rng::TrngSource::decrease_entropy_source_counter(unsafe { + esp_hal::Internal::conjure() + }); } } pub(crate) fn esp_ieee802154_enable( radio: IEEE802154<'_>, -) -> (PhyClockGuard<'_>, PhyInitGuard<'_>, RadioClockGuard) { - init_radio_clocks(); +) -> ( + EntropySourceGuard, + PhyClockGuard<'_>, + PhyInitGuard<'_>, + RadioClockGuard, +) { + // The modem power domain (and, with it, the modem reset) and the BT baseband are shared with + // BLE: taken here so that a BLE controller created later does not reset the MAC configured + // below, and so that the baseband is initialized once, by whichever radio comes first. + crate::acquire_modem_domain(); let phy_clock_guard = esp_phy::enable_phy_clock(); enable_ieee802154(true); let phy_init_guard = esp_phy::enable_phy(); + let entropy_source_guard = EntropySourceGuard::new(); - esp_btbb_enable(); + crate::btbb_enable(); ieee802154_mac_init(radio); info!("date={:x}", mac_date()); - (phy_clock_guard, phy_init_guard, RadioClockGuard) -} - -fn esp_btbb_enable() { - unsafe { bt_bb_v2_init_cmplx(PHY_ENABLE_VERSION_PRINT) }; + ( + entropy_source_guard, + phy_clock_guard, + phy_init_guard, + RadioClockGuard, + ) } fn ieee802154_mac_init(radio: IEEE802154<'_>) { - #[cfg(any(esp32c6, esp32c5))] + #[cfg(soc_has_wifi)] unsafe { unsafe extern "C" { static mut coex_pti_tab_ptr: u32; @@ -454,8 +490,8 @@ pub fn set_extended_address(index: u8, address: [u8; IEEE802154_FRAME_EXT_ADDR_S ieee802154_pib_set_extended_address(index, address); } -pub fn set_cca_theshold(cca_threshold: i8) { - ieee802154_pib_set_cca_theshold(cca_threshold); +pub fn set_cca_threshold(cca_threshold: i8) { + ieee802154_pib_set_cca_threshold(cca_threshold); } pub fn set_cca_mode(mode: CcaMode) { diff --git a/esp-radio/src/interrupt_dispatch.rs b/esp-radio/src/interrupt_dispatch.rs index f8eaf6214e6..e298aaaaffa 100644 --- a/esp-radio/src/interrupt_dispatch.rs +++ b/esp-radio/src/interrupt_dispatch.rs @@ -28,7 +28,10 @@ impl Handler { core::mem::transmute::<*const c_void, unsafe extern "C" fn(*mut c_void)>(f) }; let arg = self.arg.load(Ordering::Relaxed); - trace!("calling {:x} with {:x}", f as usize, arg as usize); + trace!( + "calling interrupt handler {:x} with {:x}", + f as usize, arg as usize + ); unsafe { func(arg) }; trace!("{:x} done", f as usize); } diff --git a/esp-radio/src/lib.rs b/esp-radio/src/lib.rs index ab286764801..d0e850895cf 100644 --- a/esp-radio/src/lib.rs +++ b/esp-radio/src/lib.rs @@ -44,7 +44,7 @@ //! //! // THIS IS IMPORTANT FOR WIFI AND BLE: You MUST start the scheduler //! // before initializing the radio! -//! esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); +//! esp_rtos::start(timg0.timer0); #![cfg_attr( wifi_driver_supported, doc = r#" @@ -68,7 +68,8 @@ if let Ok(controller) = BleConnector::new(peripherals.BT, Default::default()) {} //! ```toml //! [dependencies.esp-radio] //! # A supported chip needs to be specified, as well as specific use-case features -#![doc = concat!(r#"features = [""#, chip!(), r#"", "wifi", "esp-now", "esp-alloc"]"#)] +#![cfg_attr(wifi_driver_supported, doc = concat!(r#"features = [""#, chip!(), r#"", "wifi", "esp-now", "esp-alloc"]"#))] +#![cfg_attr(not(wifi_driver_supported), doc = concat!(r#"features = [""#, chip!(), r#"", "ble", "esp-alloc"]"#))] //! [dependencies.esp-rtos] #![doc = concat!(r#"features = [""#, chip!(), r#"", "esp-radio", "esp-alloc"]"#)] //! [dependencies.esp-alloc] @@ -176,8 +177,6 @@ mod coex_utils; mod fmt; pub(crate) mod reg_access; -use core::marker::PhantomData; - use esp_hal as hal; #[instability::unstable] pub use esp_phy::CalibrationResult; @@ -200,10 +199,14 @@ pub(crate) mod sys { pub use esp_wifi_sys_esp32c61::*; #[cfg(esp32h2)] pub use esp_wifi_sys_esp32h2::*; + #[cfg(esp32h4)] + pub use esp_wifi_sys_esp32h4::*; #[cfg(esp32s2)] pub use esp_wifi_sys_esp32s2::*; #[cfg(esp32s3)] pub use esp_wifi_sys_esp32s3::*; + #[cfg(esp32s31)] + pub use esp_wifi_sys_esp32s31::*; } use crate::refcount::Refcount; @@ -234,6 +237,10 @@ macro_rules! unstable_module { mod asynch; mod compat; +#[cfg(any(esp32h4, esp32s31))] +mod compiler_rt_abi; +#[cfg(any(feature = "wifi", all(feature = "ble", bt_controller = "btdm2")))] +mod drop_guard; mod interrupt_dispatch; mod radio_clocks; mod refcount; @@ -256,9 +263,6 @@ unstable_module! { pub(crate) mod common_adapter; -#[cfg(all(feature = "ble", bt_controller = "npl"))] -pub(crate) static ESP_RADIO_LOCK: esp_sync::RawMutex = esp_sync::RawMutex::new(); - // this is just to verify that we use the correct defaults in `build.rs` #[allow(clippy::assertions_on_constants)] // TODO: try assert_eq once it's usable in const context const _: () = { @@ -305,7 +309,6 @@ pub(crate) fn init() { "ADC2 is currently in use by esp-hal, but esp-radio requires it for Wi-Fi operation." ); } - esp_hal::rtc_cntl::WakeLock::acquire(); } if !preempt::initialized() { @@ -322,13 +325,7 @@ pub(crate) fn init() { ); } - // Ungate the modem clocks first: `enable_wifi_power_domain` pulses the - // modem reset, which is ineffective while the clocks are gated — and - // esp-phy's clock guard has gated them again by the time we re-init. - // (ESP-IDF never gates these clocks, so its power-up reset always lands.) - radio_clocks::init_radio_clocks(); - - crate::common_adapter::enable_wifi_power_domain(); + acquire_modem_domain(); wifi_set_log_verbose(); @@ -355,43 +352,102 @@ pub(crate) fn deinit() { ble::shutdown_ble_isr(); // Gate the BT clocks (the Wi-Fi driver gates its own clocks during - // `wifi_deinit`), power down the modem power domain, and gate the - // remaining modem clocks, mirroring ESP-IDF's fixed-mask clock control - // (`periph_ll_wifi_module_disable_clk_set_rst` and friends). This must - // only run once all radios are off: PHY teardown still needs the modem - // clocks. + // `wifi_deinit`), then let go of the modem power domain. #[cfg(feature = "ble")] - crate::radio_clocks::clocks_ll::enable_bt(false); - crate::common_adapter::disable_wifi_power_domain(); - crate::radio_clocks::deinit_radio_clocks(); - - // After the modem power domain has been powered down, the PHY driver's - // internal init flag must be reset, otherwise the next `phy_wakeup_init` - // assumes retained PHY registers that the power-down wiped (mirrors - // ESP-IDF's `esp_phy_modem_deinit`, "Fix the issue caused by the power - // domain off. This issue is only on ESP32C3."). - #[cfg(esp32c3)] - unsafe { - crate::sys::include::phy_init_flag() - }; + crate::radio_clocks::enable_bt(false); + release_modem_domain(); esp_hal::if_unstable_hal! { // Allow using `ADC2` again #[cfg(esp32)] hal::analog::adc::release_adc2(unsafe { esp_hal::Internal::conjure() }); - - esp_hal::rtc_cntl::WakeLock::release(); } debug!("Radio deinitialized"); } +/// The modem power domain, held by every radio that is up. +/// +/// Powering the domain up pulses a reset over the modem subsystems the radios share (the RF +/// frontend, the basebands and the MACs), so it must happen before the first radio initializes +/// and never again while any radio is live; powering it down gates clocks that every radio needs. +/// Hence the count: whichever radio comes up first powers the domain up, whichever goes last +/// powers it down. Wi-Fi and BLE hold it through [`RadioRefGuard`]; the IEEE 802.15.4 driver +/// holds it on its own, as it needs nothing else of [`init`] (the scheduler, coexistence). +static MODEM_DOMAIN_REFCOUNT: Refcount = Refcount::new(); + +/// Take a reference to the modem power domain, powering it up if this is the first one. +pub(crate) fn acquire_modem_domain() { + MODEM_DOMAIN_REFCOUNT.increment(|| { + // Ungate the modem clocks first: `enable_wifi_power_domain` pulses the + // modem reset, which is ineffective while the clocks are gated — and + // esp-phy's clock guard has gated them again by the time we re-init. + // (ESP-IDF never gates these clocks, so its power-up reset always lands.) + radio_clocks::init_radio_clocks(); + + crate::common_adapter::enable_wifi_power_domain(); + }); +} + +/// Release a reference to the modem power domain, powering it down if this was the last one. +pub(crate) fn release_modem_domain() { + MODEM_DOMAIN_REFCOUNT.decrement(|| { + // Power down the modem power domain and gate the remaining modem clocks, + // mirroring ESP-IDF's fixed-mask clock control + // (`periph_ll_wifi_module_disable_clk_set_rst` and friends). This must + // only run once all radios are off: PHY teardown still needs the modem + // clocks. + crate::common_adapter::disable_wifi_power_domain(); + radio_clocks::deinit_radio_clocks(); + + // After the modem power domain has been powered down, the PHY driver's + // internal init flag must be reset, otherwise the next `phy_wakeup_init` + // assumes retained PHY registers that the power-down wiped (mirrors + // ESP-IDF's `esp_phy_modem_deinit`, "Fix the issue caused by the power + // domain off. This issue is only on ESP32C3."). + #[cfg(esp32c3)] + unsafe { + crate::sys::include::phy_init_flag() + }; + }); +} + +/// The BT baseband, shared by BLE and IEEE 802.15.4. +/// +/// Whichever radio comes up first initializes it, and the one that follows leaves it alone +/// (ESP-IDF's `esp_btbb_enable`) rather than re-initializing it under the first one's feet. +/// A power-up of the modem domain resets the baseband, and no radio holds this count without +/// holding the domain, so the two counts reach zero together and the next radio re-initializes. +/// +/// The `btdm2` controller (ESP32-S31) still initializes the baseband on its own. +#[cfg(any(feature = "ieee802154", all(feature = "ble", bt_controller = "npl")))] +static BTBB_REFCOUNT: Refcount = Refcount::new(); + +/// Take a reference to the BT baseband, initializing it if this is the first one. +#[cfg(any(feature = "ieee802154", all(feature = "ble", bt_controller = "npl")))] +pub(crate) fn btbb_enable() { + unsafe extern "C" { + fn bt_bb_v2_init_cmplx(print_version: u8); // from libbtbb.a + } + + const PRINT_VERSION: u8 = 1; + + BTBB_REFCOUNT.increment(|| unsafe { bt_bb_v2_init_cmplx(PRINT_VERSION) }); +} + +/// Release a reference to the BT baseband. There is nothing to undo on the last one: the +/// baseband goes down with the modem power domain. +#[cfg(any(feature = "ieee802154", all(feature = "ble", bt_controller = "npl")))] +pub(crate) fn btbb_disable() { + BTBB_REFCOUNT.decrement(|| {}); +} + /// Management of the global reference count /// and conditional hardware initialization/deinitialization. #[derive(Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] pub(crate) struct RadioRefGuard { - _private: PhantomData<()>, + wake_lock: bool, } static RADIO_REFCOUNT: Refcount = Refcount::new(); @@ -399,13 +455,31 @@ static RADIO_REFCOUNT: Refcount = Refcount::new(); impl RadioRefGuard { /// Increments the refcount. If the old count was 0, it performs hardware init. /// If hardware init fails, it rolls back the refcount only once. - fn new() -> Self { + /// + /// The guard keeps the chip out of automatic light sleep while it exists. + #[cfg(feature = "ble")] + pub(crate) fn new() -> Self { + Self::create(true) + } + + /// Like [`Self::new`], but the chip can sleep while the guard exists. + /// + /// The driver must refuse the sleeps that are not safe for it. + #[cfg(any(feature = "ble", feature = "wifi"))] + pub(crate) fn without_wake_lock() -> Self { + Self::create(false) + } + + fn create(wake_lock: bool) -> Self { debug!("Creating RadioRefGuard"); RADIO_REFCOUNT.increment(init); - RadioRefGuard { - _private: PhantomData, + if wake_lock { + esp_hal::if_unstable_hal! { + esp_hal::rtc_cntl::WakeLock::acquire(); + } } + RadioRefGuard { wake_lock } } } @@ -415,6 +489,11 @@ impl Drop for RadioRefGuard { debug!("Dropping RadioRefGuard"); RADIO_REFCOUNT.decrement(deinit); + if self.wake_lock { + esp_hal::if_unstable_hal! { + esp_hal::rtc_cntl::WakeLock::release(); + } + } } } @@ -422,7 +501,7 @@ impl Drop for RadioRefGuard { /// Does nothing unless the `print-logs-from-driver` feature is enabled. #[instability::unstable] pub fn wifi_set_log_verbose() { - #[cfg(all(feature = "print-logs-from-driver", not(esp32h2)))] + #[cfg(all(feature = "print-logs-from-driver", not(any(esp32h2, esp32h4))))] unsafe { use crate::sys::include::{ esp_wifi_internal_set_log_level, diff --git a/esp-radio/src/radio_clocks/clocks_ll/esp32c2.rs b/esp-radio/src/radio_clocks/clocks_ll/esp32c2.rs index aa0f76f6ae9..3f30beb90de 100644 --- a/esp-radio/src/radio_clocks/clocks_ll/esp32c2.rs +++ b/esp-radio/src/radio_clocks/clocks_ll/esp32c2.rs @@ -41,29 +41,7 @@ pub(crate) fn deinit_clocks() { } pub(crate) fn ble_rtc_clk_init() { - regs!(MODEM_CLKRST).modem_lp_timer_conf().modify(|_, w| { - w.lp_timer_sel_xtal32k().clear_bit(); - w.lp_timer_sel_xtal().set_bit(); - w.lp_timer_sel_8m().clear_bit(); - w.lp_timer_sel_rtc_slow().clear_bit() - }); - - let xtal_frequency = esp_hal::clock::xtal_clock(); - let bt_lpclk_target = match xtal_frequency.as_mhz() { - 26 => 40000, - // 40MHz - _ => 32000, - }; - let divider = xtal_frequency.as_hz() / (5 * bt_lpclk_target) - 1; - - regs!(MODEM_CLKRST) - .modem_lp_timer_conf() - .modify(|_, w| unsafe { w.lp_timer_clk_div_num().bits(divider as u8) }); - - regs!(MODEM_CLKRST).etm_clk_conf().modify(|_, w| { - w.etm_clk_active().set_bit(); - w.etm_clk_sel().clear_bit() - }); + // `BLE_LP_CLK` is programmed by the clock tree. } pub(crate) fn reset_rpa() { diff --git a/esp-radio/src/radio_clocks/clocks_ll/esp32c5.rs b/esp-radio/src/radio_clocks/clocks_ll/esp32c5.rs index 33608d46e9f..1441b0dd35a 100644 --- a/esp-radio/src/radio_clocks/clocks_ll/esp32c5.rs +++ b/esp-radio/src/radio_clocks/clocks_ll/esp32c5.rs @@ -1,60 +1,58 @@ pub(crate) fn enable_wifi(en: bool) { regs!(MODEM_SYSCON).clk_conf1().modify(|_, w| { w.clk_wifi_apb_en().bit(en); - w.clk_wifibb_44m_en().bit(en); w.clk_wifimac_en().bit(en); - w.clk_fe_apb_en().bit(en); - w.clk_fe_80m_en().bit(en); - w.clk_fe_160m_en().bit(en) + + w.clk_wifibb_22m_en().bit(en); + w.clk_wifibb_40m_en().bit(en); + w.clk_wifibb_44m_en().bit(en); + w.clk_wifibb_80m_en().bit(en); + w.clk_wifibb_40x_en().bit(en); + w.clk_wifibb_80x_en().bit(en); + w.clk_wifibb_40x1_en().bit(en); + w.clk_wifibb_80x1_en().bit(en); + w.clk_wifibb_160x1_en().bit(en) }); } +pub(crate) fn enable_bt_ieee802154_common(en: bool) { + fn enable_common(en: bool) { + regs!(MODEM_SYSCON).clk_conf().modify(|r, w| { + w.clk_etm_en().bit(en); + w.clk_modem_sec_en().bit(en); + w.clk_modem_sec_ecb_en().bit(en); + w.clk_modem_sec_ccm_en().bit(en); + w.clk_modem_sec_bah_en().bit(en); + w.clk_modem_sec_apb_en().bit(en); + w.clk_ble_timer_en().bit(en) + }); + + regs!(MODEM_SYSCON).clk_conf1().modify(|_, w| { + w.clk_bt_apb_en().bit(en); + w.clk_btbb_en().bit(en); + w.clk_btmac_en().bit(en) + }); + } + + use crate::radio_clocks::Refcount; + + static REFCOUNT: Refcount = Refcount::new(); + REFCOUNT.update(en, enable_common); +} + pub(crate) fn enable_ieee802154(en: bool) { + enable_bt_ieee802154_common(en); regs!(MODEM_SYSCON).clk_conf().modify(|r, w| { - w.clk_etm_en().bit(en); w.clk_zb_apb_en().bit(en); - w.clk_zbmac_en().bit(en); - w.clk_modem_sec_en().bit(en); - w.clk_modem_sec_ecb_en().bit(en); - w.clk_modem_sec_ccm_en().bit(en); - w.clk_modem_sec_bah_en().bit(en); - w.clk_modem_sec_apb_en().bit(en); - w.clk_ble_timer_en().bit(en) - }); - - regs!(MODEM_SYSCON).clk_conf1().modify(|_, w| { - w.clk_fe_apb_en().bit(en); - w.clk_bt_apb_en().bit(en); - w.clk_btbb_en().bit(en); - w.clk_btmac_en().bit(en); - w.clk_fe_20m_en().bit(en); - w.clk_fe_40m_en().bit(en); - w.clk_fe_80m_en().bit(en); - w.clk_fe_160m_en().bit(en) + w.clk_zbmac_en().bit(en) }); } pub(crate) fn enable_bt(en: bool) { - regs!(MODEM_SYSCON).clk_conf().modify(|_, w| { - w.clk_etm_en().bit(en); - w.clk_modem_sec_en().bit(en); - w.clk_modem_sec_ecb_en().bit(en); - w.clk_modem_sec_ccm_en().bit(en); - w.clk_modem_sec_bah_en().bit(en); - w.clk_modem_sec_apb_en().bit(en); - w.clk_ble_timer_en().bit(en) - }); - - regs!(MODEM_SYSCON).clk_conf1().modify(|_, w| { - w.clk_fe_apb_en().bit(en); - w.clk_bt_apb_en().bit(en); - w.clk_btbb_en().bit(en); - w.clk_btmac_en().bit(en); - w.clk_fe_20m_en().bit(en); - w.clk_fe_40m_en().bit(en); - w.clk_fe_80m_en().bit(en); - w.clk_fe_160m_en().bit(en) - }); + enable_bt_ieee802154_common(en); + regs!(MODEM_SYSCON) + .clk_conf() + .modify(|_, w| w.clk_etm_en().bit(en)); } pub(crate) fn reset_wifi_mac() { diff --git a/esp-radio/src/radio_clocks/clocks_ll/esp32c6.rs b/esp-radio/src/radio_clocks/clocks_ll/esp32c6.rs index fe9cb47d55a..ebc4b4b0f3c 100644 --- a/esp-radio/src/radio_clocks/clocks_ll/esp32c6.rs +++ b/esp-radio/src/radio_clocks/clocks_ll/esp32c6.rs @@ -2,10 +2,6 @@ pub(crate) fn enable_wifi(en: bool) { regs!(MODEM_SYSCON).clk_conf1().modify(|_, w| { w.clk_wifi_apb_en().bit(en); w.clk_wifimac_en().bit(en); - w.clk_fe_apb_en().bit(en); - w.clk_fe_cal_160m_en().bit(en); - w.clk_fe_160m_en().bit(en); - w.clk_fe_80m_en().bit(en); w.clk_wifibb_160x1_en().bit(en); w.clk_wifibb_80x1_en().bit(en); w.clk_wifibb_40x1_en().bit(en); @@ -17,25 +13,46 @@ pub(crate) fn enable_wifi(en: bool) { w.clk_wifibb_22m_en().bit(en) }); - regs!(MODEM_LPCON).clk_conf().modify(|_, w| { - w.clk_wifipwr_en().bit(en); - w.clk_coex_en().bit(en) - }); + // `clk_wifipwr_en` stays on. The blob calls `wifi_clock_disable` at every doze, and this clock + // drives the timer that wakes the modem for the next beacon. + // + // The radios share the coexistence clock, as in ESP-IDF's `COEXIST_CLOCK_DEPS`, and the other + // radios can be active while Wi-Fi dozes. + enable_coex(en); +} + +pub(crate) fn enable_bt_ieee802154_common(en: bool) { + fn enable_common(en: bool) { + regs!(MODEM_SYSCON).clk_conf().modify(|_, w| { + w.clk_etm_en().bit(en); + w.clk_modem_sec_en().bit(en); + w.clk_modem_sec_ecb_en().bit(en); + w.clk_modem_sec_ccm_en().bit(en); + w.clk_modem_sec_bah_en().bit(en); + w.clk_modem_sec_apb_en().bit(en); + w.clk_ble_timer_en().bit(en) + }); + + regs!(MODEM_SYSCON).clk_conf1().modify(|_, w| { + w.clk_bt_apb_en().bit(en); + w.clk_bt_en().bit(en) + }); + } + + use crate::radio_clocks::Refcount; + + static REFCOUNT: Refcount = Refcount::new(); + REFCOUNT.update(en, enable_common); } pub(crate) fn enable_ieee802154(en: bool) { + enable_bt_ieee802154_common(en); regs!(MODEM_SYSCON).clk_conf().modify(|_, w| { w.clk_zb_apb_en().bit(en); w.clk_zb_mac_en().bit(en) }); regs!(MODEM_SYSCON).clk_conf1().modify(|_, w| { - w.clk_fe_apb_en().bit(en); - w.clk_fe_cal_160m_en().bit(en); - w.clk_fe_160m_en().bit(en); - w.clk_fe_80m_en().bit(en); - w.clk_bt_apb_en().bit(en); - w.clk_bt_en().bit(en); w.clk_wifibb_160x1_en().bit(en); w.clk_wifibb_80x1_en().bit(en); w.clk_wifibb_40x1_en().bit(en); @@ -47,34 +64,25 @@ pub(crate) fn enable_ieee802154(en: bool) { w.clk_wifibb_22m_en().bit(en) }); - regs!(MODEM_LPCON) - .clk_conf() - .modify(|_, w| w.clk_coex_en().bit(en)); + enable_coex(en); } pub(crate) fn enable_bt(en: bool) { - regs!(MODEM_SYSCON).clk_conf().modify(|_, w| { - w.clk_etm_en().bit(en); - w.clk_modem_sec_en().bit(en); - w.clk_modem_sec_ecb_en().bit(en); - w.clk_modem_sec_ccm_en().bit(en); - w.clk_modem_sec_bah_en().bit(en); - w.clk_modem_sec_apb_en().bit(en); - w.clk_ble_timer_en().bit(en) - }); + enable_bt_ieee802154_common(en); + enable_coex(en); +} - regs!(MODEM_SYSCON).clk_conf1().modify(|_, w| { - w.clk_fe_apb_en().bit(en); - w.clk_fe_cal_160m_en().bit(en); - w.clk_fe_160m_en().bit(en); - w.clk_fe_80m_en().bit(en); - w.clk_bt_apb_en().bit(en); - w.clk_bt_en().bit(en) - }); +fn enable_coex(en: bool) { + fn enable(en: bool) { + regs!(MODEM_LPCON) + .clk_conf() + .modify(|_, w| w.clk_coex_en().bit(en)); + } + + use crate::radio_clocks::Refcount; - regs!(MODEM_LPCON) - .clk_conf() - .modify(|_, w| w.clk_coex_en().bit(en)); + static REFCOUNT: Refcount = Refcount::new(); + REFCOUNT.update(en, enable); } pub(crate) fn reset_wifi_mac() { diff --git a/esp-radio/src/radio_clocks/clocks_ll/esp32c61.rs b/esp-radio/src/radio_clocks/clocks_ll/esp32c61.rs index bd76b088cb3..178c6c5ac49 100644 --- a/esp-radio/src/radio_clocks/clocks_ll/esp32c61.rs +++ b/esp-radio/src/radio_clocks/clocks_ll/esp32c61.rs @@ -1,11 +1,16 @@ pub(crate) fn enable_wifi(en: bool) { regs!(MODEM_SYSCON).clk_conf1().modify(|_, w| { - w.clk_wifi_apb_en().bit(en); + w.clk_wifibb_22m_en().bit(en); + w.clk_wifibb_40m_en().bit(en); w.clk_wifibb_44m_en().bit(en); - w.clk_wifimac_en().bit(en); - w.clk_fe_apb_en().bit(en); - w.clk_fe_80m_en().bit(en); - w.clk_fe_160m_en().bit(en) + w.clk_wifibb_80m_en().bit(en); + w.clk_wifibb_40x_en().bit(en); + w.clk_wifibb_80x_en().bit(en); + w.clk_wifibb_40x1_en().bit(en); + w.clk_wifibb_80x1_en().bit(en); + w.clk_wifibb_160x1_en().bit(en); + w.clk_wifi_apb_en().bit(en); + w.clk_wifimac_en().bit(en) }); } @@ -21,14 +26,9 @@ pub(crate) fn enable_bt(en: bool) { }); regs!(MODEM_SYSCON).clk_conf1().modify(|_, w| { - w.clk_fe_apb_en().bit(en); w.clk_bt_apb_en().bit(en); w.clk_btbb_en().bit(en); - w.clk_btmac_en().bit(en); - w.clk_fe_20m_en().bit(en); - w.clk_fe_40m_en().bit(en); - w.clk_fe_80m_en().bit(en); - w.clk_fe_160m_en().bit(en) + w.clk_btmac_en().bit(en) }); } diff --git a/esp-radio/src/radio_clocks/clocks_ll/esp32h2.rs b/esp-radio/src/radio_clocks/clocks_ll/esp32h2.rs index 0960c4d9a1d..c21650cd2ca 100644 --- a/esp-radio/src/radio_clocks/clocks_ll/esp32h2.rs +++ b/esp-radio/src/radio_clocks/clocks_ll/esp32h2.rs @@ -29,12 +29,21 @@ fn ble_ieee802154_clock_enable(en: bool) { .modify(|_, w| w.clk_coex_en().bit(en)); } +/// BLE and IEEE 802.15.4 run on one and the same set of clocks here, so it stays on for as long +/// as either of them is up. +fn enable_bt_ieee802154_common(en: bool) { + use crate::radio_clocks::Refcount; + + static REFCOUNT: Refcount = Refcount::new(); + REFCOUNT.update(en, ble_ieee802154_clock_enable); +} + pub(crate) fn enable_bt(en: bool) { - ble_ieee802154_clock_enable(en); + enable_bt_ieee802154_common(en); } pub(crate) fn enable_ieee802154(en: bool) { - ble_ieee802154_clock_enable(en); + enable_bt_ieee802154_common(en); } pub(crate) fn init_clocks() { diff --git a/esp-radio/src/radio_clocks/clocks_ll/esp32h4.rs b/esp-radio/src/radio_clocks/clocks_ll/esp32h4.rs new file mode 100644 index 00000000000..8f45b579f0b --- /dev/null +++ b/esp-radio/src/radio_clocks/clocks_ll/esp32h4.rs @@ -0,0 +1,104 @@ +// Clock dependencies follow ESP-IDF's `esp_hw_support/modem/port/esp32h4/modem_clock_impl.c`. + +pub(crate) fn enable_ieee802154(en: bool) { + enable_bt_ieee802154_common(en); + regs!(MODEM_SYSCON).clk_conf().modify(|_, w| { + w.clk_zb_apb_en().bit(en); + w.clk_zbmac_en().bit(en) + }); +} + +pub(crate) fn enable_bt(en: bool) { + enable_bt_ieee802154_common(en); + regs!(MODEM_SYSCON).clk_conf().modify(|_, w| { + w.clk_modem_sec_en().bit(en); + w.clk_modem_sec_ecb_en().bit(en); + w.clk_modem_sec_ccm_en().bit(en); + w.clk_modem_sec_bah_en().bit(en); + w.clk_ble_timer_en().bit(en) + }); + regs!(MODEM_SYSCON) + .clk_conf1() + .modify(|_, w| w.clk_btmac_en().bit(en)); +} + +/// The clocks that BLE and IEEE 802.15.4 share, so they stay on for as long as either of them +/// is up. +fn enable_bt_ieee802154_common(en: bool) { + fn enable_common(en: bool) { + regs!(MODEM_SYSCON).clk_conf().modify(|_, w| { + w.clk_etm_en().bit(en); + w.clk_modem_sec_apb_en().bit(en) + }); + regs!(MODEM_SYSCON).clk_conf1().modify(|_, w| { + w.clk_bt_apb_en().bit(en); + w.clk_btbb_en().bit(en) + }); + regs!(MODEM_LPCON) + .clk_conf() + .modify(|_, w| w.clk_coex_en().bit(en)); + } + + use crate::radio_clocks::Refcount; + + static REFCOUNT: Refcount = Refcount::new(); + REFCOUNT.update(en, enable_common); +} + +pub(crate) fn init_clocks() { + const ICG_NOGATING_MODEM: u8 = 1 << 1; + const ICG_NOGATING_ACTIVE: u8 = 1 << 2; + const ICG_NOGATING_ACTIVE_MODEM: u8 = ICG_NOGATING_ACTIVE | ICG_NOGATING_MODEM; + + // IDF `modem_clock_domain_icg_config`. The maps must be in place before the PMU switches to + // the codes below, or the switch gates the modem clocks. + regs!(MODEM_SYSCON) + .clk_conf_power_st() + .modify(|r, w| unsafe { + w.clk_modem_apb_st_map() + .bits(r.clk_modem_apb_st_map().bits() | ICG_NOGATING_ACTIVE_MODEM); + w.clk_modem_peri_st_map() + .bits(r.clk_modem_peri_st_map().bits() | ICG_NOGATING_ACTIVE); + w.clk_bt_st_map() + .bits(r.clk_bt_st_map().bits() | ICG_NOGATING_ACTIVE); + w.clk_fe_st_map() + .bits(r.clk_fe_st_map().bits() | ICG_NOGATING_ACTIVE_MODEM); + w.clk_zb_st_map() + .bits(r.clk_zb_st_map().bits() | ICG_NOGATING_ACTIVE) + }); + regs!(MODEM_LPCON) + .clk_conf_power_st() + .modify(|r, w| unsafe { + w.clk_lp_apb_st_map() + .bits(r.clk_lp_apb_st_map().bits() | ICG_NOGATING_ACTIVE_MODEM); + w.clk_i2c_mst_st_map() + .bits(r.clk_i2c_mst_st_map().bits() | ICG_NOGATING_ACTIVE_MODEM); + w.clk_coex_st_map() + .bits(r.clk_coex_st_map().bits() | ICG_NOGATING_ACTIVE_MODEM) + }); + + // IDF `pmu_init` defaults (`PMU_HP_*_CLOCK_CONFIG_DEFAULT` in `pmu_param.c`). + let pmu = regs!(PMU); + pmu.hp_sleep_icg_modem() + .modify(|_, w| unsafe { w.hp_sleep_dig_icg_modem_code().bits(0) }); + pmu.hp_modem_icg_modem() + .modify(|_, w| unsafe { w.hp_modem_dig_icg_modem_code().bits(1) }); + pmu.hp_active_icg_modem() + .modify(|_, w| unsafe { w.hp_active_dig_icg_modem_code().bits(2) }); + pmu.imm_modem_icg() + .write(|w| w.update_dig_icg_modem_en().set_bit()); + pmu.imm_sleep_sysclk() + .write(|w| w.update_dig_icg_switch().set_bit()); +} + +pub(crate) fn deinit_clocks() { + // IDF sets the ICG configuration once and keeps it. +} + +pub(crate) fn ble_rtc_clk_init() { + // `BLE_LP_CLK` is programmed by the clock tree. +} + +pub(crate) fn reset_rpa() { + // nothing for this target (yet) +} diff --git a/esp-radio/src/radio_clocks/clocks_ll/esp32s2.rs b/esp-radio/src/radio_clocks/clocks_ll/esp32s2.rs index 52749c172cf..91cbaf4d4c0 100644 --- a/esp-radio/src/radio_clocks/clocks_ll/esp32s2.rs +++ b/esp-radio/src/radio_clocks/clocks_ll/esp32s2.rs @@ -41,6 +41,17 @@ pub(crate) fn init_clocks() { regs!(SYSCON) .wifi_clk_en() .modify(|r, w| unsafe { w.bits(r.bits() & !WIFI_BT_SDIO_CLK | DPORT_WIFI_CLK_WIFI_EN) }); + + // The Wi-Fi light sleep clock: the RTC slow clock, undivided. The divider resets to 255. + regs!(SYSTEM) + .lpck_div_int() + .modify(|_, w| unsafe { w.lpck_div_num().bits(0) }); + regs!(SYSTEM).bt_lpck_div_frac().modify(|_, w| { + w.lpclk_sel_xtal32k().clear_bit(); + w.lpclk_sel_xtal().clear_bit(); + w.lpclk_sel_8m().clear_bit(); + w.lpclk_sel_rtc_slow().set_bit() + }); } pub(crate) fn deinit_clocks() { diff --git a/esp-radio/src/radio_clocks/clocks_ll/esp32s31.rs b/esp-radio/src/radio_clocks/clocks_ll/esp32s31.rs new file mode 100644 index 00000000000..ad12319ed43 --- /dev/null +++ b/esp-radio/src/radio_clocks/clocks_ll/esp32s31.rs @@ -0,0 +1,112 @@ +pub(crate) fn enable_wifi(en: bool) { + regs!(MODEM_SYSCON) + .clk_conf1() + .modify(|_, w| w.clk_wifimac_en().bit(en)); + + // The radios share the coexistence clock, as in ESP-IDF's `COEXIST_CLOCK_DEPS`, and the other + // radios can be active while Wi-Fi dozes. + enable_coex(en); +} + +pub(crate) fn enable_ieee802154(en: bool) { + enable_bt_ieee802154_common(en); + regs!(MODEM_SYSCON).clk_conf().modify(|_, w| { + w.clk_zb_apb_en().bit(en); + w.clk_zbmac_en().bit(en) + }); + enable_coex(en); +} + +fn enable_coex(en: bool) { + fn enable(en: bool) { + regs!(MODEM_LPCON) + .clk_conf() + .modify(|_, w| w.clk_coex_en().bit(en)); + } + + use crate::radio_clocks::Refcount; + + static REFCOUNT: Refcount = Refcount::new(); + REFCOUNT.update(en, enable); +} + +pub(crate) fn enable_bt_ieee802154_common(en: bool) { + fn enable_common(en: bool) { + regs!(MODEM_SYSCON).clk_conf().modify(|_, w| { + w.clk_etm_en().bit(en); + w.clk_modem_sec_en().bit(en); + w.clk_modem_sec_ecb_en().bit(en); + w.clk_modem_sec_ccm_en().bit(en); + w.clk_modem_sec_bah_en().bit(en); + w.clk_modem_sec_apb_en().bit(en); + w.clk_ble_timer_en().bit(en) + }); + + regs!(MODEM_SYSCON).clk_conf1().modify(|_, w| { + w.clk_bt_apb_en().bit(en); + w.clk_btbb_en().bit(en); + w.clk_btmac_en().bit(en) + }); + } + + use crate::radio_clocks::Refcount; + + static REFCOUNT: Refcount = Refcount::new(); + REFCOUNT.update(en, enable_common); +} + +pub(crate) fn enable_bt(en: bool) { + if en { + ble_rtc_clk_init(); + // IDF `trng_ll_enable` / `bootloader_random_enable`. Advertising + // enable is the first `ble_ll_rand()`; that path busy-waits on + // HW samples. S31 CONF.sample_enable is off at reset. + enable_trng(); + } + + enable_bt_ieee802154_common(en); + enable_coex(en); +} + +/// IDF `hal/esp32s31/include/hal/trng_ll.h` `trng_ll_enable`. +fn enable_trng() { + regs!(LP_PERICLKRST) + .rng_ctrl() + .modify(|_, w| w.lp_rng_clk_en().set_bit()); + regs!(LP_PERICLKRST) + .rng_ctrl() + .modify(|_, w| w.lp_rng_rst_en().set_bit()); + regs!(LP_PERICLKRST) + .rng_ctrl() + .modify(|_, w| w.lp_rng_rst_en().clear_bit()); + regs!(TRNG).date().modify(|_, w| w.clk_en().set_bit()); + regs!(TRNG).conf().modify(|_, w| { + w.sample_enable().set_bit(); + w.noise_crc_en().set_bit() + }); +} + +pub(crate) fn reset_wifi_mac() { + regs!(MODEM_SYSCON) + .modem_rst_conf() + .modify(|_, w| w.rst_wifimac().set_bit()); + regs!(MODEM_SYSCON) + .modem_rst_conf() + .modify(|_, w| w.rst_wifimac().clear_bit()); +} + +pub(crate) fn init_clocks() { + // done in esp-hal +} + +pub(crate) fn deinit_clocks() { + // nothing to do, `init_clocks` is a no-op +} + +pub(crate) fn ble_rtc_clk_init() { + // `BLE_LP_CLK` is programmed by the clock tree. +} + +pub(crate) fn reset_rpa() { + // nothing for this target (yet) +} diff --git a/esp-radio/src/radio_clocks/mod.rs b/esp-radio/src/radio_clocks/mod.rs index 370968f47b3..7a45715d6b6 100644 --- a/esp-radio/src/radio_clocks/mod.rs +++ b/esp-radio/src/radio_clocks/mod.rs @@ -1,3 +1,5 @@ +use esp_sync::NonReentrantMutex; + #[cfg_attr(esp32, path = "clocks_ll/esp32.rs")] #[cfg_attr(esp32c2, path = "clocks_ll/esp32c2.rs")] #[cfg_attr(esp32c3, path = "clocks_ll/esp32c3.rs")] @@ -5,8 +7,10 @@ #[cfg_attr(esp32c6, path = "clocks_ll/esp32c6.rs")] #[cfg_attr(esp32c61, path = "clocks_ll/esp32c61.rs")] #[cfg_attr(esp32h2, path = "clocks_ll/esp32h2.rs")] +#[cfg_attr(esp32h4, path = "clocks_ll/esp32h4.rs")] #[cfg_attr(esp32s2, path = "clocks_ll/esp32s2.rs")] #[cfg_attr(esp32s3, path = "clocks_ll/esp32s3.rs")] +#[cfg_attr(esp32s31, path = "clocks_ll/esp32s31.rs")] #[allow(unused)] pub(crate) mod clocks_ll; @@ -22,3 +26,55 @@ pub(crate) fn init_radio_clocks() { pub(crate) fn deinit_radio_clocks() { clocks_ll::deinit_clocks(); } + +// TODO: radio clocks should be modelled to some extent + +struct Refcount { + count: NonReentrantMutex, +} + +impl Refcount { + const fn new() -> Self { + Self { + count: NonReentrantMutex::new(0), + } + } + + fn update(&self, en: bool, f: fn(bool)) { + self.count.with(|refcount| { + let count = *refcount; + + let run = if en { + *refcount = unwrap!(count.checked_add(1), "Clock ref count overflowed."); + count == 0 + } else { + // Asymmetric because currently we may disable clocks more times than we enable them + // (e.g. radio deinit turns off BLE even if it wasn't enabled.). + *refcount = count.saturating_sub(1); + count == 1 + }; + + if run { + f(en); + } + }); + } +} + +#[cfg(feature = "wifi")] +pub(crate) fn enable_wifi(en: bool) { + static REFCOUNT: Refcount = Refcount::new(); + REFCOUNT.update(en, clocks_ll::enable_wifi); +} + +#[cfg(feature = "ble")] +pub(crate) fn enable_bt(en: bool) { + static REFCOUNT: Refcount = Refcount::new(); + REFCOUNT.update(en, clocks_ll::enable_bt); +} + +#[cfg(feature = "ieee802154")] +pub(crate) fn enable_ieee802154(en: bool) { + static REFCOUNT: Refcount = Refcount::new(); + REFCOUNT.update(en, clocks_ll::enable_ieee802154); +} diff --git a/esp-radio/src/refcount.rs b/esp-radio/src/refcount.rs index 846bb9aab4f..bbd02c2680b 100644 --- a/esp-radio/src/refcount.rs +++ b/esp-radio/src/refcount.rs @@ -33,6 +33,34 @@ impl Refcount { } } + #[cfg(feature = "wifi")] + pub fn try_increment(&self, on_first: impl FnOnce() -> Result<(), E>) -> Result { + loop { + let op = self + .0 + .fetch_update(Ordering::Release, Ordering::Acquire, |old| { + if old == 1 { None } else { Some(old + 1) } + }); + + match op { + Ok(0) => { + return match on_first() { + Ok(()) => { + self.0.store(2, Ordering::Release); + Ok(true) + } + Err(e) => { + self.0.store(0, Ordering::Release); + Err(e) + } + }; + } + Ok(_) => return Ok(false), + Err(_) => {} + } + } + } + pub fn decrement(&self, on_last: impl FnOnce()) { loop { let op = self diff --git a/esp-radio/src/reg_access.rs b/esp-radio/src/reg_access.rs index 5f073260dcc..b7f9d2fb633 100644 --- a/esp-radio/src/reg_access.rs +++ b/esp-radio/src/reg_access.rs @@ -17,10 +17,14 @@ pub(crate) use esp32c6 as pac; pub(crate) use esp32c61 as pac; #[cfg(esp32h2)] pub(crate) use esp32h2 as pac; +#[cfg(esp32h4)] +pub(crate) use esp32h4 as pac; #[cfg(esp32s2)] pub(crate) use esp32s2 as pac; #[cfg(esp32s3)] pub(crate) use esp32s3 as pac; +#[cfg(esp32s31)] +pub(crate) use esp32s31 as pac; /// Get a peripheral register block reference from the PAC. macro_rules! regs { diff --git a/esp-radio/src/time.rs b/esp-radio/src/time.rs index 78183fc6548..a9fa85ceb77 100644 --- a/esp-radio/src/time.rs +++ b/esp-radio/src/time.rs @@ -4,18 +4,22 @@ #![allow(unused)] +#[inline(always)] pub(crate) const fn blob_ticks_to_micros(ticks: u32) -> u32 { ticks.saturating_mul(1_000) } +#[inline(always)] pub(crate) const fn micros_to_blob_ticks(micros: u32) -> u32 { micros / 1_000 } +#[inline(always)] pub(crate) const fn blob_ticks_to_millis(ticks: u32) -> u32 { ticks } +#[inline(always)] pub(crate) const fn millis_to_blob_ticks(millis: u32) -> u32 { millis } diff --git a/esp-radio/src/wifi/ap.rs b/esp-radio/src/wifi/ap.rs index e0300685e3d..1de01489b0a 100644 --- a/esp-radio/src/wifi/ap.rs +++ b/esp-radio/src/wifi/ap.rs @@ -2,33 +2,8 @@ use procmacros::BuilderLite; -#[cfg(feature = "unstable")] -use super::CountryInfo; -use super::{AuthenticationMethod, DisconnectReason, Protocols, SecondaryChannel, Ssid}; -use crate::{WifiError, sys::include::wifi_ap_record_t, wifi::AuthenticationMethodConfig}; - -/// Information about a detected Wi-Fi access point. -#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "defmt", derive(defmt::Format))] -#[non_exhaustive] -pub struct AccessPointInfo { - /// The SSID of the access point. - pub ssid: Ssid, - /// The BSSID (MAC address) of the access point. - pub bssid: [u8; 6], - /// The channel the access point is operating on. - pub channel: u8, - /// The secondary channel configuration of the access point. - pub secondary_channel: SecondaryChannel, - /// The signal strength of the access point (RSSI). - pub signal_strength: i8, - /// The authentication method used by the access point. - pub auth_method: Option, - #[cfg(feature = "unstable")] - #[cfg_attr(docsrs, doc(cfg(feature = "unstable")))] - /// The country information of the access point (if available from beacon frames). - pub country: Option, -} +use super::{DisconnectReason, Protocols, SecondaryChannel, Ssid}; +use crate::{WifiError, wifi::AuthenticationMethodConfig}; /// Configuration for a Wi-Fi access point. #[derive(Clone, PartialEq, Eq, BuilderLite, Hash, Debug)] @@ -39,6 +14,10 @@ pub struct AccessPointConfig { /// Whether the SSID is hidden or visible. pub(crate) ssid_hidden: bool, /// The channel the access point will operate on. + /// + /// The channel must be allowed in the configured country (see + /// [`ControllerConfig`](super::ControllerConfig)). Applying the configuration fails with + /// [`WifiError::InvalidArguments`] if the channel is not allowed. pub(crate) channel: u8, /// The secondary channel configuration. pub(crate) secondary_channel: Option, @@ -137,23 +116,3 @@ pub enum EventInfo { /// Information about a station disconnected from the access point. Disconnected(DisconnectedInfo), } - -#[allow(non_upper_case_globals)] -pub(crate) fn convert_ap_info(record: &wifi_ap_record_t) -> AccessPointInfo { - // `record.ssid` is 33 bytes to always fit the NUL terminator of a - // maximum-length SSID - clamp to 32 in case the driver ever hands us one - // without it. - let str_len = record.ssid.iter().position(|&c| c == 0).unwrap_or(32); - let ssid = Ssid::try_from(&record.ssid[..str_len]).expect("SSID length is valid"); - - AccessPointInfo { - ssid, - bssid: record.bssid, - channel: record.primary, - secondary_channel: SecondaryChannel::from_raw(record.second), - signal_strength: record.rssi, - auth_method: Some(AuthenticationMethod::from_raw(record.authmode)), - #[cfg(feature = "unstable")] - country: CountryInfo::try_from_c(&record.country), - } -} diff --git a/esp-radio/src/wifi/event.rs b/esp-radio/src/wifi/event.rs index 58d86495506..a997da08895 100644 --- a/esp-radio/src/wifi/event.rs +++ b/esp-radio/src/wifi/event.rs @@ -68,7 +68,7 @@ pub enum WifiEvent { /// Received report of Fine-Timing-Measurement procedure. FineTimingMeasurementReport, - /// Station Receive-Signal-Strenght-Indicator goes below the configured threshold. + /// Station Receive-Signal-Strength-Indicator goes below the configured threshold. StationBasicServiceSetReceivedSignalStrengthIndicatorLow, /// Status indication of Action Transmission operation. ActionTransmissionStatus, @@ -255,7 +255,6 @@ impl_wifi_event!( AccessPointCredential, wifi_event_sta_wps_er_success_t__bindgen_ty_1 ); -impl_wifi_event!(FineTimingMeasurementReportEntry, wifi_ftm_report_entry_t); impl AccessPointStationConnected<'_> { /// Get the MAC address of the connected station. @@ -419,43 +418,6 @@ impl StationWifiProtectedStatusEnrolleePin<'_> { } } -impl FineTimingMeasurementReportEntry<'_> { - /// Gets the Dialog Token of the FTM frame. - pub fn dialog_token(&self) -> u8 { - self.0.dlog_token - } - - /// Gets the Received Signal Strength Indicator (RSSI) of the FTM frame. - pub fn rssi(&self) -> i8 { - self.0.rssi - } - - /// Gets the Round Trip Time (RTT) in picoseconds. - pub fn rtt(&self) -> u32 { - self.0.rtt - } - - /// Gets T1: Time of departure of the FTM frame from the Responder (in picoseconds). - pub fn t1(&self) -> u64 { - self.0.t1 - } - - /// Gets T2: Time of arrival of the FTM frame at the Initiator (in picoseconds). - pub fn t2(&self) -> u64 { - self.0.t2 - } - - /// Gets T3: Time of departure of the ACK from the Initiator (in picoseconds). - pub fn t3(&self) -> u64 { - self.0.t3 - } - - /// Gets T4: Time of arrival of the ACK at the Responder (in picoseconds). - pub fn t4(&self) -> u64 { - self.0.t4 - } -} - impl FineTimingMeasurementReport<'_> { /// Get the MAC address of the FTM peer. pub fn peer_mac(&self) -> &[u8] { @@ -488,20 +450,55 @@ impl FineTimingMeasurementReport<'_> { } /// Returns an iterator over the detailed FTM report entries. - pub fn entries(&self) -> impl Iterator> + '_ { - let ptr = self.0.ftm_report_data; + /// + /// Entries are copied via `esp_wifi_ftm_get_report`, which frees the + /// driver's report. The first fetch (including [`EventInfo`] construction) + /// consumes it; later calls return an empty iterator. The iterator is also + /// empty if there are no entries or if the driver fails to copy them. + pub fn entries(&self) -> impl Iterator { + self.load_entries().into_iter() + } + + fn load_entries(&self) -> alloc::vec::Vec { let len = self.0.ftm_report_num_entries as usize; + if len == 0 { + return alloc::vec::Vec::new(); + } - // Return an empty slice when there are no entries. - let entries_slice = if ptr.is_null() || len == 0 { - &[] - } else { - // Otherwise, it's the slice from the data. - // Can we trust the C API to provide a valid pointer and length? - unsafe { core::slice::from_raw_parts(ptr, len) } - }; + let mut buf = alloc::vec![ + crate::sys::include::wifi_ftm_report_entry_t { + dlog_token: 0, + rssi: 0, + rtt: 0, + t1: 0, + t2: 0, + t3: 0, + t4: 0, + ppm: 0, + }; + len + ]; + + // Frees the driver's report; a later call cannot retrieve the same entries. + let rc = + unsafe { crate::sys::include::esp_wifi_ftm_get_report(buf.as_mut_ptr(), len as u8) }; + if rc != 0 { + warn!("esp_wifi_ftm_get_report failed: {}", rc); + return alloc::vec::Vec::new(); + } - entries_slice.iter().map(FineTimingMeasurementReportEntry) + buf.into_iter() + .map(|entry| FineTimingMeasurementReportInfo { + dlog_token: entry.dlog_token, + rssi: entry.rssi, + rtt: entry.rtt, + t1: entry.t1, + t2: entry.t2, + t3: entry.t3, + t4: entry.t4, + ppm: entry.ppm, + }) + .collect() } } @@ -655,8 +652,8 @@ impl NeighborAwarenessNetworkingReceive<'_> { } /// Get Peer Service Info. - pub fn peer_svc_info(&self) -> &[u8; 64] { - &self.0.peer_svc_info + pub fn peer_svc_info(&self) -> &[u8] { + unsafe { self.0.ssi.as_slice(self.0.ssi_len as usize) } } } @@ -682,8 +679,8 @@ impl NeighborDiscoveryProtocolIndication<'_> { } /// Get Service Specific Info. - pub fn svc_info(&self) -> &[u8; 64] { - &self.0.svc_info + pub fn svc_info(&self) -> &[u8] { + unsafe { self.0.ssi.as_slice(self.0.ssi_len as usize) } } } @@ -714,8 +711,8 @@ impl NeighborDiscoveryProtocolConfirmation<'_> { } /// Get Service Specific Info. - pub fn svc_info(&self) -> &[u8; 64] { - &self.0.svc_info + pub fn svc_info(&self) -> &[u8] { + unsafe { self.0.ssi.as_slice(self.0.ssi_len as usize) } } } @@ -761,7 +758,7 @@ impl HomeChannelChange<'_> { impl StationNeighborRep<'_> { /// Get the Neighbor Report received from the access point. pub fn report(&self) -> &[u8] { - &self.0.report[..self.0.report_len as usize] + unsafe { self.0.n_report.as_slice(self.0.report_len as usize) } } /// Get the length of report. @@ -789,6 +786,8 @@ pub struct FineTimingMeasurementReportInfo { pub t3: u64, /// Time of arrival of ACK at FTM Responder in pSec pub t4: u64, + /// Clock frequency offset in parts per million between local and peer device + pub ppm: i16, } /// Credential info record. @@ -953,7 +952,7 @@ pub enum EventInfo { entries: Collection, }, - /// Station Receive-Signal-Strenght-Indicator goes below the configured threshold. + /// Station Receive-Signal-Strength-Indicator goes below the configured threshold. StationBasicServiceSetReceivedSignalStrengthIndicatorLow { /// RSSI value of bss rssi: i8, @@ -1178,18 +1177,7 @@ impl EventInfo { rtt_raw: ev.rtt_raw(), rtt_est: ev.rtt_est(), dist_est: ev.dist_est(), - entries: Collection(ev - .entries() - .map(|entry| FineTimingMeasurementReportInfo { - dlog_token: entry.dialog_token(), - rssi: entry.rssi(), - rtt: entry.rtt(), - t1: entry.t1(), - t2: entry.t2(), - t3: entry.t3(), - t4: entry.t4(), - }) - .collect()), + entries: Collection(ev.entries().collect()), }) } WifiEvent::StationBasicServiceSetReceivedSignalStrengthIndicatorLow => { diff --git a/esp-radio/src/wifi/ftm_calibration.rs b/esp-radio/src/wifi/ftm_calibration.rs new file mode 100644 index 00000000000..7935fcccf7c --- /dev/null +++ b/esp-radio/src/wifi/ftm_calibration.rs @@ -0,0 +1,271 @@ +//! FTM PHY compensation constants used by the Wi-Fi blob. +//! +//! Values come from ESP-IDF `esp_private/ftm_calibration_data.h` / `ftm_load_calibration.c`. + +#![allow(non_upper_case_globals)] + +macro_rules! ftm_u16 { + ($($name:ident = $val:expr;)*) => { + $( + #[unsafe(no_mangle)] + #[used] + pub static mut $name: u16 = $val; + )* + }; +} + +#[cfg(esp32s2)] +mod values { + pub const I_20_20U: u16 = 367; + pub const R_20_20U: u16 = 366; + pub const I_20_20D: u16 = 374; + pub const R_20_20D: u16 = 359; + pub const I_20_20U_DIS: u16 = 364; + pub const I_20_20D_DIS: u16 = 373; + pub const R_20_20U_DIS: u16 = 366; + pub const R_20_20D_DIS: u16 = 359; + pub const I_20_40U: u16 = 229; + pub const R_20_40U: u16 = 363; + pub const I_20_40D: u16 = 234; + pub const R_20_40D: u16 = 356; + pub const I_20_40U_DIS: u16 = 221; + pub const R_20_40U_DIS: u16 = 222; + pub const I_20_40D_DIS: u16 = 228; + pub const R_20_40D_DIS: u16 = 216; + pub const I_40_40U: u16 = 403; + pub const R_40_40U: u16 = 42; + pub const I_40_40D: u16 = 403; + pub const R_40_40D: u16 = 41; + pub const I_40_40U_DIS: u16 = 403; + pub const R_40_40U_DIS: u16 = 42; + pub const I_40_40D_DIS: u16 = 402; + pub const R_40_40D_DIS: u16 = 41; +} + +#[cfg(esp32c3)] +mod values { + pub const I_20_20U: u16 = 451; + pub const R_20_20U: u16 = 439; + pub const I_20_20D: u16 = 454; + pub const R_20_20D: u16 = 431; + pub const I_20_20U_DIS: u16 = 448; + pub const I_20_20D_DIS: u16 = 455; + pub const R_20_20U_DIS: u16 = 441; + pub const R_20_20D_DIS: u16 = 433; + pub const I_20_40U: u16 = 260; + pub const R_20_40U: u16 = 252; + pub const I_20_40D: u16 = 268; + pub const R_20_40D: u16 = 247; + pub const I_20_40U_DIS: u16 = 267; + pub const R_20_40U_DIS: u16 = 259; + pub const I_20_40D_DIS: u16 = 270; + pub const R_20_40D_DIS: u16 = 250; + pub const I_40_40U: u16 = 443; + pub const R_40_40U: u16 = 82; + pub const I_40_40D: u16 = 440; + pub const R_40_40D: u16 = 80; + pub const I_40_40U_DIS: u16 = 439; + pub const R_40_40U_DIS: u16 = 86; + pub const I_40_40D_DIS: u16 = 440; + pub const R_40_40D_DIS: u16 = 81; +} + +#[cfg(esp32c2)] +mod values { + pub const I_20_20U: u16 = 443; + pub const R_20_20U: u16 = 441; + pub const I_20_20D: u16 = 451; + pub const R_20_20D: u16 = 432; + pub const I_20_20U_DIS: u16 = 443; + pub const I_20_20D_DIS: u16 = 452; + pub const R_20_20U_DIS: u16 = 441; + pub const R_20_20D_DIS: u16 = 432; +} + +#[cfg(esp32s3)] +mod values { + pub const I_20_20U: u16 = 453; + pub const R_20_20U: u16 = 444; + pub const I_20_20D: u16 = 453; + pub const R_20_20D: u16 = 440; + pub const I_20_20U_DIS: u16 = 453; + pub const I_20_20D_DIS: u16 = 454; + pub const R_20_20U_DIS: u16 = 444; + pub const R_20_20D_DIS: u16 = 440; + pub const I_20_40U: u16 = 271; + pub const R_20_40U: u16 = 262; + pub const I_20_40D: u16 = 270; + pub const R_20_40D: u16 = 261; + pub const I_20_40U_DIS: u16 = 269; + pub const R_20_40U_DIS: u16 = 262; + pub const I_20_40D_DIS: u16 = 270; + pub const R_20_40D_DIS: u16 = 258; + pub const I_40_40U: u16 = 443; + pub const R_40_40U: u16 = 88; + pub const I_40_40D: u16 = 443; + pub const R_40_40D: u16 = 84; + pub const I_40_40U_DIS: u16 = 442; + pub const R_40_40U_DIS: u16 = 89; + pub const I_40_40D_DIS: u16 = 445; + pub const R_40_40D_DIS: u16 = 82; +} + +#[cfg(esp32c6)] +mod values { + pub const I_20_20U: u16 = 704; + pub const R_20_20U: u16 = 714; + pub const I_20_20D: u16 = 707; + pub const R_20_20D: u16 = 712; + pub const I_20_20U_DIS: u16 = 711; + pub const I_20_20D_DIS: u16 = 717; + pub const R_20_20U_DIS: u16 = 706; + pub const R_20_20D_DIS: u16 = 702; + pub const I_20_40U: u16 = 601; + pub const R_20_40U: u16 = 609; + pub const I_20_40D: u16 = 605; + pub const R_20_40D: u16 = 608; + pub const I_20_40U_DIS: u16 = 610; + pub const R_20_40U_DIS: u16 = 614; + pub const I_20_40D_DIS: u16 = 616; + pub const R_20_40D_DIS: u16 = 611; + pub const I_40_40U: u16 = 786; + pub const R_40_40U: u16 = 436; + pub const I_40_40D: u16 = 791; + pub const R_40_40D: u16 = 436; + pub const I_40_40U_DIS: u16 = 786; + pub const R_40_40U_DIS: u16 = 436; + pub const I_40_40D_DIS: u16 = 794; + pub const R_40_40D_DIS: u16 = 433; +} + +#[cfg(esp32c61)] +mod values { + pub const I_20_20U: u16 = 854; + pub const R_20_20U: u16 = 869; + pub const I_20_20D: u16 = 857; + pub const R_20_20D: u16 = 864; + pub const I_20_20U_DIS: u16 = 854; + pub const I_20_20D_DIS: u16 = 857; + pub const R_20_20U_DIS: u16 = 869; + pub const R_20_20D_DIS: u16 = 864; + pub const I_20_40U: u16 = 739; + pub const R_20_40U: u16 = 753; + pub const I_20_40D: u16 = 740; + pub const R_20_40D: u16 = 747; + pub const I_20_40U_DIS: u16 = 739; + pub const R_20_40U_DIS: u16 = 753; + pub const I_20_40D_DIS: u16 = 740; + pub const R_20_40D_DIS: u16 = 747; + pub const I_40_40U: u16 = 922; + pub const R_40_40U: u16 = 582; + pub const I_40_40D: u16 = 932; + pub const R_40_40D: u16 = 572; + pub const I_40_40U_DIS: u16 = 922; + pub const R_40_40U_DIS: u16 = 592; + pub const I_40_40D_DIS: u16 = 932; + pub const R_40_40D_DIS: u16 = 572; +} + +#[cfg(esp32s31)] +mod values { + // IDF `ftm_calibration_data.h` ESP32-S31 values (marked dummy in IDF). + pub const I_20_20U: u16 = 437; + pub const R_20_20U: u16 = 426; + pub const I_20_20D: u16 = 443; + pub const R_20_20D: u16 = 420; + pub const I_20_20U_DIS: u16 = 433; + pub const I_20_20D_DIS: u16 = 442; + pub const R_20_20U_DIS: u16 = 429; + pub const R_20_20D_DIS: u16 = 421; + pub const I_20_40U: u16 = 462; + pub const R_20_40U: u16 = 425; + pub const I_20_40D: u16 = 438; + pub const R_20_40D: u16 = 420; + pub const I_20_40U_DIS: u16 = 433; + pub const R_20_40U_DIS: u16 = 430; + pub const I_20_40D_DIS: u16 = 442; + pub const R_20_40D_DIS: u16 = 420; + pub const I_40_40U: u16 = 237; + pub const R_40_40U: u16 = 626; + pub const I_40_40D: u16 = 234; + pub const R_40_40D: u16 = 629; + pub const I_40_40U_DIS: u16 = 237; + pub const R_40_40U_DIS: u16 = 626; + pub const I_40_40D_DIS: u16 = 234; + pub const R_40_40D_DIS: u16 = 629; +} + +#[cfg(esp32c5)] +mod values { + pub const I_20_20U: u16 = 931; + pub const R_20_20U: u16 = 972; + pub const I_20_20D: u16 = 937; + pub const R_20_20D: u16 = 918; + pub const I_20_20U_DIS: u16 = 972; + pub const I_20_20D_DIS: u16 = 937; + pub const R_20_20U_DIS: u16 = 974; + pub const R_20_20D_DIS: u16 = 918; + pub const I_20_40U: u16 = 817; + pub const R_20_40U: u16 = 815; + pub const I_20_40D: u16 = 822; + pub const R_20_40D: u16 = 833; + pub const I_20_40U_DIS: u16 = 812; + pub const R_20_40U_DIS: u16 = 808; + pub const I_20_40D_DIS: u16 = 822; + pub const R_20_40D_DIS: u16 = 807; + pub const I_40_40U: u16 = 988; + pub const R_40_40U: u16 = 640; + pub const I_40_40D: u16 = 993; + pub const R_40_40D: u16 = 629; + pub const I_40_40U_DIS: u16 = 988; + pub const R_40_40U_DIS: u16 = 640; + pub const I_40_40D_DIS: u16 = 993; + pub const R_40_40D_DIS: u16 = 629; +} + +ftm_u16! { + est_PHY_INIT_FTM_COMP_20_20U_MHZ = values::I_20_20U; + est_PHY_RESP_FTM_COMP_20_20U_MHZ = values::R_20_20U; + est_PHY_INIT_FTM_COMP_20_20D_MHZ = values::I_20_20D; + est_PHY_RESP_FTM_COMP_20_20D_MHZ = values::R_20_20D; + est_PHY_INIT_FTM_COMP_20_20U_MHZ_DIS = values::I_20_20U_DIS; + est_PHY_INIT_FTM_COMP_20_20D_MHZ_DIS = values::I_20_20D_DIS; + est_PHY_RESP_FTM_COMP_20_20U_MHZ_DIS = values::R_20_20U_DIS; + est_PHY_RESP_FTM_COMP_20_20D_MHZ_DIS = values::R_20_20D_DIS; +} + +#[cfg(not(esp32c2))] +ftm_u16! { + est_PHY_INIT_FTM_COMP_40_40U_MHZ = values::I_40_40U; + est_PHY_RESP_FTM_COMP_40_40U_MHZ = values::R_40_40U; + est_PHY_INIT_FTM_COMP_40_40D_MHZ = values::I_40_40D; + est_PHY_RESP_FTM_COMP_40_40D_MHZ = values::R_40_40D; + est_PHY_INIT_FTM_COMP_20_40U_MHZ = values::I_20_40U; + est_PHY_RESP_FTM_COMP_20_40U_MHZ = values::R_20_40U; + est_PHY_INIT_FTM_COMP_20_40D_MHZ = values::I_20_40D; + est_PHY_RESP_FTM_COMP_20_40D_MHZ = values::R_20_40D; + est_PHY_INIT_FTM_COMP_20_40U_MHZ_DIS = values::I_20_40U_DIS; + est_PHY_RESP_FTM_COMP_20_40U_MHZ_DIS = values::R_20_40U_DIS; + est_PHY_INIT_FTM_COMP_20_40D_MHZ_DIS = values::I_20_40D_DIS; + est_PHY_RESP_FTM_COMP_20_40D_MHZ_DIS = values::R_20_40D_DIS; + est_PHY_INIT_FTM_COMP_40_40U_MHZ_DIS = values::I_40_40U_DIS; + est_PHY_RESP_FTM_COMP_40_40U_MHZ_DIS = values::R_40_40U_DIS; + est_PHY_INIT_FTM_COMP_40_40D_MHZ_DIS = values::I_40_40D_DIS; + est_PHY_RESP_FTM_COMP_40_40D_MHZ_DIS = values::R_40_40D_DIS; +} + +#[cfg(esp32c5)] +ftm_u16! { + est_PHY_INIT_FTM_COMP_20_20_MHZ_5G = 975; + est_PHY_INIT_FTM_COMP_20_20_MHZ_5G_DIS = 976; + est_PHY_RESP_FTM_COMP_20_20_MHZ_5G = 966; + est_PHY_RESP_FTM_COMP_20_20_MHZ_5G_DIS = 966; + est_PHY_INIT_FTM_COMP_20_40_MHZ_5G = 798; + est_PHY_INIT_FTM_COMP_20_40_MHZ_5G_DIS = 840; + est_PHY_RESP_FTM_COMP_20_40_MHZ_5G = 966; + est_PHY_RESP_FTM_COMP_20_40_MHZ_5G_DIS = 828; + est_PHY_INIT_FTM_COMP_40_40_MHZ_5G = 825; + est_PHY_INIT_FTM_COMP_40_40_MHZ_5G_DIS = 823; + est_PHY_RESP_FTM_COMP_40_40_MHZ_5G = 840; + est_PHY_RESP_FTM_COMP_40_40_MHZ_5G_DIS = 840; +} diff --git a/esp-radio/src/wifi/internal.rs b/esp-radio/src/wifi/internal.rs index 97e892bc1b6..712bac09e37 100644 --- a/esp-radio/src/wifi/internal.rs +++ b/esp-radio/src/wifi/internal.rs @@ -22,6 +22,7 @@ unsafe extern "C" { ... ); + #[allow(improper_ctypes)] pub unsafe fn __esp_radio_log_writev( level: crate::sys::c_types::c_uint, tag: *const crate::sys::c_types::c_char, @@ -148,8 +149,8 @@ pub(crate) static __ESP_RADIO_G_WIFI_OSI_FUNCS: wifi_osi_funcs_t = wifi_osi_func _rand: Some(rand), _dport_access_stall_other_cpu_start_wrap: Some(dport_access_stall_other_cpu_start_wrap), _dport_access_stall_other_cpu_end_wrap: Some(dport_access_stall_other_cpu_end_wrap), - _wifi_apb80m_request: Some(wifi_apb80m_request), - _wifi_apb80m_release: Some(wifi_apb80m_release), + _wifi_pm_sleep_lock_acquire: Some(wifi_pm_sleep_lock_acquire), + _wifi_pm_sleep_lock_release: Some(wifi_pm_sleep_lock_release), _phy_disable: Some(os_adapter::phy_disable), _phy_enable: Some(os_adapter::phy_enable), _phy_update_country_info: Some(phy_update_country_info), @@ -217,7 +218,7 @@ pub(crate) static __ESP_RADIO_G_WIFI_OSI_FUNCS: wifi_osi_funcs_t = wifi_osi_func _coex_schm_curr_period_get: Some(coex_schm_curr_period_get), _coex_schm_curr_phase_get: Some(coex_schm_curr_phase_get), #[cfg(any( - esp32c3, esp32c2, esp32c5, esp32c6, esp32c61, esp32h2, esp32s3, esp32s2 + esp32c3, esp32c2, esp32c5, esp32c6, esp32c61, esp32h2, esp32s3, esp32s2, esp32s31 ))] _slowclk_cal_get: Some(slowclk_cal_get), #[cfg(any(esp32, esp32s2))] @@ -226,11 +227,11 @@ pub(crate) static __ESP_RADIO_G_WIFI_OSI_FUNCS: wifi_osi_funcs_t = wifi_osi_func _phy_common_clock_enable: Some(os_adapter_chip_specific::phy_common_clock_enable), _coex_register_start_cb: Some(coex_register_start_cb), - #[cfg(any(esp32c6, esp32c5, esp32c61))] + #[cfg(any(esp32c6, esp32c5, esp32c61, esp32s31))] _regdma_link_set_write_wait_content: Some( os_adapter_chip_specific::regdma_link_set_write_wait_content_dummy, ), - #[cfg(any(esp32c6, esp32c5, esp32c61))] + #[cfg(any(esp32c6, esp32c5, esp32c61, esp32s31))] _sleep_retention_find_link_by_id: Some( os_adapter_chip_specific::sleep_retention_find_link_by_id_dummy, ), @@ -241,18 +242,41 @@ pub(crate) static __ESP_RADIO_G_WIFI_OSI_FUNCS: wifi_osi_funcs_t = wifi_osi_func _coex_schm_flexible_period_get: Some(coex_schm_flexible_period_get), _coex_schm_get_phase_by_idx: Some(coex_schm_get_phase_by_idx), + #[cfg(esp32s31)] + _coex_configure_preemption_end_cb: Some(coex_configure_preemption_end_cb), + #[cfg(wifi_has_wifi6)] + _wifi_disable_ac_ax: Some(wifi_disable_ac_ax), + #[cfg(wifi_has_wifi6)] + _wifi_bb_sleep_retention_attach: Some(wifi_sleep_retention_unsupported), + #[cfg(wifi_has_wifi6)] + _wifi_bb_sleep_retention_detach: Some(wifi_sleep_retention_unsupported), + #[cfg(wifi_has_wifi6)] + _wifi_mac_sleep_retention_attach: Some(wifi_sleep_retention_unsupported), + #[cfg(wifi_has_wifi6)] + _wifi_mac_sleep_retention_detach: Some(wifi_sleep_retention_unsupported), + _magic: ESP_WIFI_OS_ADAPTER_MAGIC as i32, }; const WIFI_ENABLE_WPA3_SAE: u64 = 1 << 0; const WIFI_ENABLE_ENTERPRISE: u64 = 1 << 7; -// const WIFI_FTM_INITIATOR: u64 = 1 << 2; -// const WIFI_FTM_RESPONDER: u64 = 1 << 3; +pub(super) const WIFI_FTM_INITIATOR: u64 = if cfg!(all(wifi_ftm_enable, wifi_ftm_initiator_support)) +{ + 1 << 2 +} else { + 0 +}; +const WIFI_FTM_RESPONDER: u64 = if cfg!(all(wifi_ftm_enable, wifi_ftm_responder_support)) { + 1 << 3 +} else { + 0 +}; // const WIFI_ENABLE_GCMP: u64 = 1 << 4; // const WIFI_ENABLE_GMAC: u64 = 1 << 5; // const WIFI_ENABLE_11R: u64 = 1 << 6; -const WIFI_FEATURE_CAPS: u64 = WIFI_ENABLE_WPA3_SAE | WIFI_ENABLE_ENTERPRISE; +const WIFI_FEATURE_CAPS: u64 = + WIFI_ENABLE_WPA3_SAE | WIFI_ENABLE_ENTERPRISE | WIFI_FTM_INITIATOR | WIFI_FTM_RESPONDER; #[unsafe(no_mangle)] pub(super) static mut __ESP_RADIO_G_WIFI_FEATURE_CAPS: u64 = WIFI_FEATURE_CAPS; diff --git a/esp-radio/src/wifi/mod.rs b/esp-radio/src/wifi/mod.rs index a7db7de98e4..e2c35018170 100644 --- a/esp-radio/src/wifi/mod.rs +++ b/esp-radio/src/wifi/mod.rs @@ -68,6 +68,8 @@ use event::EVENT_CHANNEL; use portable_atomic::{AtomicU8, AtomicUsize, Ordering}; use procmacros::BuilderLite; +#[cfg(wifi_softap_support)] +use self::ap::AccessPointConfig; pub(crate) use self::os_adapter::*; #[cfg(all(feature = "sniffer", feature = "unstable"))] #[cfg_attr(docsrs, doc(cfg(feature = "unstable")))] @@ -75,9 +77,15 @@ use self::sniffer::Sniffer; #[cfg(feature = "wifi-eap")] use self::sta::eap::EapStationConfig; use self::{ - ap::{AccessPointConfig, AccessPointInfo, convert_ap_info}, private::PacketBuffer, - scan::{FreeApListOnDrop, ScanConfig, ScanResults, ScanTypeConfig}, + scan::{ + AccessPointInfo, + ScanConfig, + ScanResults, + ScanTypeConfig, + convert_ap_info, + free_ap_list_on_drop, + }, sta::StationConfig, state::*, }; @@ -85,16 +93,18 @@ use crate::{ RadioRefGuard, asynch::AtomicWaker, hal::ram, + refcount::Refcount, sys::{ c_types, include::{self, *}, }, wifi::event::{EventInfo, WifiEvent}, }; +#[cfg(wifi_softap_support)] pub mod ap; unstable_module!( - #[cfg(all(feature = "csi", wifi_csi_supported))] + #[cfg(feature = "csi")] #[cfg_attr(docsrs, doc(cfg(feature = "csi")))] pub mod csi; pub mod event; @@ -107,9 +117,15 @@ pub mod scan; pub mod sta; pub(crate) mod os_adapter; +esp_hal::if_unstable_hal! { + pub(crate) mod sleep; +} pub(crate) mod state; +#[cfg(wifi_ftm_enable)] +mod ftm_calibration; mod internal; +mod weak_overrides; const MTU: usize = esp_config_int!(usize, "ESP_RADIO_CONFIG_WIFI_MTU"); @@ -367,9 +383,11 @@ pub enum Config { Station(StationConfig), /// Access point configuration. + #[cfg(wifi_softap_support)] AccessPoint(AccessPointConfig), /// Simultaneous station and access point configuration. + #[cfg(wifi_softap_support)] AccessPointStation(StationConfig, AccessPointConfig), /// EAP station configuration for enterprise Wi-Fi. @@ -381,9 +399,11 @@ impl Config { fn validate(&self) -> Result<(), WifiError> { match self { Config::Station(station_configuration) => station_configuration.validate(), + #[cfg(wifi_softap_support)] Config::AccessPoint(access_point_configuration) => { access_point_configuration.validate() } + #[cfg(wifi_softap_support)] Config::AccessPointStation(station_configuration, access_point_configuration) => { station_configuration.validate()?; access_point_configuration.validate() @@ -416,9 +436,9 @@ impl AuthenticationMethod { AuthenticationMethod::Wpa3EntSuiteB192Bit => { include::wifi_auth_mode_t_WIFI_AUTH_WPA3_ENT_192 } - AuthenticationMethod::Wpa3ExtPsk => include::wifi_auth_mode_t_WIFI_AUTH_WPA3_EXT_PSK, - AuthenticationMethod::Wpa3ExtPskMixed => { - include::wifi_auth_mode_t_WIFI_AUTH_WPA3_EXT_PSK_MIXED_MODE + // Deprecated Ext-PSK variants have no dedicated IDF auth mode. + AuthenticationMethod::Wpa3ExtPsk | AuthenticationMethod::Wpa3ExtPskMixed => { + include::wifi_auth_mode_t_WIFI_AUTH_WPA3_PSK } AuthenticationMethod::Dpp => include::wifi_auth_mode_t_WIFI_AUTH_DPP, AuthenticationMethod::Wpa3Enterprise => { @@ -454,10 +474,9 @@ impl AuthenticationMethod { include::wifi_auth_mode_t_WIFI_AUTH_WPA3_ENT_192 => { AuthenticationMethod::Wpa3EntSuiteB192Bit } - include::wifi_auth_mode_t_WIFI_AUTH_WPA3_EXT_PSK => AuthenticationMethod::Wpa3ExtPsk, - include::wifi_auth_mode_t_WIFI_AUTH_WPA3_EXT_PSK_MIXED_MODE => { - AuthenticationMethod::Wpa3ExtPskMixed - } + // Unused IDF auth-mode slots; same as the Ext-PSK write path. + include::wifi_auth_mode_t_WIFI_AUTH_DUMMY_1 + | include::wifi_auth_mode_t_WIFI_AUTH_DUMMY_2 => AuthenticationMethod::Wpa3Personal, include::wifi_auth_mode_t_WIFI_AUTH_DPP => AuthenticationMethod::Dpp, include::wifi_auth_mode_t_WIFI_AUTH_WPA3_ENTERPRISE => { AuthenticationMethod::Wpa3Enterprise @@ -531,8 +550,10 @@ impl WifiMode { impl From<&Config> for WifiMode { fn from(config: &Config) -> Self { match config { + #[cfg(wifi_softap_support)] Config::AccessPoint(_) => Self::AccessPoint, Config::Station(_) => Self::Station, + #[cfg(wifi_softap_support)] Config::AccessPointStation(_, _) => Self::AccessPointStation, #[cfg(feature = "wifi-eap")] Config::EapStation(_) => Self::Station, @@ -638,7 +659,7 @@ pub enum DisconnectReason { /// Transmission link establishment failed TransmissionLinkEstablishmentFailed, /// Alternative channel occupied - AlterativeChannelOccupied, + AlternativeChannelOccupied, /// Beacon timeout BeaconTimeout, /// No access point found @@ -716,7 +737,7 @@ impl DisconnectReason { 50 => Self::InvalidMde, 51 => Self::InvalidFte, 67 => Self::TransmissionLinkEstablishmentFailed, - 68 => Self::AlterativeChannelOccupied, + 68 => Self::AlternativeChannelOccupied, 200 => Self::BeaconTimeout, 201 => Self::NoAccessPointFound, 202 => Self::AuthenticationFailed, @@ -780,7 +801,11 @@ impl Ssid { }) } - pub(crate) fn as_bytes(&self) -> &[u8] { + /// The SSID as raw bytes. + /// + /// An SSID is at most 32 bytes and is not required to be valid UTF-8. + #[instability::unstable] + pub fn as_bytes(&self) -> &[u8] { &self.ssid[..self.len as usize] } @@ -795,6 +820,9 @@ impl Ssid { } /// The SSID as a string slice. + /// + /// An SSID is not required to be valid UTF-8; the result stops at the + /// first invalid byte. Use `as_bytes` for the full bytes. pub fn as_str(&self) -> &str { let part = &self.ssid[..self.len as usize]; match str::from_utf8(part) { @@ -830,6 +858,8 @@ impl TryFrom for Ssid { } } +#[allow(unknown_lints)] +#[allow(clippy::try_from_instead_of_from_str)] impl TryFrom<&str> for Ssid { type Error = WifiError; @@ -974,6 +1004,8 @@ impl TryFrom for Password { } } +#[allow(unknown_lints)] +#[allow(clippy::try_from_instead_of_from_str)] impl TryFrom<&str> for Password { type Error = WifiError; @@ -1051,6 +1083,7 @@ impl PacketQueue { } } +#[cfg(wifi_softap_support)] static DATA_QUEUE_RX_AP: NonReentrantMutex = NonReentrantMutex::new(PacketQueue::new()); @@ -1068,8 +1101,8 @@ pub enum WifiError { /// Passed arguments are invalid. InvalidArguments, - /// Generic failure - not further specified. - Failed, + /// An unspecified error occurred in the radio driver. + Other, /// Out of memory. OutOfMemory, @@ -1086,17 +1119,42 @@ pub enum WifiError { impl WifiError { fn from_error_code(code: i32) -> Self { - if crate::sys::include::ESP_FAIL == code { - return WifiError::Failed; + use crate::sys::include::*; + + // `ESP_FAIL` is a generic, unspecified failure. Map it to the opaque + // `Other` variant. + if code == ESP_FAIL { + return WifiError::Other; } match code as u32 { - crate::sys::include::ESP_ERR_NO_MEM => WifiError::OutOfMemory, - crate::sys::include::ESP_ERR_INVALID_ARG => WifiError::InvalidArguments, - crate::sys::include::ESP_ERR_WIFI_SSID => WifiError::InvalidSsid, - crate::sys::include::ESP_ERR_WIFI_PASSWORD => WifiError::InvalidPassword, - crate::sys::include::ESP_ERR_WIFI_NOT_CONNECT => WifiError::NotConnected, - _ => panic!("Unknown error code: {}", code), + // Meaningful, public mappings. These are ordinary outcomes, so they + // are returned without any logging. + ESP_ERR_NO_MEM => WifiError::OutOfMemory, + ESP_ERR_INVALID_ARG => WifiError::InvalidArguments, + ESP_ERR_WIFI_SSID => WifiError::InvalidSsid, + ESP_ERR_WIFI_PASSWORD => WifiError::InvalidPassword, + ESP_ERR_WIFI_NOT_CONNECT => WifiError::NotConnected, + + // Known driver state-machine and timeout codes. These occur in + // perfectly normal operation. + ESP_ERR_WIFI_NOT_INIT + | ESP_ERR_WIFI_NOT_STARTED + | ESP_ERR_WIFI_STATE + | ESP_ERR_WIFI_CONN + | ESP_ERR_WIFI_STOP_STATE + | ESP_ERR_WIFI_TIMEOUT => WifiError::Other, + + // Any code we don't recognise: warn so it can be reported, then fall + // back to the opaque variant. We must never panic here - an + // unexpected code from the driver should not bring down the firmware. + _ => { + warn!( + "Unmapped Wi-Fi error code: {}. Please open an issue at .", + code + ); + WifiError::Other + } } } } @@ -1133,6 +1191,18 @@ fn set_mac_time_update_cb(_wifi: crate::hal::peripherals::WIFI<'_>) { } } +fn wifi_init_feature_caps() -> u64 { + let caps = unsafe { internal::__ESP_RADIO_G_WIFI_FEATURE_CAPS }; + + // ESP-IDF disables the FTM initiator on ESP32-C6 v0.0 and v0.1. + #[cfg(all(esp32c6, wifi_ftm_enable))] + if esp_hal::efuse::chip_revision().combined() <= 1 { + return caps & !internal::WIFI_FTM_INITIATOR; + } + + caps +} + pub(crate) fn wifi_init(_wifi: crate::hal::peripherals::WIFI<'_>) -> Result<(), WifiError> { #[cfg(esp32)] set_mac_time_update_cb(_wifi); @@ -1148,16 +1218,22 @@ pub(crate) fn wifi_init(_wifi: crate::hal::peripherals::WIFI<'_>) -> Result<(), esp_wifi_result!(esp_wifi_set_tx_done_cb(Some(esp_wifi_tx_done_cb)))?; esp_wifi_result!(esp_wifi_internal_reg_rxcb( - esp_interface_t_ESP_IF_WIFI_STA, + wifi_interface_t_WIFI_IF_STA, Some(recv_cb_sta) ))?; // until we support APSTA we just register the same callback for AP and station + #[cfg(wifi_softap_support)] esp_wifi_result!(esp_wifi_internal_reg_rxcb( - esp_interface_t_ESP_IF_WIFI_AP, + wifi_interface_t_WIFI_IF_AP, Some(recv_cb_ap) ))?; + // As in ESP-IDF (`modem_clock_configure_wifi_status`), the MAC and baseband clocks stay on + // while the driver is initialized, even though it calls `wifi_clock_disable` at every doze. + #[cfg(soc_has_modem_syscon)] + crate::radio_clocks::enable_wifi(true); + Ok(()) } } @@ -1203,11 +1279,14 @@ fn wifi_deinit() -> Result<(), WifiError> { while let Some(packet) = DATA_QUEUE_RX_STA.with(|q| q.pop_front()) { drop(packet); } + #[cfg(wifi_softap_support)] while let Some(packet) = DATA_QUEUE_RX_AP.with(|q| q.pop_front()) { drop(packet); } esp_wifi_result!(unsafe { esp_wifi_deinit_internal() })?; + #[cfg(soc_has_modem_syscon)] + crate::radio_clocks::enable_wifi(false); esp_wifi_result!(unsafe { esp_supplicant_deinit() })?; Ok(()) } @@ -1233,6 +1312,7 @@ unsafe extern "C" fn recv_cb_sta( } } +#[cfg(wifi_softap_support)] unsafe extern "C" fn recv_cb_ap( buffer: *mut c_types::c_void, len: u16, @@ -1297,6 +1377,8 @@ pub(crate) fn wifi_start_scan( min: min.as_millis() as u32, max: max.as_millis() as u32, }, + // 0 keeps the default set by `esp_wifi_set_scan_parameters` (120 ms) for + // passive-only channels. passive: 0, }, wifi_scan_type_t_WIFI_SCAN_TYPE_ACTIVE, @@ -1384,6 +1466,7 @@ enum InterfaceType { /// Station mode. Station, /// Access Point mode. + #[cfg(wifi_softap_support)] AccessPoint, } @@ -1394,6 +1477,7 @@ impl InterfaceType { InterfaceType::Station => { esp_hal::efuse::interface_mac_address(InterfaceMacAddress::Station) } + #[cfg(wifi_softap_support)] InterfaceType::AccessPoint => { esp_hal::efuse::interface_mac_address(InterfaceMacAddress::AccessPoint) } @@ -1407,6 +1491,7 @@ impl InterfaceType { fn data_queue_rx(&self) -> &'static NonReentrantMutex { match self { InterfaceType::Station => &DATA_QUEUE_RX_STA, + #[cfg(wifi_softap_support)] InterfaceType::AccessPoint => &DATA_QUEUE_RX_AP, } } @@ -1454,22 +1539,24 @@ impl InterfaceType { fn interface(&self) -> wifi_interface_t { match self { InterfaceType::Station => wifi_interface_t_WIFI_IF_STA, + #[cfg(wifi_softap_support)] InterfaceType::AccessPoint => wifi_interface_t_WIFI_IF_AP, } } - fn register_transmit_waker(&self, cx: &mut core::task::Context<'_>) { - TRANSMIT_WAKER.register(cx.waker()) + fn register_transmit_waker(&self, waker: &core::task::Waker) { + TRANSMIT_WAKER.register(waker) } - fn register_receive_waker(&self, cx: &mut core::task::Context<'_>) { - self.data_queue_rx().with(|q| q.register_waker(cx.waker())); + fn register_receive_waker(&self, waker: &core::task::Waker) { + self.data_queue_rx().with(|q| q.register_waker(waker)); } - fn register_link_state_waker(&self, cx: &mut core::task::Context<'_>) { + fn register_link_state_waker(&self, waker: &core::task::Waker) { match self { - InterfaceType::Station => STA_LINK_STATE_WAKER.register(cx.waker()), - InterfaceType::AccessPoint => AP_LINK_STATE_WAKER.register(cx.waker()), + InterfaceType::Station => STA_LINK_STATE_WAKER.register(waker), + #[cfg(wifi_softap_support)] + InterfaceType::AccessPoint => AP_LINK_STATE_WAKER.register(waker), } } @@ -1478,6 +1565,7 @@ impl InterfaceType { InterfaceType::Station => { matches!(station_state(), WifiStationState::Connected) } + #[cfg(wifi_softap_support)] InterfaceType::AccessPoint => { matches!(access_point_state(), WifiAccessPointState::Started) } @@ -1494,6 +1582,7 @@ impl InterfaceType { static SINGLETONS: AtomicU8 = AtomicU8::new(0); const STA_BIT: u8 = 1 << 0; +#[cfg(wifi_softap_support)] const AP_BIT: u8 = 1 << 1; #[cfg(feature = "sniffer")] pub(super) const SNIFFER_BIT: u8 = 1 << 2; @@ -1508,8 +1597,9 @@ pub(super) fn release(bit: u8) { /// Wi-Fi interface. /// -/// This implements the `embassy-net-driver` trait for up to three latest versions of that crate. -/// While that crate isn't stable we make an exception here from the [API Guidelines](https://rust-lang.github.io/api-guidelines/necessities.html#c-stable) +/// This implements the `embassy-net-driver` trait for up to three latest versions of that crate, +/// and the `xarxa-driver` trait. +/// While those crates aren't stable we make an exception here from the [API Guidelines](https://rust-lang.github.io/api-guidelines/necessities.html#c-stable) /// in exposing unstable dependencies. /// /// Each interface mode (station, access point) is a singleton — only one @@ -1553,6 +1643,7 @@ impl Interface { /// /// Panics if an access-point interface already exists. /// Use [`try_access_point()`](Self::try_access_point) for a non-panicking alternative. + #[cfg(wifi_softap_support)] pub fn access_point() -> Self { Self::try_access_point().expect("access point interface already taken") } @@ -1560,6 +1651,7 @@ impl Interface { /// Tries to create the access-point-mode interface. /// /// Returns `None` if an access-point interface already exists. + #[cfg(wifi_softap_support)] pub fn try_access_point() -> Option { if try_acquire(AP_BIT) { Some(Self { @@ -1606,6 +1698,7 @@ impl Drop for Interface { fn drop(&mut self) { let bit = match self.mode { InterfaceType::Station => STA_BIT, + #[cfg(wifi_softap_support)] InterfaceType::AccessPoint => AP_BIT, }; release(bit); @@ -1660,8 +1753,8 @@ pub enum Bandwidth { impl Bandwidth { fn to_raw(self) -> wifi_bandwidth_t { match self { - Bandwidth::_20MHz => wifi_bandwidth_t_WIFI_BW_HT20, - Bandwidth::_40MHz => wifi_bandwidth_t_WIFI_BW_HT40, + Bandwidth::_20MHz => wifi_bandwidth_t_WIFI_BW20, + Bandwidth::_40MHz => wifi_bandwidth_t_WIFI_BW40, Bandwidth::_80MHz => wifi_bandwidth_t_WIFI_BW80, Bandwidth::_160MHz => wifi_bandwidth_t_WIFI_BW160, Bandwidth::_80_80MHz => wifi_bandwidth_t_WIFI_BW80_BW80, @@ -1670,8 +1763,8 @@ impl Bandwidth { fn from_raw(raw: wifi_bandwidth_t) -> Self { match raw { - raw if raw == wifi_bandwidth_t_WIFI_BW_HT20 => Bandwidth::_20MHz, - raw if raw == wifi_bandwidth_t_WIFI_BW_HT40 => Bandwidth::_40MHz, + raw if raw == wifi_bandwidth_t_WIFI_BW20 => Bandwidth::_20MHz, + raw if raw == wifi_bandwidth_t_WIFI_BW40 => Bandwidth::_40MHz, raw if raw == wifi_bandwidth_t_WIFI_BW80 => Bandwidth::_80MHz, raw if raw == wifi_bandwidth_t_WIFI_BW160 => Bandwidth::_160MHz, raw if raw == wifi_bandwidth_t_WIFI_BW80_BW80 => Bandwidth::_80_80MHz, @@ -2040,17 +2133,11 @@ fn dump_packet_info(_buffer: &mut [u8]) { macro_rules! esp_wifi_result { ($value:expr) => {{ - use num_traits::FromPrimitive; let result = $value; if result != $crate::sys::include::ESP_OK as i32 { - let error = unwrap!(FromPrimitive::from_i32(result)); - warn!( - "{} returned an error: {:?} ({}). If this error is unmapped, please open an issue at .", - stringify!($value), - error, - result - ); - Err(WifiError::from_error_code(error)) + // `from_error_code` decides how to classify and (only for truly + // unmapped codes) log the result, so we don't warn here. + Err(WifiError::from_error_code(result)) } else { Ok::<(), WifiError>(()) } @@ -2111,18 +2198,18 @@ pub(crate) mod embassy_02 { &mut self, cx: &mut core::task::Context<'_>, ) -> Option<(Self::RxToken<'_>, Self::TxToken<'_>)> { - self.mode.register_receive_waker(cx); - self.mode.register_transmit_waker(cx); + self.mode.register_receive_waker(cx.waker()); + self.mode.register_transmit_waker(cx.waker()); self.mode.rx_token() } fn transmit(&mut self, cx: &mut core::task::Context<'_>) -> Option> { - self.mode.register_transmit_waker(cx); + self.mode.register_transmit_waker(cx.waker()); self.mode.tx_token() } fn link_state(&mut self, cx: &mut core::task::Context<'_>) -> LinkState { - self.mode.register_link_state_waker(cx); + self.mode.register_link_state_waker(cx.waker()); match self.mode.link_state() { super::LinkState::Down => LinkState::Down, super::LinkState::Up => LinkState::Up, @@ -2150,20 +2237,124 @@ pub(crate) mod embassy_02 { } } -/// Power saving mode settings for the modem. +pub(crate) mod xarxa { + use xarxa_driver::{ + Capabilities, + Driver, + HardwareAddress, + LinkState, + NotSupported, + PacketBuf, + config::PACKET_BUF_SIZE, + }; + + use super::*; + + /// The largest frame this driver can pass on to the stack. + /// + /// The packet pool has a fixed buffer size, so a larger configured MTU cannot be used. + const XARXA_MTU: usize = if MTU < PACKET_BUF_SIZE { + MTU + } else { + PACKET_BUF_SIZE + }; + + impl Driver for Interface { + fn capabilities(&self) -> Capabilities { + let mut caps = Capabilities::default(); + caps.max_transmission_unit = XARXA_MTU; + caps + } + + fn hardware_address(&self) -> HardwareAddress { + HardwareAddress::Ethernet(self.mac_address()) + } + + fn link_state(&mut self) -> LinkState { + match self.mode.link_state() { + super::LinkState::Down => LinkState::Down, + super::LinkState::Up => LinkState::Up, + } + } + + fn register_waker(&mut self, waker: &core::task::Waker) -> Result<(), NotSupported> { + // The driver has one waker per event, the stack has one waker for all of them. + self.mode.register_receive_waker(waker); + self.mode.register_transmit_waker(waker); + self.mode.register_link_state_waker(waker); + Ok(()) + } + + fn receive(&mut self) -> Option { + // We handle the received data outside of the lock because PacketBuffer::drop must + // not be called in a critical section. Dropping a PacketBuffer calls + // `esp_wifi_internal_free_rx_buffer` which will try to lock an internal mutex. If + // the mutex is already taken, the function will try to trigger a context switch, + // which will fail if we are in an interrupt-free context. + let mut packet = self.mode.data_queue_rx().with(|queue| queue.pop_front())?; + + let data = packet.as_slice_mut(); + dump_packet_info(data); + + if data.len() > PACKET_BUF_SIZE { + warn!( + "Dropping a {} byte frame, the packet buffer holds {} bytes", + data.len(), + PACKET_BUF_SIZE + ); + return None; + } + + // The pool is shared with the rest of the stack and can be empty. Dropping the + // packet is the only option, the hardware does not hold it for us. + let mut buffer = PacketBuf::try_new()?; + buffer.set_len(data.len()); + buffer.copy_from_slice(data); + + Some(buffer) + } + + fn can_transmit(&mut self) -> bool { + self.mode.can_send() && self.mode.link_state() == super::LinkState::Up + } + + fn transmit(&mut self, mut buffer: PacketBuf) -> Result<(), PacketBuf> { + if !self.can_transmit() { + return Err(buffer); + } + + self.mode.increase_in_flight_counter(); + esp_wifi_send_data(self.mode.interface(), &mut buffer); + + Ok(()) + } + } +} + +/// Power saving mode of the Wi-Fi modem in Station mode. +/// +/// In power save, the station tells the access point that it sleeps. The access point keeps the +/// frames for the station, and the station wakes up only to receive beacons. Between the beacons, +/// the modem turns off the radio. The CPU keeps running. +/// +/// Power save increases the receive latency and decreases the throughput. For this reason, the +/// default is [`PowerSaveMode::None`]. #[derive(Clone, Copy, PartialEq, Eq, Debug, Default, Hash)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[instability::unstable] #[non_exhaustive] pub enum PowerSaveMode { - /// No power saving. + /// No power saving. The radio stays on. #[default] None, - /// Minimum power save mode. In this mode, station wakes up to receive beacon every DTIM - /// period. + /// Minimum power save mode. The station wakes up to receive every DTIM beacon. + /// + /// The receive latency increases by up to one DTIM period. Minimum, - /// Maximum power save mode. In this mode, interval to receive beacons is determined by the - /// `listen_interval` config option. + /// Maximum power save mode. The station wakes up once every listen interval, see + /// [`StationConfig::with_listen_interval`](sta::StationConfig::with_listen_interval). + /// + /// The receive latency increases by up to one listen interval. Maximum, } @@ -2175,6 +2366,9 @@ pub(crate) fn apply_power_saving(ps: PowerSaveMode) -> Result<(), WifiError> { PowerSaveMode::Maximum => crate::sys::include::wifi_ps_type_t_WIFI_PS_MAX_MODEM, }) })?; + esp_hal::if_unstable_hal! { + sleep::set_power_save(ps != PowerSaveMode::None); + } Ok(()) } @@ -2237,7 +2431,7 @@ impl OperatingClass { #[procmacros::doc_replace] /// Country information. /// -/// Defaults to China (CN) with Operating Class "0". +/// Defaults to "01" (world safe mode) with IEEE 802.11d enabled. /// /// To create a [`CountryInfo`] instance, use the `from` method first, then set additional /// properties using the builder methods. @@ -2264,6 +2458,10 @@ pub struct CountryInfo { /// Operating class. #[builder_lite(unstable)] operating_class: OperatingClass, + + /// Whether IEEE 802.11d is enabled. Disable it to find hidden access points on all channels. + #[builder_lite(unstable)] + ieee80211d_enabled: bool, } impl From<[u8; 2]> for CountryInfo { @@ -2271,32 +2469,12 @@ impl From<[u8; 2]> for CountryInfo { Self { country, operating_class: OperatingClass::default(), + ieee80211d_enabled: true, } } } impl CountryInfo { - fn into_blob(self) -> wifi_country_t { - wifi_country_t { - cc: [ - self.country[0], - self.country[1], - self.operating_class.into_code(), - ], - // TODO: these may be valid defaults, but they should be configurable. - schan: 1, - nchan: 13, - // This field is output-only: esp_wifi_set_country ignores it. The actual TX power - // is controlled exclusively via esp_wifi_set_max_tx_power after WiFi start. - // See: https://github.com/espressif/esp-idf/blob/20f5e18/components/esp_wifi/include/esp_wifi_types.h#L46 - max_tx_power: 0, - policy: wifi_country_policy_t_WIFI_COUNTRY_POLICY_MANUAL, - - #[cfg(wifi_has_5g)] - wifi_5g_channel_mask: 0, - } - } - #[cfg_attr(not(feature = "unstable"), expect(dead_code))] fn try_from_c(info: &wifi_country_t) -> Option { let cc = &info.cc; @@ -2305,11 +2483,16 @@ impl CountryInfo { Some(Self { country: [cc[0], cc[1]], operating_class, + ieee80211d_enabled: info.policy == wifi_country_policy_t_WIFI_COUNTRY_POLICY_AUTO, }) } } /// Wi-Fi configuration. +/// +/// The default country is `"01"` (world safe mode) with IEEE 802.11d enabled, which only allows +/// channels that are permitted in all regions unless updated by a connected access point or +/// configured explicitly. #[derive(Clone, BuilderLite, Debug, Hash, PartialEq, Eq)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[non_exhaustive] @@ -2449,7 +2632,7 @@ impl Default for ControllerConfig { espnow_max_encrypt_num: crate::sys::include::CONFIG_ESP_WIFI_ESPNOW_MAX_ENCRYPT_NUM as _, - country_info: CountryInfo::from(*b"CN"), + country_info: CountryInfo::from(*b"01"), initial_config: Config::Station(StationConfig::default()), } @@ -2470,37 +2653,61 @@ impl ControllerConfig { } } -/// Wi-Fi controller. -/// -/// When the controller is dropped, the Wi-Fi driver is -/// deinitialized and Wi-Fi is stopped. +static WIFI_REFCOUNT: Refcount = Refcount::new(); + +/// Keeps Wi-Fi initialized until the last guard is dropped. #[derive(Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] -pub struct WifiController<'d> { - _guard: RadioRefGuard, - _phantom: PhantomData<&'d ()>, +pub(crate) struct WifiRefGuard { + _radio_guard: RadioRefGuard, } -impl Drop for WifiController<'_> { +impl Clone for WifiRefGuard { + fn clone(&self) -> Self { + let _radio_guard = RadioRefGuard::without_wake_lock(); + WIFI_REFCOUNT.increment(|| {}); + Self { _radio_guard } + } +} + +impl Drop for WifiRefGuard { fn drop(&mut self) { - state::locked(|| { - set_access_point_state(WifiAccessPointState::Uninitialized); - set_station_state(WifiStationState::Uninitialized); + WIFI_REFCOUNT.decrement(|| { + state::locked(|| { + set_access_point_state(WifiAccessPointState::Uninitialized); + set_station_state(WifiStationState::Uninitialized); - if let Err(e) = crate::wifi::wifi_deinit() { - warn!("Failed to cleanly deinit wifi: {:?}", e); - } + esp_hal::if_unstable_hal! { + sleep::release_wake_source(); + } - #[cfg(rng_trng_supported)] - esp_hal::if_unstable_hal! { - esp_hal::rng::TrngSource::decrease_entropy_source_counter(unsafe { - esp_hal::Internal::conjure() - }); - } - }) + if let Err(e) = crate::wifi::wifi_deinit() { + warn!("Failed to cleanly deinit wifi: {:?}", e); + } + + #[cfg(rng_trng_supported)] + esp_hal::if_unstable_hal! { + esp_hal::rng::TrngSource::decrease_entropy_source_counter(unsafe { + esp_hal::Internal::conjure() + }); + } + }) + }); } } +/// Wi-Fi controller. +/// +/// When the controller is dropped, the Wi-Fi driver is deinitialized and Wi-Fi +/// is stopped unless an ESP-NOW or sniffer instance created from it is still +/// alive. In that case, Wi-Fi keeps running until that instance is dropped too. +#[derive(Debug)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub struct WifiController<'d> { + _guard: WifiRefGuard, + _phantom: PhantomData<&'d ()>, +} + impl<'d> WifiController<'d> { #[procmacros::doc_replace( "esp_now" => { @@ -2515,7 +2722,8 @@ impl<'d> WifiController<'d> { /// Create a Wi-Fi controller. The default initial configuration is /// [`Config::Station`]`(`[`StationConfig::default()`]`)`. /// - /// Dropping the controller will deinitialize / stop Wi-Fi. + /// Dropping the controller deinitializes Wi-Fi unless an ESP-NOW or sniffer + /// instance created from it is still alive. /// /// Create [`Interface`]s separately via [`Interface::station()`] / /// [`Interface::access_point()`]. @@ -2537,8 +2745,6 @@ impl<'d> WifiController<'d> { device: crate::hal::peripherals::WIFI<'d>, config: ControllerConfig, ) -> Result { - let _guard = RadioRefGuard::new(); - config.validate(); event::enable_wifi_events( @@ -2553,60 +2759,84 @@ impl<'d> WifiController<'d> { | WifiEvent::ScanDone, ); - unsafe { - internal::G_CONFIG = wifi_init_config_t { - osi_funcs: (&raw const internal::__ESP_RADIO_G_WIFI_OSI_FUNCS).cast_mut(), - - wpa_crypto_funcs: g_wifi_default_wpa_crypto_funcs, - static_rx_buf_num: config.static_rx_buf_num as _, - dynamic_rx_buf_num: config.dynamic_rx_buf_num as _, - tx_buf_type: crate::sys::include::CONFIG_ESP_WIFI_TX_BUFFER_TYPE as i32, - static_tx_buf_num: config.static_tx_buf_num as _, - dynamic_tx_buf_num: config.dynamic_tx_buf_num as _, - rx_mgmt_buf_type: crate::sys::include::CONFIG_ESP_WIFI_DYNAMIC_RX_MGMT_BUF as i32, - rx_mgmt_buf_num: crate::sys::include::CONFIG_ESP_WIFI_RX_MGMT_BUF_NUM_DEF as i32, - cache_tx_buf_num: crate::sys::include::WIFI_CACHE_TX_BUFFER_NUM as i32, - csi_enable: cfg!(feature = "csi") as i32, - ampdu_rx_enable: config.ampdu_rx_enable as _, - ampdu_tx_enable: config.ampdu_tx_enable as _, - amsdu_tx_enable: config.amsdu_tx_enable as _, - nvs_enable: 0, - nano_enable: 0, - rx_ba_win: config.rx_ba_win as _, - wifi_task_core_id: Cpu::current() as _, - beacon_max_len: crate::sys::include::WIFI_SOFTAP_BEACON_MAX_LEN as i32, - mgmt_sbuf_num: crate::sys::include::WIFI_MGMT_SBUF_NUM as i32, - feature_caps: internal::__ESP_RADIO_G_WIFI_FEATURE_CAPS, - sta_disconnected_pm: config.sta_disconnected_pm as _, - espnow_max_encrypt_num: config.espnow_max_encrypt_num as _, - - tx_hetb_queue_num: 3, - dump_hesigb_enable: false, - - magic: WIFI_INIT_CONFIG_MAGIC as i32, - }; - } - - DATA_QUEUE_RX_AP.with(|queue| queue.change_capacity(config.rx_queue_size))?; - DATA_QUEUE_RX_STA.with(|queue| queue.change_capacity(config.rx_queue_size))?; - - TX_QUEUE_SIZE.store(config.tx_queue_size, Ordering::Relaxed); - - crate::wifi::wifi_init(device)?; - - // At some point the "High-speed ADC" entropy source became available. - #[cfg(rng_trng_supported)] - esp_hal::if_unstable_hal! { + let radio_guard = RadioRefGuard::without_wake_lock(); + + let first = WIFI_REFCOUNT.try_increment(|| -> Result<(), WifiError> { unsafe { - esp_hal::rng::TrngSource::increase_entropy_source_counter() - }; + internal::G_CONFIG = wifi_init_config_t { + osi_funcs: (&raw const internal::__ESP_RADIO_G_WIFI_OSI_FUNCS).cast_mut(), + + wpa_crypto_funcs: g_wifi_default_wpa_crypto_funcs, + static_rx_buf_num: config.static_rx_buf_num as _, + dynamic_rx_buf_num: config.dynamic_rx_buf_num as _, + tx_buf_type: crate::sys::include::CONFIG_ESP_WIFI_TX_BUFFER_TYPE as i32, + static_tx_buf_num: config.static_tx_buf_num as _, + dynamic_tx_buf_num: config.dynamic_tx_buf_num as _, + rx_mgmt_buf_type: crate::sys::include::CONFIG_ESP_WIFI_DYNAMIC_RX_MGMT_BUF + as i32, + rx_mgmt_buf_num: crate::sys::include::CONFIG_ESP_WIFI_RX_MGMT_BUF_NUM_DEF + as i32, + cache_tx_buf_num: crate::sys::include::WIFI_CACHE_TX_BUFFER_NUM as i32, + csi_enable: cfg!(feature = "csi") as i32, + ampdu_rx_enable: config.ampdu_rx_enable as _, + ampdu_tx_enable: config.ampdu_tx_enable as _, + amsdu_tx_enable: config.amsdu_tx_enable as _, + nvs_enable: 0, + nano_enable: 0, + rx_ba_win: config.rx_ba_win as _, + wifi_task_core_id: Cpu::current() as _, + beacon_max_len: crate::sys::include::WIFI_SOFTAP_BEACON_MAX_LEN as i32, + mgmt_sbuf_num: crate::sys::include::WIFI_MGMT_SBUF_NUM as i32, + feature_caps: wifi_init_feature_caps(), + sta_disconnected_pm: config.sta_disconnected_pm as _, + espnow_max_encrypt_num: config.espnow_max_encrypt_num as _, + + tx_hetb_queue_num: 3, + dump_hesigb_enable: false, + + // WIFI_INIT_CONFIG_DEFAULT: both are off unless the matching sdkconfig is set. + privacy_enhancements: false, + rmac_auto_reset_int: 0, + + magic: WIFI_INIT_CONFIG_MAGIC as i32, + }; + } + + #[cfg(wifi_softap_support)] + DATA_QUEUE_RX_AP.with(|queue| queue.change_capacity(config.rx_queue_size))?; + DATA_QUEUE_RX_STA.with(|queue| queue.change_capacity(config.rx_queue_size))?; + + TX_QUEUE_SIZE.store(config.tx_queue_size, Ordering::Relaxed); + + crate::wifi::wifi_init(device)?; + + esp_hal::if_unstable_hal! { + sleep::claim_wake_source(); + } + + #[cfg(rng_trng_supported)] + esp_hal::if_unstable_hal! { + unsafe { + esp_hal::rng::TrngSource::increase_entropy_source_counter() + }; + } + + Ok(()) + })?; + + if !first { + warn!( + "Wi-Fi is already initialized; init-only ControllerConfig settings were ignored: \ + static_rx_buf_num, dynamic_rx_buf_num, static_tx_buf_num, dynamic_tx_buf_num, \ + rx_queue_size, tx_queue_size, rx_ba_win, espnow_max_encrypt_num, \ + ampdu_rx_enable, ampdu_tx_enable, amsdu_tx_enable" + ); } - // Only create WifiController after we've enabled TRNG - otherwise returning an - // error from this function will cause panic because WifiController::drop tries - // to disable the TRNG. let mut controller = WifiController { - _guard, + _guard: WifiRefGuard { + _radio_guard: radio_guard, + }, _phantom: Default::default(), }; @@ -2624,30 +2854,36 @@ impl<'d> WifiController<'d> { } impl WifiController<'_> { - /// Returns an ESP-NOW instance tied to this controller's lifetime. + /// Returns an ESP-NOW instance independent of this controller. + /// + /// Wi-Fi stays initialized, configured, and running until the instance is + /// dropped. /// /// # Panics /// /// Panics if an ESP-NOW instance already exists. - #[cfg(all(feature = "esp-now", feature = "unstable"))] + #[cfg(feature = "esp-now")] #[instability::unstable] - pub fn esp_now(&self) -> crate::esp_now::EspNow<'_> { - crate::esp_now::EspNow::new_internal() + pub fn esp_now(&self) -> crate::esp_now::EspNow { + crate::esp_now::EspNow::new_internal(self._guard.clone()) } - /// Returns a sniffer instance tied to this controller's lifetime. + /// Returns a sniffer instance independent of this controller. + /// + /// Wi-Fi stays initialized, configured, and running until the instance is + /// dropped. /// /// # Panics /// /// Panics if a sniffer instance already exists. - #[cfg(all(feature = "sniffer", feature = "unstable"))] + #[cfg(feature = "sniffer")] #[instability::unstable] - pub fn sniffer(&self) -> Sniffer<'_> { - Sniffer::new() + pub fn sniffer(&self) -> Sniffer { + Sniffer::new(self._guard.clone()) } /// Set CSI configuration and register the receiving callback. - #[cfg(all(feature = "csi", feature = "unstable"))] + #[cfg(feature = "csi")] #[instability::unstable] pub fn set_csi( &mut self, @@ -2715,6 +2951,9 @@ impl WifiController<'_> { #[procmacros::doc_replace] /// Configures modem power saving. /// + /// The different power saving options trade off power consumption and receive latency. See + /// [`PowerSaveMode`] for more information. + /// /// ## Example /// /// ```rust,no_run @@ -2731,9 +2970,19 @@ impl WifiController<'_> { } fn set_country_info(&mut self, country: &CountryInfo) -> Result<(), WifiError> { + // A zero operating class code terminates the string early, which the driver treats as + // "all environments". + let code = [ + country.country[0], + country.country[1], + country.operating_class.into_code(), + 0, + ]; unsafe { - let country = country.into_blob(); - esp_wifi_result!(esp_wifi_set_country(&country))?; + esp_wifi_result!(esp_wifi_set_country_code( + code.as_ptr().cast(), + country.ieee80211d_enabled + ))?; } Ok(()) } @@ -2833,6 +3082,9 @@ impl WifiController<'_> { /// /// ## Errors /// + /// Returns [`WifiError::InvalidArguments`] if the access point channel is not allowed in the + /// configured country (see [`ControllerConfig`]). + /// /// If this function returns an error, the Wi-Fi mode is reset to `NULL` and /// the controller is stopped. /// @@ -2880,7 +3132,9 @@ impl WifiController<'_> { let mode = match conf { Config::Station(_) => wifi_mode_t_WIFI_MODE_STA, + #[cfg(wifi_softap_support)] Config::AccessPoint(_) => wifi_mode_t_WIFI_MODE_AP, + #[cfg(wifi_softap_support)] Config::AccessPointStation(_, _) => wifi_mode_t_WIFI_MODE_APSTA, #[cfg(feature = "wifi-eap")] Config::EapStation(_) => wifi_mode_t_WIFI_MODE_STA, @@ -2897,10 +3151,12 @@ impl WifiController<'_> { self.apply_sta_config(config)?; Self::apply_protocols(wifi_interface_t_WIFI_IF_STA, &config.protocols)?; } + #[cfg(wifi_softap_support)] Config::AccessPoint(config) => { self.apply_ap_config(config)?; Self::apply_protocols(wifi_interface_t_WIFI_IF_AP, &config.protocols)?; } + #[cfg(wifi_softap_support)] Config::AccessPointStation(sta_config, ap_config) => { self.apply_ap_config(ap_config)?; Self::apply_protocols(wifi_interface_t_WIFI_IF_AP, &ap_config.protocols)?; @@ -2914,12 +3170,31 @@ impl WifiController<'_> { } } + esp_hal::if_unstable_hal! { + sleep::set_station_only(mode == wifi_mode_t_WIFI_MODE_STA); + } + if previous_mode != mode { set_access_point_state(WifiAccessPointState::Starting); set_station_state(WifiStationState::Starting); // `esp_wifi_start` is actually not async - i.e. we get the even before it returns esp_wifi_result!(unsafe { esp_wifi_start() })?; + + // Default for all scans, including connect scans. Requires a started station. + // `wifi_start_scan` only overrides the active or passive time for a single scan and + // the driver restores these defaults when a scan finishes. + if mode != wifi_mode_t_WIFI_MODE_AP { + let params = wifi_scan_default_params_t { + scan_time: wifi_scan_time_t { + active: wifi_active_scan_time_t { min: 0, max: 0 }, + // Covers one typical beacon interval (102.4 ms). + passive: 120, + }, + home_chan_dwell_time: 0, + }; + esp_wifi_result!(unsafe { esp_wifi_set_scan_parameters(¶ms) })?; + } } reset_mode_on_error.defuse(); @@ -3098,7 +3373,7 @@ ignored." #[procmacros::doc_replace] /// An async Wi-Fi network scan with caller-provided scanning options. /// - /// Scanning is not supported in AcessPoint-only mode. + /// Scanning is not supported in AccessPoint-only mode. /// /// ## Example /// @@ -3125,7 +3400,7 @@ ignored." esp_wifi_result!(wifi_start_scan(false, *config))?; // Prevents memory leak if `scan_async`'s future is dropped. - let guard = FreeApListOnDrop; + let guard = free_ap_list_on_drop(); loop { let event = subscriber.next_message_pure().await; @@ -3228,6 +3503,8 @@ ignored." #[procmacros::doc_replace] /// Disconnect Wi-Fi station from the AP. /// + /// If a connection attempt is currently in progress, it is aborted. + /// /// This function will wait for the connection to be closed before returning. /// /// ## Example @@ -3248,9 +3525,14 @@ ignored." /// } /// # {after_snippet} pub async fn disconnect_async(&mut self) -> Result { - // If not connected it would wait forever for a `StationDisconnected` event that will never - // happen. Return early instead of hanging. - if !self.is_connected() { + // If neither connected nor connecting it would wait forever for a `StationDisconnected` + // event that will never happen. Return early instead of hanging. Disconnecting while + // `Connecting` is allowed: `esp_wifi_disconnect` cancels an in-progress connection + // attempt and posts a `StationDisconnected` event. + if !matches!( + station_state(), + WifiStationState::Connected | WifiStationState::Connecting + ) { return Err(WifiError::NotConnected); } @@ -3313,6 +3595,7 @@ ignored." } /// Wait for connected / disconnected events. + #[cfg(wifi_softap_support)] pub async fn wait_for_access_point_connected_event_async( &self, ) -> Result { @@ -3356,7 +3639,7 @@ ignored." /// Subscribe to events. /// /// # Errors - /// This returns [WifiError::Failed] if no more subscriptions are available. + /// This returns [WifiError::Other] if no more subscriptions are available. /// Consider increasing the internal event channel subscriber count in this case. #[instability::unstable] pub fn subscribe<'a>(&'a self) -> Result, WifiError> { @@ -3364,9 +3647,10 @@ ignored." return Ok(event::EventSubscriber::new(subscriber)); } - Err(WifiError::Failed) + Err(WifiError::Other) } + #[cfg(wifi_softap_support)] fn apply_ap_config(&mut self, config: &AccessPointConfig) -> Result<(), WifiError> { config.validate()?; @@ -3396,8 +3680,10 @@ ignored." sae_pwe_h2e: 0, csa_count: 3, dtim_period: config.dtim_period, - transition_disable: 0, - sae_ext: 0, + _bitfield_align_1: [0; 0], + // transition_disable, sae_ext, wpa3_compatible_mode, reserved. + // wpa3_compatible_mode is opt-in: enabling it overrides AP authmode. + _bitfield_1: wifi_ap_config_t::new_bitfield_1(0, 0, 0, 0), bss_max_idle_cfg: include::wifi_bss_max_idle_config_t { period: 0, protected_keep_alive: false, @@ -3418,12 +3704,22 @@ ignored." let mut current: wifi_config_t = core::mem::zeroed(); if esp_wifi_get_config(wifi_interface_t_WIFI_IF_AP, &mut current) == include::ESP_OK as i32 - && current.ap == cfg.ap + && same_access_point_config(¤t.ap, &cfg.ap) { return Ok(()); } - esp_wifi_result!(esp_wifi_set_config(wifi_interface_t_WIFI_IF_AP, &mut cfg)) + esp_wifi_result!(esp_wifi_set_config(wifi_interface_t_WIFI_IF_AP, &mut cfg)).inspect_err( + |e| { + if *e == WifiError::InvalidArguments { + warn!( + "The access point configuration was rejected. Channel {} might not be \ + allowed in the configured country, see `ControllerConfig::country_info`.", + config.channel + ); + } + }, + ) } } @@ -3616,3 +3912,19 @@ ignored." } } } + +/// Compares the fields that come from [`AccessPointConfig`]. The driver changes others in +/// the configuration it stores (`sae_pwe_h2e`; `pmf_cfg` and `pairwise_cipher` for some +/// authentication methods), so a comparison of the whole configuration never matches. +#[cfg(wifi_softap_support)] +fn same_access_point_config(current: &wifi_ap_config_t, new: &wifi_ap_config_t) -> bool { + current.ssid == new.ssid + && current.ssid_len == new.ssid_len + && current.password == new.password + && current.channel == new.channel + && current.authmode == new.authmode + && current.ssid_hidden == new.ssid_hidden + && current.max_connection == new.max_connection + && current.beacon_interval == new.beacon_interval + && current.dtim_period == new.dtim_period +} diff --git a/esp-radio/src/wifi/os_adapter/esp32s31.rs b/esp-radio/src/wifi/os_adapter/esp32s31.rs new file mode 100644 index 00000000000..bb3bc74c288 --- /dev/null +++ b/esp-radio/src/wifi/os_adapter/esp32s31.rs @@ -0,0 +1,81 @@ +use crate::{ + hal::{interrupt::Priority, peripherals::WIFI, ram}, + interrupt_dispatch::Handler, + sys::c_types::{c_int, c_void}, +}; + +static ISR_INTERRUPT_1: Handler = Handler::new(); + +pub(crate) fn chip_ints_on(mask: u32) { + // set_intr called with intr_num = 1 -> mask = 1 << 1 == 2 + trace!("chip_ints_on - mask {:#x}", mask); + if mask & 2 == 2 { + unsafe { + WIFI::steal().enable_mac_interrupt(Priority::Priority1); + WIFI::steal().enable_pwr_interrupt(Priority::Priority1); + } + } +} + +pub(crate) fn chip_ints_off(mask: u32) { + trace!("chip_ints_off - mask {:#x}", mask); + if mask & 2 == 2 { + unsafe { + WIFI::steal().disable_mac_interrupt_on_all_cores(); + WIFI::steal().disable_pwr_interrupt_on_all_cores(); + } + } +} + +pub(crate) unsafe extern "C" fn set_intr( + cpu_no: i32, + intr_source: u32, + intr_num: u32, + intr_prio: i32, +) { + trace!( + "set_intr - core {} interrupt {} num {:?} prio {:?}", + cpu_no, intr_source, intr_num, intr_prio + ); + // These are expected to be direct-bound, but we don't do that for now. +} + +pub(crate) unsafe extern "C" fn regdma_link_set_write_wait_content_dummy( + _arg1: *mut c_void, + _arg2: u32, + _arg3: u32, +) { + todo!() +} + +pub(crate) unsafe extern "C" fn sleep_retention_find_link_by_id_dummy(_arg1: c_int) -> *mut c_void { + todo!() +} + +pub unsafe extern "C" fn set_isr(n: i32, f: *mut c_void, arg: *mut c_void) { + trace!("set_isr - interrupt {} function {:?} arg {:?}", n, f, arg); + + match n { + 1 => ISR_INTERRUPT_1.set(f, arg), + _ => panic!("set_isr - unsupported interrupt number {}", n), + } +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn MODEM_WIFI_MAC() { + ISR_INTERRUPT_1.dispatch(); +} + +#[unsafe(no_mangle)] +#[ram] +extern "C" fn MODEM_WIFI_PWR() { + ISR_INTERRUPT_1.dispatch(); +} + +pub(crate) fn shutdown_wifi_isr() { + unsafe { + WIFI::steal().disable_mac_interrupt_on_all_cores(); + WIFI::steal().disable_pwr_interrupt_on_all_cores(); + } +} diff --git a/esp-radio/src/wifi/os_adapter/mod.rs b/esp-radio/src/wifi/os_adapter/mod.rs index 2936a959548..c1e26d93bc2 100644 --- a/esp-radio/src/wifi/os_adapter/mod.rs +++ b/esp-radio/src/wifi/os_adapter/mod.rs @@ -7,6 +7,7 @@ #[cfg_attr(esp32h2, path = "esp32h2.rs")] #[cfg_attr(esp32s2, path = "esp32s2.rs")] #[cfg_attr(esp32s3, path = "esp32s3.rs")] +#[cfg_attr(esp32s31, path = "esp32s31.rs")] pub(crate) mod os_adapter_chip_specific; use core::ptr::NonNull; @@ -756,24 +757,51 @@ pub unsafe extern "C" fn dport_access_stall_other_cpu_end_wrap() { trace!("dport_access_stall_other_cpu_end_wrap") } /// ************************************************************************** -/// Name: wifi_apb80m_request +/// Name: wifi_pm_sleep_lock_acquire /// /// Description: /// Take Wi-Fi lock in auto-sleep /// /// ************************************************************************* -pub unsafe extern "C" fn wifi_apb80m_request() { - trace!("wifi_apb80m_request - no-op") +pub unsafe extern "C" fn wifi_pm_sleep_lock_acquire() { + trace!("wifi_pm_sleep_lock_acquire"); + esp_hal::if_unstable_hal! { + super::sleep::acquire_sleep_lock(); + } } /// ************************************************************************** -/// Name: wifi_apb80m_release +/// Name: wifi_pm_sleep_lock_release /// /// Description: /// Release Wi-Fi lock in auto-sleep /// /// ************************************************************************* -pub unsafe extern "C" fn wifi_apb80m_release() { - trace!("wifi_apb80m_release - no-op") +pub unsafe extern "C" fn wifi_pm_sleep_lock_release() { + trace!("wifi_pm_sleep_lock_release"); + esp_hal::if_unstable_hal! { + super::sleep::release_sleep_lock(); + } +} + +#[cfg(wifi_has_wifi6)] +pub unsafe extern "C" fn wifi_disable_ac_ax() -> bool { + // IDF's C6/C5/C61 wrappers return false: disabling 11ac/11ax is not supported. + false +} + +#[cfg(wifi_has_wifi6)] +pub unsafe extern "C" fn wifi_sleep_retention_unsupported() -> i32 { + // IDF returns 1 when CONFIG_MAC_BB_PD is off. + 1 +} + +#[cfg(esp32s31)] +pub unsafe extern "C" fn coex_configure_preemption_end_cb( + _is_register: bool, + _cb: Option crate::sys::c_types::c_int>, +) -> crate::sys::c_types::c_int { + // IDF's wrapper returns 0 unless software coex and BLE ISO are both on. + 0 } /// ************************************************************************** @@ -813,6 +841,24 @@ pub unsafe extern "C" fn phy_enable() { trace!("phy_enable"); // Wi-Fi modem enable: also sets Wi-Fi RX (unlike the common-clock gate). esp_phy::enable_phy_with_wifi_rx(); + + // ESP-IDF turns off the baseband idle check (maximum 139 ms) to prevent an unexpected + // RXTXPANIC. + #[cfg(any(esp32c5, esp32c61, esp32s31))] + unsafe { + unsafe extern "C" { + fn set_bb_wdg( + busy_chk: bool, + srch_chk: bool, + max_busy: u16, + max_srch: u16, + rst_en: bool, + int_en: bool, + clr: bool, + ); + } + set_bb_wdg(true, false, 0x18, 0xaa, false, false, false); + } } /// ************************************************************************** @@ -825,9 +871,9 @@ pub unsafe extern "C" fn phy_enable() { #[allow(clippy::unnecessary_cast)] pub unsafe extern "C" fn phy_update_country_info(country: *const c_char) -> c_int { unsafe { - // not implemented in original code + // FIXME trace!("phy_update_country_info {}", str_from_c(country.cast())); - -1 + 0 } } @@ -864,7 +910,7 @@ pub unsafe extern "C" fn wifi_reset_mac() { /// ************************************************************************* pub unsafe extern "C" fn wifi_clock_enable() { trace!("wifi_clock_enable"); - crate::radio_clocks::clocks_ll::enable_wifi(true); + crate::radio_clocks::enable_wifi(true); } /// ************************************************************************** @@ -882,7 +928,7 @@ pub unsafe extern "C" fn wifi_clock_enable() { /// ************************************************************************* pub unsafe extern "C" fn wifi_clock_disable() { trace!("wifi_clock_disable"); - crate::radio_clocks::clocks_ll::enable_wifi(false); + crate::radio_clocks::enable_wifi(false); } /// ************************************************************************** @@ -1481,23 +1527,16 @@ pub unsafe extern "C" fn coex_schm_register_cb_wrapper( pub unsafe extern "C" fn slowclk_cal_get() -> u32 { trace!("slowclk_cal_get"); - // TODO not hardcode this - - #[cfg(esp32s2)] - return 44462; - - #[cfg(esp32s3)] - return 44462; - - #[cfg(esp32c3)] - return 28639; - - #[cfg(esp32c2)] - return 28639; + // esp-hal stores the RTC slow clock period in STORE1, in microseconds, with 19 fractional + // bits. The Wi-Fi driver expects 12 fractional bits. + const RTC_CLK_CAL_FRACT: u32 = 19; + const WIFI_LIGHT_SLEEP_CLK_WIDTH: u32 = 12; - #[cfg(any(esp32c6, esp32h2, esp32c5, esp32c61))] - return 0; + let period = cfg_select! { + esp32s31 => regs!(LP_SYS).lp_store(1).read().bits(), + soc_has_lp_aon => regs!(LP_AON).store1().read().bits(), + _ => regs!(RTC_CNTL).store1().read().bits(), + }; - #[cfg(esp32)] - return 28639; + period >> (RTC_CLK_CAL_FRACT - WIFI_LIGHT_SLEEP_CLK_WIDTH) } diff --git a/esp-radio/src/wifi/scan.rs b/esp-radio/src/wifi/scan.rs index f507849f3e7..3d52cbe7756 100644 --- a/esp-radio/src/wifi/scan.rs +++ b/esp-radio/src/wifi/scan.rs @@ -5,13 +5,17 @@ use core::{marker::PhantomData, mem::MaybeUninit}; use esp_hal::time::Duration; use procmacros::BuilderLite; +#[cfg(feature = "unstable")] +use crate::wifi::CountryInfo; use crate::{ + drop_guard::DropGuard, sys::include, wifi::{ + AuthenticationMethod, + SecondaryChannel, Ssid, WifiController, WifiError, - ap::{AccessPointInfo, convert_ap_info}, esp_wifi_result, }, }; @@ -105,6 +109,49 @@ pub struct ScanConfig { pub(crate) max: Option, } +/// Information about a detected Wi-Fi access point. +#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +#[non_exhaustive] +pub struct AccessPointInfo { + /// The SSID of the access point. + pub ssid: Ssid, + /// The BSSID (MAC address) of the access point. + pub bssid: [u8; 6], + /// The channel the access point is operating on. + pub channel: u8, + /// The secondary channel configuration of the access point. + pub secondary_channel: SecondaryChannel, + /// The signal strength of the access point (RSSI). + pub signal_strength: i8, + /// The authentication method used by the access point. + pub auth_method: Option, + #[cfg(feature = "unstable")] + #[cfg_attr(docsrs, doc(cfg(feature = "unstable")))] + /// The country information of the access point (if available from beacon frames). + pub country: Option, +} + +#[allow(non_upper_case_globals)] +pub(crate) fn convert_ap_info(record: &include::wifi_ap_record_t) -> AccessPointInfo { + // `record.ssid` is 33 bytes to always fit the NUL terminator of a + // maximum-length SSID - clamp to 32 in case the driver ever hands us one + // without it. + let str_len = record.ssid.iter().position(|&c| c == 0).unwrap_or(32); + let ssid = Ssid::try_from(&record.ssid[..str_len]).expect("SSID length is valid"); + + AccessPointInfo { + ssid, + bssid: record.bssid, + channel: record.primary, + secondary_channel: SecondaryChannel::from_raw(record.second), + signal_strength: record.rssi, + auth_method: Some(AuthenticationMethod::from_raw(record.authmode)), + #[cfg(feature = "unstable")] + country: CountryInfo::try_from_c(&record.country), + } +} + /// Wi-Fi scan results. #[derive(Debug)] #[cfg_attr(feature = "defmt", derive(defmt::Format))] @@ -125,7 +172,7 @@ impl<'d> ScanResults<'d> { // returns an error. let mut this = Self { remaining: 0, - _drop_guard: FreeApListOnDrop, + _drop_guard: free_ap_list_on_drop(), _marker: PhantomData, }; @@ -162,21 +209,10 @@ impl Iterator for ScanResults<'_> { } /// AP list on-drop guard. -#[derive(Debug)] -#[cfg_attr(feature = "defmt", derive(defmt::Format))] -pub(super) struct FreeApListOnDrop; +pub(super) type FreeApListOnDrop = DropGuard<(), fn(())>; -impl FreeApListOnDrop { - /// Do not automatically free the AP list when the guard is dropped. - pub fn defuse(self) { - core::mem::forget(self); - } -} - -impl Drop for FreeApListOnDrop { - fn drop(&mut self) { - unsafe { - include::esp_wifi_clear_ap_list(); - } - } +pub(super) fn free_ap_list_on_drop() -> FreeApListOnDrop { + DropGuard::new((), |_| unsafe { + include::esp_wifi_clear_ap_list(); + }) } diff --git a/esp-radio/src/wifi/sleep.rs b/esp-radio/src/wifi/sleep.rs new file mode 100644 index 00000000000..02de938c013 --- /dev/null +++ b/esp-radio/src/wifi/sleep.rs @@ -0,0 +1,87 @@ +//! Light sleep while the station is in power save. +//! +//! The blob wakes the chip for each beacon through the TSF hardware and the `Wifi` wakeup source, +//! or with software timers on the ESP32. The entry hook refuses every sleep that the blob is not +//! ready for. + +use esp_hal::rtc_cntl::{WakeupSource, sleep::WrappedSleepConfig}; +use portable_atomic::{AtomicBool, AtomicU32, Ordering}; + +#[cfg(not(esp32))] +unsafe extern "C" { + fn esp_wifi_internal_is_tsf_active() -> bool; + fn esp_wifi_internal_update_light_sleep_wake_ahead_time(time_us: u32); +} + +/// Time from the wake of the chip to the moment the blob can receive, in microseconds. +/// +/// The blob starts this much earlier before a beacon. esp-hal does not measure its wake time, so +/// this is an estimate with margin. ESP-IDF uses about 370 µs on the C6. +#[cfg(not(esp32))] +const WAKE_AHEAD_US: u32 = 2000; + +static POWER_SAVE: AtomicBool = AtomicBool::new(false); +static STATION_ONLY: AtomicBool = AtomicBool::new(false); + +/// The number of holders of the blob's sleep lock. +static SLEEP_LOCK: AtomicU32 = AtomicU32::new(0); + +/// Records whether the station uses a power save mode. +pub(crate) fn set_power_save(enabled: bool) { + POWER_SAVE.store(enabled, Ordering::Relaxed); +} + +/// Records whether the configured mode is Station mode, without an access point. +pub(crate) fn set_station_only(station_only: bool) { + STATION_ONLY.store(station_only, Ordering::Relaxed); +} + +/// The blob takes this lock while it must stay awake, for example during a scan or while it waits +/// for a beacon. +pub(crate) fn acquire_sleep_lock() { + SLEEP_LOCK.fetch_add(1, Ordering::Relaxed); +} + +/// Releases the lock taken by [`acquire_sleep_lock`]. +pub(crate) fn release_sleep_lock() { + let _ = SLEEP_LOCK.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_sub(1)); +} + +/// Claims the `Wifi` wakeup source, so that the chip can sleep while the station is in power +/// save. +/// +/// Call this after `esp_wifi_init`. +pub(crate) fn claim_wake_source() { + let mhz = esp_hal::clock::cpu_clock().as_mhz() as i32; + unsafe { + #[cfg(not(esp32))] + esp_wifi_internal_update_light_sleep_wake_ahead_time(WAKE_AHEAD_US); + // Without this call, the blob does not arm the TSF wakeup for the next beacon. + crate::sys::include::esp_wifi_internal_update_light_sleep_default_params(mhz, mhz); + } + + WakeupSource::Wifi.enable_with_hooks(Some(sleep_entry), None); +} + +/// Releases the claim taken by [`claim_wake_source`]. +/// +/// Call this before `esp_wifi_deinit`. +pub(crate) fn release_wake_source() { + WakeupSource::Wifi.disable(); +} + +fn sleep_entry(config: &mut WrappedSleepConfig<'_>) { + if config.is_deep_sleep() { + return; + } + + let station_idle = POWER_SAVE.load(Ordering::Relaxed) && STATION_ONLY.load(Ordering::Relaxed); + let tsf_active = cfg_select! { + esp32 => false, + _ => unsafe { esp_wifi_internal_is_tsf_active() }, + }; + + if !station_idle || SLEEP_LOCK.load(Ordering::Relaxed) > 0 || tsf_active { + config.reject_sleep(); + } +} diff --git a/esp-radio/src/wifi/sniffer.rs b/esp-radio/src/wifi/sniffer.rs index a335c6c3d96..ef6a2048bb5 100644 --- a/esp-radio/src/wifi/sniffer.rs +++ b/esp-radio/src/wifi/sniffer.rs @@ -1,10 +1,8 @@ //! Wi-Fi sniffer. -use core::marker::PhantomData; - use esp_sync::NonReentrantMutex; -use super::{RxControlInfo, SNIFFER_BIT, release, try_acquire}; +use super::{RxControlInfo, SNIFFER_BIT, WifiRefGuard, release, try_acquire}; use crate::{ WifiError, sys::include::{ @@ -78,12 +76,12 @@ unsafe extern "C" fn promiscuous_rx_cb(buf: *mut core::ffi::c_void, frame_type: #[cfg_attr(feature = "defmt", derive(defmt::Format))] #[instability::unstable] #[non_exhaustive] -pub struct Sniffer<'d> { - _phantom: PhantomData<&'d ()>, +pub struct Sniffer { + _wifi_guard: WifiRefGuard, } -impl Sniffer<'_> { - pub(crate) fn new() -> Self { +impl Sniffer { + pub(crate) fn new(guard: WifiRefGuard) -> Self { assert!(try_acquire(SNIFFER_BIT), "sniffer already in use"); // If registering the callback fails we panic, so release the singleton @@ -95,9 +93,7 @@ impl Sniffer<'_> { unwrap!(res); } - Self { - _phantom: PhantomData, - } + Self { _wifi_guard: guard } } /// Set promiscuous mode enabled or disabled. @@ -108,6 +104,9 @@ impl Sniffer<'_> { } /// Transmit a raw frame. + /// + /// Returns [`WifiError::Unsupported`] when `use_sta_interface` is `false` and the + /// `ESP_RADIO_CONFIG_WIFI_SOFTAP_SUPPORT` configuration option is disabled. #[instability::unstable] pub fn send_raw_frame( &mut self, @@ -115,6 +114,10 @@ impl Sniffer<'_> { buffer: &[u8], use_internal_seq_num: bool, ) -> Result<(), WifiError> { + if !use_sta_interface && cfg!(not(wifi_softap_support)) { + return Err(WifiError::Unsupported); + } + esp_wifi_result!(unsafe { esp_wifi_80211_tx( if use_sta_interface { @@ -136,7 +139,7 @@ impl Sniffer<'_> { } } -impl Drop for Sniffer<'_> { +impl Drop for Sniffer { fn drop(&mut self) { // Clear the user callback first so the C trampoline becomes a no-op even // if it fires during the teardown window below. diff --git a/esp-radio/src/wifi/state.rs b/esp-radio/src/wifi/state.rs index a90597d720d..055b7c5ff61 100644 --- a/esp-radio/src/wifi/state.rs +++ b/esp-radio/src/wifi/state.rs @@ -1,7 +1,7 @@ use core::sync::atomic::Ordering; +use embassy_sync::lazy_lock::LazyLock; use esp_radio_rtos_driver::semaphore::{SemaphoreHandle, SemaphoreKind}; -use esp_sync::NonReentrantMutex; use portable_atomic_enum::atomic_enum; use super::event::WifiEvent; @@ -113,19 +113,14 @@ pub(crate) fn set_station_state(state: WifiStationState) { } pub(crate) fn locked(f: impl FnOnce() -> R) -> R { - static LOCK: NonReentrantMutex> = NonReentrantMutex::new(None); + static LOCK: LazyLock = + LazyLock::new(|| SemaphoreHandle::new(SemaphoreKind::Mutex)); - LOCK.with(|sem| { - sem.get_or_insert_with(|| SemaphoreHandle::new(SemaphoreKind::Mutex)) - .take(None) - }); + let sem = LOCK.get(); - let res: R = f(); - - LOCK.with(|sem| { - sem.get_or_insert_with(|| SemaphoreHandle::new(SemaphoreKind::Mutex)) - .give() - }); + sem.take(None); + let res = f(); + sem.give(); res } diff --git a/esp-radio/src/wifi/weak_overrides.rs b/esp-radio/src/wifi/weak_overrides.rs new file mode 100644 index 00000000000..1422127b84b --- /dev/null +++ b/esp-radio/src/wifi/weak_overrides.rs @@ -0,0 +1,172 @@ +//! Strong definitions overriding weak symbols in the Wi-Fi blobs, mirroring the stubs ESP-IDF +//! defines in `components/esp_wifi/src/wifi_init.c` when the corresponding feature is disabled. +//! +//! Each group must only be compiled for chips whose blobs define the overridden symbols: +//! these `no_mangle` functions can't be garbage-collected, so on other chips they only waste flash. + +#[cfg(any( + all(wifi_has_nan, not(wifi_nan_sync_enable)), + all(wifi_has_ftm, not(wifi_ftm_enable)) +))] +use crate::sys::include::{ESP_OK, esp_err_t}; + +#[cfg(all(wifi_has_nan, not(wifi_nan_sync_enable)))] +mod nan { + use super::*; + use crate::sys::{ + c_types::{c_int, c_void}, + include::wifi_nan_sync_config_t, + }; + + #[unsafe(no_mangle)] + extern "C" fn nan_start() -> esp_err_t { + ESP_OK as esp_err_t + } + + #[unsafe(no_mangle)] + extern "C" fn nan_stop() -> esp_err_t { + ESP_OK as esp_err_t + } + + #[unsafe(no_mangle)] + extern "C" fn nan_input(_p1: *mut c_void, _p2: c_int, _p3: c_int) -> c_int { + 0 + } + + #[unsafe(no_mangle)] + extern "C" fn nan_sm_handle_event(_p1: *mut c_void, _p2: c_int) {} + + #[unsafe(no_mangle)] + extern "C" fn wifi_create_nan() -> c_int { + 0 + } + + #[unsafe(no_mangle)] + extern "C" fn wifi_nan_set_config_local(_p: *mut wifi_nan_sync_config_t) -> c_int { + 0 + } + + #[unsafe(no_mangle)] + extern "C" fn nan_dp_post_tx(_p1: *mut c_void, _p2: *mut c_void) -> esp_err_t { + ESP_OK as esp_err_t + } + + #[unsafe(no_mangle)] + extern "C" fn nan_dp_delete_peer(_p: *mut c_void) {} + + #[unsafe(no_mangle)] + extern "C" fn nan_dp_search_node(_p: *const u8) -> *mut c_void { + core::ptr::null_mut() + } + + #[unsafe(no_mangle)] + extern "C" fn nan_ndp_resp_timeout_process(_p: *mut c_void) {} +} + +#[cfg(all(wifi_has_ftm, not(wifi_ftm_enable)))] +mod ftm { + use super::*; + + #[unsafe(no_mangle)] + extern "C" fn ieee80211_ftm_attach() -> esp_err_t { + ESP_OK as esp_err_t + } + + #[unsafe(no_mangle)] + extern "C" fn ftm_initiator_cleanup() {} +} + +#[cfg(not(wifi_softap_support))] +mod softap { + use crate::sys::c_types::{c_int, c_void}; + + #[unsafe(no_mangle)] + extern "C" fn net80211_softap_funcs_init() {} + + #[unsafe(no_mangle)] + extern "C" fn ieee80211_ap_try_sa_query(_p: *mut c_void) -> bool { + false + } + + #[unsafe(no_mangle)] + extern "C" fn ieee80211_ap_sa_query_timeout(_p: *mut c_void) -> bool { + false + } + + #[unsafe(no_mangle)] + extern "C" fn add_mic_ie_bip(_p: *mut c_void) -> c_int { + 0 + } + + #[unsafe(no_mangle)] + extern "C" fn ieee80211_free_beacon_eb() {} + + #[unsafe(no_mangle)] + extern "C" fn ieee80211_pwrsave(_p1: *mut c_void, _p2: *mut c_void) -> c_int { + 0 + } + + #[unsafe(no_mangle)] + extern "C" fn cnx_node_remove(_p: *mut c_void) {} + + #[unsafe(no_mangle)] + extern "C" fn ieee80211_set_tim(_p: *mut c_void, _arg: c_int) -> c_int { + 0 + } + + #[unsafe(no_mangle)] + extern "C" fn ieee80211_is_bufferable_mmpdu(_p: *mut c_void) -> bool { + false + } + + #[unsafe(no_mangle)] + extern "C" fn cnx_node_leave(_p: *mut c_void, _arg: u8) {} + + #[unsafe(no_mangle)] + extern "C" fn ieee80211_beacon_construct( + _p1: *mut c_void, + _p2: *mut c_void, + _p3: *mut c_void, + _p4: *mut c_void, + ) { + } + + #[unsafe(no_mangle)] + extern "C" fn ieee80211_assoc_resp_construct(_p: *mut c_void, _arg: c_int) -> *mut c_void { + core::ptr::null_mut() + } + + #[unsafe(no_mangle)] + extern "C" fn ieee80211_alloc_proberesp(_p: *mut c_void, _arg: c_int) -> *mut c_void { + core::ptr::null_mut() + } + + #[unsafe(no_mangle)] + extern "C" fn hostap_query_mac_in_list(_p: *const u8, _arg: c_int) -> bool { + false + } + + #[unsafe(no_mangle)] + extern "C" fn hostap_add_in_mac_list(_p: *const u8, _arg: c_int) -> c_int { + 0 + } + + #[unsafe(no_mangle)] + extern "C" fn hostap_del_mac_info_from_list(_p: *const u8, _arg: c_int) -> c_int { + 0 + } + + #[unsafe(no_mangle)] + extern "C" fn create_new_bss_for_sa_query_failed_sta(_arg: u8) {} +} + +mod beacon_offset { + unsafe extern "C" { + fn pm_beacon_offset_funcs_empty_init(); + } + + #[unsafe(no_mangle)] + extern "C" fn pm_beacon_offset_funcs_init() { + unsafe { pm_beacon_offset_funcs_empty_init() } + } +} diff --git a/esp-riscv-rt/src/lib.rs b/esp-riscv-rt/src/lib.rs index b3982420e4f..d076c11061b 100644 --- a/esp-riscv-rt/src/lib.rs +++ b/esp-riscv-rt/src/lib.rs @@ -85,6 +85,18 @@ __pre_init:"#, addi a0, a0, 4 blt a0, a1, 1b 2: +"#, + // Zero .dram2_uninit.bss + r#" + la a0, _dram2_uninit_bss_start + la a1, _dram2_uninit_bss_end + bge a0, a1, 2f + mv a3, x0 + 1: + sw a3, 0(a0) + addi a0, a0, 4 + blt a0, a1, 1b + 2: "#, r#" ret diff --git a/esp-rom-sys/Cargo.toml b/esp-rom-sys/Cargo.toml index a8f48a1aab1..beb6a33b71a 100644 --- a/esp-rom-sys/Cargo.toml +++ b/esp-rom-sys/Cargo.toml @@ -29,20 +29,21 @@ test = false [dependencies] document-features = "0.2" -esp32 = { version = "0.41", features = ["critical-section"], optional = true } -esp32c2 = { version = "0.30", features = ["critical-section"], optional = true } -esp32c3 = { version = "0.33", features = ["critical-section"], optional = true } -esp32c5 = { version = "0.3", features = ["critical-section"], optional = true } -esp32c6 = { version = "0.24", features = ["critical-section"], optional = true } -esp32c61 = { version = "0.4", features = ["critical-section"], optional = true } -esp32h2 = { version = "0.20", features = ["critical-section"], optional = true } -esp32s2 = { version = "0.32", features = ["critical-section"], optional = true } -esp32s3 = { version = "0.36", features = ["critical-section"], optional = true } -esp32s31 = { version = "0.2", features = ["critical-section"], optional = true } -esp32p4 = { version = "0.3", features = ["critical-section"], optional = true } +esp32 = { version = "0.42", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32c2 = { version = "0.31", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32c3 = { version = "0.34", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32c5 = { version = "0.4", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32c6 = { version = "0.25", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32c61 = { version = "0.5", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32h2 = { version = "0.21", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32h4 = { version = "0.1", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32s2 = { version = "0.33", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32s3 = { version = "0.37", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32s31 = { version = "0.3", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32p4 = { version = "0.4", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } [build-dependencies] -esp-metadata-generated = { version = "0.5.0", path = "../esp-metadata-generated", features = ["build-script"] } +esp-metadata-generated = { version = "0.6.0", path = "../esp-metadata-generated", features = ["build-script"] } [features] __internal_rom_symbols = [] @@ -65,6 +66,8 @@ esp32c61 = [ "dep:esp32c61" ] ## esp32h2 = [ "dep:esp32h2" ] ## +esp32h4 = [ "dep:esp32h4" ] +## esp32p4 = [ "dep:esp32p4" ] ## esp32s2 = [ "dep:esp32s2" ] diff --git a/esp-rom-sys/ld/esp32/rom/esp32.rom.ld b/esp-rom-sys/ld/esp32/rom/esp32.rom.ld index 6cca533158f..3ba8fce757d 100644 --- a/esp-rom-sys/ld/esp32/rom/esp32.rom.ld +++ b/esp-rom-sys/ld/esp32/rom/esp32.rom.ld @@ -674,6 +674,7 @@ PROVIDE ( ld_inq_end = 0x4003ab48 ); PROVIDE ( ld_inq_sched = 0x4003aba4 ); PROVIDE ( ld_inq_frm_cbk = 0x4003ae4c ); PROVIDE ( ld_pscan_frm_cbk = 0x4003ebe4 ); +PROVIDE ( ld_pscan_evt_start_cbk = 0x4003e924 ); PROVIDE ( r_ld_acl_active_hop_types_get = 0x40036e10 ); PROVIDE ( r_ld_acl_afh_confirm = 0x40036d40 ); PROVIDE ( r_ld_acl_afh_prepare = 0x40036c84 ); @@ -776,12 +777,14 @@ PROVIDE ( r_ld_iscan_restart = 0x4003ba44 ); PROVIDE ( r_ld_iscan_start = 0x4003bb28 ); PROVIDE ( r_ld_iscan_stop = 0x4003bf1c ); PROVIDE ( r_ld_iscan_tx_pwr_get = 0x4003c138 ); +PROVIDE ( ld_iscan_evt_start_cbk = 0x4003b58c ); PROVIDE ( r_ld_page_init = 0x4003d808 ); PROVIDE ( r_ld_page_reset = 0x4003d814 ); PROVIDE ( r_ld_page_start = 0x4003d848 ); PROVIDE ( r_ld_page_stop = 0x4003da54 ); PROVIDE ( ld_page_frm_cbk = 0x4003d280 ); PROVIDE ( ld_page_em_init = 0x4003cb34 ); +PROVIDE ( ld_page_evt_start_cbk = 0x4003cf40 ); PROVIDE ( r_ld_pca_coarse_clock_adjust = 0x4003e324 ); PROVIDE ( r_ld_pca_init = 0x4003deb4 ); PROVIDE ( r_ld_pca_initiate_clock_dragging = 0x4003e4ac ); diff --git a/esp-rom-sys/ld/esp32h4/libesp_rom_sys.a b/esp-rom-sys/ld/esp32h4/libesp_rom_sys.a new file mode 100644 index 00000000000..aff08cf6348 --- /dev/null +++ b/esp-rom-sys/ld/esp32h4/libesp_rom_sys.a @@ -0,0 +1 @@ +INCLUDE "rom-functions.x" diff --git a/esp-rom-sys/ld/esp32h4/rom-functions.x b/esp-rom-sys/ld/esp32h4/rom-functions.x new file mode 100644 index 00000000000..bf4f4658d94 --- /dev/null +++ b/esp-rom-sys/ld/esp32h4/rom-functions.x @@ -0,0 +1,9 @@ +/* Taken from esp-idf commit 2067f3ae32b. + The ESP32-H4 ROM does not provide heap (TLSF) or RVFP linker scripts. */ +INCLUDE "rom/esp32h4.rom.api.ld" +INCLUDE "rom/esp32h4.rom.ld" +INCLUDE "rom/esp32h4.rom.libgcc.ld" +INCLUDE "rom/esp32h4.rom.spiflash.ld" +INCLUDE "rom/esp32h4.rom.version.ld" + +INCLUDE "rom/additional.ld" diff --git a/esp-rom-sys/ld/esp32h4/rom/additional.ld b/esp-rom-sys/ld/esp32h4/rom/additional.ld new file mode 100644 index 00000000000..22075d23b3e --- /dev/null +++ b/esp-rom-sys/ld/esp32h4/rom/additional.ld @@ -0,0 +1,29 @@ +memset = 0x40000498; +memcpy = 0x4000049c; +memmove = 0x400004a0; +memcmp = 0x400004a4; + +strncmp = 0x400004b4; +strncpy = 0x400004ac; +strcpy = 0x400004a8; + +abs = 0x4000055c; + +PROVIDE( strcat = 0x40000518 ); +PROVIDE( strcmp = 0x400004b0 ); +PROVIDE( strchr = 0x4000051c ); +PROVIDE( strlcpy = 0x4000052c ); +PROVIDE( strstr = 0x400004bc ); +PROVIDE( strcasecmp = 0x40000510 ); + +PROVIDE( memchr = 0x40000508 ); + +EXTERN(__mktime); +EXTERN(__strnlen); +EXTERN(__atoi); + +PROVIDE ( strnlen = __strnlen ); +PROVIDE ( atoi = __atoi ); +PROVIDE ( mktime = __mktime ); + +syscall_table_ptr = 0x4085ffd0; diff --git a/esp-rom-sys/ld/esp32h4/rom/esp32h4.rom.api.ld b/esp-rom-sys/ld/esp32h4/rom/esp32h4.rom.api.ld new file mode 100644 index 00000000000..0b49e76e4be --- /dev/null +++ b/esp-rom-sys/ld/esp32h4/rom/esp32h4.rom.api.ld @@ -0,0 +1,67 @@ +/* + * SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +/** ROM APIs + */ + +PROVIDE ( esp_rom_crc32_le = crc32_le ); +PROVIDE ( esp_rom_crc16_le = crc16_le ); +PROVIDE ( esp_rom_crc8_le = crc8_le ); +PROVIDE ( esp_rom_crc32_be = crc32_be ); +PROVIDE ( esp_rom_crc16_be = crc16_be ); +PROVIDE ( esp_rom_crc8_be = crc8_be ); + +PROVIDE ( esp_rom_gpio_pad_select_gpio = rom_gpio_pad_select_gpio ); +PROVIDE ( esp_rom_gpio_pad_pullup_only = rom_gpio_pad_pullup ); +PROVIDE ( esp_rom_gpio_pad_set_drv = rom_gpio_pad_set_drv ); +PROVIDE ( esp_rom_gpio_pad_unhold = rom_gpio_pad_unhold ); +PROVIDE ( esp_rom_gpio_connect_in_signal = rom_gpio_matrix_in ); +PROVIDE ( esp_rom_gpio_connect_out_signal = rom_gpio_matrix_out ); + +PROVIDE ( esp_rom_efuse_mac_address_crc8 = esp_crc8 ); +PROVIDE ( esp_rom_efuse_is_secure_boot_enabled = ets_efuse_secure_boot_enabled ); + +PROVIDE ( esp_rom_uart_flush_tx = uart_tx_flush ); +PROVIDE ( esp_rom_uart_tx_one_char = uart_tx_one_char2 ); +PROVIDE ( esp_rom_uart_tx_wait_idle = uart_tx_wait_idle ); +PROVIDE ( esp_rom_uart_rx_one_char = uart_rx_one_char ); +PROVIDE ( esp_rom_uart_rx_string = UartRxString ); +PROVIDE ( esp_rom_uart_set_as_console = uart_tx_switch ); +PROVIDE ( esp_rom_uart_putc = ets_write_char_uart ); + +PROVIDE ( esp_rom_usb_serial_putc = uart_tx_one_char3 ); + +PROVIDE ( esp_rom_output_flush_tx = uart_tx_flush ); +PROVIDE ( esp_rom_output_tx_one_char = uart_tx_one_char ); +PROVIDE ( esp_rom_output_tx_wait_idle = uart_tx_wait_idle ); +PROVIDE ( esp_rom_output_rx_one_char = uart_rx_one_char ); +PROVIDE ( esp_rom_output_rx_string = UartRxString ); +PROVIDE ( esp_rom_output_set_as_console = uart_tx_switch ); +PROVIDE ( esp_rom_output_putc = ets_write_char_uart ); + +PROVIDE ( esp_rom_md5_init = MD5Init ); +PROVIDE ( esp_rom_md5_update = MD5Update ); +PROVIDE ( esp_rom_md5_final = MD5Final ); + +PROVIDE ( esp_rom_software_reset_system = software_reset ); +PROVIDE ( esp_rom_software_reset_cpu = software_reset_cpu ); + +PROVIDE ( esp_rom_printf = ets_printf ); +PROVIDE ( esp_rom_install_uart_printf = ets_install_uart_printf ); +PROVIDE ( esp_rom_delay_us = ets_delay_us ); +PROVIDE ( esp_rom_get_reset_reason = rtc_get_reset_reason ); +PROVIDE ( esp_rom_route_intr_matrix = intr_matrix_set ); +PROVIDE ( esp_rom_get_cpu_ticks_per_us = ets_get_cpu_frequency ); +PROVIDE ( esp_rom_set_cpu_ticks_per_us = ets_update_cpu_frequency ); + +PROVIDE ( esp_rom_spiflash_attach = spi_flash_attach ); +PROVIDE ( esp_rom_spiflash_clear_bp = esp_rom_spiflash_unlock ); +PROVIDE ( esp_rom_spiflash_write_enable = SPI_write_enable ); +PROVIDE ( esp_rom_spiflash_erase_area = SPIEraseArea ); + +PROVIDE ( esp_rom_spiflash_fix_dummylen = spi_dummy_len_fix ); +PROVIDE ( esp_rom_spiflash_set_drvs = SetSpiDrvs); +PROVIDE ( esp_rom_spiflash_select_padsfunc = SelectSpiFunction ); +PROVIDE ( esp_rom_spiflash_common_cmd = SPI_Common_Command ); diff --git a/esp-rom-sys/ld/esp32h4/rom/esp32h4.rom.ld b/esp-rom-sys/ld/esp32h4/rom/esp32h4.rom.ld new file mode 100644 index 00000000000..44b02fa5e3d --- /dev/null +++ b/esp-rom-sys/ld/esp32h4/rom/esp32h4.rom.ld @@ -0,0 +1,403 @@ +/* + * SPDX-FileCopyrightText: 2025-2026 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +/* ROM function interface esp32h4.rom.ld for esp32h4 + * + * + * Generated from ../../rom/target/esp32h4/interface-esp32h4.yml md5sum bb9ee317148d3c5b10610936a3675a65 + * + * Compatible with ROM where ECO version equal or greater to 0. + * + * THIS FILE WAS AUTOMATICALLY GENERATED. DO NOT EDIT. + */ + +/*************************************** + Group common + ***************************************/ + +/* Functions */ +rtc_get_reset_reason = 0x40000018; +rtc_get_wakeup_cause = 0x4000001c; +pmu_enable_unhold_pads = 0x40000020; +ets_printf = 0x40000024; +ets_install_putc1 = 0x40000028; +ets_install_putc2 = 0x4000002c; +ets_install_uart_printf = 0x40000030; +ets_install_usb_printf = 0x40000034; +ets_get_printf_channel = 0x40000038; +ets_delay_us = 0x4000003c; +ets_get_cpu_frequency = 0x40000040; +ets_update_cpu_frequency = 0x40000044; +ets_install_lock = 0x40000048; +UartRxString = 0x4000004c; +UartGetCmdLn = 0x40000050; +uart_tx_one_char = 0x40000054; +uart_tx_one_char2 = 0x40000058; +uart_tx_one_char3 = 0x4000005c; +uart_rx_one_char = 0x40000060; +uart_rx_one_char_block = 0x40000064; +uart_rx_intr_handler = 0x40000068; +uart_rx_readbuff = 0x4000006c; +uartAttach = 0x40000070; +uart_tx_flush = 0x40000074; +uart_tx_wait_idle = 0x40000078; +uart_div_modify = 0x4000007c; +ets_write_char_uart = 0x40000080; +uart_tx_switch = 0x40000084; +uart_buff_switch = 0x40000088; +roundup2 = 0x4000008c; +multofup = 0x40000090; +software_reset = 0x40000094; +software_reset_cpu = 0x40000098; +ets_clk_assist_debug_clock_enable = 0x4000009c; +clear_super_wdt_reset_flag = 0x400000a0; +disable_default_watchdog = 0x400000a4; +ets_set_appcpu_boot_addr = 0x400000a8; +send_packet = 0x400000ac; +recv_packet = 0x400000b0; +GetUartDevice = 0x400000b4; +UartDwnLdProc = 0x400000b8; +GetSecurityInfoProc = 0x400000bc; +Uart_Init = 0x400000c0; +ets_set_user_start = 0x400000c4; +/* Data (.data, .bss, .rodata) */ +ets_rom_layout_p = 0x4001fffc; +ets_ops_table_ptr = 0x4085fff4; +g_saved_pc = 0x4085fff8; + + +/*************************************** + Group miniz + ***************************************/ + +/* Functions */ +mz_adler32 = 0x400000c8; +mz_free = 0x400000cc; +tdefl_compress = 0x400000d0; +tdefl_compress_buffer = 0x400000d4; +tdefl_compress_mem_to_heap = 0x400000d8; +tdefl_compress_mem_to_mem = 0x400000dc; +tdefl_compress_mem_to_output = 0x400000e0; +tdefl_get_adler32 = 0x400000e4; +tdefl_get_prev_return_status = 0x400000e8; +tdefl_init = 0x400000ec; +tdefl_write_image_to_png_file_in_memory = 0x400000f0; +tdefl_write_image_to_png_file_in_memory_ex = 0x400000f4; +tinfl_decompress = 0x400000f8; +tinfl_decompress_mem_to_callback = 0x400000fc; +tinfl_decompress_mem_to_heap = 0x40000100; +tinfl_decompress_mem_to_mem = 0x40000104; + + +/*************************************** + Group spi_extmem_common + ***************************************/ + +/* Functions */ +esp_rom_spi_cmd_config = 0x40000108; +esp_rom_spi_cmd_start = 0x4000010c; +esp_rom_spi_set_op_mode = 0x40000110; + + +/*************************************** + Group spiflash_legacy + ***************************************/ + +/* Functions */ +esp_rom_spiflash_wait_idle = 0x40000114; +esp_rom_spiflash_write_encrypted = 0x40000118; +esp_rom_spiflash_write_encrypted_dest = 0x4000011c; +esp_rom_spiflash_write_encrypted_enable = 0x40000120; +esp_rom_spiflash_write_encrypted_disable = 0x40000124; +esp_rom_spiflash_erase_chip = 0x40000128; +_esp_rom_spiflash_erase_sector = 0x4000012c; +_esp_rom_spiflash_erase_block = 0x40000130; +_esp_rom_spiflash_write = 0x40000134; +_esp_rom_spiflash_read = 0x40000138; +_esp_rom_spiflash_unlock = 0x4000013c; +_SPIEraseArea = 0x40000140; +_SPI_write_enable = 0x40000144; +esp_rom_spiflash_erase_sector = 0x40000148; +esp_rom_spiflash_erase_block = 0x4000014c; +esp_rom_spiflash_write = 0x40000150; +esp_rom_spiflash_read = 0x40000154; +esp_rom_spiflash_unlock = 0x40000158; +SPIEraseArea = 0x4000015c; +SPI_write_enable = 0x40000160; +esp_rom_spiflash_config_param = 0x40000164; +esp_rom_spiflash_read_user_cmd = 0x40000168; +esp_rom_spiflash_select_qio_pins = 0x4000016c; +esp_rom_spi_flash_auto_sus_res = 0x40000170; +esp_rom_spi_flash_send_resume = 0x40000174; +esp_rom_spi_flash_update_id = 0x40000178; +esp_rom_spiflash_config_clk = 0x4000017c; +esp_rom_spiflash_config_readmode = 0x40000180; +esp_rom_spiflash_read_status = 0x40000184; +esp_rom_spiflash_read_statushigh = 0x40000188; +esp_rom_spiflash_write_status = 0x4000018c; +esp_rom_spiflash_write_disable = 0x40000190; +spi_cache_mode_switch = 0x40000194; +spi_common_set_dummy_output = 0x40000198; +spi_common_set_flash_cs_timing = 0x4000019c; +esp_rom_spi_set_address_bit_len = 0x400001a0; +SPILock = 0x400001a4; +SPIMasterReadModeCnfig = 0x400001a8; +SPI_Common_Command = 0x400001ac; +SPI_WakeUp = 0x400001b0; +SPI_block_erase = 0x400001b4; +SPI_chip_erase = 0x400001b8; +SPI_init = 0x400001bc; +SPI_page_program = 0x400001c0; +SPI_read_data = 0x400001c4; +SPI_sector_erase = 0x400001c8; +SelectSpiFunction = 0x400001cc; +SetSpiDrvs = 0x400001d0; +Wait_SPI_Idle = 0x400001d4; +spi_dummy_len_fix = 0x400001d8; +Disable_QMode = 0x400001dc; +Enable_QMode = 0x400001e0; +spi_flash_attach = 0x400001e4; +spi_flash_get_chip_size = 0x400001e8; +spi_flash_guard_set = 0x400001ec; +spi_flash_guard_get = 0x400001f0; +spi_flash_read_encrypted = 0x400001f4; +/* Data (.data, .bss, .rodata) */ +rom_spiflash_legacy_funcs = 0x4085ffec; +rom_spiflash_legacy_data = 0x4085ffe8; +g_flash_guard_ops = 0x4085fff0; + + +/*************************************** + Group cache + ***************************************/ + +/* Functions */ +Cache_Get_Line_Size = 0x400005a8; +Cache_Get_Mode = 0x400005ac; +Cache_Address_Through_Cache = 0x400005b0; +ROM_Boot_Cache_Init = 0x400005b4; +Cache_Sync_Items = 0x400005b8; +Cache_Op_Addr = 0x400005bc; +Cache_Invalidate_Addr = 0x400005c0; +Cache_Clean_Addr = 0x400005c4; +PROVIDE( Cache_WriteBack_Addr = 0x400005c8 ); +PROVIDE( Cache_WriteBack_Invalidate_Addr = 0x400005cc ); +Cache_Invalidate_All = 0x400005d0; +Cache_Clean_All = 0x400005d4; +PROVIDE( Cache_WriteBack_All = 0x400005d8 ); +PROVIDE( Cache_WriteBack_Invalidate_All = 0x400005dc ); +Cache_Mask_All = 0x400005e0; +Cache_UnMask_Dram0 = 0x400005e4; +Cache_Suspend_Autoload = 0x400005e8; +Cache_Resume_Autoload = 0x400005ec; +Cache_Start_Preload = 0x400005f0; +Cache_Preload_Done = 0x400005f4; +Cache_End_Preload = 0x400005f8; +Cache_Config_Autoload = 0x400005fc; +Cache_Enable_Autoload = 0x40000600; +Cache_Disable_Autoload = 0x40000604; +Cache_Enable_PreLock = 0x40000608; +Cache_Disable_PreLock = 0x4000060c; +Cache_Lock_Items = 0x40000610; +Cache_Lock_Addr = 0x40000614; +Cache_Unlock_Addr = 0x40000618; +Cache_Disable_Cache = 0x4000061c; +Cache_Enable_Cache = 0x40000620; +Cache_Suspend_Cache = 0x40000624; +Cache_Resume_Cache = 0x40000628; +Cache_Freeze_Enable = 0x4000062c; +Cache_Freeze_Disable = 0x40000630; +Cache_Set_IDROM_MMU_Size = 0x40000634; +Cache_Get_IROM_MMU_End = 0x40000638; +Cache_Get_DROM_MMU_End = 0x4000063c; +Cache_MMU_Init = 0x40000640; +Cache_MSPI_MMU_Set = 0x40000644; +Cache_MSPI_MMU_Set_Secure = 0x40000648; +Cache_Count_Flash_Pages = 0x4000064c; +flash2spiram_instruction_offset = 0x40000650; +flash2spiram_rodata_offset = 0x40000654; +flash_instr_rodata_start_page = 0x40000658; +flash_instr_rodata_end_page = 0x4000065c; +Cache_Set_IDROM_MMU_Info = 0x40000660; +Cache_Flash_To_SPIRAM_Copy = 0x40000664; +/* Data (.data, .bss, .rodata) */ +rom_cache_op_cb = 0x4085ffc8; +rom_cache_internal_table_ptr = 0x4085ffc4; + + +/*************************************** + Group clock + ***************************************/ + +/* Functions */ +ets_clk_get_xtal_freq = 0x40000668; +ets_clk_get_cpu_freq = 0x4000066c; + + +/*************************************** + Group gpio + ***************************************/ + +/* Functions */ +rom_gpio_set_output_level = 0x40000670; +rom_gpio_get_input_level = 0x40000674; +rom_gpio_matrix_in = 0x40000678; +rom_gpio_matrix_out = 0x4000067c; +rom_gpio_bypass_matrix_in = 0x40000680; +rom_gpio_output_disable = 0x40000684; +rom_gpio_output_enable = 0x40000688; +rom_gpio_pad_input_disable = 0x4000068c; +rom_gpio_pad_input_enable = 0x40000690; +rom_gpio_pad_pulldown = 0x40000694; +rom_gpio_pad_pullup = 0x40000698; +rom_gpio_pad_select_gpio = 0x4000069c; +rom_gpio_pad_set_drv = 0x400006a0; +rom_gpio_pad_unhold = 0x400006a4; +rom_gpio_pad_hold = 0x400006a8; + + +/*************************************** + Group interrupts + ***************************************/ + +/* Functions */ +esprv_intc_int_set_priority = 0x400006ac; +esprv_intc_int_set_threshold = 0x400006b0; +esprv_intc_int_enable = 0x400006b4; +esprv_intc_int_disable = 0x400006b8; +esprv_intc_int_set_type = 0x400006bc; +PROVIDE( intr_handler_set = 0x400006c0 ); +intr_matrix_set = 0x400006c4; +ets_intr_register_ctx = 0x400006c8; +ets_intr_lock = 0x400006cc; +ets_intr_unlock = 0x400006d0; +ets_isr_attach = 0x400006d4; +ets_isr_mask = 0x400006d8; +ets_isr_unmask = 0x400006dc; + + +/*************************************** + Group crc + ***************************************/ + +/* Functions */ +crc32_le = 0x400006e0; +crc16_le = 0x400006e4; +crc8_le = 0x400006e8; +crc32_be = 0x400006ec; +crc16_be = 0x400006f0; +crc8_be = 0x400006f4; +esp_crc8 = 0x400006f8; +/* Data (.data, .bss, .rodata) */ +crc32_le_table_ptr = 0x4001fff8; +crc16_le_table_ptr = 0x4001fff4; +crc8_le_table_ptr = 0x4001fff0; +crc32_be_table_ptr = 0x4001ffec; +crc16_be_table_ptr = 0x4001ffe8; +crc8_be_table_ptr = 0x4001ffe4; + + +/*************************************** + Group md5 + ***************************************/ + +/* Functions */ +md5_vector = 0x400006fc; +MD5Init = 0x40000700; +MD5Update = 0x40000704; +MD5Final = 0x40000708; + + +/*************************************** + Group hwcrypto + ***************************************/ + +/* Functions */ +ets_sha_enable = 0x4000070c; +ets_sha_disable = 0x40000710; +ets_sha_get_state = 0x40000714; +ets_sha_init = 0x40000718; +ets_sha_process = 0x4000071c; +ets_sha_starts = 0x40000720; +ets_sha_update = 0x40000724; +ets_sha_finish = 0x40000728; +ets_sha_clone = 0x4000072c; +ets_hmac_enable = 0x40000730; +ets_hmac_disable = 0x40000734; +ets_hmac_calculate_message = 0x40000738; +ets_hmac_calculate_downstream = 0x4000073c; +ets_hmac_invalidate_downstream = 0x40000740; +ets_aes_enable = 0x40000744; +ets_aes_disable = 0x40000748; +ets_aes_setkey = 0x4000074c; +ets_aes_block = 0x40000750; +ets_aes_setkey_dec = 0x40000754; +ets_aes_setkey_enc = 0x40000758; + + +/*************************************** + Group efuse + ***************************************/ + +/* Functions */ +ets_efuse_read = 0x4000075c; +ets_efuse_program = 0x40000760; +ets_efuse_clear_program_registers = 0x40000764; +ets_efuse_write_key = 0x40000768; +ets_efuse_get_read_register_address = 0x4000076c; +ets_efuse_get_key_purpose = 0x40000770; +ets_efuse_key_block_unused = 0x40000774; +ets_efuse_find_unused_key_block = 0x40000778; +ets_efuse_rs_calculate = 0x4000077c; +ets_efuse_count_unused_key_blocks = 0x40000780; +ets_efuse_secure_boot_enabled = 0x40000784; +ets_efuse_secure_boot_aggressive_revoke_enabled = 0x40000788; +ets_efuse_cache_encryption_enabled = 0x4000078c; +ets_efuse_download_modes_disabled = 0x40000790; +ets_efuse_find_purpose = 0x40000794; +ets_efuse_force_send_resume = 0x40000798; +ets_efuse_get_flash_delay_us = 0x4000079c; +ets_efuse_get_uart_print_control = 0x400007a0; +ets_efuse_direct_boot_mode_disabled = 0x400007a4; +ets_efuse_security_download_modes_enabled = 0x400007a8; +ets_efuse_jtag_disabled = 0x400007ac; +ets_efuse_usb_print_is_disabled = 0x400007b0; +ets_efuse_usb_download_mode_disabled = 0x400007b4; +ets_efuse_usb_device_disabled = 0x400007b8; +ets_jtag_enable_temporarily = 0x400007bc; + + +/*************************************** + Group key_mgr + ***************************************/ + +/* Functions */ +esp_rom_check_recover_key = 0x400007c0; +esp_rom_km_huk_conf = 0x400007c4; +esp_rom_km_huk_risk = 0x400007c8; +esp_rom_recover_key = 0x400007cc; + + +/*************************************** + Group secureboot + ***************************************/ + +/* Functions */ +ets_ecdsa_verify = 0x400007d0; +ets_secure_boot_verify_bootloader_with_keys = 0x400007d4; +ets_secure_boot_verify_signature = 0x400007d8; +ets_secure_boot_read_key_digests = 0x400007dc; +ets_secure_boot_revoke_public_key_digest = 0x400007e0; + + +/*************************************** + Group usb_device_uart + ***************************************/ + +/* Functions */ +usb_serial_device_rx_one_char = 0x40000910; +usb_serial_device_rx_one_char_block = 0x40000914; +usb_serial_device_tx_flush = 0x40000918; +usb_serial_device_tx_one_char = 0x4000091c; diff --git a/esp-rom-sys/ld/esp32h4/rom/esp32h4.rom.libgcc.ld b/esp-rom-sys/ld/esp32h4/rom/esp32h4.rom.libgcc.ld new file mode 100644 index 00000000000..23a382adc8b --- /dev/null +++ b/esp-rom-sys/ld/esp32h4/rom/esp32h4.rom.libgcc.ld @@ -0,0 +1,95 @@ +/* + * SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +/* ROM function interface esp32h4.rom.libgcc.ld for esp32h4 + * + * + * Generated from ../../rom/target/esp32h4/interface-esp32h4.yml md5sum bb9ee317148d3c5b10610936a3675a65 + * + * Compatible with ROM where ECO version equal or greater to 0. + * + * THIS FILE WAS AUTOMATICALLY GENERATED. DO NOT EDIT. + */ + +/*************************************** + Group libgccdf + ***************************************/ + +/* Functions */ +__absvdi2 = 0x400007e4; +__absvsi2 = 0x400007e8; +__adddf3 = 0x400007ec; +__addvdi3 = 0x400007f0; +__addvsi3 = 0x400007f4; +__ashldi3 = 0x400007f8; +__ashrdi3 = 0x400007fc; +__bswapdi2 = 0x40000800; +__bswapsi2 = 0x40000804; +__clear_cache = 0x40000808; +__clrsbdi2 = 0x4000080c; +__clrsbsi2 = 0x40000810; +__clzdi2 = 0x40000814; +__clzsi2 = 0x40000818; +__cmpdi2 = 0x4000081c; +__ctzdi2 = 0x40000820; +__ctzsi2 = 0x40000824; +__divdc3 = 0x40000828; +__divdf3 = 0x4000082c; +__divdi3 = 0x40000830; +__divsc3 = 0x40000834; +__divsi3 = 0x40000838; +__eqdf2 = 0x4000083c; +__extendsfdf2 = 0x40000840; +__ffsdi2 = 0x40000844; +__ffssi2 = 0x40000848; +__fixdfdi = 0x4000084c; +__fixdfsi = 0x40000850; +__fixsfdi = 0x40000854; +__fixunsdfsi = 0x40000858; +__fixunssfdi = 0x4000085c; +__fixunssfsi = 0x40000860; +__floatdidf = 0x40000864; +__floatdisf = 0x40000868; +__floatsidf = 0x4000086c; +__floatundidf = 0x40000870; +__floatundisf = 0x40000874; +__floatunsidf = 0x40000878; +__gcc_bcmp = 0x4000087c; +__gedf2 = 0x40000880; +__gtdf2 = 0x40000884; +__ledf2 = 0x40000888; +__lshrdi3 = 0x4000088c; +__ltdf2 = 0x40000890; +__moddi3 = 0x40000894; +__modsi3 = 0x40000898; +__muldc3 = 0x4000089c; +__muldf3 = 0x400008a0; +__muldi3 = 0x400008a4; +__mulsc3 = 0x400008a8; +__mulsi3 = 0x400008ac; +__mulvdi3 = 0x400008b0; +__mulvsi3 = 0x400008b4; +__nedf2 = 0x400008b8; +__negdf2 = 0x400008bc; +__negdi2 = 0x400008c0; +__negvdi2 = 0x400008c4; +__negvsi2 = 0x400008c8; +__paritysi2 = 0x400008cc; +__popcountdi2 = 0x400008d0; +__popcountsi2 = 0x400008d4; +__powidf2 = 0x400008d8; +__subdf3 = 0x400008dc; +__subvdi3 = 0x400008e0; +__subvsi3 = 0x400008e4; +__ucmpdi2 = 0x400008e8; +__udivdi3 = 0x400008ec; +__udivmoddi4 = 0x400008f0; +__udivsi3 = 0x400008f4; +__udiv_w_sdiv = 0x400008f8; +__umoddi3 = 0x400008fc; +__umodsi3 = 0x40000900; +__unorddf2 = 0x40000904; +__extenddftf2 = 0x40000908; +__trunctfdf2 = 0x4000090c; diff --git a/esp-rom-sys/ld/esp32h4/rom/esp32h4.rom.spiflash.ld b/esp-rom-sys/ld/esp32h4/rom/esp32h4.rom.spiflash.ld new file mode 100644 index 00000000000..867021de143 --- /dev/null +++ b/esp-rom-sys/ld/esp32h4/rom/esp32h4.rom.spiflash.ld @@ -0,0 +1,129 @@ +/* + * SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +/* ROM function interface esp32h4.rom.spiflash.ld for esp32h4 + * + * + * Generated from ../../rom/target/esp32h4/interface-esp32h4.yml md5sum bb9ee317148d3c5b10610936a3675a65 + * + * Compatible with ROM where ECO version equal or greater to 0. + * + * THIS FILE WAS AUTOMATICALLY GENERATED. DO NOT EDIT. + */ + +/*************************************** + Group spi_flash_cache + ***************************************/ + +/* Functions */ +rom_spi_flash_disable_cache = 0x400001f8; +rom_spi_flash_restore_cache = 0x400001fc; +spi_flash_cache_enabled = 0x40000200; +spi_flash_enable_cache = 0x40000204; +esp_enable_cache_flash_wrap = 0x40000208; + + +/*************************************** + Group esp_flash + ***************************************/ + +/* Functions */ +esp_flash_chip_driver_initialized = 0x4000020c; +esp_flash_read_id = 0x40000210; +esp_flash_get_size = 0x40000214; +esp_flash_erase_chip = 0x40000218; +esp_flash_erase_region = 0x4000021c; +esp_flash_get_chip_write_protect = 0x40000220; +esp_flash_set_chip_write_protect = 0x40000224; +esp_flash_get_protectable_regions = 0x40000228; +esp_flash_get_protected_region = 0x4000022c; +esp_flash_set_protected_region = 0x40000230; +PROVIDE( esp_flash_read = 0x40000234 ); +esp_flash_write = 0x40000238; +esp_flash_write_encrypted = 0x4000023c; +esp_flash_read_encrypted = 0x40000240; +PROVIDE( esp_flash_get_io_mode = 0x40000244 ); +esp_flash_set_io_mode = 0x40000248; +spi_flash_boot_attach = 0x4000024c; +esp_flash_read_chip_id = 0x40000250; +detect_spi_flash_chip = 0x40000254; +esp_flash_suspend_cmd_init = 0x40000258; +/* Data (.data, .bss, .rodata) */ +esp_flash_default_chip = 0x4085ffe4; +esp_flash_api_funcs = 0x4085ffe0; + + +/*************************************** + Group spi_flash_chips + ***************************************/ + +/* Functions */ +spi_flash_chip_generic_probe = 0x4000025c; +spi_flash_chip_generic_detect_size = 0x40000260; +spi_flash_chip_generic_write = 0x40000264; +spi_flash_chip_generic_write_encrypted = 0x40000268; +spi_flash_chip_generic_set_write_protect = 0x4000026c; +spi_flash_common_write_status_16b_wrsr = 0x40000270; +spi_flash_chip_generic_reset = 0x40000274; +spi_flash_chip_generic_erase_chip = 0x40000278; +spi_flash_chip_generic_erase_sector = 0x4000027c; +spi_flash_chip_generic_erase_block = 0x40000280; +spi_flash_chip_generic_page_program = 0x40000284; +spi_flash_chip_generic_get_write_protect = 0x40000288; +spi_flash_common_read_status_16b_rdsr_rdsr2 = 0x4000028c; +spi_flash_chip_generic_read_reg = 0x40000290; +spi_flash_chip_generic_yield = 0x40000294; +spi_flash_generic_wait_host_idle = 0x40000298; +spi_flash_chip_generic_wait_idle = 0x4000029c; +spi_flash_chip_generic_config_host_io_mode = 0x400002a0; +spi_flash_chip_generic_read = 0x400002a4; +spi_flash_common_read_status_8b_rdsr2 = 0x400002a8; +spi_flash_chip_generic_get_io_mode = 0x400002ac; +spi_flash_common_read_status_8b_rdsr = 0x400002b0; +spi_flash_common_write_status_8b_wrsr = 0x400002b4; +spi_flash_common_write_status_8b_wrsr2 = 0x400002b8; +spi_flash_common_set_io_mode = 0x400002bc; +spi_flash_chip_generic_set_io_mode = 0x400002c0; +spi_flash_chip_generic_read_unique_id = 0x400002c4; +spi_flash_chip_generic_get_caps = 0x400002c8; +spi_flash_chip_generic_suspend_cmd_conf = 0x400002cc; +spi_flash_chip_gd_get_io_mode = 0x400002d0; +spi_flash_chip_gd_probe = 0x400002d4; +spi_flash_chip_gd_set_io_mode = 0x400002d8; +/* Data (.data, .bss, .rodata) */ +spi_flash_chip_generic_config_data = 0x4085ffdc; +spi_flash_encryption = 0x4085ffd8; + + +/*************************************** + Group hal_spiflash + ***************************************/ + +/* Functions */ +spi_flash_hal_poll_cmd_done = 0x400002dc; +spi_flash_hal_device_config = 0x400002e0; +spi_flash_hal_configure_host_io_mode = 0x400002e4; +spi_flash_hal_common_command = 0x400002e8; +spi_flash_hal_read = 0x400002ec; +spi_flash_hal_erase_chip = 0x400002f0; +spi_flash_hal_erase_sector = 0x400002f4; +spi_flash_hal_erase_block = 0x400002f8; +spi_flash_hal_program_page = 0x400002fc; +spi_flash_hal_set_write_protect = 0x40000300; +spi_flash_hal_host_idle = 0x40000304; +spi_flash_hal_check_status = 0x40000308; +spi_flash_hal_setup_read_suspend = 0x4000030c; +spi_flash_hal_setup_auto_suspend_mode = 0x40000310; +spi_flash_hal_setup_auto_resume_mode = 0x40000314; +spi_flash_hal_disable_auto_suspend_mode = 0x40000318; +spi_flash_hal_disable_auto_resume_mode = 0x4000031c; +spi_flash_hal_resume = 0x40000320; +spi_flash_hal_suspend = 0x40000324; +spi_flash_encryption_hal_enable = 0x40000328; +spi_flash_encryption_hal_disable = 0x4000032c; +spi_flash_encryption_hal_prepare = 0x40000330; +spi_flash_encryption_hal_done = 0x40000334; +spi_flash_encryption_hal_destroy = 0x40000338; +spi_flash_encryption_hal_check = 0x4000033c; diff --git a/esp-rom-sys/ld/esp32h4/rom/esp32h4.rom.version.ld b/esp-rom-sys/ld/esp32h4/rom/esp32h4.rom.version.ld new file mode 100644 index 00000000000..32221447522 --- /dev/null +++ b/esp-rom-sys/ld/esp32h4/rom/esp32h4.rom.version.ld @@ -0,0 +1,13 @@ +/* + * SPDX-FileCopyrightText: 2025 Espressif Systems (Shanghai) CO LTD + * + * SPDX-License-Identifier: Apache-2.0 + */ +/* ROM version variables for esp32h4 + * + * These addresses should be compatible with any ROM version for this chip. + * + * THIS FILE WAS AUTOMATICALLY GENERATED. DO NOT EDIT. + */ +_rom_chip_id = 0x40000010; +_rom_eco_version = 0x40000014; diff --git a/esp-rom-sys/ld/esp32s3/rom/additional.ld b/esp-rom-sys/ld/esp32s3/rom/additional.ld index 44a37290194..6137e510e6c 100644 --- a/esp-rom-sys/ld/esp32s3/rom/additional.ld +++ b/esp-rom-sys/ld/esp32s3/rom/additional.ld @@ -11,6 +11,7 @@ bzero = 0x40001260; PROVIDE(cache_dbus_mmu_set = 0x400019b0); PROVIDE( Cache_Suspend_DCache_Autoload = 0x40001734 ); +PROVIDE( Cache_Suspend_ICache = 0x4000189c ); PROVIDE( Cache_Suspend_DCache = 0x400018b4 ); PROVIDE( strcat = 0x40001374 ); diff --git a/esp-phy/esp-phy b/esp-rom-sys/libs/esp32h4/unused similarity index 100% rename from esp-phy/esp-phy rename to esp-rom-sys/libs/esp32h4/unused diff --git a/esp-rom-sys/src/reg_access.rs b/esp-rom-sys/src/reg_access.rs index 9cb8cae174b..d960f905f7a 100644 --- a/esp-rom-sys/src/reg_access.rs +++ b/esp-rom-sys/src/reg_access.rs @@ -20,6 +20,8 @@ pub(crate) use esp32c61 as pac; #[cfg(esp32h2)] #[expect(unused)] pub(crate) use esp32h2 as pac; +#[cfg(esp32h4)] +pub(crate) use esp32h4 as pac; #[cfg(esp32p4)] #[expect(unused)] pub(crate) use esp32p4 as pac; diff --git a/esp-rom-sys/src/rom/mod.rs b/esp-rom-sys/src/rom/mod.rs index bd3f5603bab..30821bc714c 100644 --- a/esp-rom-sys/src/rom/mod.rs +++ b/esp-rom-sys/src/rom/mod.rs @@ -62,7 +62,7 @@ pub fn software_reset() -> ! { } /// Set App cpu Entry code, code can be called in PRO CPU. -#[cfg(any(esp32s3, esp32p4, esp32s31))] +#[cfg(any(esp32s3, esp32h4, esp32p4, esp32s31))] #[inline(always)] pub fn ets_set_appcpu_boot_addr(boot_addr: u32) { unsafe extern "C" { @@ -93,8 +93,9 @@ extern "C" fn rtc_clk_xtal_freq_get() -> i32 { // just rely on RTC_CNTL_STORE4 (regs!(RTC_CNTL).store4().read().bits() & 0xff) as i32 } - any(esp32c5, esp32c61) => { - // PCR_CLK_XTAL_FREQ updates its value based on EFUSE_XTAL_48M_SEL. + any(esp32c5, esp32c61, esp32h4) => { + // PCR_CLK_XTAL_FREQ holds the XTAL frequency in MHz. On the ESP32-C5 + // and ESP32-C61 it is updated based on EFUSE_XTAL_48M_SEL. regs!(PCR).sysclk_conf().read().clk_xtal_freq().bits() as i32 } _ => { diff --git a/esp-rom-sys/src/rom/spiflash.rs b/esp-rom-sys/src/rom/spiflash.rs index 5f0b23cc3aa..e1440041c6c 100644 --- a/esp-rom-sys/src/rom/spiflash.rs +++ b/esp-rom-sys/src/rom/spiflash.rs @@ -33,8 +33,10 @@ unsafe extern "C" { /// Write data to flash with transparent encryption. /// - /// `flash_addr` and `len` must be 32-byte aligned. The sector must already be - /// erased. + /// The sector must already be erased. `data` may be encrypted in place. + /// + /// On ESP32, `flash_addr` and `len` must be 32-byte aligned. On later + /// chips the ROM accepts 16-, 32-, or 64-byte rows (chip-dependent max). pub fn esp_rom_spiflash_write_encrypted(flash_addr: u32, data: *mut u32, len: u32) -> i32; /// Enable SPI flash encryption mode. diff --git a/esp-rtos/CHANGELOG.md b/esp-rtos/CHANGELOG.md index 5bdb128fbab..45c3523fc2c 100644 --- a/esp-rtos/CHANGELOG.md +++ b/esp-rtos/CHANGELOG.md @@ -9,8 +9,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- Initial support for ESP32-P4 (#5523, #5535) -- Add ESP32-S31 support (#5922) ### Changed @@ -21,6 +19,37 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Removed +## [v0.4.0] - 2026-08-25 + +### Added + +- Initial support for ESP32-P4 (#5523, #5535) +- Add ESP32-S31 support (#5922) +- `start_on_second_core_only` on multi-core chips, for applications where it is simpler to keep the first core bare metal. (#6044) +- Configuration for the esp-radio timer thread priority. (#5908) +- Sleep: enabled auto-lightsleep when esp-rtos runs on multiple cores (#5825) +- `rearm_alarm` to manually adjust the time base after waking up from light sleep (#5778) +- ESP32-C6, ESP32-H2: `auto_light_sleep`, an idle-hook factory that puts the system into light sleep when idle long enough, restoring timekeeping and re-arming the scheduler timer on wake. (#5756) +- `ESP_RTOS_CONFIG_LIGHT_SLEEP_MIN_US` config option setting the minimum residency below which light sleep is skipped. (#5756) + +### Changed + +- `start` functions and `InterruptExecutor::new` now take `FROM_CPU_INTRn` singletons instead of `SoftwareInterrupt` structs. (#6142) +- `DeepSleep::deep_sleep` no longer takes a list of wakeup sources. (#6060) +- The automatic light sleep hook owns one wakeup source, the timer deadline, and leaves every (#6060) +- `auto_light_sleep` has been removed. Instead, the `sleep` module now has a `configure` function that returns `Sleep`. `Sleep` holds the idle hook function, as well as a deep sleep handle. (#5839) +- updated defmt to 1.1 (#5752) + +### Fixed + +- the main task can no longer be deleted (on either core) (#6032) +- deleting a task no longer allows reallocating its stack memory while the stack may be in use. (#6032) +- a task deleting itself no longer blocks going to sleep (#6032) +- deleting the other core's current task now triggers switching away from that task (#6032) +- main task stack sizes are correctly tracked (#6027) +- the idle tasks now perform stack overflow checking (#6027) +- fixed a potential crash on RISC-V devices (#5641) + ## [v0.3.0] - 2026-04-16 ### Added @@ -87,4 +116,5 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 [v0.1.1]: https://github.com/esp-rs/esp-hal/compare/esp-rtos-v0.1.0...esp-rtos-v0.1.1 [v0.2.0]: https://github.com/esp-rs/esp-hal/compare/esp-rtos-v0.1.1...esp-rtos-v0.2.0 [v0.3.0]: https://github.com/esp-rs/esp-hal/compare/esp-rtos-v0.2.0...esp-rtos-v0.3.0 -[Unreleased]: https://github.com/esp-rs/esp-hal/compare/esp-rtos-v0.3.0...HEAD +[v0.4.0]: https://github.com/esp-rs/esp-hal/compare/esp-rtos-v0.3.0...esp-rtos-v0.4.0 +[Unreleased]: https://github.com/esp-rs/esp-hal/compare/esp-rtos-v0.4.0...HEAD diff --git a/esp-rtos/Cargo.toml b/esp-rtos/Cargo.toml index 64438d888e3..c365a6a9d42 100644 --- a/esp-rtos/Cargo.toml +++ b/esp-rtos/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "esp-rtos" -version = "0.3.0" +version = "0.4.0" edition = "2024" rust-version = "1.95.0" description = "A task scheduler for Espressif devices" @@ -12,9 +12,10 @@ license = "MIT OR Apache-2.0" [package.metadata.espressif] chip-features-matter = true -doc-config = { features = ["esp-hal/unstable", "embassy", "esp-radio"] } +doc-config = { features = ["esp-hal/unstable", "embassy", "esp-radio", "defmt"] } check-configs = [ { features = ["esp-hal/unstable"] }, + { features = ["esp-hal/unstable", "alloc"] }, { features = ["esp-hal/unstable", "esp-alloc"] }, { features = ["esp-hal/unstable", "esp-radio"] }, { features = ["esp-hal/unstable", "esp-radio", "embassy"] }, @@ -35,7 +36,7 @@ features = ["esp32c6", "embassy", "esp-radio"] bench = false [dependencies] -esp-hal = { version = "~1.2.0-rc.0", path = "../esp-hal", default-features = false, features = [ +esp-hal = { version = "~1.2.0", path = "../esp-hal", default-features = false, features = [ # FIXME: rt technically shouldn't be enabled, but rtos requires `TrapFrame` # and uses reexported riscv/xtensa-lx from esp-hal "requires-unstable", "rt" @@ -48,10 +49,10 @@ rtos-trace = { version = "0.2.0", optional = true } allocator-api2 = { version = "0.3.0", default-features = false, features = ["alloc"], optional = true } document-features = "0.2" embassy-sync = "0.8" -esp-alloc = { version = "0.10.0", path = "../esp-alloc", optional = true, default-features = false } +esp-alloc = { version = "0.11.0", path = "../esp-alloc", optional = true, default-features = false } esp-config = { version = "0.8.0", path = "../esp-config" } esp-sync = { version = "0.3.0", path = "../esp-sync" } -esp-radio-rtos-driver = { version = "0.3.0", path = "../esp-radio-rtos-driver", features = ["ipc-implementations"], optional = true } +esp-radio-rtos-driver = { version = "0.4.2", path = "../esp-radio-rtos-driver", features = ["ipc-implementations"], optional = true } macros = { version = "0.23.0", package = "esp-hal-procmacros", path = "../esp-hal-procmacros" } portable-atomic = { version = "1.11", default-features = false } @@ -72,10 +73,10 @@ xtensa-lx = { version = "0.13.0", path = "../xtensa-lx" } [build-dependencies] esp-config = { version = "0.8.0", path = "../esp-config", features = ["build"] } -esp-metadata-generated = { version = "0.5.0", path = "../esp-metadata-generated", features = ["build-script"] } +esp-metadata-generated = { version = "0.6.0", path = "../esp-metadata-generated", features = ["build-script"] } [dev-dependencies] -esp-hal = { version = "~1.2.0-rc.0", path = "../esp-hal", features = ["unstable"] } +esp-hal = { version = "~1.2.0", path = "../esp-hal", features = ["unstable"] } static_cell = "2" [features] @@ -87,18 +88,18 @@ embassy = ["dep:embassy-time-driver", "dep:embassy-executor", "dep:embassy-time- ## Enable esp-radio support. esp-radio = ["alloc", "dep:esp-radio-rtos-driver"] -# Not documented because we don't currently expose anything that requires alloc, but isn't related to esp-radio. -# TODO: make this public once we actually have alloc-based APIs. -alloc = ["dep:allocator-api2", "dep:esp-radio-rtos-driver", "defmt?/alloc"] - -## Enable the use of the `esp-alloc` crate for dynamic memory allocation. +## Enable APIs that dynamically allocate memory, such as spawning a thread on a heap-allocated stack. +## +## Memory allocation is required by `esp-radio`. ## -## Memory allocation is required by `esp-radio`. If you choose to not enable -## this feature, you need to provide implementations for the following functions: +## Without `esp-alloc` you must provide the following functions: ## - `pub extern "C" fn malloc_internal(size: usize) -> *mut u8` ## - `pub extern "C" fn free_internal(ptr: *mut u8)` -## +## ## Note that the untyped nature of the allocator functions means that esp-alloc is likely the more memory efficient option. +alloc = ["dep:allocator-api2", "defmt?/alloc"] + +## Enable the use of the `esp-alloc` crate for dynamic memory allocation. Also enables `alloc`. esp-alloc = ["alloc", "dep:esp-alloc"] ## Enable [`rtos-trace`](https://crates.io/crates/rtos-trace) support. @@ -157,6 +158,13 @@ esp32h2 = [ "esp-rom-sys/esp32h2", ] ## +esp32h4 = [ + "esp-hal/esp32h4", + "esp-alloc?/esp32h4", + "esp-metadata-generated/esp32h4", + "esp-rom-sys/esp32h4", +] +## esp32p4 = [ "esp-hal/esp32p4", "esp-alloc?/esp32p4", diff --git a/esp-rtos/src/esp_radio/mod.rs b/esp-rtos/src/esp_radio/mod.rs index b8ec5c31e40..b836118529b 100644 --- a/esp-rtos/src/esp_radio/mod.rs +++ b/esp-rtos/src/esp_radio/mod.rs @@ -20,9 +20,11 @@ use esp_radio_rtos_driver::{ }; use crate::{ + SCHEDULER, run_queue::{MaxPriority, Priority}, scheduler::Scheduler, task::{self, Task, TaskExt as _}, + thread::ThreadSpawner, wait_queue::WaitQueue, }; @@ -68,23 +70,32 @@ impl esp_radio_rtos_driver::SchedulerImplementation for Scheduler { pin_to_core: Option, task_stack_size: usize, ) -> ThreadPtr { - self.create_task( - name, - task, - param, - task_stack_size, - priority.min(self.max_task_priority()), - pin_to_core.and_then(|core| match core { - 0 => Some(Cpu::ProCpu), - #[cfg(multi_core)] - 1 => Some(Cpu::AppCpu), - _ => { - warn!("Invalid core number: {}", core); - None - } - }), - ) - .cast() + debug!( + "task_create {} {:?}({:?}) stack_size = {} priority = {}", + name, task, param, task_stack_size, priority + ); + + // Debug builds use a lot more stack than release builds do. + #[cfg(debug_build)] + let task_stack_size = task_stack_size + 6 * 1024; + + let mut spawner = ThreadSpawner::new(task_stack_size) + .with_priority(priority.min(self.max_task_priority()) as usize); + + let pin_to_core = pin_to_core.and_then(|core| match core { + 0 => Some(Cpu::ProCpu), + #[cfg(multi_core)] + 1 => Some(Cpu::AppCpu), + _ => { + warn!("Invalid core number: {}", core); + None + } + }); + if let Some(cpu) = pin_to_core { + spawner = spawner.with_pinned_to(cpu); + } + + spawner.spawn_extern(task, param).cast() } fn current_task(&self) -> ThreadPtr { @@ -147,20 +158,22 @@ impl WaitQueueImplementation for WaitQueue { } unsafe fn wait_until(queue: WaitQueuePtr, deadline_instant: Option) { - let wait_queue = unsafe { Self::from_ptr(queue) }; - - wait_queue.wait_with_deadline( - Instant::EPOCH - + deadline_instant - .map(Duration::from_micros) - .unwrap_or(Duration::MAX), - ) + let deadline = Instant::EPOCH + + deadline_instant + .map(Duration::from_micros) + .unwrap_or(Duration::MAX); + + SCHEDULER.with(|scheduler| { + let wait_queue = unsafe { Self::from_ptr(queue) }; + wait_queue.wait_with_deadline(scheduler, deadline) + }) } unsafe fn notify(queue: WaitQueuePtr) { - let wait_queue = unsafe { Self::from_ptr(queue) }; - - wait_queue.notify() + SCHEDULER.with(|scheduler| { + let wait_queue = unsafe { Self::from_ptr(queue) }; + wait_queue.notify(scheduler) + }) } unsafe fn notify_from_isr(queue: WaitQueuePtr, _higher_prio_task_waken: Option<&mut bool>) { diff --git a/esp-rtos/src/fmt.rs b/esp-rtos/src/fmt.rs index 14722707e80..339c97e0ba7 100644 --- a/esp-rtos/src/fmt.rs +++ b/esp-rtos/src/fmt.rs @@ -252,6 +252,7 @@ macro_rules! unwrap { #[cold] #[inline(never)] +#[track_caller] #[cfg(not(feature = "defmt"))] pub(crate) fn __unwrap_failed(arg: &str, e: impl ::core::fmt::Debug) -> ! { ::core::panic!("unwrap of `{}` failed: {:?}", arg, e); @@ -259,6 +260,7 @@ pub(crate) fn __unwrap_failed(arg: &str, e: impl ::core::fmt::Debug) -> ! { #[cold] #[inline(never)] +#[track_caller] #[cfg(not(feature = "defmt"))] pub(crate) fn __unwrap_failed_with_message( arg: &str, diff --git a/esp-rtos/src/lib.rs b/esp-rtos/src/lib.rs index b5b0a54b9e9..667b8d2fa7e 100644 --- a/esp-rtos/src/lib.rs +++ b/esp-rtos/src/lib.rs @@ -9,8 +9,7 @@ //! //! ## Setup //! -//! This crate requires an `esp-hal` timer, as well as the `FROM_CPU0` software interrupt to -//! operate, and needs to be started like so: +//! This crate requires an `esp-hal` timer to operate, and needs to be started like so: //! //! ```rust, no_run #![doc = esp_hal::before_snippet!()] @@ -28,7 +27,7 @@ //! use esp_hal::timer::timg::TimerGroup; //! let timg0 = TimerGroup::new(peripherals.TIMG0); //! -//! esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); +//! esp_rtos::start(timg0.timer0); #![cfg_attr( multi_core, doc = " @@ -39,7 +38,6 @@ use esp_hal::system::Stack; static STACK: ConstStaticCell> = ConstStaticCell::new(Stack::new()); esp_rtos::start_second_core( peripherals.CPU_CTRL, - peripherals.FROM_CPU_INTR1, STACK.take(), || {}, // Second core's main function. ); @@ -51,6 +49,11 @@ esp_rtos::start_second_core( #![doc = esp_hal::after_snippet!()] //! ``` //! +//! ## Threads +//! +//! Use the [`thread`] module to run code on a separate stack. See its documentation for the +//! details. +//! //! To write `async` code, enable the `embassy` feature, and make the main function `async`. //! This will create a thread-mode executor on the main thread. Note that, to create async tasks, you will need //! the `task` macro from the `embassy-executor` crate. Do NOT enable any of the `arch-*` features on `embassy-executor`. @@ -122,7 +125,6 @@ let sleep = esp_rtos::sleep::configure(p.LPWR); esp_rtos::start_with_idle_hook( timg0.timer0, - p.FROM_CPU_INTR0, sleep.light_sleep_hook, ); # } @@ -157,9 +159,8 @@ mod scheduler; pub mod sleep; mod syscall; mod task; +pub mod thread; mod timer; -// TODO: these esp-radio gates will need to be cleaned up once we re-introduce IPC objects. -#[cfg(feature = "esp-radio")] mod wait_queue; #[cfg(feature = "embassy")] @@ -176,14 +177,13 @@ use esp_hal::timer::systimer::Alarm; use esp_hal::timer::timg::Timer; use esp_hal::{ Blocking, - peripherals::FROM_CPU_INTR0, system::Cpu, time::Instant, timer::{AnyTimer, OneShotTimer, any::Degrade}, }; #[cfg(multi_core)] use esp_hal::{ - peripherals::{CPU_CTRL, FROM_CPU_INTR1}, + peripherals::CPU_CTRL, system::{CpuControl, Stack}, time::Duration, }; @@ -356,6 +356,7 @@ fn init_tracing() { } } +#[track_caller] fn assert_thread_mode(function: &str) { assert!( esp_hal::interrupt::RunLevel::current().is_thread(), @@ -372,8 +373,8 @@ fn assert_thread_mode(function: &str) { /// idle hook will wait for an interrupt. /// /// For information about the arguments, see [`start_with_idle_hook`]. -pub fn start(timer: impl TimerSource, int0: FROM_CPU_INTR0<'static>) { - start_with_idle_hook(timer, int0, crate::task::idle_hook) +pub fn start(timer: impl TimerSource) { + start_with_idle_hook(timer, crate::task::idle_hook) } /// Starts the scheduler, with a custom idle hook. @@ -393,11 +394,7 @@ pub fn start(timer: impl TimerSource, int0: FROM_CPU_INTR0<'static>) { /// - A `OneShotTimer` instance /// /// For an example, see the [crate-level documentation][self]. -pub fn start_with_idle_hook( - timer: impl TimerSource, - int0: FROM_CPU_INTR0<'static>, - idle_hook: IdleFn, -) { +pub fn start_with_idle_hook(timer: impl TimerSource, idle_hook: IdleFn) { init_tracing(); trace!("Starting scheduler for the first core"); @@ -431,7 +428,7 @@ pub fn start_with_idle_hook( unsafe { (&raw const __stack_chk_guard).read_volatile() }, ); - task::setup_multitasking(int0); + task::setup_multitasking(); // Set up the main task's context. task::yield_task(); @@ -451,11 +448,10 @@ pub fn start_with_idle_hook( #[cfg(multi_core)] pub fn start_second_core( cpu_control: CPU_CTRL, - int1: FROM_CPU_INTR1<'static>, stack: &'static mut Stack, func: impl FnOnce() + Send + 'static, ) { - start_second_core_with_stack_guard_offset::(cpu_control, int1, stack, None, func); + start_second_core_with_stack_guard_offset::(cpu_control, stack, None, func); } /// The stack of the second core, in a form that can be moved into the second core's main function. @@ -542,7 +538,6 @@ fn suspend_main_task() { #[cfg(multi_core)] pub fn start_second_core_with_stack_guard_offset( cpu_control: CPU_CTRL, - int1: FROM_CPU_INTR1<'static>, stack: &'static mut Stack, stack_guard_offset: Option, func: impl FnOnce() + Send + 'static, @@ -562,7 +557,7 @@ pub fn start_second_core_with_stack_guard_offset( .start_app_core_with_stack_guard_offset(stack, Some(stack_guard_offset), move || { trace!("Second core running"); SCHEDULER.with(move |scheduler| { - task::setup_smp(int1); + task::setup_multitasking(); assert!( scheduler.time_driver.is_some(), "The scheduler must be started on the first core first." @@ -639,7 +634,6 @@ pub fn start_second_core_with_stack_guard_offset( /// /// esp_rtos::start_on_second_core_only( /// peripherals.CPU_CTRL, -/// peripherals.FROM_CPU_INTR1, /// timg0.timer0, /// STACK.take(), /// || { @@ -653,7 +647,6 @@ pub fn start_second_core_with_stack_guard_offset( #[cfg(multi_core)] pub fn start_on_second_core_only( cpu_control: CPU_CTRL<'static>, - int1: FROM_CPU_INTR1<'static>, timer: impl TimerSource + Send, stack: &'static mut Stack, func: impl FnOnce() + Send + 'static, @@ -677,7 +670,7 @@ pub fn start_on_second_core_only( .start_app_core_with_stack_guard_offset(stack, Some(stack_guard_offset), move || { trace!("Second core running"); SCHEDULER.with(move |scheduler| { - task::setup_multitasking(int1); + task::setup_multitasking(); // The time driver must be created here, and not on the first core: // `Timer::set_interrupt_handler` binds the timer interrupt to the core that calls diff --git a/esp-rtos/src/run_queue.rs b/esp-rtos/src/run_queue.rs index 8e51d1b2fae..6dd3296c9cc 100644 --- a/esp-rtos/src/run_queue.rs +++ b/esp-rtos/src/run_queue.rs @@ -167,7 +167,6 @@ impl RunQueue { let priority_n = priority.get(); ready_task.set_state(TaskState::Ready); - #[cfg(feature = "esp-radio")] { let mut ready_task = ready_task; if let Some(mut containing_queue) = @@ -244,8 +243,15 @@ impl RunQueue { } } + /// Removes the highest priority task that the current CPU can run. + /// + /// `other_cpu_task` is the current task of the other CPU. The other CPU still runs on its + /// stack, even if the task is ready again, so this function does not return it. #[esp_hal::ram] - pub(crate) fn pop(&mut self) -> Option { + pub(crate) fn pop( + &mut self, + #[cfg(multi_core)] other_cpu_task: *const crate::task::Task, + ) -> Option { let current_prio = self.ready_priority.ready(); trace!("pop - from level: {}", current_prio); @@ -265,7 +271,9 @@ impl RunQueue { let mut current_prio = current_prio; let mut popped; loop { - popped = self.ready_tasks[current_prio].pop_if(|t| t.pinned_to != Some(other)); + popped = self.ready_tasks[current_prio].pop_if(|t| { + t.pinned_to != Some(other) && !core::ptr::eq(t, other_cpu_task) + }); if popped.is_none() { priority_level.unmark(current_prio); diff --git a/esp-rtos/src/scheduler.rs b/esp-rtos/src/scheduler.rs index dc2e856f0e9..e1e1f5dbafe 100644 --- a/esp-rtos/src/scheduler.rs +++ b/esp-rtos/src/scheduler.rs @@ -5,21 +5,17 @@ use core::{ ptr::NonNull, }; -#[cfg(feature = "alloc")] -use allocator_api2::boxed::Box; use embassy_sync::blocking_mutex::Mutex; use esp_hal::{system::Cpu, time::Instant}; use esp_sync::RawMutex; use macros::ram; -#[cfg(feature = "alloc")] -use crate::InternalMemory; #[cfg(feature = "rtos-trace")] use crate::TraceEvents; #[cfg(feature = "embassy")] use crate::timer::embassy::TimerQueue; use crate::{ - run_queue::{Priority, RunQueue}, + run_queue::{Priority, RunQueue, RunSchedulerOn}, task::{ self, ContextExt, @@ -129,13 +125,13 @@ impl CpuState { main_task: Task { cpu_context: CpuContext::new(), thread_local: ThreadLocalData::new(), + name: None, state: TaskState::Ready, stack: core::ptr::slice_from_raw_parts_mut(core::ptr::null_mut(), 0), #[cfg(any(hw_task_overflow_detection, sw_task_overflow_detection))] stack_guard: core::ptr::null_mut(), #[cfg(sw_task_overflow_detection)] stack_guard_value: 0, - #[cfg(feature = "esp-radio")] current_wait_queue: None, priority: Priority::ZERO, #[cfg(multi_core)] @@ -150,8 +146,7 @@ impl CpuState { timer_queue_item: TaskListItem::None, delete_list_item: TaskListItem::None, - #[cfg(feature = "alloc")] - heap_allocated: false, + thread: None, }, } } @@ -175,7 +170,12 @@ impl SchedulerState { #[cfg(multi_core)] pub(crate) fn priority_of_core(per_cpu: &[CpuState], core: usize) -> Priority { - unsafe { per_cpu[core].current_task.as_ref() } + Self::priority_of_task(per_cpu[core].current_task) + } + + #[cfg(multi_core)] + fn priority_of_task(task: *mut Task) -> Priority { + unsafe { task.as_ref() } .map(|task| task.priority) .unwrap_or(Priority::ZERO) } @@ -194,22 +194,18 @@ impl SchedulerState { ); self.time_driver = Some(time_driver); self.active_cores = ActiveCores::Single(Cpu::current()); - for cpu in 0..Cpu::COUNT { - task::set_idle_hook_entry(&mut self.per_cpu[cpu].idle_context, idle_hook); + for per_cpu in &mut self.per_cpu { + task::set_idle_hook_entry(&mut per_cpu.idle_context, idle_hook); } } - #[cfg(feature = "esp-radio")] - pub(crate) fn create_task( - &mut self, - name: &str, - task: extern "C" fn(*mut c_void), - param: *mut c_void, - task_stack_size: usize, - priority: usize, - pinned_to: Option, - ) -> TaskPtr { - if let Some(cpu) = pinned_to { + /// Adds a task to the scheduler. + /// + /// The caller must have initialized the `Task` object, and must keep it alive until the task + /// is deleted. + pub(crate) fn register_task(&mut self, mut task_ptr: TaskPtr) { + #[cfg(multi_core)] + if let Some(cpu) = unsafe { task_ptr.as_ref().pinned_to } { assert!( self.active_cores.contains(cpu), "Cannot create a task on {:?}, because the scheduler does not run on it", @@ -217,13 +213,6 @@ impl SchedulerState { ); } - let mut task = Box::new_in( - Task::new(name, task, param, task_stack_size, priority, pinned_to), - InternalMemory, - ); - task.heap_allocated = true; - let mut task_ptr = NonNull::from(Box::leak(task)); - unsafe { task_ptr .as_mut() @@ -240,17 +229,17 @@ impl SchedulerState { .mark_task_ready(&self.per_cpu, self.active_cores, task_ptr); task::trigger_scheduler(run_scheduler); - debug!("Task '{}' created: {:?}", name, task_ptr); - - task_ptr + debug!("Task created: {:?}", task_ptr); } /// Deletes the tasks marked for deletion on `cpu`, except the one that owns `current_sp`. /// /// A task that deletes itself keeps running on its own stack until the scheduler switches away /// from it. Freeing that stack here would hand it back to the allocator while this CPU still - /// writes to it, and the other core could hand it out again. Such a task stays in the list, and - /// a later scheduler run deletes it, once this CPU runs on a different stack. + /// writes to it, and the other core could hand it out again. Such a task stays in the list, + /// and this function requests another scheduler run, which deletes the task once this CPU runs + /// on a different stack. Without that request the task could stay in the list forever, because + /// a CPU that has nothing else to run goes idle. /// /// Only the task the CPU currently runs on can be deferred, so the list holds at most one task /// after this function returns. @@ -274,6 +263,7 @@ impl SchedulerState { if let Some(task_ptr) = in_use { self.per_cpu[cpu as usize].to_delete.push(task_ptr); + task::trigger_scheduler(RunSchedulerOn::RunOnCore(cpu)); } } @@ -335,7 +325,14 @@ impl SchedulerState { } let mut arm_next_timeslice_tick = false; - let next_task = self.run_queue.pop(); + + #[cfg(multi_core)] + let other_core_task = self.per_cpu[1 - current_cpu].current_task; + + let next_task = self.run_queue.pop( + #[cfg(multi_core)] + other_core_task, + ); if next_task != current_task || deleted_self { debug!("Switching task {:?} -> {:?}", current_task, next_task); @@ -355,8 +352,7 @@ impl SchedulerState { #[cfg(multi_core)] if self.active_cores.is_smp() && current_ref.pinned_to.is_none() - && current_ref.priority - >= Self::priority_of_core(&self.per_cpu, 1 - current_cpu) + && current_ref.priority >= Self::priority_of_task(other_core_task) { task::schedule_other_core(); } @@ -441,7 +437,6 @@ impl SchedulerState { } /// Returns whether `task` is the main task of any CPU. - #[cfg(feature = "esp-radio")] fn is_main_task(&self, task: TaskPtr) -> bool { self.per_cpu .iter() @@ -449,7 +444,7 @@ impl SchedulerState { } /// Returns the CPU that runs `task`, if that CPU is not the current one. - #[cfg(all(multi_core, feature = "esp-radio"))] + #[cfg(multi_core)] fn other_cpu_running(&self, task: TaskPtr) -> Option { let current_cpu = Cpu::current(); Cpu::all().find(|cpu| { @@ -458,7 +453,6 @@ impl SchedulerState { }) } - #[cfg(feature = "esp-radio")] pub(crate) fn schedule_task_deletion(&mut self, task_to_delete: Option) -> bool { let current_task = SCHEDULER.current_task(); let task_to_delete = task_to_delete.unwrap_or(current_task); @@ -505,7 +499,6 @@ impl SchedulerState { } /// Marks `task` deleted, and queues it to be deleted by a scheduler run on `cpu`. - #[cfg(feature = "esp-radio")] fn mark_for_deletion(&mut self, cpu: Cpu, task: TaskPtr) { if task.state() != TaskState::Deleted { self.per_cpu[cpu as usize].to_delete.push(task); @@ -529,33 +522,26 @@ impl SchedulerState { task::trigger_scheduler(run_scheduler); } - fn delete_task(&mut self, mut to_delete: TaskPtr) { + fn delete_task(&mut self, to_delete: TaskPtr) { unsafe { - cfg_select! { - xtensa => { - let saved_sp = to_delete.as_ref().cpu_context.A1 as usize; - } - _ => { - let saved_sp = to_delete.as_ref().cpu_context.sp; - } - } + let saved_sp = cfg_select! { + xtensa => to_delete.as_ref().cpu_context.A1 as usize, + _ => to_delete.as_ref().cpu_context.sp, + }; to_delete.as_ref().ensure_no_stack_overflow(saved_sp) }; debug!("Dropping task: {:x}", to_delete.as_ptr() as usize); - unsafe { - #[cfg(feature = "alloc")] - if to_delete.as_ref().heap_allocated { - let task = Box::from_raw_in(to_delete.as_ptr(), InternalMemory); - core::mem::drop(task); - return; - } - core::ptr::drop_in_place(to_delete.as_mut()); - } + // The task locates the memory block of the thread, so the owner of the block destroys the + // task when it releases the memory. + let thread = unwrap!( + unsafe { to_delete.as_ref().thread }, + "The main task cannot be deleted" + ); + unsafe { crate::thread::release(thread, self) }; } - #[cfg(feature = "esp-radio")] fn remove_from_all_queues(&mut self, mut task: TaskPtr) { self.all_tasks.remove(task); unwrap!(self.time_driver.as_mut()).timer_queue.remove(task); @@ -573,12 +559,7 @@ impl SchedulerState { let task = unsafe { task.as_ref() }; let in_queue = task.in_run_or_wait_queue; - let in_waitqueue = cfg_select! { - feature = "esp-radio" => task.current_wait_queue.is_some(), - _ => false, - }; - - in_queue && !in_waitqueue + in_queue && task.current_wait_queue.is_none() }; if task_in_run_queue { @@ -659,32 +640,10 @@ impl Scheduler { unwrap!( TaskPtr::new(tp), - "The scheduler has not been started. Make sure to call `esp_rtos::init()` before trying to access the current task." + "The scheduler has not been started. Make sure to call `esp_rtos::start()` before trying to access the current task." ) } - #[cfg(feature = "esp-radio")] - pub(crate) fn create_task( - &self, - name: &str, - task: extern "C" fn(*mut c_void), - param: *mut c_void, - task_stack_size: usize, - priority: u32, - pinned_to: Option, - ) -> TaskPtr { - self.with(|state| { - state.create_task( - name, - task, - param, - task_stack_size, - priority as usize, - pinned_to, - ) - }) - } - pub(crate) fn sleep_until(&self, wake_at: Instant) -> bool { self.with(|scheduler| { let current_task = SCHEDULER.current_task(); diff --git a/esp-rtos/src/sleep.rs b/esp-rtos/src/sleep.rs index b761df81b08..278f3aea91a 100644 --- a/esp-rtos/src/sleep.rs +++ b/esp-rtos/src/sleep.rs @@ -1,15 +1,20 @@ //! Power management utilities. +#[cfg(supports_tagmem_power_down)] +use esp_hal::rtc_cntl::{CacheTagRetentionMemory, CacheTagRetentionMemoryError}; +#[cfg(supports_cpu_power_down)] +use esp_hal::rtc_cntl::{CpuRetentionMemory, CpuRetentionMemoryError}; #[cfg(multi_core)] -use esp_hal::{peripherals::CPU_CTRL, system::Cpu, system::CpuControl}; +use esp_hal::system::Cpu; use esp_hal::{ peripherals::LPWR, rtc_cntl::{ WakeLock, - sleep::{LowPower, RtcSleepConfig}, + sleep::{LightSleep, LowPower, RtcSleepConfig}, }, time::{Duration, Instant}, }; +use esp_sync::raw::{RawLock, SingleCoreInterruptLock}; use crate::{SCHEDULER, task::IdleFn}; #[cfg(multi_core)] @@ -28,6 +33,53 @@ pub struct Sleep { pub light_sleep_hook: IdleFn, } +#[cfg(supports_cpu_power_down)] +impl Sleep { + /// Lets automatic light sleep power the CPU domain down. + /// + /// A light sleep keeps the CPU state in `memory` while the CPU domain has no power, which + /// draws less current than a light sleep that keeps the domain powered. The saving costs the + /// memory, and it adds the save and the restore to the sleep and the wake. + /// + /// Every light sleep after this call powers the CPU domain down. Nothing turns it off again, + /// because the memory stays with the driver for the life of the program. + /// + /// # Errors + /// + /// Returns [`CpuRetentionMemoryError`] if a buffer is installed already, or if `memory` is + /// outside the range that the retention hardware reaches. See + /// [`LowPower::install_cpu_retention_memory`] for how to place the static. + pub fn enable_cpu_powerdown( + &mut self, + memory: &'static mut CpuRetentionMemory, + ) -> Result<(), CpuRetentionMemoryError> { + // `configure` took `LPWR`, so this is the only driver, and the idle hook takes it the same + // way for every sleep. + LowPower::new(unsafe { LPWR::steal() }).install_cpu_retention_memory(memory) + } + + /// Keeps the cache tag memory across a light sleep that powers the CPU domain down. + /// + /// This shortens the wake, because the caches keep what they held before the sleep. Without + /// it, the wake path invalidates both caches, and the code that runs next takes a miss for + /// every line it needs. The memory it costs buys latency only, never correctness. + /// + /// This does nothing on its own: the tag memory is lost only when the CPU domain powers down, + /// which needs [`enable_cpu_powerdown`][Self::enable_cpu_powerdown]. + /// + /// # Errors + /// + /// Returns [`CacheTagRetentionMemoryError`] if a buffer is installed already, or if `memory` + /// is outside the range that the retention hardware reaches. + #[cfg(supports_tagmem_power_down)] + pub fn keep_cache_tags( + &mut self, + memory: &'static mut CacheTagRetentionMemory, + ) -> Result<(), CacheTagRetentionMemoryError> { + LowPower::new(unsafe { LPWR::steal() }).install_cache_tag_retention_memory(memory) + } +} + /// A handle you can use to enter deep sleep. #[cfg(sleep_deep_sleep)] pub struct DeepSleep { @@ -57,24 +109,45 @@ impl DeepSleep { /// /// Pass the idle hook to [`start_with_idle_hook`] to enable automatic light sleep. /// -/// Each time the scheduler runs out of ready tasks, the hook (with interrupts -/// disabled) checks that: +/// Each time the scheduler runs out of ready tasks, the hook disables interrupts on this core, +/// takes the scheduler lock, and checks that: /// - no [`WakeLock`] is held, /// - all cores are idle, /// - the next wakeup is at least `ESP_RTOS_CONFIG_LIGHT_SLEEP_MIN_US` microseconds away. /// -/// If all hold, it calls [`LowPower::sleep_light`] for the next wakeup; otherwise -/// it falls back to `WFI`. The minimum-residency threshold is configurable via the +/// If all hold, it releases the lock and calls [`LowPower::sleep_light`] with interrupts still +/// disabled. [`LowPower::sleep_light`] disables interrupts for the whole sleep path. A sleep that +/// keeps the CPU domain powered hardware-stalls every other running core for the duration of the +/// sleep. A sleep that powers the domain down instead asks the other core to save itself, and that +/// core keeps running. After the sleep, the hook takes the scheduler lock again to rearm the time +/// driver and to wake the scheduler on the other cores, then it enables interrupts and falls back +/// to `WFI`. +/// +/// A wakeup source can refuse the sleep. The hook then falls back to `WFI`, as it does when a +/// check above fails. A wakeup source can also bound the sleep. The driver clamps the wake timer +/// inside the sleep call, after this hook has armed the next scheduler wakeup. The sooner of the +/// two wins. +/// +/// The minimum-residency threshold is configurable via the /// `ESP_RTOS_CONFIG_LIGHT_SLEEP_MIN_US` build-time option (default `1000`). /// -/// On multi-core chips, the core that commits to sleep hardware-stalls the other core(s) -/// for the duration of the sleep so their CPU state is frozen and restored coherently, -/// then thaws them on wakeup. +/// Light sleep keeps the CPU domain powered, unless the program calls +/// [`Sleep::enable_cpu_powerdown`]. /// /// See [`WakeLock`] for the wake-lock contract that governs when sleeping is safe. /// /// [`start_with_idle_hook`]: crate::start_with_idle_hook pub fn configure(lpwr: LPWR<'static>) -> Sleep { + // SAFETY: the handler only reads scheduler state, it takes the scheduler lock, which no core + // holds across a sleep, and it lives as long as this crate. + #[cfg(multi_core)] + unsafe { + esp_hal::rtc_cntl::sleep::__rtos_implementation::set_can_sleep_handler(can_sleep) + }; + + #[cfg(not(sleep_deep_sleep))] + let _ = lpwr; + Sleep { #[cfg(sleep_deep_sleep)] deep_sleep: DeepSleep { lpwr }, @@ -82,52 +155,52 @@ pub fn configure(lpwr: LPWR<'static>) -> Sleep { } } +/// Answers whether this core agrees to a light sleep that the other core requests. +/// +/// esp-hal calls this from the rendezvous of the sleep, after it disabled the interrupts of this +/// core. A task that became ready after the other core decided, and a [`WakeLock`] that any core +/// took after that decision, both stop the sleep here. +#[cfg(multi_core)] +fn can_sleep() -> bool { + if WakeLock::is_active() { + return false; + } + + SCHEDULER.with(|scheduler| { + !scheduler.run_queue.has_ready_tasks() && scheduler.cpu_idle(Cpu::current()) + }) +} + extern "C" fn auto_light_sleep_hook() -> ! { loop { - // ESP32-P4 HP wakeup handling is coordinated by the primary core. If - // AppCpu enters sleep after parking ProCpu, an HP peripheral wakeup - // such as GPIO cannot resume the parked primary core. - #[cfg(all(multi_core, esp32p4))] - if Cpu::current() == Cpu::AppCpu { - // Kick the other core so that it can put the system to sleep. - task::trigger_scheduler(RunSchedulerOn::RunOnCore(Cpu::ProCpu)); - esp_hal::interrupt::wait_for_interrupt(); - continue; - } + // Interrupts stay off from the decision until the sleep is over. A handler on this core + // can take a `WakeLock`, and a sleep must not start after that. + let irq_token = unsafe { SingleCoreInterruptLock.enter() }; - SCHEDULER.with(|scheduler| { + let sleep = SCHEDULER.with(|scheduler| { if WakeLock::is_active() { - return; + return false; } #[cfg(multi_core)] { if scheduler.run_queue.has_ready_tasks() { - return; + return false; } for cpu in Cpu::all() { if !scheduler.cpu_idle(cpu) { - return; + return false; } } - // All cores are ready to sleep. Since we are here in a critical section, - // the other core must be waiting for the scheduler lock. We will go to sleep, - // and after wakeup the other core will reattempt this check. - - // FIXME: We hardware-stall the other core(s) for the duration of the sleep so - // their CPU state is frozen and restored coherently. The other core is frozen - // wherever it happens to be - including in the middle of an interrupt handler - // that holds a cross-core lock (e.g. the clock tree, peripheral refcount, or - // UART locks taken by the light-sleep enter/exit path in `Rtc::sleep`). If that - // happens, this core will spin forever trying to take that lock during sleep - // prep, because the frozen core can never release it. We accept this (unlikely) - // deadlock risk for now rather than ordering all lock-taking work before the - // stall. + // Every core is ready to sleep. The other core can make a task ready again after + // this function gives the lock back. The rendezvous of esp-hal closes that + // window: it asks the other core through [`can_sleep`] before it powers the CPU + // domain down, and that core answers with its interrupts already off. } let Some(time_driver) = scheduler.time_driver.as_mut() else { - return; + return false; }; let next_wakeup = time_driver.next_wakeup(); @@ -135,56 +208,59 @@ extern "C" fn auto_light_sleep_hook() -> ! { // The deadline stays until other code clears it, so each pass writes it, also a pass // that makes no sleep. A deadline from an earlier pass expires, and the - // next sleep then returns immediately. + // next sleep then returns immediately. A wakeup source can shorten this deadline + // inside `sleep_light`, or arm the timer when this hook cleared it. This call stays + // the scheduler's request. `sleep_light` restores it. if next_wakeup == u64::MAX { lpwr.clear_wakeup_deadline(); } else { lpwr.set_wakeup_deadline(Instant::EPOCH + Duration::from_micros(next_wakeup)); if next_wakeup.saturating_sub(crate::now()) < LIGHT_SLEEP_MIN_US { - return; + return false; } } - // We have committed to sleeping. Park (hardware-stall) the other core(s) so their - // CPU state is frozen and restored coherently across the sleep, then enter light - // sleep, then thaw them. - cfg_select! { - multi_core => { - let mut cpu_control = CpuControl::new(unsafe { CPU_CTRL::steal() }); - for cpu in Cpu::other() { - if scheduler.active_cores.contains(cpu) { - unsafe { cpu_control.park_core(cpu) }; - // FIXME: this is insufficient when we power down the CPU - we will - // need to force the other core to be parked in a known place, saving - // its state so we can restore it after wakeup. - } - } - } - _ => {} - } + true + }); - // The driver of each other wakeup source enables it. A listening pin wakes the chip - // because it listens, and this hook cannot know which pins listen. If no source is - // enabled, the call refuses the sleep and returns immediately. The code then reaches - // the same `WFI` that this hook would select. - lpwr.sleep_light(RtcSleepConfig::default()); + // The other core can take a `WakeLock` in the window that the release of the lock opens. + // This read closes most of that window, and [`can_sleep`] closes the rest for a sleep + // that powers the CPU domain down. + if sleep && !WakeLock::is_active() { + // Each driver enables the wakeup source it owns. This hook does not know which + // sources are enabled. `sleep_light` returns immediately when none are enabled. + // It also returns immediately when a source refuses the sleep. Do not call it + // again here. The refusal is still true, and a retry would spin. `WFI` below + // waits for an interrupt. + let result = + LowPower::new(unsafe { LPWR::steal() }).sleep_light(RtcSleepConfig::default()); - // The alarm timer was gated during light sleep, so its pre-armed alarm is - // stale. Force a re-arm against the restored time base so the tick handler - // fires promptly and drains the timer queue. - time_driver.rearm(crate::now()); + SCHEDULER.with(|scheduler| { + let Some(time_driver) = scheduler.time_driver.as_mut() else { + return; + }; - // Trigger the scheduler on the other core to prevent it from putting - // the system back to sleep immediately. - #[cfg(multi_core)] - for cpu in Cpu::other() { - if scheduler.active_cores.contains(cpu) { - cpu_control.unpark_core(cpu); - task::trigger_scheduler(RunSchedulerOn::RunOnCore(cpu)); + // The alarm timer was gated during light sleep, so its pre-armed alarm is + // stale. Force a re-arm against the restored time base so the tick handler + // fires promptly and drains the timer queue. A refusal leaves the timer + // running, so its alarm is still valid. + if result == LightSleep::Ended { + time_driver.rearm(crate::now()); } - } - }); + + // Trigger the scheduler on the other core to prevent it from putting + // the system back to sleep immediately. + #[cfg(multi_core)] + for cpu in Cpu::other() { + if scheduler.active_cores.contains(cpu) { + task::trigger_scheduler(RunSchedulerOn::RunOnCore(cpu)); + } + } + }); + } + + unsafe { SingleCoreInterruptLock.exit(irq_token) }; esp_hal::interrupt::wait_for_interrupt(); } diff --git a/esp-rtos/src/task/mod.rs b/esp-rtos/src/task/mod.rs index 96b5fedcb92..9e47ce8a5af 100644 --- a/esp-rtos/src/task/mod.rs +++ b/esp-rtos/src/task/mod.rs @@ -2,17 +2,13 @@ #[cfg_attr(xtensa, path = "xtensa.rs")] pub(crate) mod arch_specific; -#[cfg(feature = "esp-radio")] -use core::ffi::c_void; -use core::{marker::PhantomData, mem::MaybeUninit, ptr::NonNull}; +use core::{ffi::c_void, marker::PhantomData, mem::MaybeUninit, ptr::NonNull}; #[cfg(feature = "alloc")] -use allocator_api2::{ - alloc::{Allocator, Layout}, - boxed::Box, -}; +use allocator_api2::boxed::Box; pub(crate) use arch_specific::*; use esp_hal::{ + interrupt::__rtos_implementation::request_context_switch, system::Cpu, time::{Duration, Instant}, }; @@ -21,14 +17,12 @@ use esp_radio_rtos_driver::semaphore::{SemaphoreHandle, SemaphorePtr}; #[cfg(feature = "rtos-trace")] use rtos_trace::TaskInfo; -#[cfg(feature = "alloc")] -use crate::InternalMemory; -#[cfg(feature = "esp-radio")] -use crate::wait_queue::WaitQueue; use crate::{ SCHEDULER, run_queue::{Priority, RunQueue, RunSchedulerOn}, scheduler::SchedulerState, + thread::{ThreadOptions, ThreadPtr}, + wait_queue::WaitQueue, }; pub type IdleFn = extern "C" fn() -> !; @@ -130,7 +124,7 @@ impl TaskExt for TaskPtr { #[cfg(feature = "rtos-trace")] fn rtos_trace_info(self, run_queue: &mut RunQueue) -> TaskInfo { TaskInfo { - name: "", + name: unsafe { self.as_ref().name.unwrap_or("") }, priority: self.priority(run_queue).get() as u32, stack_base: unsafe { self.as_ref().stack.addr() }, stack_size: unsafe { self.as_ref().stack.len() }, @@ -201,7 +195,6 @@ impl TaskList { popped } - #[cfg(feature = "esp-radio")] pub fn remove(&mut self, task: TaskPtr) { if E::is_in_queue(task) == Some(false) { return; @@ -349,6 +342,8 @@ pub(crate) struct Task { pub thread_local: ThreadLocalData, + pub name: Option<&'static str>, + pub state: TaskState, pub stack: *mut [MaybeUninit], @@ -369,7 +364,6 @@ pub(crate) struct Task { pub timer_queued: bool, /// The current wait queue this task is in. - #[cfg(feature = "esp-radio")] pub(crate) current_wait_queue: Option>, // Lists a task can be in: @@ -385,9 +379,9 @@ pub(crate) struct Task { /// The list of tasks scheduled for deletion pub delete_list_item: TaskListItem, - /// Whether the task was allocated on the heap. - #[cfg(feature = "alloc")] - pub(crate) heap_allocated: bool, + /// The memory block this task lives in, for tasks that were not statically allocated by the + /// scheduler. The main tasks have no such block. + pub(crate) thread: Option, } pub(crate) trait ContextExt { @@ -430,75 +424,48 @@ impl ContextExt for CpuContext { } } -#[cfg(feature = "esp-radio")] extern "C" fn task_wrapper(task_fn: extern "C" fn(*mut c_void), param: *mut c_void) { task_fn(param); schedule_task_deletion(None); } impl Task { - #[cfg(feature = "esp-radio")] + /// Creates a task that runs `entry(param)` on a caller-provided stack. + /// + /// The stack guard is placed at the low end of `stack`, so the region must be larger than the + /// stack guard offset. `thread` is the memory block the task lives in. pub(crate) fn new( - name: &str, - task_fn: extern "C" fn(*mut c_void), + options: &ThreadOptions, + entry: extern "C" fn(*mut c_void), param: *mut c_void, - task_stack_size: usize, - priority: usize, - pinned_to: Option, + stack: *mut [MaybeUninit], + thread: ThreadPtr, ) -> Self { debug!( - "task_create {} {:?}({:?}) stack_size = {} priority = {} pinned_to = {:?}", - name, task_fn, param, task_stack_size, priority, pinned_to + "task_create {:?} {:?}({:?}) stack = {:?} priority = {} pinned_to = {:?}", + options.name, entry, param, stack, options.priority, options.pinned_to ); - // Make sure the stack guard doesn't eat into the stack size. - let extra_stack = if cfg!(any(hw_task_overflow_detection, sw_task_overflow_detection)) { - 4 + esp_config::esp_config_int!(usize, "ESP_HAL_CONFIG_STACK_GUARD_OFFSET") - } else { - 0 - }; - - #[cfg(debug_build)] - // This is a lot, but debug builds fail in different ways without. - let extra_stack = extra_stack.max(6 * 1024); - - let task_stack_size = task_stack_size + extra_stack; - - // Make sure stack size is also aligned to 16 bytes. - const MIN_STACK_ALIGNMENT: usize = 16; - let task_stack_size = (task_stack_size & !(MIN_STACK_ALIGNMENT - 1)) + MIN_STACK_ALIGNMENT; - - let stack = unwrap!( - Layout::from_size_align(task_stack_size, MIN_STACK_ALIGNMENT) - .ok() - .and_then(|layout| InternalMemory.allocate(layout).ok()), - "Failed to allocate stack", - ) - .as_ptr(); - - let stack_bottom = stack.cast::>(); - let stack_len_bytes = stack.len(); - let stack_guard_offset = esp_config::esp_config_int!(usize, "ESP_HAL_CONFIG_STACK_GUARD_OFFSET"); - let stack_words = core::ptr::slice_from_raw_parts_mut(stack_bottom, stack_len_bytes / 4); - let stack_top = unsafe { stack_bottom.add(stack_words.len()).cast() }; + let stack_bottom = stack.cast::>(); + let stack_top = unsafe { stack_bottom.add(stack.len()).cast() }; let mut task = Task { - cpu_context: new_task_context(task_fn, param, stack_top), + cpu_context: new_task_context(entry, param, stack_top), thread_local: ThreadLocalData::new(), + name: options.name, state: TaskState::Ready, - stack: stack_words, + stack, #[cfg(any(hw_task_overflow_detection, sw_task_overflow_detection))] - stack_guard: stack_words.cast(), + stack_guard: stack.cast(), #[cfg(sw_task_overflow_detection)] stack_guard_value: 0, - #[cfg(feature = "esp-radio")] current_wait_queue: None, - priority: Priority::new(priority), + priority: Priority::new(options.priority), #[cfg(multi_core)] - pinned_to, + pinned_to: options.pinned_to, wakeup_at: 0, timer_queued: false, @@ -509,8 +476,7 @@ impl Task { timer_queue_item: TaskListItem::None, delete_list_item: TaskListItem::None, - #[cfg(feature = "alloc")] - heap_allocated: false, + thread: Some(thread), }; task.set_up_stack_guard(stack_guard_offset, 0xDEED_BAAD); @@ -582,21 +548,6 @@ impl Task { } } -impl Drop for Task { - fn drop(&mut self) { - debug!("Dropping task: {:?}", self as *mut Task); - - #[cfg(feature = "alloc")] - if self.heap_allocated { - let layout = unwrap!( - Layout::from_size_align(self.stack.len() * 4, 16).ok(), - "Cannot compute Layout for stack" - ); - unsafe { InternalMemory.deallocate(unwrap!(NonNull::new(self.stack.cast())), layout) }; - } - } -} - pub(super) fn allocate_main_task( scheduler: &mut SchedulerState, stack: *mut [MaybeUninit], @@ -668,6 +619,13 @@ impl CurrentThreadHandle { } } + /// Returns the name of the current thread. + /// + /// The main threads and the threads created by `esp-radio` have no name. + pub fn name(self) -> Option<&'static str> { + unsafe { self.task.as_ref().name } + } + /// Delays the current task for the specified duration. pub fn delay(self, duration: Duration) { self.delay_until(Instant::now() + duration); @@ -694,7 +652,6 @@ impl CurrentThreadHandle { } } -#[cfg(feature = "esp-radio")] pub(super) fn schedule_task_deletion(task: Option>) { trace!("schedule_task_deletion {:?}", task); if SCHEDULER.with(|scheduler| scheduler.schedule_task_deletion(task)) { @@ -707,30 +664,30 @@ pub(super) fn schedule_task_deletion(task: Option>) { pub(crate) fn trigger_scheduler(run_scheduler: RunSchedulerOn) { match run_scheduler { RunSchedulerOn::DontRun => {} - RunSchedulerOn::RunOnCore(_core) => { - cfg_select! { - multi_core => { - if _core == Cpu::current() { - yield_task() - } else { - schedule_other_core() - } - } - _ => yield_task(), - } - } + RunSchedulerOn::RunOnCore(core) => request_context_switch(core), } } +/// Asks the other CPU to run its context-switch handler. #[inline] #[cfg(multi_core)] pub(crate) fn schedule_other_core() { - use esp_hal::{ - interrupt::software::SoftwareInterrupt, - peripherals::{FROM_CPU_INTR0, FROM_CPU_INTR1}, + let other = match Cpu::current() { + Cpu::ProCpu => Cpu::AppCpu, + Cpu::AppCpu => Cpu::ProCpu, }; - match Cpu::current() { - Cpu::ProCpu => SoftwareInterrupt::new(unsafe { FROM_CPU_INTR1::steal() }).raise(), - Cpu::AppCpu => SoftwareInterrupt::new(unsafe { FROM_CPU_INTR0::steal() }).raise(), + request_context_switch(other); +} + +/// Asks the current CPU to run its context-switch handler. +#[inline] +pub(crate) fn yield_task() { + #[cfg(feature = "rtos-trace")] + { + use crate::TraceEvents; + + rtos_trace::trace::marker_begin(TraceEvents::YieldTask as u32); + rtos_trace::trace::marker_end(TraceEvents::YieldTask as u32); } + request_context_switch(Cpu::current()) } diff --git a/esp-rtos/src/task/riscv.rs b/esp-rtos/src/task/riscv.rs index 41d3495928f..ec27e891b3c 100644 --- a/esp-rtos/src/task/riscv.rs +++ b/esp-rtos/src/task/riscv.rs @@ -1,19 +1,7 @@ -#[cfg(feature = "esp-radio")] use core::ffi::c_void; -#[cfg(multi_core)] -use esp_hal::peripherals::FROM_CPU_INTR1; -use esp_hal::{ - interrupt::{ - self, - software::{Instance, SoftwareInterrupt}, - }, - peripherals::FROM_CPU_INTR0, - system::Cpu, -}; +use esp_hal::{interrupt::__rtos_implementation::set_context_switch_handler, system::Cpu}; -#[cfg(feature = "rtos-trace")] -use crate::TraceEvents; use crate::{ SCHEDULER, task::{IdleFn, Task}, @@ -128,7 +116,6 @@ pub(crate) fn write_thread_pointer(task: *mut Task) { unsafe { core::arch::asm!("c.mv tp, {0}", in(reg) task, options(nostack)) }; } -#[cfg(feature = "esp-radio")] pub(crate) fn new_task_context( task: extern "C" fn(*mut c_void), param: *mut c_void, @@ -150,43 +137,24 @@ pub(crate) fn new_task_context( /// /// Task switching happens when exiting the interrupt handler. The handler detects that `tp` has /// changed, and saves/restores registers accordingly. -pub fn task_switch(_old_ctx: *mut CpuContext, new_ctx: *mut CpuContext) { +#[inline] +pub(crate) fn task_switch(_old_ctx: *mut CpuContext, new_ctx: *mut CpuContext) { unsafe { core::arch::asm!("mv tp, {}", in(reg) new_ctx as *const CpuContext as usize); } } -pub(crate) fn setup_multitasking(_irq: impl Instance + 'static) { - // Register a direct-bound interrupt handler, so that we don't have to worry about other - // interrupt handlers interfering. - - let interrupt = match IRQ { - 0 => esp_hal::peripherals::Interrupt::FROM_CPU_INTR0, - 1 => esp_hal::peripherals::Interrupt::FROM_CPU_INTR1, - 2 => esp_hal::peripherals::Interrupt::FROM_CPU_INTR2, - 3 => esp_hal::peripherals::Interrupt::FROM_CPU_INTR3, - _ => panic!("Invalid IRQ number"), - }; - - interrupt::enable_direct( - interrupt, - interrupt::Priority::min(), - interrupt::DirectBindableCpuInterrupt::Interrupt0, - swint_handler_trampoline, - ); -} - -#[cfg(multi_core)] -pub(crate) fn setup_smp(irq: impl Instance + 'static) { - setup_multitasking(irq); +pub(crate) fn setup_multitasking() { + // The HAL runs this handler in the lowest-priority interrupt of this CPU. + unsafe { + set_context_switch_handler(Cpu::current(), swint_handler_trampoline); + } } -// We need to place this close to the trap handler for the jump to be resolved properly -/// Task switch wrapper +/// Direct-bound interrupt handler for the context switch. /// -/// This function is the direct interrupt handler for the context switch software interrupt. -/// It stores context into the Context behind the current thread pointer, calls the scheduler, -/// and restores context from the Context behind the next thread pointer. +/// Stores context into the `CpuContext` behind the current thread pointer, calls the scheduler, +/// and restores context from the `CpuContext` behind the next thread pointer. /// /// The scheduler itself only changes the thread pointer. The new thread pointer is guaranteed to be non-zero. /// @@ -204,6 +172,9 @@ pub(crate) fn setup_smp(irq: impl Instance + 'static) { unsafe extern "C" fn swint_handler_trampoline() { core::arch::naked_asm! {" .cfi_startproc + # Restore t0. The HAL stub stored the interrupted t0 in mscratch. + csrr t0, mscratch + # https://github.com/riscv-non-isa/riscv-elf-psabi-doc/blob/139d8d8e1d8ee8c0c3ee150de709ceaab5c08417/riscv-dwarf.adoc # .cfi_register ra, 0x1341 # Unwind with MEPC as return address, crashes probe-rs @@ -372,26 +343,5 @@ unsafe extern "C" fn swint_handler_trampoline() { #[esp_hal::ram] extern "C" fn swint_handler() { - match Cpu::current() { - Cpu::ProCpu => SoftwareInterrupt::new(unsafe { FROM_CPU_INTR0::steal() }).reset(), - #[cfg(multi_core)] - Cpu::AppCpu => SoftwareInterrupt::new(unsafe { FROM_CPU_INTR1::steal() }).reset(), - } - SCHEDULER.with(|scheduler| scheduler.switch_task()); } - -#[inline] -pub(crate) fn yield_task() { - #[cfg(feature = "rtos-trace")] - { - rtos_trace::trace::marker_begin(TraceEvents::YieldTask as u32); - rtos_trace::trace::marker_end(TraceEvents::YieldTask as u32); - } - - match Cpu::current() { - Cpu::ProCpu => SoftwareInterrupt::new(unsafe { FROM_CPU_INTR0::steal() }).raise(), - #[cfg(multi_core)] - Cpu::AppCpu => SoftwareInterrupt::new(unsafe { FROM_CPU_INTR1::steal() }).raise(), - } -} diff --git a/esp-rtos/src/task/xtensa.rs b/esp-rtos/src/task/xtensa.rs index 5899b91551c..4085741e574 100644 --- a/esp-rtos/src/task/xtensa.rs +++ b/esp-rtos/src/task/xtensa.rs @@ -4,32 +4,16 @@ //! saves context to the stack. The OS copies the state to memory, replaces it with the new task's //! state, then returns from the interrupt handler. //! -//! To trigger a context switch on the same core, we (where possible) use the Software0 CPU -//! interrupt. To trigger a cross-core context switch, we use the FROM_CPUn CPU interrupts. On -//! ESP32, Software0 is not available, so we use FROM_CPUn there, as well. -//! -//! Context switching must happen at the lower interrupt priority level. This ensures that context -//! switching does not interfere with other interrupts, so we don't leave an interrupt handler only -//! partially executed. +//! The HAL owns the interrupt that carries the context switch. Context switching must happen at +//! the lowest interrupt priority. A switch then does not interfere with other interrupts, and no +//! interrupt handler is left partially executed. -#[cfg(feature = "esp-radio")] -use core::ffi::c_void; -use core::sync::atomic::Ordering; +use core::{ffi::c_void, sync::atomic::Ordering}; pub(crate) use esp_hal::trapframe::TrapFrame as CpuContext; -#[cfg(not(esp32))] -use esp_hal::xtensa_lx::interrupt; -use esp_hal::{interrupt::software::Instance, ram}; -#[cfg(multi_core)] -use esp_hal::{ - interrupt::{InterruptHandler, Priority, software::SoftwareInterrupt}, - peripherals::{FROM_CPU_INTR0, FROM_CPU_INTR1}, - system::Cpu, -}; +use esp_hal::{interrupt::__rtos_implementation::set_context_switch_handler, ram, system::Cpu}; use portable_atomic::AtomicPtr; -#[cfg(feature = "rtos-trace")] -use crate::TraceEvents; use crate::{ SCHEDULER, task::{IdleFn, Task}, @@ -57,7 +41,6 @@ const PS_UM: u32 = 1 << 5; // Windowed mode. const PS_WOE: u32 = 1 << 18; // CALLINC field value for call4 instruction. -#[cfg(feature = "esp-radio")] const PS_CALLINC_CALL4: u32 = 1 << 16; pub(crate) fn set_idle_hook_entry(idle_context: &mut CpuContext, hook_fn: IdleFn) { @@ -86,7 +69,6 @@ pub(crate) fn write_thread_pointer(task: *mut Task) { unsafe { core::arch::asm!("wur.threadptr {0}", in(reg) task, options(nostack)) }; } -#[cfg(feature = "esp-radio")] pub(crate) fn new_task_context( task_fn: extern "C" fn(*mut c_void), param: *mut c_void, @@ -119,6 +101,7 @@ pub(crate) fn new_task_context( } } +#[inline] pub(crate) fn task_switch( current_context: *mut CpuContext, next_context: *mut CpuContext, @@ -130,85 +113,14 @@ pub(crate) fn task_switch( unsafe { core::ptr::copy_nonoverlapping(next_context, trap_frame, 1) }; } -// S2 and S3 use Software0 (priority 1) for same-core task switching. This is slightly faster than -// the FROM_CPU0 interrupt. -#[cfg(not(esp32))] -const SW_INTERRUPT: u32 = 1 << 7; - -pub(crate) fn setup_multitasking(mut _irq: impl Instance + 'static) { - #[cfg(not(esp32))] +pub(crate) fn setup_multitasking() { + // The HAL runs this handler in the lowest-priority interrupt of this CPU. unsafe { - // Set up a CPU-internal interrupt, which will be used to trigger a context switch on the - // same core. - interrupt::enable_mask(SW_INTERRUPT); - } - - #[cfg(multi_core)] - { - let mut irq = SoftwareInterrupt::new(_irq); - irq.set_interrupt_handler(InterruptHandler::new( - unsafe { - core::mem::transmute::<*const (), extern "C" fn()>( - cross_core_yield_handler as *const (), - ) - }, - Priority::min(), - )); + set_context_switch_handler(Cpu::current(), trigger_task_switch); } } -#[cfg(multi_core)] -pub(crate) fn setup_smp(irq: impl Instance + 'static) { - setup_multitasking(irq); -} - -// Non-ESP32 can use Software0 (priority 1) for same-core task switching. This is slightly faster -// than the FROM_CPU0 interrupt. On ESP32, this is not available because the bluetooth driver uses -// Software0. -#[allow(non_snake_case)] #[ram] -#[cfg(not(esp32))] -#[unsafe(export_name = "Software0")] -fn task_switch_interrupt(context: &mut CpuContext) { - unsafe { interrupt::clear(SW_INTERRUPT) }; - - trigger_task_switch(context); -} - -#[inline] -pub(crate) fn yield_task() { - #[cfg(feature = "rtos-trace")] - { - rtos_trace::trace::marker_begin(TraceEvents::YieldTask as u32); - rtos_trace::trace::marker_end(TraceEvents::YieldTask as u32); - } - - #[cfg(not(esp32))] - unsafe { - interrupt::set(SW_INTERRUPT); - } - - #[cfg(esp32)] - match Cpu::current() { - Cpu::ProCpu => SoftwareInterrupt::new(unsafe { FROM_CPU_INTR0::steal() }).raise(), - Cpu::AppCpu => SoftwareInterrupt::new(unsafe { FROM_CPU_INTR1::steal() }).raise(), - } -} - -#[cfg(multi_core)] -#[ram] -extern "C" fn cross_core_yield_handler(context: &mut CpuContext) { - match Cpu::current() { - Cpu::ProCpu => SoftwareInterrupt::new(unsafe { FROM_CPU_INTR0::steal() }).reset(), - Cpu::AppCpu => SoftwareInterrupt::new(unsafe { FROM_CPU_INTR1::steal() }).reset(), - } - - trigger_task_switch(context); -} - -// Having this function separate ensures there is a single un-inlined copy of the task switch logic -// living in RAM. `ram` is conditional to ensure the function is inlined on ESP32 and S2. -#[cfg_attr(esp32s3, ram)] -fn trigger_task_switch(context: &mut CpuContext) { +extern "C" fn trigger_task_switch(context: &mut CpuContext) { SCHEDULER.with(|scheduler| scheduler.switch_task(context)); } diff --git a/esp-rtos/src/thread.rs b/esp-rtos/src/thread.rs new file mode 100644 index 00000000000..3108bc96ea5 --- /dev/null +++ b/esp-rtos/src/thread.rs @@ -0,0 +1,698 @@ +//! Threads. +//! +//! A thread runs a function or a closure on its own stack. Threads are scheduled by priority, and +//! threads of the same priority share the CPU in a round-robin fashion. +//! +//! A thread is created by a [`ThreadSpawner`], which owns the memory the thread runs on. The +//! memory is either allocated on the heap by [`ThreadSpawner::new`], or provided by the caller as +//! a [`Stack`] via [`ThreadSpawner::from_static`]. +//! +//! [`ThreadSpawner::spawn`] starts the thread and returns a [`JoinHandle`]. Use the handle to wait +//! for the thread and to read the value the thread returns. If you drop the handle, the thread is +//! detached, and it continues to run until it exits. +//! +//! A thread can not be deleted. It exits when its function returns. +//! +//! ## Example +//! +//! ```rust, no_run +#![doc = esp_hal::before_snippet!()] +//! # struct FakeHeap; +//! # unsafe impl core::alloc::GlobalAlloc for FakeHeap { +//! # unsafe fn alloc(&self, _: core::alloc::Layout) -> *mut u8 { +//! # unimplemented!() +//! # } +//! # unsafe fn dealloc(&self, _: *mut u8, _: core::alloc::Layout) { +//! # unimplemented!() +//! # } +//! # } +//! # #[global_allocator] +//! # static ALLOCATOR: FakeHeap = FakeHeap; +//! use esp_hal::timer::timg::TimerGroup; +//! use esp_rtos::thread::{Stack, ThreadSpawner}; +//! use static_cell::ConstStaticCell; +//! +//! static STACK: ConstStaticCell> = ConstStaticCell::new(Stack::new()); +//! +//! let timg0 = TimerGroup::new(peripherals.TIMG0); +//! esp_rtos::start(timg0.timer0); +//! +//! let offset = 10; +//! let handle = ThreadSpawner::from_static(STACK.take()) +//! .with_name("worker") +//! .with_priority(2) +//! .spawn(move || 32 + offset); +//! +//! let (result, spawner) = handle.join(); +//! assert_eq!(result, 42); +//! +//! // `spawner` owns the stack again, and can start another thread on it. +#![doc = esp_hal::after_snippet!()] +//! ``` + +use core::{ + alloc::Layout, + ffi::c_void, + marker::PhantomData, + mem::{ManuallyDrop, MaybeUninit}, + ptr::NonNull, +}; + +#[cfg(feature = "alloc")] +use allocator_api2::alloc::Allocator; +use esp_hal::{ + system::Cpu, + time::{Duration, Instant}, +}; + +#[doc(no_inline)] +pub use crate::CurrentThreadHandle; +#[cfg(feature = "alloc")] +use crate::InternalMemory; +use crate::{ + SCHEDULER, + run_queue::MaxPriority, + scheduler::SchedulerState, + task::{Task, TaskPtr}, + wait_queue::WaitQueue, +}; + +/// The alignment of a stack, and the granularity of stack sizes. +const STACK_ALIGN: usize = 16; + +/// The number of bytes reserved below the usable stack, for the stack guard. +const GUARD_RESERVE: usize = if cfg!(any(hw_task_overflow_detection, sw_task_overflow_detection)) { + (esp_config::esp_config_int!(usize, "ESP_HAL_CONFIG_STACK_GUARD_OFFSET") + 4) + .next_multiple_of(STACK_ALIGN) +} else { + 0 +}; + +/// The smallest stack a thread can run on, after the payload is placed on it. +const MIN_STACK: usize = 512; + +/// The memory a thread runs on. +/// +/// `SIZE` is the number of stack bytes available to the thread. The stack guard and the +/// bookkeeping of the scheduler are stored outside of it, so `Stack<4096>` occupies more than 4096 +/// bytes. The closure and the return value of the thread, however, are placed on the stack, and so +/// they reduce the number of bytes the thread can use. +/// +/// Pass the stack to [`ThreadSpawner::from_static`] to run a thread on it. +#[repr(C, align(16))] +pub struct Stack { + // The stack grows down, so the guard must come first. The scheduler's bookkeeping comes last, + // where an overflow cannot reach it. + guard: MaybeUninit<[u8; GUARD_RESERVE]>, + stack: MaybeUninit<[u8; SIZE]>, + resources: MaybeUninit, +} + +// The stack contains uninitialized memory only, until a thread is started on it. The thread's data +// is not reachable through the `Stack`, and only the thread that owns the memory can access it. +unsafe impl Send for Stack {} +unsafe impl Sync for Stack {} + +impl Default for Stack { + fn default() -> Self { + Self::new() + } +} + +impl Stack { + /// Creates a new stack, uninitialized. + pub const fn new() -> Self { + const { + ::core::assert!( + SIZE.is_multiple_of(STACK_ALIGN), + "The stack size must be a multiple of 16 bytes" + ); + ::core::assert!(SIZE > MIN_STACK, "The stack is too small"); + } + + Self { + resources: MaybeUninit::uninit(), + guard: MaybeUninit::uninit(), + stack: MaybeUninit::uninit(), + } + } +} + +/// The scheduler's per-thread bookkeeping, at the end of the thread's memory. +#[repr(C, align(16))] +struct Resources { + task: Task, + inner: ThreadInner, +} + +/// The state a thread shares with its [`JoinHandle`]. It is destroyed when both the scheduler and +/// the `JoinHandle` are done with the thread. +/// +/// The scheduler lock protects the flags. Both the thread and its `JoinHandle` change them, and +/// the two can run on different CPUs. +struct ThreadInner { + /// The thread wrote its return value into the payload. + has_result: bool, + /// The `JoinHandle` was dropped, so nobody will read the return value. + detached: bool, + /// The scheduler no longer uses the thread's memory. + released: bool, + /// Whether the memory block must be returned to the allocator. + heap: bool, + wait_queue: WaitQueue, + /// The closure of the thread, replaced by its return value when the thread exits. + payload: *mut u8, +} + +/// A pointer to the bookkeeping of a thread, which holds a [`Task`] and a [`ThreadInner`], and +/// which sits at the end of the thread's memory block. +#[derive(Clone, Copy)] +pub(crate) struct ThreadPtr(NonNull); + +impl ThreadPtr { + pub(crate) fn task(self) -> TaskPtr { + unsafe { NonNull::new_unchecked(&raw mut (*self.0.as_ptr()).task) } + } + + fn inner_ptr(self) -> *mut ThreadInner { + unsafe { &raw mut (*self.0.as_ptr()).inner } + } + + /// # Safety + /// + /// The thread must be prepared, and the caller must not create a second reference to the same + /// `ThreadInner`. + unsafe fn inner<'a>(self) -> &'a mut ThreadInner { + unsafe { &mut *self.inner_ptr() } + } + + fn as_param(self) -> *mut c_void { + self.0.as_ptr().cast() + } + + /// # Safety + /// + /// `param` must come from [`ThreadPtr::as_param`]. + unsafe fn from_param(param: *mut c_void) -> Self { + Self(unwrap!(NonNull::new(param.cast::()))) + } + + /// The start of the memory block, which is the low end of the task's stack. + /// + /// # Safety + /// + /// The task must be in place. + unsafe fn base(self) -> NonNull { + unsafe { NonNull::new_unchecked(self.task().as_ref().stack.cast::()) } + } + + /// Places the payload between the stack and the bookkeeping, so that a stack overflow hits the + /// stack guard first. + fn reserve_payload(self, base: NonNull, payload: Layout) -> *mut u8 { + let stack_bottom = base.as_ptr() as usize; + let payload_end = self.0.as_ptr() as usize; + + let payload_addr = align_down(payload_end - payload.size(), payload.align().max(4)); + + assert!( + align_down(payload_addr, STACK_ALIGN) >= stack_bottom + GUARD_RESERVE + MIN_STACK, + "The thread does not fit its stack: it needs {} bytes for the closure and the return \ + value, and at least {} bytes of stack, but the stack is {} bytes", + payload.size(), + MIN_STACK, + payload_end - stack_bottom - GUARD_RESERVE + ); + + payload_addr as *mut u8 + } + + /// Creates the task of a prepared thread, which runs `entry(param)`, and hands it to the + /// scheduler. + /// + /// The stack spans from the stack guard to the payload. + /// + /// # Safety + /// + /// The closure the thread runs, if any, must already be in place. + unsafe fn launch( + self, + base: NonNull, + options: &ThreadOptions, + entry: extern "C" fn(*mut c_void), + param: *mut c_void, + ) { + let stack_bottom = base.as_ptr(); + let stack_top = align_down(unsafe { self.inner().payload } as usize, STACK_ALIGN); + let stack = core::ptr::slice_from_raw_parts_mut( + stack_bottom.cast::>(), + (stack_top - stack_bottom as usize) / 4, + ); + + let task = self.task(); + unsafe { + task.as_ptr() + .write(Task::new(options, entry, param, stack, self)) + }; + + SCHEDULER.with(|scheduler| scheduler.register_task(task)); + } + + /// Destroys the bookkeeping of the thread. The scheduler leaves the [`Task`] in place when it + /// deletes the thread, because the task locates the memory block. + /// + /// # Safety + /// + /// The thread must be prepared, and nothing may use the bookkeeping afterwards. + unsafe fn destroy(self) { + unsafe { core::ptr::drop_in_place(self.task().as_ptr()) }; + unsafe { core::ptr::drop_in_place(self.inner_ptr()) }; + } + + /// Returns the memory block to the allocator, if it came from there. + /// + /// # Safety + /// + /// Nothing may use the block afterwards. + unsafe fn deallocate(self, base: NonNull, heap: bool) { + if heap { + cfg_select! { + feature = "alloc" => unsafe { + let block = self.0.as_ptr().add(1) as usize - base.as_ptr() as usize; + let size = block - GUARD_RESERVE - size_of::(); + InternalMemory.deallocate(base, block_layout(size)) + }, + _ => { + _ = base; + } + } + } + } +} + +/// The layout of a memory block that offers `size` bytes of stack. +#[cfg(feature = "alloc")] +fn block_layout(size: usize) -> Layout { + unwrap!( + Layout::from_size_align(GUARD_RESERVE + size + size_of::(), STACK_ALIGN).ok(), + "The stack size is too large" + ) +} + +/// The properties of a thread, which a `join` returns so that the next thread can reuse them. +#[derive(Clone, Copy)] +pub(crate) struct ThreadOptions { + pub name: Option<&'static str>, + pub priority: usize, + pub pinned_to: Option, +} + +impl ThreadOptions { + const fn new() -> Self { + Self { + name: None, + priority: 0, + pinned_to: None, + } + } +} + +const fn align_down(addr: usize, align: usize) -> usize { + addr & !(align - 1) +} + +/// The error returned when a thread stack cannot be allocated. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +#[cfg_attr(feature = "defmt", derive(defmt::Format))] +pub struct OutOfMemory(usize); + +impl core::fmt::Display for OutOfMemory { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!( + f, + "Failed to allocate {} bytes of memory for the thread", + self.0 + ) + } +} + +impl core::error::Error for OutOfMemory {} + +/// Owns the memory of a thread, and starts the thread on it. +/// +/// The spawner is consumed by [`ThreadSpawner::spawn`], and [`JoinHandle::join`] returns it, so +/// that the next thread can run on the same memory. +pub struct ThreadSpawner { + /// The start of the memory block, which holds no thread yet. + base: NonNull, + /// The bookkeeping at the end of the block. + thread: ThreadPtr, + /// Whether the block must be returned to the allocator. + heap: bool, + options: ThreadOptions, +} + +unsafe impl Send for ThreadSpawner {} + +impl ThreadSpawner { + /// Allocates a stack of `stack_size` bytes in internal memory. + /// + /// The closure and the return value of the thread are placed on this stack, so they reduce the + /// number of bytes the thread can use. + /// + /// This function panics if the allocation fails. Use [`ThreadSpawner::try_new`] to handle the + /// failure. + #[cfg(feature = "alloc")] + #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))] + pub fn new(stack_size: usize) -> Self { + unwrap!( + Self::try_new(stack_size).ok(), + "Failed to allocate a thread stack" + ) + } + + /// Allocates a stack of `stack_size` bytes in internal memory. + /// + /// This function returns an error if the allocation fails. + #[cfg(feature = "alloc")] + #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))] + pub fn try_new(stack_size: usize) -> Result { + let size = stack_size.next_multiple_of(STACK_ALIGN); + let base = InternalMemory + .allocate(block_layout(size)) + .map_err(|_| OutOfMemory(stack_size))? + .cast::(); + + Ok(Self { + base, + thread: ThreadPtr(unsafe { base.add(GUARD_RESERVE + size) }.cast()), + heap: true, + options: ThreadOptions::new(), + }) + } + + /// Runs the thread on a statically allocated stack. + pub fn from_static(stack: &'static mut Stack) -> Self { + Self { + base: NonNull::from(&mut *stack).cast(), + thread: ThreadPtr(NonNull::from(&mut stack.resources).cast()), + heap: false, + options: ThreadOptions::new(), + } + } + + /// Sets the name of the thread. + /// + /// The name is used by the logs and by `rtos-trace`. Threads have no name by default. + #[must_use] + pub fn with_name(mut self, name: &'static str) -> Self { + self.options.name = Some(name); + self + } + + /// Sets the priority of the thread. + /// + /// Higher numbers mean higher priority. The default priority is 0, which is the lowest. + /// + /// This function panics if `priority` is greater than the highest supported priority. + #[must_use] + pub fn with_priority(mut self, priority: usize) -> Self { + assert!( + priority <= MaxPriority::MAX_PRIORITY, + "The priority must not be greater than {}", + MaxPriority::MAX_PRIORITY + ); + self.options.priority = priority; + self + } + + /// Runs the thread on a single CPU. + /// + /// By default a thread can run on any CPU the scheduler runs on. + #[must_use] + pub fn with_pinned_to(mut self, cpu: Cpu) -> Self { + self.options.pinned_to = Some(cpu); + self + } + + /// Starts the thread. + /// + /// The thread runs `f`, and exits when `f` returns. Drop the returned handle to detach the + /// thread, or use [`JoinHandle::join`] to wait for it and to read its return value. + /// + /// This function panics if `f` and its return value do not fit the thread's stack, if the + /// scheduler is not running, if it is called from an interrupt handler, or if the thread is + /// pinned to a CPU that does not run the scheduler. + pub fn spawn(self, f: F) -> JoinHandle + where + F: FnOnce() -> T + Send + 'static, + T: Send + 'static, + { + crate::assert_thread_mode("ThreadSpawner::spawn"); + + let payload = unwrap!( + Layout::from_size_align( + size_of::().max(size_of::()), + align_of::().max(align_of::()), + ) + .ok() + ); + + let (base, options) = (self.base, self.options); + let thread = self.prepare(payload); + + unsafe { thread.inner().payload.cast::().write(f) }; + unsafe { thread.launch(base, &options, thread_entry::, thread.as_param()) }; + + JoinHandle { + thread, + options, + _result: PhantomData, + } + } + + /// Starts a thread that runs a C-compatible function. + #[cfg(feature = "esp-radio")] + pub(crate) fn spawn_extern( + self, + entry: extern "C" fn(*mut c_void), + param: *mut c_void, + ) -> TaskPtr { + let (base, options) = (self.base, self.options); + let thread = self.prepare(Layout::new::<()>()); + + // These threads have no `JoinHandle`, so the scheduler releases their memory when they + // exit. + unsafe { thread.inner().detached = true }; + unsafe { thread.launch(base, &options, entry, param) }; + + thread.task() + } + + /// Reserves the payload, and initializes the state the thread shares with its `JoinHandle`. + /// + /// The caller must move the closure, if any, into `ThreadInner::payload`, and must then call + /// [`ThreadPtr::launch`] to start the thread. + fn prepare(self, payload: Layout) -> ThreadPtr { + assert!( + SCHEDULER.with(|scheduler| scheduler.time_driver.is_some()), + "The scheduler is not running. Call esp_rtos::start before spawning a thread." + ); + + // The thread owns its memory from here on. `JoinHandle` or the scheduler releases it. + let this = ManuallyDrop::new(self); + + let thread = this.thread; + unsafe { + thread.inner_ptr().write(ThreadInner { + has_result: false, + detached: false, + released: false, + heap: this.heap, + wait_queue: WaitQueue::new(), + payload: thread.reserve_payload(this.base, payload), + }) + }; + + thread + } +} + +impl Drop for ThreadSpawner { + fn drop(&mut self) { + unsafe { self.thread.deallocate(self.base, self.heap) }; + } +} + +extern "C" fn thread_entry(param: *mut c_void) +where + F: FnOnce() -> T + Send + 'static, + T: Send + 'static, +{ + let thread = unsafe { ThreadPtr::from_param(param) }; + + let payload = unsafe { thread.inner().payload }; + let f = unsafe { payload.cast::().read() }; + + let result = f(); + + unsafe { publish(thread, result) }; +} + +/// Hands the return value of the thread to the `JoinHandle`, or drops it if the thread is +/// detached. +unsafe fn publish(thread: ThreadPtr, result: T) { + // The thread is still running, so nobody can release its memory while we write. + let payload = unsafe { thread.inner().payload.cast::() }; + unsafe { payload.write(result) }; + + let detached = SCHEDULER.with(|_scheduler| { + let inner = unsafe { thread.inner() }; + inner.has_result = !inner.detached; + inner.detached + }); + + if detached { + unsafe { payload.drop_in_place() }; + } +} + +/// Releases the memory of an exited thread. The scheduler calls this after it switched off the +/// thread's stack for the last time, so the memory can be reused from this point on. +/// +/// # Safety +/// +/// The scheduler must no longer use the `Task` of the thread. +pub(crate) unsafe fn release(thread: ThreadPtr, scheduler: &mut SchedulerState) { + let inner = unsafe { thread.inner() }; + inner.released = true; + + if inner.detached { + unsafe { free(thread) }; + } else { + inner.wait_queue.notify(scheduler); + } +} + +/// Destroys the thread's bookkeeping, and returns heap-allocated memory to the allocator. +unsafe fn free(thread: ThreadPtr) { + let base = unsafe { thread.base() }; + let heap = unsafe { thread.inner().heap }; + + unsafe { thread.destroy() }; + unsafe { thread.deallocate(base, heap) }; +} + +/// A handle to a running thread. +/// +/// Dropping the handle detaches the thread. The thread keeps running, but its return value is +/// dropped, and the memory of a thread that runs on a heap-allocated stack is returned to the +/// allocator when the thread exits. The memory of a thread that runs on a [`Stack`] is not +/// recovered. +pub struct JoinHandle { + thread: ThreadPtr, + /// The properties of the thread, which outlive it, so that [`JoinHandle::join`] can return a + /// spawner that starts an identical thread. + options: ThreadOptions, + _result: PhantomData, +} + +unsafe impl Send for JoinHandle {} + +impl JoinHandle { + /// Returns the name of the thread. + pub fn name(&self) -> Option<&'static str> { + self.options.name + } + + /// Returns whether the thread has finished running its closure. + pub fn is_finished(&self) -> bool { + SCHEDULER.with(|_scheduler| unsafe { self.thread.inner().has_result }) + } + + /// Detaches the thread. + /// + /// The thread keeps running until it exits, but its return value is dropped, and its memory + /// cannot be reused. + pub fn detach(self) {} + + /// Waits for the thread to exit, and returns its return value together with a spawner that + /// owns the memory the thread ran on. The spawner has the properties of the thread that + /// exited. + /// + /// The current thread sleeps until the thread exits. This function does not change the + /// priority of the thread it waits for, so a thread of a middle priority can delay a + /// high-priority thread that waits for a low-priority one. + /// + /// This function panics if a thread tries to join itself. + pub fn join(self) -> (T, ThreadSpawner) { + let this = ManuallyDrop::new(self); + let thread = this.thread; + + assert!( + thread.task() != SCHEDULER.current_task(), + "A thread cannot join itself" + ); + + // The memory is safe to reuse once the scheduler marks the thread released. + loop { + let released = SCHEDULER.with(|scheduler| { + let inner = unsafe { thread.inner() }; + if inner.released { + true + } else { + inner + .wait_queue + .wait_with_deadline(scheduler, Instant::EPOCH + Duration::MAX); + false + } + }); + + if released { + break; + } + } + + let inner = unsafe { thread.inner() }; + + debug_assert!( + inner.has_result, + "The thread exited without publishing its return value" + ); + + let result = unsafe { inner.payload.cast::().read() }; + let base = unsafe { thread.base() }; + let heap = inner.heap; + + unsafe { thread.destroy() }; + + ( + result, + ThreadSpawner { + base, + thread, + heap, + options: this.options, + }, + ) + } +} + +impl Drop for JoinHandle { + fn drop(&mut self) { + // The scheduler releases the thread's memory while it holds its lock, and it may do so as + // soon as we mark the thread detached. Working under the same lock makes sure that exactly + // one of the two frees the memory, and that the other one stops using it. + SCHEDULER.with(|_scheduler| { + let inner = unsafe { self.thread.inner() }; + inner.detached = true; + + if inner.has_result { + unsafe { inner.payload.cast::().drop_in_place() }; + } + + if inner.released { + unsafe { free(self.thread) }; + } + }); + } +} diff --git a/esp-rtos/src/timer/embassy.rs b/esp-rtos/src/timer/embassy.rs index cd921b83fbf..145f33fe8ae 100644 --- a/esp-rtos/src/timer/embassy.rs +++ b/esp-rtos/src/timer/embassy.rs @@ -56,7 +56,10 @@ impl embassy_time_driver::Driver for EmbassyTimeDriver { if embassy_timer_queue.schedule_wake(at, waker) { // Next wakeup time became shorter, re-arm the timer. let mut scheduler = global_state.scheduler(); - let time_driver = unwrap!(scheduler.time_driver.as_mut()); + let time_driver = unwrap!( + scheduler.time_driver.as_mut(), + "The scheduler has not been started. Make sure to call `esp_rtos::start()` before using async features", + ); time_driver .timer_queue diff --git a/esp-rtos/src/timer/mod.rs b/esp-rtos/src/timer/mod.rs index 0c5d73375ff..f0b7ab88bdb 100644 --- a/esp-rtos/src/timer/mod.rs +++ b/esp-rtos/src/timer/mod.rs @@ -301,6 +301,11 @@ extern "C" fn timer_tick_handler() { if active_cores.contains(cpu) && now >= time_driver.timer_queue.time_slice_target[cpu as usize] { + // The context switch cannot preempt this handler, because it runs at the lowest + // interrupt priority. Clear the expired target, or this handler keeps re-arming + // the alarm for a time in the past, and its interrupt starves the context switch. + // The scheduler sets the next target when the context switch runs. + time_driver.set_time_slice(cpu, now, false); task::trigger_scheduler(RunSchedulerOn::RunOnCore(cpu)); } } diff --git a/esp-rtos/src/wait_queue.rs b/esp-rtos/src/wait_queue.rs index 4c31d46c26f..e024414339c 100644 --- a/esp-rtos/src/wait_queue.rs +++ b/esp-rtos/src/wait_queue.rs @@ -4,9 +4,14 @@ use esp_hal::time::Instant; use crate::{ SCHEDULER, + scheduler::SchedulerState, task::{TaskList, TaskPtr, TaskReadyQueueElement}, }; +/// A list of tasks that wait for an event. +/// +/// The methods take the locked scheduler, because the caller usually needs to inspect the state +/// the queue protects, in the same critical section. pub(crate) struct WaitQueue { // A task is either blocked, or ready. Since it can't be both, we can reuse the ready queue // element. Note however, that a task can simultaneously be in the timer queue and a wait @@ -21,26 +26,24 @@ impl WaitQueue { } } - pub(crate) fn notify(&mut self) { - SCHEDULER.with(|scheduler| { - // Expergiscere eos. Novit enim Ordinator qui sunt eius. - while let Some(waken_task) = self.waiting_tasks.pop() { - scheduler.resume_task(waken_task); - } - }); + /// Wakes up every waiting task. + pub(crate) fn notify(&mut self, scheduler: &mut SchedulerState) { + // Expergiscere eos. Novit enim Ordinator qui sunt eius. + while let Some(waken_task) = self.waiting_tasks.pop() { + scheduler.resume_task(waken_task); + } } - pub(crate) fn wait_with_deadline(&mut self, deadline: Instant) { - SCHEDULER.with(|scheduler| { - let mut task = SCHEDULER.current_task(); - if scheduler.sleep_task_until(task, deadline) { - self.waiting_tasks.push(task); - unsafe { - task.as_mut().current_wait_queue = Some(NonNull::from(self)); - } - crate::task::yield_task(); + /// Puts the current task to sleep until the queue is notified, or the deadline passes. + pub(crate) fn wait_with_deadline(&mut self, scheduler: &mut SchedulerState, deadline: Instant) { + let mut task = SCHEDULER.current_task(); + if scheduler.sleep_task_until(task, deadline) { + self.waiting_tasks.push(task); + unsafe { + task.as_mut().current_wait_queue = Some(NonNull::from(self)); } - }); + crate::task::yield_task(); + } } pub(crate) fn remove(&mut self, task: TaskPtr) { diff --git a/esp-storage/CHANGELOG.md b/esp-storage/CHANGELOG.md index 13f221788fd..00d065aa7d9 100644 --- a/esp-storage/CHANGELOG.md +++ b/esp-storage/CHANGELOG.md @@ -9,7 +9,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- Add ESP32-S31 support (#5922) ### Changed @@ -20,6 +19,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Removed +## [v0.10.0] - 2026-08-25 + +### Added + +- Add ESP32-S31 support (#5922) +- `FlashStorage::read_encrypted` and `FlashStorage::write_encrypted` for transparent flash encryption read/write (#5810) +- `flash_encryption()` helper to query whether flash encryption is enabled in eFuses (#5810) +- Support for ESP32-P4 (#5751) +- Inherent flash I/O methods on `FlashStorage`: `read`, `write`, `capacity`, `read_nor`, `write_nor`, and `erase` (#5739) + +### Changed + +- `FlashStorage::read_encrypted` now follows the multi-core strategy, so it can return `OtherCoreRunning`. (#6120) +- esp-storage can now be built with any opt-level (#5911) +- updated defmt to 1.1 (#5752) +- `embedded-storage` trait implementations are now an opt-in feature (non-default) (#5739) + +### Fixed + +- On ESP32, reading and writing encrypted flash no longer hangs. The flash MMU and the cache are now changed with the cache turned off, as the hardware requires. (#6120) +- `FlashStorage::erase` rejects reversed ranges (`to < from`) (#6045) + ## [v0.9.0] - 2026-04-16 ### Added @@ -96,4 +117,5 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 [v0.8.0]: https://github.com/esp-rs/esp-hal/compare/esp-storage-v0.7.0...esp-storage-v0.8.0 [v0.8.1]: https://github.com/esp-rs/esp-hal/compare/esp-storage-v0.8.0...esp-storage-v0.8.1 [v0.9.0]: https://github.com/esp-rs/esp-hal/compare/esp-storage-v0.8.1...esp-storage-v0.9.0 -[Unreleased]: https://github.com/esp-rs/esp-hal/compare/esp-storage-v0.9.0...HEAD +[v0.10.0]: https://github.com/esp-rs/esp-hal/compare/esp-storage-v0.9.0...esp-storage-v0.10.0 +[Unreleased]: https://github.com/esp-rs/esp-hal/compare/esp-storage-v0.10.0...HEAD diff --git a/esp-storage/Cargo.toml b/esp-storage/Cargo.toml index 64f855bfdbc..cc2eb9f8490 100644 --- a/esp-storage/Cargo.toml +++ b/esp-storage/Cargo.toml @@ -1,9 +1,9 @@ [package] name = "esp-storage" -version = "0.9.0" +version = "0.10.0" edition = "2024" rust-version = "1.95.0" -description = "Access ESP32 flash, including encrypted read/write. Optionally implements esp-storage traits for unencrypted flash." +description = "Deprecated in favor of esp_hal::flash (esp-hal) and the partition API of esp-bootloader-esp-idf. Access ESP32 flash, including encrypted read/write." documentation = "https://docs.espressif.com/projects/rust/esp-storage/latest/" keywords = ["embedded-storage", "esp32", "espressif", "no-std"] categories = ["embedded", "hardware-support", "no-std"] @@ -12,6 +12,7 @@ license = "MIT OR Apache-2.0" [package.metadata.espressif] chip-features-matter = true +doc-config = { env = { CARGO_PROFILE_DEBUG_OPT_LEVEL = "3" } } check-configs = [ { features = [] }, { features = ["embedded-storage"] }, @@ -21,6 +22,12 @@ check-configs = [ { features = ["embedded-storage", "critical-section", "bytewise-read"] }, ] clippy-configs = [{ features = ["embedded-storage", "critical-section", "bytewise-read"] }] +host-test-configs = [ + { features = ["emulation"], test-args = ["--test-threads=1"] }, + { features = ["emulation", "bytewise-read"], test-args = ["--test-threads=1"] }, + { features = ["emulation"], test-args = ["--test-threads=1"], miri = true }, + { features = ["emulation", "bytewise-read"], test-args = ["--test-threads=1"], miri = true }, +] [package.metadata.docs.rs] default-target = "riscv32imac-unknown-none-elf" @@ -32,31 +39,32 @@ bench = false [dependencies] embedded-storage = { version = "0.3.1", optional = true } procmacros = { version = "0.23.0", package = "esp-hal-procmacros", path = "../esp-hal-procmacros" } -esp-hal = { version = "~1.2.0-rc.0", path = "../esp-hal", default-features = false, optional = true } -esp-metadata-generated = { version = "0.5.0", path = "../esp-metadata-generated" } +esp-hal = { version = "~1.2.0", path = "../esp-hal", default-features = false, optional = true } +esp-metadata-generated = { version = "0.6.0", path = "../esp-metadata-generated" } # Optional dependencies esp-sync = { version = "0.3.0", path = "../esp-sync", optional = true } -esp-rom-sys = { version = "~0.1", path = "../esp-rom-sys", optional = true } +esp-rom-sys = { version = "0.1.5", path = "../esp-rom-sys", optional = true } defmt = { version = "1.1", optional = true } -esp32 = { version = "0.41", features = ["critical-section"], optional = true } -esp32c2 = { version = "0.30", features = ["critical-section"], optional = true } -esp32c3 = { version = "0.33", features = ["critical-section"], optional = true } -esp32c5 = { version = "0.3", features = ["critical-section"], optional = true } -esp32c6 = { version = "0.24", features = ["critical-section"], optional = true } -esp32c61 = { version = "0.4", features = ["critical-section"], optional = true } -esp32h2 = { version = "0.20", features = ["critical-section"], optional = true } -esp32s2 = { version = "0.32", features = ["critical-section"], optional = true } -esp32s3 = { version = "0.36", features = ["critical-section"], optional = true } -esp32s31 = { version = "0.2", features = ["critical-section"], optional = true } -esp32p4 = { version = "0.3", features = ["critical-section"], optional = true } +esp32 = { version = "0.42", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32c2 = { version = "0.31", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32c3 = { version = "0.34", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32c5 = { version = "0.4", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32c6 = { version = "0.25", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32c61 = { version = "0.5", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32h2 = { version = "0.21", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32h4 = { version = "0.1", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32s2 = { version = "0.33", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32s3 = { version = "0.37", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32s31 = { version = "0.3", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } +esp32p4 = { version = "0.4", features = ["critical-section"], optional = true, git = "https://github.com/esp-rs/esp-pacs.git", rev = "5cb8c50" } # Unstable dependencies that are not (strictly) part of the public API document-features = "0.2" [build-dependencies] -esp-metadata-generated = { version = "0.5.0", path = "../esp-metadata-generated", features = ["build-script"] } +esp-metadata-generated = { version = "0.6.0", path = "../esp-metadata-generated", features = ["build-script"] } [features] default = ["critical-section"] @@ -89,6 +97,8 @@ esp32c61 = ["esp-hal/esp32c61", "esp-hal/unstable", "esp-rom-sys/esp32c61", "es ## esp32h2 = ["esp-hal/esp32h2", "esp-hal/unstable", "esp-rom-sys/esp32h2", "esp-sync/esp32h2", "dep:esp32h2"] ## +esp32h4 = ["esp-hal/esp32h4", "esp-hal/unstable", "esp-rom-sys/esp32h4", "esp-sync/esp32h4", "dep:esp32h4"] +## esp32p4 = ["esp-hal/esp32p4", "esp-hal/unstable", "esp-rom-sys/esp32p4", "esp-sync/esp32p4", "dep:esp32p4"] ## esp32 = ["esp-hal/esp32", "esp-hal/unstable", "esp-rom-sys/esp32", "esp-sync/esp32", "dep:esp32"] diff --git a/esp-storage/README.md b/esp-storage/README.md index 9a30dca767c..a670aace189 100644 --- a/esp-storage/README.md +++ b/esp-storage/README.md @@ -6,6 +6,18 @@ ![Crates.io](https://img.shields.io/crates/l/esp-storage?labelColor=1C2C2E&style=flat-square) [![Matrix](https://img.shields.io/matrix/esp-rs:matrix.org?label=join%20matrix&labelColor=1C2C2E&color=BEC5C9&logo=matrix&style=flat-square)](https://matrix.to/#/#esp-rs:matrix.org) +> **Deprecated.** Use instead: +> +> - `esp_hal::flash::Flash` from [esp-hal](https://docs.espressif.com/projects/rust/esp-hal/latest/) for raw and encrypted flash I/O +> (`read`, `write`, `erase`, `read_encrypted`, `write_encrypted`). This driver is unstable (requires the `unstable` feature of `esp-hal`). +> It works on `u32` word buffers in DRAM at 4-byte-aligned offsets, does not erase before writing, and does not implement `embedded-storage` traits. +> - `FlashRegion`, `EncryptedFlashRegion` and `AutoFlashRegion` from [esp-bootloader-esp-idf](https://docs.espressif.com/projects/rust/esp-bootloader-esp-idf/latest/) +> for byte-oriented, partition-scoped access, including encrypted partitions. +> With the `embedded-storage` feature, `FlashRegion` implements `ReadNorFlash`, `NorFlash` and `MultiwriteNorFlash`. +> For the read-modify-write behavior of the `Storage` trait, wrap it in `embedded_storage::nor_flash::RmwMultiwriteNorFlashStorage`. +> +> See [#6447](https://github.com/esp-rs/esp-hal/pull/6447) for migration notes. + This crate provides functionality to access ESP32 flash. Enable the `embedded-storage` feature for [`embedded-storage`](https://github.com/rust-embedded-community/embedded-storage) trait implementations. diff --git a/esp-storage/src/lib.rs b/esp-storage/src/lib.rs index 069f3c8c8b3..f590e9a4624 100644 --- a/esp-storage/src/lib.rs +++ b/esp-storage/src/lib.rs @@ -1,6 +1,23 @@ //! `esp-storage` contains API functions related to reading, writing and erasing memory for data in //! the external flash. //! +//!
+//! +//! This crate is deprecated. Use instead: +//! +//! - [`esp_hal::flash::Flash`] for raw and encrypted flash I/O +//! ([`Flash::read_encrypted`](esp_hal::flash::Flash::read_encrypted), +//! [`Flash::write_encrypted`](esp_hal::flash::Flash::write_encrypted)). This driver is unstable, +//! works on `u32` word buffers in DRAM, and does not implement `embedded-storage` traits. +//! - `FlashRegion`, `EncryptedFlashRegion` and `AutoFlashRegion` from [`esp-bootloader-esp-idf`](https://docs.espressif.com/projects/rust/esp-bootloader-esp-idf/latest/) +//! for byte-oriented, partition-scoped access. With the `embedded-storage` feature of that crate, +//! `FlashRegion` implements the `embedded-storage` NOR flash traits. +//! +//! `esp_bootloader_esp_idf::partitions::FlashStorage` is an alias for [`esp_hal::flash::Flash`], +//! not this crate's [`FlashStorage`]. +//! +//!
+//! //! For higher-level functionality which works with partitions defined in the partition table, see //! `esp-bootloader-esp-idf`. //! diff --git a/esp-storage/src/mmu.rs b/esp-storage/src/mmu.rs index df0a11d8c22..20a56a239f2 100644 --- a/esp-storage/src/mmu.rs +++ b/esp-storage/src/mmu.rs @@ -19,6 +19,8 @@ use esp32c6 as pac; use esp32c61 as pac; #[cfg(esp32h2)] use esp32h2 as pac; +#[cfg(esp32h4)] +use esp32h4 as pac; #[cfg(esp32p4)] use esp32p4 as pac; #[cfg(esp32s2)] @@ -182,7 +184,7 @@ pub(crate) fn invalidate_flash_cache(start: u32, len: u32) { } } -#[cfg(not(any(esp32, esp32p4, esp32s31)))] +#[cfg(not(any(esp32, esp32h4, esp32p4, esp32s31)))] fn invalidate_cache(vaddr: u32, size: u32) { unsafe extern "C" { fn Cache_Invalidate_Addr(addr: u32, size: u32); @@ -192,7 +194,7 @@ fn invalidate_cache(vaddr: u32, size: u32) { } } -#[cfg(esp32s31)] +#[cfg(any(esp32h4, esp32s31))] fn invalidate_cache(vaddr: u32, size: u32) { const CACHE_MAP_L1_DCACHE: u32 = 1 << 4; @@ -308,11 +310,11 @@ mod indexed { } fn flash_mapping_from_entry(entry: pac::spi0::mmu_item_content::R) -> bool { - #[cfg(any(esp32c5, esp32c61))] + #[cfg(any(esp32c5, esp32c61, esp32h4))] { !entry.access_spiram().bit() } - #[cfg(not(any(esp32c5, esp32c61)))] + #[cfg(not(any(esp32c5, esp32c61, esp32h4)))] { let _ = entry; true @@ -336,7 +338,7 @@ mod indexed { select_entry(entry_id); spi0().mmu_item_content().write(|w| { unsafe { w.paddr().bits(page) }; - #[cfg(any(esp32c5, esp32c61))] + #[cfg(any(esp32c5, esp32c61, esp32h4))] w.access_spiram().clear_bit(); w.valid().set_bit(); if encrypted { diff --git a/esp-sync/Cargo.toml b/esp-sync/Cargo.toml index 32117fc5c9c..acf445d1ae4 100644 --- a/esp-sync/Cargo.toml +++ b/esp-sync/Cargo.toml @@ -20,7 +20,7 @@ clippy-configs = [{ features = ["defmt"] }] [dependencies] document-features = "0.2" -esp-metadata-generated = { version = "0.5.0", path = "../esp-metadata-generated" } +esp-metadata-generated = { version = "0.6.0", path = "../esp-metadata-generated" } embassy-sync-06 = { package = "embassy-sync", version = "0.6" } embassy-sync-07 = { package = "embassy-sync", version = "0.7" } embassy-sync-08 = { package = "embassy-sync", version = "0.8" } @@ -36,7 +36,7 @@ riscv = { version = "0.15" } xtensa-lx = { version = "0.13.0", path = "../xtensa-lx" } [build-dependencies] -esp-metadata-generated = { version = "0.5.0", path = "../esp-metadata-generated", features = ["build-script"] } +esp-metadata-generated = { version = "0.6.0", path = "../esp-metadata-generated", features = ["build-script"] } [features] #! ### Chip Support Feature Flags @@ -54,6 +54,8 @@ esp32c6 = ["esp-metadata-generated/esp32c6"] esp32c61 = ["esp-metadata-generated/esp32c61"] ## Target the ESP32-H2. esp32h2 = ["esp-metadata-generated/esp32h2"] +## Target the ESP32-H4. +esp32h4 = ["esp-metadata-generated/esp32h4"] ## Target the ESP32-P4. esp32p4 = ["esp-metadata-generated/esp32p4"] ## Target the ESP32-S2. diff --git a/esp-sync/src/lib.rs b/esp-sync/src/lib.rs index 05efbb89c04..1c2bca12752 100644 --- a/esp-sync/src/lib.rs +++ b/esp-sync/src/lib.rs @@ -1,4 +1,4 @@ -//! Syncronization primitives for ESP32 devices +//! Synchronization primitives for ESP32 devices //! //! ## Feature Flags #![doc = document_features::document_features!(feature_label = r#"{feature}"#)] @@ -116,17 +116,17 @@ mod single_core { mod multi_core { use core::sync::atomic::{AtomicUsize, Ordering}; - // Safety: Ensure that when adding new chips `raw_core` doesn't return this - // value. - const UNUSED_THREAD_ID_VALUE: usize = 0x100; + // Zero, so that a static mutex is placed in `.bss`. + const UNUSED_THREAD_ID_VALUE: usize = 0; #[inline] fn thread_id() -> usize { // This method must never return UNUSED_THREAD_ID_VALUE cfg_select! { - all(multi_core, riscv) => riscv::register::mhartid::read(), - all(multi_core, xtensa) => (xtensa_lx::get_processor_id() & 0x2000) as usize, - _ => 0, + // `mhartid` is 0 on the first core. + all(multi_core, riscv) => riscv::register::mhartid::read() + 1, + // `PRID` is 0xCDCD on the PRO CPU and 0xABAB on the APP CPU. + all(multi_core, xtensa) => xtensa_lx::get_processor_id() as usize, } } @@ -288,7 +288,7 @@ impl GenericRawMutex { #[cfg_attr( multi_core, doc = r#"It needs a bit of memory, but it does not take a global critical - section, making it preferrable for use in multi-core systems."# + section, making it preferable for use in multi-core systems."# )] pub struct RawMutex { inner: GenericRawMutex, diff --git a/esp-sync/src/raw.rs b/esp-sync/src/raw.rs index f6c6cae484c..ab3f05c9216 100644 --- a/esp-sync/src/raw.rs +++ b/esp-sync/src/raw.rs @@ -35,9 +35,8 @@ impl RawLock for SingleCoreInterruptLock { #[inline] unsafe fn enter(&self) -> RestoreState { cfg_select! { - esp32p4 => { - // TODO: any with zcmp - // ESP32-P4 (v3.2/ECO7 etc.) Zcmp hardware bug workaround (IDF-14279 / DIG-661): + soc_cpu_has_zcmp_workaround => { + // Zcmp hardware bug workaround (IDF-14279 / DIG-661): // Clearing mstatus.mie alone does not fully mask CLIC interrupts -- an // interrupt can still fire mid-instruction on cm.push (and possibly on // other multi-cycle sequences). Fix: raise mintthresh (CSR 0x347) to 0xFF @@ -89,20 +88,20 @@ impl RawLock for SingleCoreInterruptLock { #[inline] unsafe fn exit(&self, token: RestoreState) { - // Ensure no preceeding memory accesses are reordered to after interrupts are + // Ensure no preceding memory accesses are reordered to after interrupts are // enabled. compiler_fence(Ordering::SeqCst); let token = token.inner(); cfg_select! { - esp32p4 => { + soc_cpu_has_zcmp_workaround => { if (token & 0b1000) != 0 { unsafe { riscv::interrupt::enable(); } } - // Restore mintthresh AFTER re-enabling mie (P4 Zcmp workaround, see enter()). + // Restore mintthresh AFTER re-enabling mie (Zcmp workaround, see enter()). let old_mintthresh = (token >> 8) & 0xff; unsafe { core::arch::asm!( diff --git a/examples/README.md b/examples/README.md index 341f97bf342..03168da4729 100644 --- a/examples/README.md +++ b/examples/README.md @@ -10,27 +10,29 @@ For more information regarding the examples, refer to the `README.md` file in an ## Building Examples -You can build all examples for a given device using the `build examples` subcommand: +Build all examples for a given device: ```shell -cargo xtask build examples --chip esp32 all +cargo xtask build examples all esp32 ``` -Or build a single example with: +Or build a single example: ```shell -cargo xtask build examples --chip esp32c6 hello_world +cargo xtask build hello_world esp32c6 ``` ## Running Examples -You can also build and then subsequently flash and run an example using the `run example` subcommand. With a target device connected to your host system, run: +With a target device connected, chip is inferred when possible: ```shell -cargo xtask run example embassy_hello_world --chip=esp32c6 +cargo xtask run embassy_hello_world ``` -Again, note that we must specify which package to build the example from, plus which example to build and flash to the target device. +Pass the chip name when inference is unavailable. + +QA binaries live in `examples/qa` and run the same way (`cargo xtask run sleep_timer`). ## Adding Examples diff --git a/examples/async/embassy_auto_light_sleep/Cargo.toml b/examples/async/embassy_auto_light_sleep/Cargo.toml index 9c91b775222..aa472f8f596 100644 --- a/examples/async/embassy_auto_light_sleep/Cargo.toml +++ b/examples/async/embassy_auto_light_sleep/Cargo.toml @@ -63,6 +63,13 @@ esp32h2 = [ "esp-rtos/esp32h2", "esp-hal/esp32h2", ] +esp32h4 = [ + "multi_core", + "esp-backtrace/esp32h4", + "esp-bootloader-esp-idf/esp32h4", + "esp-rtos/esp32h4", + "esp-hal/esp32h4", +] esp32p4 = [ "multi_core", "esp-backtrace/esp32p4", @@ -83,6 +90,13 @@ esp32s3 = [ "esp-rtos/esp32s3", "esp-hal/esp32s3", ] +esp32s31 = [ + "multi_core", + "esp-backtrace/esp32s31", + "esp-bootloader-esp-idf/esp32s31", + "esp-rtos/esp32s31", + "esp-hal/esp32s31", +] [profile.release] debug = true diff --git a/examples/async/embassy_auto_light_sleep/src/main.rs b/examples/async/embassy_auto_light_sleep/src/main.rs index dc7281a1c48..8df505db75c 100644 --- a/examples/async/embassy_auto_light_sleep/src/main.rs +++ b/examples/async/embassy_auto_light_sleep/src/main.rs @@ -33,6 +33,36 @@ use esp_hal::{ esp_bootloader_esp_idf::esp_app_desc!(); +cfg_select! { + feature = "esp32s3" => { + use esp_hal::rtc_cntl::CacheTagRetentionStorage; + + #[esp_hal::ram(reclaimed, unstable(zeroed))] + static CACHE_TAGMEM: CacheTagRetentionStorage = CacheTagRetentionStorage::new(); + } + _ => {} +} +// An example reads no chip capability, so this condition and the one at `enable_cpu_powerdown` +// list the chips that `supports_cpu_power_down` holds for. +cfg_select! { + any( + feature = "esp32c3", + feature = "esp32s3", + feature = "esp32c5", + feature = "esp32c6", + feature = "esp32c61", + feature = "esp32h2", + feature = "esp32s31", + feature = "esp32p4" + ) => { + use esp_hal::rtc_cntl::CpuRetentionStorage; + + #[esp_hal::ram(reclaimed, unstable(zeroed))] + static CPU_RETENTION_MEMORY: CpuRetentionStorage = CpuRetentionStorage::new(); + } + _ => {} +} + #[embassy_executor::task] async fn periodic() { loop { @@ -52,6 +82,9 @@ cfg_select! { feature = "esp32c5" => { use peripherals::GPIO28 as BOOT_GPIO; } + feature = "esp32h4" => { + use peripherals::GPIO34 as BOOT_GPIO; + } feature = "esp32p4" => { use peripherals::GPIO35 as BOOT_GPIO; } @@ -109,12 +142,33 @@ async fn main(spawner: Spawner) { let timg0 = TimerGroup::new(p.TIMG0); - let sleep = esp_rtos::sleep::configure(p.LPWR); - esp_rtos::start_with_idle_hook(timg0.timer0, p.FROM_CPU_INTR0, sleep.light_sleep_hook); + // ESP32, C2 and S2 have no CPU powerdown, but no need to complicate this any further. + #[allow(unused_mut)] + let mut sleep = esp_rtos::sleep::configure(p.LPWR); + + #[cfg(any( + feature = "esp32c3", + feature = "esp32s3", + feature = "esp32c5", + feature = "esp32c6", + feature = "esp32c61", + feature = "esp32h2", + feature = "esp32s31", + feature = "esp32p4" + ))] + sleep + .enable_cpu_powerdown(CPU_RETENTION_MEMORY.take()) + .unwrap(); + + #[cfg(feature = "esp32s3")] + sleep.keep_cache_tags(CACHE_TAGMEM.take()).unwrap(); + + esp_rtos::start_with_idle_hook(timg0.timer0, sleep.light_sleep_hook); let boot_btn = cfg_select! { any(feature = "esp32", feature = "esp32s2", feature = "esp32s3") => p.GPIO0, feature = "esp32c5" => p.GPIO28, + feature = "esp32h4" => p.GPIO34, feature = "esp32p4" => p.GPIO35, // esp32c2, esp32c3, esp32c6, esp32c61, esp32h2 _ => p.GPIO9, @@ -133,7 +187,7 @@ async fn main(spawner: Spawner) { static APP_CORE_STACK: StaticCell> = StaticCell::new(); let app_core_stack = APP_CORE_STACK.init(Stack::new()); - esp_rtos::start_second_core(p.CPU_CTRL, p.FROM_CPU_INTR1, app_core_stack, move || { + esp_rtos::start_second_core(p.CPU_CTRL, app_core_stack, move || { static EXECUTOR: StaticCell = StaticCell::new(); let executor = EXECUTOR.init(Executor::new()); executor.run(|spawner| { diff --git a/examples/async/embassy_ethernet/Cargo.toml b/examples/async/embassy_ethernet/Cargo.toml index 646db7e9f60..af0e5bf1b24 100644 --- a/examples/async/embassy_ethernet/Cargo.toml +++ b/examples/async/embassy_ethernet/Cargo.toml @@ -47,3 +47,12 @@ esp32p4 = [ "esp-hal/esp32p4", "esp-rtos/esp32p4", ] + +esp32s31 = [ + "esp-alloc/esp32s31", + "esp-println/esp32s31", + "esp-backtrace/esp32s31", + "esp-bootloader-esp-idf/esp32s31", + "esp-hal/esp32s31", + "esp-rtos/esp32s31", +] diff --git a/examples/async/embassy_ethernet/src/main.rs b/examples/async/embassy_ethernet/src/main.rs index 2475cadc931..ce2f8a7b1a9 100644 --- a/examples/async/embassy_ethernet/src/main.rs +++ b/examples/async/embassy_ethernet/src/main.rs @@ -1,29 +1,37 @@ //! Ethernet DHCP Example //! -//! Demonstrates RMII Ethernet: initialises the Ethernet peripheral, waits for a DHCP-assigned IP +//! Demonstrates Ethernet: initialises the Ethernet peripheral, waits for a DHCP-assigned IP //! address, then periodically issues an HTTP GET request to httpbin.org and prints the response //! body. //! -//! The example is configured for ESP32-Ethernet-Kit v1.2 and ESP32-P4-Function EV Board. +//! The example is configured for ESP32-Ethernet-Kit v1.2 (RMII), ESP32-P4-Function EV Board +//! (RMII), and ESP32-S31-Function-Coreboard (RGMII, YT8531 PHY). //! -//! The dev kits use an IP101GRI PHY, which is compatible with `GenericPhy`, but this example -//! showcases a more efficient wrapper using embassy-time. +//! The ESP32 and ESP32-P4 kits use an IP101GRI PHY, the ESP32-S31 a Motorcomm +//! YT8531. Both are driven by `GenericPhy`, which this example wraps to poll +//! the link from embassy-time. //! //! # Board pin mapping //! -//! | Signal | ESP32-Ethernet-Kit v1.2 | ESP32-P4-Function EV Board | -//! |--------------|-------------------------|----------------------------| -//! | REF_CLK (in) | 0 | 50 | -//! | MDC | 23 | 31 | -//! | MDIO | 18 | 52 | -//! | RXD0 | 25 | 29 | -//! | RXD1 | 26 | 30 | -//! | RX_DV / CRS | 27 | 28 | -//! | TXD0 | 19 | 34 | -//! | TXD1 | 22 | 35 | -//! | TX_EN | 21 | 49 | -//! | PHY Reset | 5 | 51 | -//! | PHY address | 1 | 1 | +//! | Signal | ESP32-Ethernet-Kit v1.2 | ESP32-P4-Function EV Board | ESP32-S31-Function-Coreboard | +//! |--------------|-------------------------|----------------------------|------------------------------| +//! | REF_CLK (in) | 0 | 50 | — | +//! | RX_CLK | — | — | 14 | +//! | TX_CLK (out) | — | — | 13 | +//! | MDC | 23 | 31 | 5 | +//! | MDIO | 18 | 52 | 6 | +//! | RXD0 | 25 | 29 | 19 | +//! | RXD1 | 26 | 30 | 18 | +//! | RXD2 | — | — | 17 | +//! | RXD3 | — | — | 16 | +//! | RX_DV / CTL | 27 | 28 | 15 | +//! | TXD0 | 19 | 34 | 8 | +//! | TXD1 | 22 | 35 | 9 | +//! | TXD2 | — | — | 10 | +//! | TXD3 | — | — | 11 | +//! | TX_EN / CTL | 21 | 49 | 12 | +//! | PHY Reset | 5 | 51 | 7 | +//! | PHY address | 1 | 1 | auto | //% CHIP_FILTER: ethernet_driver_supported @@ -42,13 +50,19 @@ use embassy_net::{ use embassy_time::{Duration, Timer}; use esp_alloc as _; use esp_backtrace as _; +cfg_select! { + feature = "esp32s31" => { + use esp_hal::ethernet::RgmiiPinBundle; + } + _ => { + use esp_hal::ethernet::{RmiiPinBundle, clock::ExternalRefClock}; + } +} use esp_hal::{ clock::CpuClock, ethernet::{ Ethernet, EthernetDmaStorage, - RmiiPinBundle, - clock::ExternalRefClock, mac::{Duplex, LinkState, Speed}, phy::{MdioBus, Phy, PhyError, generic::GenericPhy}, }, @@ -79,8 +93,7 @@ static TCP_CLIENT_STATE: ConstStaticCell> = type EthDriver = Ethernet<'static, esp_hal::Async, ExamplePhy>; -/// A custom PHY implementation that wraps [`GenericPhy`], and uses embassy-time -/// to implement polling instead of the busy looping done by GenericPhy. +/// Wraps [`GenericPhy`] to poll it from embassy-time instead of busy-looping. struct ExamplePhy { phy: GenericPhy, timer: Timer, @@ -106,8 +119,8 @@ impl Phy for ExamplePhy { self.phy.address() } - fn init(&mut self, mdio: &mut M) -> Result<(), PhyError> { - self.phy.init(mdio) + fn init(&mut self, mdio: &mut M, max_speed: Speed) -> Result<(), PhyError> { + self.phy.init(mdio, max_speed) } fn poll_link(&mut self, mdio: &mut M, cx: Option<&mut Context<'_>>) -> LinkState { @@ -123,12 +136,13 @@ impl Phy for ExamplePhy { let _ = self.timer.poll_unpin(cx); } - // Poll the PHY for link state. Do not pass `cx`, we're handling the scheduling. - self.cached_link_state = self.phy.poll_link(mdio, None); - - // Uncomment to observe how often the link state is polled - // println!("Polled link state: {:?}", self.cached_link_state); - + let new_state = self.phy.poll_link(mdio, None); + if new_state.up != self.cached_link_state.up + || new_state.speed != self.cached_link_state.speed + { + println!("Link {:?}", new_state); + } + self.cached_link_state = new_state; self.cached_link_state } } @@ -142,7 +156,7 @@ async fn main(spawner: Spawner) { let peripherals = esp_hal::init(esp_hal::Config::default().with_cpu_clock(CpuClock::max())); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); // ── PHY reset ───────────────────────────────────────────────────────────── // Assert reset for at least 100 ms, then release and wait ≥ 300 ms for the PHY to stabilise. @@ -152,6 +166,9 @@ async fn main(spawner: Spawner) { #[cfg(feature = "esp32p4")] let mut phy_reset = Output::new(peripherals.GPIO51, Level::Low, OutputConfig::default()); + #[cfg(feature = "esp32s31")] + let mut phy_reset = Output::new(peripherals.GPIO7, Level::Low, OutputConfig::default()); + Timer::after(Duration::from_millis(100)).await; phy_reset.set_high(); Timer::after(Duration::from_millis(300)).await; @@ -200,6 +217,32 @@ async fn main(spawner: Spawner) { .expect("Ethernet init failed") .into_async(); + #[cfg(feature = "esp32s31")] + let eth: EthDriver = Ethernet::new( + peripherals.ETH, + STORAGE.take(), + MAC_ADDR, + ExamplePhy::new_auto(), + RgmiiPinBundle { + rx_clk: peripherals.GPIO14, + tx_clk: peripherals.GPIO13, + rx_ctl: peripherals.GPIO15, + tx_ctl: peripherals.GPIO12, + rxd0: peripherals.GPIO19, + rxd1: peripherals.GPIO18, + rxd2: peripherals.GPIO17, + rxd3: peripherals.GPIO16, + txd0: peripherals.GPIO8, + txd1: peripherals.GPIO9, + txd2: peripherals.GPIO10, + txd3: peripherals.GPIO11, + mdc: peripherals.GPIO5, + mdio: peripherals.GPIO6, + }, + ) + .expect("Ethernet init failed") + .into_async(); + // ── Network stack ───────────────────────────────────────────────────────── let config = embassy_net::Config::dhcpv4(Default::default()); @@ -216,7 +259,8 @@ async fn main(spawner: Spawner) { spawner.spawn(net_task(runner).unwrap()); - // ── Wait for DHCP ───────────────────────────────────────────────────────── + // `wait_config_up` is DHCP, not PHY link, so wait for the link first. + stack.wait_link_up().await; println!("Waiting for DHCP lease…"); stack.wait_config_up().await; diff --git a/examples/async/embassy_hello_world/Cargo.toml b/examples/async/embassy_hello_world/Cargo.toml index dc68d0b129f..c4a795cc9de 100644 --- a/examples/async/embassy_hello_world/Cargo.toml +++ b/examples/async/embassy_hello_world/Cargo.toml @@ -59,6 +59,12 @@ esp32h2 = [ "esp-rtos/esp32h2", "esp-hal/esp32h2", ] +esp32h4 = [ + "esp-backtrace/esp32h4", + "esp-bootloader-esp-idf/esp32h4", + "esp-rtos/esp32h4", + "esp-hal/esp32h4", +] esp32p4 = [ "esp-backtrace/esp32p4", "esp-bootloader-esp-idf/esp32p4", diff --git a/examples/async/embassy_hello_world/src/main.rs b/examples/async/embassy_hello_world/src/main.rs index b7149cb90ff..82ca70dd172 100644 --- a/examples/async/embassy_hello_world/src/main.rs +++ b/examples/async/embassy_hello_world/src/main.rs @@ -29,7 +29,7 @@ async fn main(spawner: Spawner) { esp_println::println!("Init!"); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); spawner.spawn(run().unwrap()); diff --git a/examples/async/embassy_hello_world_defmt/Cargo.toml b/examples/async/embassy_hello_world_defmt/Cargo.toml index 8034efbb694..620e2d9eb69 100644 --- a/examples/async/embassy_hello_world_defmt/Cargo.toml +++ b/examples/async/embassy_hello_world_defmt/Cargo.toml @@ -68,6 +68,13 @@ esp32h2 = [ "esp-rtos/esp32h2", "esp-hal/esp32h2", ] +esp32h4 = [ + "esp-backtrace/esp32h4", + "esp-println/esp32h4", + "esp-bootloader-esp-idf/esp32h4", + "esp-rtos/esp32h4", + "esp-hal/esp32h4", +] esp32p4 = [ "esp-backtrace/esp32p4", "esp-println/esp32p4", @@ -89,6 +96,13 @@ esp32s3 = [ "esp-rtos/esp32s3", "esp-hal/esp32s3", ] +esp32s31 = [ + "esp-backtrace/esp32s31", + "esp-println/esp32s31", + "esp-bootloader-esp-idf/esp32s31", + "esp-rtos/esp32s31", + "esp-hal/esp32s31", +] [profile.release] debug = true diff --git a/examples/async/embassy_hello_world_defmt/src/main.rs b/examples/async/embassy_hello_world_defmt/src/main.rs index 9570796a58d..03188742d22 100644 --- a/examples/async/embassy_hello_world_defmt/src/main.rs +++ b/examples/async/embassy_hello_world_defmt/src/main.rs @@ -29,7 +29,7 @@ async fn main(spawner: Spawner) { defmt::info!("Init!"); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); spawner.spawn(run().unwrap()); diff --git a/examples/async/embassy_multicore/Cargo.toml b/examples/async/embassy_multicore/Cargo.toml index 931a0504faa..f01804470f6 100644 --- a/examples/async/embassy_multicore/Cargo.toml +++ b/examples/async/embassy_multicore/Cargo.toml @@ -43,6 +43,12 @@ esp32p4 = [ "esp-rtos/esp32p4", "esp-hal/esp32p4", ] +esp32h4 = [ + "esp-backtrace/esp32h4", + "esp-bootloader-esp-idf/esp32h4", + "esp-rtos/esp32h4", + "esp-hal/esp32h4", +] [profile.release] debug = true diff --git a/examples/async/embassy_multicore/src/main.rs b/examples/async/embassy_multicore/src/main.rs index 97371b06803..a1a49949734 100644 --- a/examples/async/embassy_multicore/src/main.rs +++ b/examples/async/embassy_multicore/src/main.rs @@ -60,7 +60,7 @@ async fn main(_spawner: Spawner) { let app_core_stack = APP_CORE_STACK.init(Stack::new()); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); static LED_CTRL: StaticCell> = StaticCell::new(); let led_ctrl_signal = &*LED_CTRL.init(Signal::new()); @@ -71,18 +71,13 @@ async fn main(_spawner: Spawner) { }; let led = Output::new(gpio, Level::Low, OutputConfig::default()); - esp_rtos::start_second_core( - peripherals.CPU_CTRL, - peripherals.FROM_CPU_INTR1, - app_core_stack, - move || { - static EXECUTOR: StaticCell = StaticCell::new(); - let executor = EXECUTOR.init(Executor::new()); - executor.run(|spawner| { - spawner.spawn(control_led(led, led_ctrl_signal).unwrap()); - }); - }, - ); + esp_rtos::start_second_core(peripherals.CPU_CTRL, app_core_stack, move || { + static EXECUTOR: StaticCell = StaticCell::new(); + let executor = EXECUTOR.init(Executor::new()); + executor.run(|spawner| { + spawner.spawn(control_led(led, led_ctrl_signal).unwrap()); + }); + }); // Sends periodic messages to control_led, enabling or disabling it. println!( diff --git a/examples/async/embassy_multicore_interrupt/Cargo.toml b/examples/async/embassy_multicore_interrupt/Cargo.toml index 7902af0e447..2e3ded02279 100644 --- a/examples/async/embassy_multicore_interrupt/Cargo.toml +++ b/examples/async/embassy_multicore_interrupt/Cargo.toml @@ -43,6 +43,12 @@ esp32p4 = [ "esp-rtos/esp32p4", "esp-hal/esp32p4", ] +esp32h4 = [ + "esp-backtrace/esp32h4", + "esp-bootloader-esp-idf/esp32h4", + "esp-rtos/esp32h4", + "esp-hal/esp32h4", +] [profile.release] debug = true diff --git a/examples/async/embassy_multicore_interrupt/src/main.rs b/examples/async/embassy_multicore_interrupt/src/main.rs index 4e460ce8205..0444c6a2f3c 100644 --- a/examples/async/embassy_multicore_interrupt/src/main.rs +++ b/examples/async/embassy_multicore_interrupt/src/main.rs @@ -74,7 +74,7 @@ fn main() -> ! { let peripherals = esp_hal::init(esp_hal::Config::default()); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let mut cpu_control = CpuControl::new(peripherals.CPU_CTRL); @@ -83,8 +83,8 @@ fn main() -> ! { let led = Output::new(peripherals.GPIO0, Level::Low, OutputConfig::default()); - static EXECUTOR_CORE_1: StaticCell> = StaticCell::new(); - let executor_core1 = InterruptExecutor::new(peripherals.FROM_CPU_INTR1); + static EXECUTOR_CORE_1: StaticCell> = StaticCell::new(); + let executor_core1 = InterruptExecutor::new(peripherals.FROM_CPU_INTR3); let executor_core1 = EXECUTOR_CORE_1.init(executor_core1); static APP_CORE_STACK: StaticCell> = StaticCell::new(); diff --git a/examples/async/embassy_multiprio/Cargo.toml b/examples/async/embassy_multiprio/Cargo.toml index 8a41f10e391..6afb2ab71cb 100644 --- a/examples/async/embassy_multiprio/Cargo.toml +++ b/examples/async/embassy_multiprio/Cargo.toml @@ -36,18 +36,36 @@ esp32c3 = [ "esp-rtos/esp32c3", "esp-hal/esp32c3", ] +esp32c5 = [ + "esp-backtrace/esp32c5", + "esp-bootloader-esp-idf/esp32c5", + "esp-rtos/esp32c5", + "esp-hal/esp32c5", +] esp32c6 = [ "esp-backtrace/esp32c6", "esp-bootloader-esp-idf/esp32c6", "esp-rtos/esp32c6", "esp-hal/esp32c6", ] +esp32c61 = [ + "esp-backtrace/esp32c61", + "esp-bootloader-esp-idf/esp32c61", + "esp-rtos/esp32c61", + "esp-hal/esp32c61", +] esp32h2 = [ "esp-backtrace/esp32h2", "esp-bootloader-esp-idf/esp32h2", "esp-rtos/esp32h2", "esp-hal/esp32h2", ] +esp32h4 = [ + "esp-backtrace/esp32h4", + "esp-bootloader-esp-idf/esp32h4", + "esp-rtos/esp32h4", + "esp-hal/esp32h4", +] esp32p4 = [ "esp-backtrace/esp32p4", "esp-bootloader-esp-idf/esp32p4", @@ -66,6 +84,12 @@ esp32s3 = [ "esp-rtos/esp32s3", "esp-hal/esp32s3", ] +esp32s31 = [ + "esp-backtrace/esp32s31", + "esp-bootloader-esp-idf/esp32s31", + "esp-rtos/esp32s31", + "esp-hal/esp32s31", +] [profile.release] debug = true diff --git a/examples/async/embassy_multiprio/src/main.rs b/examples/async/embassy_multiprio/src/main.rs index bebfccc2076..33c6c51c726 100644 --- a/examples/async/embassy_multiprio/src/main.rs +++ b/examples/async/embassy_multiprio/src/main.rs @@ -71,7 +71,7 @@ async fn main(low_prio_spawner: Spawner) { let peripherals = esp_hal::init(esp_hal::Config::default()); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); static EXECUTOR: StaticCell> = StaticCell::new(); let executor = InterruptExecutor::new(peripherals.FROM_CPU_INTR2); diff --git a/examples/async/embassy_rmt_rx/src/main.rs b/examples/async/embassy_rmt_rx/src/main.rs index d618a2edcb5..1fc9eba774c 100644 --- a/examples/async/embassy_rmt_rx/src/main.rs +++ b/examples/async/embassy_rmt_rx/src/main.rs @@ -45,7 +45,7 @@ async fn main(spawner: Spawner) { let peripherals = esp_hal::init(esp_hal::Config::default()); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let freq = cfg_select! { feature = "esp32h2" => Rate::from_mhz(32), diff --git a/examples/async/embassy_rmt_tx/src/main.rs b/examples/async/embassy_rmt_tx/src/main.rs index d637005b663..e2ff2db73fa 100644 --- a/examples/async/embassy_rmt_tx/src/main.rs +++ b/examples/async/embassy_rmt_tx/src/main.rs @@ -31,7 +31,7 @@ async fn main(_spawner: Spawner) { let peripherals = esp_hal::init(esp_hal::Config::default()); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let freq = cfg_select! { feature = "esp32h2" => Rate::from_mhz(32), diff --git a/examples/async/embassy_serial/Cargo.toml b/examples/async/embassy_serial/Cargo.toml index 52c015828d9..3e8676b00d5 100644 --- a/examples/async/embassy_serial/Cargo.toml +++ b/examples/async/embassy_serial/Cargo.toml @@ -61,6 +61,12 @@ esp32h2 = [ "esp-rtos/esp32h2", "esp-hal/esp32h2", ] +esp32h4 = [ + "esp-backtrace/esp32h4", + "esp-bootloader-esp-idf/esp32h4", + "esp-rtos/esp32h4", + "esp-hal/esp32h4", +] esp32s2 = [ "esp-backtrace/esp32s2", "esp-bootloader-esp-idf/esp32s2", diff --git a/examples/async/embassy_serial/src/main.rs b/examples/async/embassy_serial/src/main.rs index 6dd75f97839..95d698d605c 100644 --- a/examples/async/embassy_serial/src/main.rs +++ b/examples/async/embassy_serial/src/main.rs @@ -71,7 +71,7 @@ async fn main(spawner: Spawner) { let peripherals = esp_hal::init(esp_hal::Config::default()); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); // Default pins for Uart communication let (tx_pin, rx_pin) = cfg_select! { @@ -82,11 +82,10 @@ async fn main(spawner: Spawner) { feature = "esp32c6" => (peripherals.GPIO16, peripherals.GPIO17), feature = "esp32c61" => (peripherals.GPIO11, peripherals.GPIO10), feature = "esp32h2" => (peripherals.GPIO24, peripherals.GPIO23), + feature = "esp32h4" => (peripherals.GPIO24, peripherals.GPIO23), feature = "esp32p4" => (peripherals.GPIO6, peripherals.GPIO5), feature = "esp32s31" => (peripherals.GPIO3, peripherals.GPIO2), - any(feature = "esp32s2", feature = "esp32s3") => { - (peripherals.GPIO43, peripherals.GPIO44) - } + any(feature = "esp32s2", feature = "esp32s3") => (peripherals.GPIO43, peripherals.GPIO44), }; let config = Config::default() diff --git a/examples/async/embassy_spi/Cargo.toml b/examples/async/embassy_spi/Cargo.toml index 6af95d23c40..484920735ff 100644 --- a/examples/async/embassy_spi/Cargo.toml +++ b/examples/async/embassy_spi/Cargo.toml @@ -60,6 +60,12 @@ esp32h2 = [ "esp-rtos/esp32h2", "esp-hal/esp32h2", ] +esp32h4 = [ + "esp-backtrace/esp32h4", + "esp-bootloader-esp-idf/esp32h4", + "esp-rtos/esp32h4", + "esp-hal/esp32h4", +] esp32s2 = [ "esp-backtrace/esp32s2", "esp-bootloader-esp-idf/esp32s2", diff --git a/examples/async/embassy_spi/src/main.rs b/examples/async/embassy_spi/src/main.rs index 7b489dbba7e..2f61b520225 100644 --- a/examples/async/embassy_spi/src/main.rs +++ b/examples/async/embassy_spi/src/main.rs @@ -41,7 +41,7 @@ async fn main(_spawner: Spawner) { let peripherals = esp_hal::init(esp_hal::Config::default()); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let sclk = peripherals.GPIO0; let miso = peripherals.GPIO2; diff --git a/examples/async/embassy_twai/src/main.rs b/examples/async/embassy_twai/src/main.rs index c345874ebef..76bc35524d2 100644 --- a/examples/async/embassy_twai/src/main.rs +++ b/examples/async/embassy_twai/src/main.rs @@ -52,7 +52,7 @@ async fn main(_spawner: Spawner) { let peripherals = esp_hal::init(esp_hal::Config::default()); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); // Without an external transceiver, we only need a single line between the two // MCUs. diff --git a/examples/async/embassy_usb_ethernet/src/main.rs b/examples/async/embassy_usb_ethernet/src/main.rs index b6c3d376e2e..d44769f68ae 100644 --- a/examples/async/embassy_usb_ethernet/src/main.rs +++ b/examples/async/embassy_usb_ethernet/src/main.rs @@ -64,7 +64,7 @@ async fn main(spawner: Spawner) -> ! { let peripherals = esp_hal::init(esp_hal::Config::default()); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let (dp, dm) = cfg_select! { feature = "esp32p4" => (peripherals.GPIO27, peripherals.GPIO26), diff --git a/examples/async/embassy_usb_hid_host/src/main.rs b/examples/async/embassy_usb_hid_host/src/main.rs index 1071f33ba5c..47af501cc7e 100644 --- a/examples/async/embassy_usb_hid_host/src/main.rs +++ b/examples/async/embassy_usb_hid_host/src/main.rs @@ -33,7 +33,7 @@ async fn main(_spawner: Spawner) { let peripherals = esp_hal::init(esp_hal::Config::default()); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let (dp, dm) = cfg_select! { feature = "esp32p4" => (peripherals.GPIO27, peripherals.GPIO26), diff --git a/examples/async/embassy_usb_hid_host_hs/src/main.rs b/examples/async/embassy_usb_hid_host_hs/src/main.rs index 04bc586c4e7..e4f362091ae 100644 --- a/examples/async/embassy_usb_hid_host_hs/src/main.rs +++ b/examples/async/embassy_usb_hid_host_hs/src/main.rs @@ -32,7 +32,7 @@ async fn main(_spawner: Spawner) { let peripherals = esp_hal::init(esp_hal::Config::default()); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let usb = Usb::new_hs(peripherals.USB_HS); static BUS_STATE: BusState = BusState::new(); diff --git a/examples/async/embassy_usb_serial/src/main.rs b/examples/async/embassy_usb_serial/src/main.rs index 2d5aa1d08ec..6c8768db803 100644 --- a/examples/async/embassy_usb_serial/src/main.rs +++ b/examples/async/embassy_usb_serial/src/main.rs @@ -41,7 +41,7 @@ async fn main(_spawner: Spawner) { let peripherals = esp_hal::init(esp_hal::Config::default()); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); #[cfg(not(feature = "esp32p4"))] let usb = Usb::new_fs(peripherals.USB_FS, peripherals.GPIO20, peripherals.GPIO19); diff --git a/examples/async/embassy_usb_serial_hs/src/main.rs b/examples/async/embassy_usb_serial_hs/src/main.rs index 4bd8349d58d..bc4f884fdf4 100644 --- a/examples/async/embassy_usb_serial_hs/src/main.rs +++ b/examples/async/embassy_usb_serial_hs/src/main.rs @@ -36,7 +36,7 @@ async fn main(_spawner: Spawner) { let peripherals = esp_hal::init(esp_hal::Config::default()); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let usb = Usb::new_hs(peripherals.USB_HS); diff --git a/examples/async/embassy_usb_serial_jtag/Cargo.toml b/examples/async/embassy_usb_serial_jtag/Cargo.toml index af7c02c634b..59ea210e914 100644 --- a/examples/async/embassy_usb_serial_jtag/Cargo.toml +++ b/examples/async/embassy_usb_serial_jtag/Cargo.toml @@ -50,6 +50,12 @@ esp32h2 = [ "esp-rtos/esp32h2", "esp-hal/esp32h2", ] +esp32h4 = [ + "esp-backtrace/esp32h4", + "esp-bootloader-esp-idf/esp32h4", + "esp-rtos/esp32h4", + "esp-hal/esp32h4", +] esp32p4 = [ "esp-backtrace/esp32p4", "esp-bootloader-esp-idf/esp32p4", diff --git a/examples/async/embassy_usb_serial_jtag/src/main.rs b/examples/async/embassy_usb_serial_jtag/src/main.rs index 02095a6caf8..36107fc87e5 100644 --- a/examples/async/embassy_usb_serial_jtag/src/main.rs +++ b/examples/async/embassy_usb_serial_jtag/src/main.rs @@ -69,7 +69,7 @@ async fn main(spawner: Spawner) { let peripherals = esp_hal::init(esp_hal::Config::default()); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let (rx, tx) = UsbSerialJtag::new(peripherals.USB_DEVICE) .into_async() diff --git a/examples/ble/bas_peripheral/Cargo.toml b/examples/ble/bas_peripheral/Cargo.toml index 040716fa7bc..9361415f1a0 100644 --- a/examples/ble/bas_peripheral/Cargo.toml +++ b/examples/ble/bas_peripheral/Cargo.toml @@ -24,7 +24,7 @@ esp-radio = { path = "../../../esp-radio", features = [ "unstable", ] } log = "0.4.27" -trouble-host = { version = "0.7.0", features = [ +trouble-host = { version = "0.8.0", features = [ "default-packet-pool-mtu-255", "derive", "scan", @@ -32,7 +32,10 @@ trouble-host = { version = "0.7.0", features = [ static_cell = "2.1.1" [features] +light_sleep = [] + esp32 = [ + "light_sleep", "esp-alloc/esp32", "esp-backtrace/esp32", "esp-bootloader-esp-idf/esp32", @@ -41,6 +44,7 @@ esp32 = [ "esp-radio/esp32", ] esp32c2 = [ + "light_sleep", "esp-alloc/esp32c2", "esp-backtrace/esp32c2", "esp-bootloader-esp-idf/esp32c2", @@ -49,6 +53,7 @@ esp32c2 = [ "esp-radio/esp32c2", ] esp32c3 = [ + "light_sleep", "esp-alloc/esp32c3", "esp-backtrace/esp32c3", "esp-bootloader-esp-idf/esp32c3", @@ -57,6 +62,7 @@ esp32c3 = [ "esp-radio/esp32c3", ] esp32c5 = [ + "light_sleep", "esp-alloc/esp32c5", "esp-backtrace/esp32c5", "esp-bootloader-esp-idf/esp32c5", @@ -65,6 +71,7 @@ esp32c5 = [ "esp-radio/esp32c5", ] esp32c6 = [ + "light_sleep", "esp-alloc/esp32c6", "esp-backtrace/esp32c6", "esp-bootloader-esp-idf/esp32c6", @@ -73,6 +80,7 @@ esp32c6 = [ "esp-radio/esp32c6", ] esp32c61 = [ + "light_sleep", "esp-alloc/esp32c61", "esp-backtrace/esp32c61", "esp-bootloader-esp-idf/esp32c61", @@ -80,7 +88,17 @@ esp32c61 = [ "esp-rtos/esp32c61", "esp-radio/esp32c61", ] +esp32s31 = [ + "light_sleep", + "esp-alloc/esp32s31", + "esp-backtrace/esp32s31", + "esp-bootloader-esp-idf/esp32s31", + "esp-hal/esp32s31", + "esp-rtos/esp32s31", + "esp-radio/esp32s31", +] esp32h2 = [ + "light_sleep", "esp-alloc/esp32h2", "esp-backtrace/esp32h2", "esp-bootloader-esp-idf/esp32h2", @@ -88,7 +106,17 @@ esp32h2 = [ "esp-rtos/esp32h2", "esp-radio/esp32h2", ] +esp32h4 = [ + "light_sleep", + "esp-alloc/esp32h4", + "esp-backtrace/esp32h4", + "esp-bootloader-esp-idf/esp32h4", + "esp-hal/esp32h4", + "esp-rtos/esp32h4", + "esp-radio/esp32h4", +] esp32s3 = [ + "light_sleep", "esp-alloc/esp32s3", "esp-backtrace/esp32s3", "esp-bootloader-esp-idf/esp32s3", diff --git a/examples/ble/bas_peripheral/src/main.rs b/examples/ble/bas_peripheral/src/main.rs index cbeb3fdb154..5ae4a4cd951 100644 --- a/examples/ble/bas_peripheral/src/main.rs +++ b/examples/ble/bas_peripheral/src/main.rs @@ -1,4 +1,23 @@ //! A bluetooth battery service example built using Embassy and trouBLE. +//! +//! The example demonstrates how to use the trouBLE library to create a BLE +//! peripheral that implements the Battery Service (BAS) GATT service. +//! It advertises itself and allows a central device to connect and read +//! the battery level characteristic, as well as receive notifications when +//! the battery level changes. +//! +//! The example also shows how to save power. Change these constants to compare: +//! +//! - `MODEM_SLEEP` lets the controller turn the radio off between its events. +//! - `LIGHT_SLEEP` lets the chip enter automatic light sleep when all tasks are idle. The chip +//! sleeps only while the controller sleeps. The ESP32 can sleep only with a 32 kHz crystal as the +//! BLE low-power clock. +//! - `CPU_POWERDOWN` lets light sleep power the CPU down, and retains its state in RAM. This saves +//! more current, but it makes the sleep and the wake slower. Only the ESP32-C3, -C5, -C6, -C61, +//! -H2, -S3 and -S31 support this. On other chips the constant has no effect. +//! +//! The USB Serial/JTAG console stops while the chip is in light sleep. Use the UART port to see +//! the output. //% CHIP_FILTER: bt_driver_supported @@ -10,23 +29,108 @@ use embassy_futures::{join::join, select::select}; use embassy_time::Timer; use esp_alloc as _; use esp_backtrace as _; -use esp_hal::{clock::CpuClock, timer::timg::TimerGroup}; +use esp_hal::{ + clock::{ClockConfig, CpuClock}, + timer::timg::TimerGroup, +}; use esp_radio::ble::controller::BleConnector; use log::{info, warn}; use trouble_host::prelude::*; esp_bootloader_esp_idf::esp_app_desc!(); +/// Whether the controller turns the radio off between its events. +const MODEM_SLEEP: bool = true; +/// Whether the chip enters automatic light sleep when all tasks are idle. Requires +/// [`MODEM_SLEEP`] to be enabled. +#[cfg(feature = "light_sleep")] +const LIGHT_SLEEP: bool = true; +/// Whether light sleep powers the CPU down. Requires [`LIGHT_SLEEP`] to be enabled. +#[cfg(feature = "light_sleep")] +const CPU_POWERDOWN: bool = true; + +// An example reads no chip capability, so this condition lists the chips that support CPU +// power-down. +#[cfg(feature = "light_sleep")] +cfg_select! { + any( + feature = "esp32c3", + feature = "esp32c5", + feature = "esp32c6", + feature = "esp32c61", + feature = "esp32h2", + feature = "esp32s3", + feature = "esp32s31", + ) => { + fn enable_cpu_powerdown(sleep: &mut esp_rtos::sleep::Sleep) { + use esp_hal::rtc_cntl::CpuRetentionStorage; + + // The memory that the bootloader used is otherwise unused after boot. + #[esp_hal::ram(reclaimed, unstable(zeroed))] + static CPU_RETENTION_MEMORY: CpuRetentionStorage = CpuRetentionStorage::new(); + + sleep + .enable_cpu_powerdown(CPU_RETENTION_MEMORY.take()) + .unwrap(); + + // Keeping the cache tags makes the wake faster, because the cache stays warm. + #[cfg(feature = "esp32s3")] + { + use esp_hal::rtc_cntl::CacheTagRetentionStorage; + + #[esp_hal::ram(reclaimed, unstable(zeroed))] + static CACHE_TAGMEM: CacheTagRetentionStorage = CacheTagRetentionStorage::new(); + + sleep.keep_cache_tags(CACHE_TAGMEM.take()).unwrap(); + } + } + } + _ => { + fn enable_cpu_powerdown(_sleep: &mut esp_rtos::sleep::Sleep) {} + } +} + #[esp_hal::main] async fn main(_s: Spawner) { esp_println::logger::init_logger_from_env(); - let peripherals = esp_hal::init(esp_hal::Config::default().with_cpu_clock(CpuClock::max())); + + let peripherals = esp_hal::init(esp_hal::Config::default().with_cpu_clock({ + #[cfg_attr(feature = "esp32c2", allow(unused_mut))] + let mut config = ClockConfig::from(CpuClock::max()); + + #[cfg(not(feature = "esp32c2"))] + { + use esp_hal::clock::ll::BleLpClkConfig; + + // `Xtal` is the default, and a safe choice even in light sleep, although keeping the + // main crystal running raises the sleep current compared to an RC oscillator. + config.ble_lp_clk = Some(BleLpClkConfig::Xtal); + } + + config + })); + esp_alloc::heap_allocator!(size: 72 * 1024); + let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + #[cfg(feature = "light_sleep")] + if LIGHT_SLEEP { + let mut sleep = esp_rtos::sleep::configure(peripherals.LPWR); + if CPU_POWERDOWN { + enable_cpu_powerdown(&mut sleep); + } + esp_rtos::start_with_idle_hook(timg0.timer0, sleep.light_sleep_hook); + } else { + esp_rtos::start(timg0.timer0); + } + #[cfg(not(feature = "light_sleep"))] + esp_rtos::start(timg0.timer0); - let bluetooth = peripherals.BT; - let connector = BleConnector::new(bluetooth, Default::default()).unwrap(); + let connector = BleConnector::new( + peripherals.BT, + esp_radio::ble::Config::default().with_modem_sleep(MODEM_SLEEP), + ) + .unwrap(); let controller: ExternalController<_, 1> = ExternalController::new(connector); ble_bas_peripheral_run(controller).await; @@ -65,7 +169,7 @@ where let address: Address = Address::random([0xff, 0x8f, 0x1a, 0x05, 0xe4, 0xff]); info!("Our address = {:?}", address); - let mut resources: HostResources<_, DefaultPacketPool, CONNECTIONS_MAX, L2CAP_CHANNELS_MAX> = + let mut resources: HostResources = HostResources::new(); let stack = trouble_host::new(controller, &mut resources) .set_random_address(address) diff --git a/examples/ble/scanner/Cargo.toml b/examples/ble/scanner/Cargo.toml index 94e36a619d0..ddad4dabc3e 100644 --- a/examples/ble/scanner/Cargo.toml +++ b/examples/ble/scanner/Cargo.toml @@ -5,7 +5,7 @@ edition = "2024" publish = false [dependencies] -bt-hci = "0.9.0" +bt-hci = "0.10.1" embassy-executor = "0.10.0" embassy-futures = "0.1" embassy-time = "0.5.0" @@ -25,7 +25,7 @@ esp-radio = { path = "../../../esp-radio", features = [ ] } heapless = "0.9.1" log = "0.4.27" -trouble-host = { version = "0.7.0", features = [ +trouble-host = { version = "0.8.0", features = [ "default-packet-pool-mtu-255", "derive", "scan", @@ -80,6 +80,14 @@ esp32c61 = [ "esp-rtos/esp32c61", "esp-radio/esp32c61", ] +esp32s31 = [ + "esp-alloc/esp32s31", + "esp-backtrace/esp32s31", + "esp-bootloader-esp-idf/esp32s31", + "esp-hal/esp32s31", + "esp-rtos/esp32s31", + "esp-radio/esp32s31", +] esp32h2 = [ "esp-alloc/esp32h2", "esp-backtrace/esp32h2", @@ -88,6 +96,14 @@ esp32h2 = [ "esp-rtos/esp32h2", "esp-radio/esp32h2", ] +esp32h4 = [ + "esp-alloc/esp32h4", + "esp-backtrace/esp32h4", + "esp-bootloader-esp-idf/esp32h4", + "esp-hal/esp32h4", + "esp-rtos/esp32h4", + "esp-radio/esp32h4", +] esp32s3 = [ "esp-alloc/esp32s3", "esp-backtrace/esp32s3", diff --git a/examples/ble/scanner/src/main.rs b/examples/ble/scanner/src/main.rs index 4eb2b3f7232..82564af55f4 100644 --- a/examples/ble/scanner/src/main.rs +++ b/examples/ble/scanner/src/main.rs @@ -29,7 +29,7 @@ async fn main(_s: Spawner) { esp_alloc::heap_allocator!(size: 72 * 1024); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let bluetooth = peripherals.BT; let connector = BleConnector::new(bluetooth, Default::default()).unwrap(); @@ -52,18 +52,18 @@ where info!("Our address = {:?}", address); - let mut resources: HostResources<_, DefaultPacketPool, CONNECTIONS_MAX, L2CAP_CHANNELS_MAX> = + let mut resources: HostResources = HostResources::new(); let stack = trouble_host::new(controller, &mut resources) .set_random_address(address) .build(); let mut runner = stack.runner(); - let central = stack.central(); + let mut central = stack.central(); let printer = Printer { seen: RefCell::new(Deque::new()), }; - let mut scanner = Scanner::new(central); + let mut scanner = Scanner::new(&mut central); let _ = join(runner.run_with_handler(&printer), async { let mut config = ScanConfig::default(); config.active = true; diff --git a/examples/esp-now/embassy_esp_now/Cargo.toml b/examples/esp-now/embassy_esp_now/Cargo.toml index 41616a56ef5..83f5e2fdf15 100644 --- a/examples/esp-now/embassy_esp_now/Cargo.toml +++ b/examples/esp-now/embassy_esp_now/Cargo.toml @@ -15,6 +15,7 @@ esp-backtrace = { path = "../../../esp-backtrace", features = [ ] } esp-bootloader-esp-idf = { path = "../../../esp-bootloader-esp-idf" } esp-hal = { path = "../../../esp-hal", features = ["log-04", "unstable"] } +esp-metadata-generated = { path = "../../../esp-metadata-generated" } esp-println = { path = "../../../esp-println", features = ["log-04"] } esp-rtos = { path = "../../../esp-rtos", features = ["esp-radio", "embassy", "log-04"] } esp-radio = { path = "../../../esp-radio", features = [ @@ -30,6 +31,7 @@ esp32 = [ "esp-backtrace/esp32", "esp-bootloader-esp-idf/esp32", "esp-hal/esp32", + "esp-metadata-generated/esp32", "esp-rtos/esp32", "esp-radio/esp32", ] @@ -38,6 +40,7 @@ esp32c2 = [ "esp-backtrace/esp32c2", "esp-bootloader-esp-idf/esp32c2", "esp-hal/esp32c2", + "esp-metadata-generated/esp32c2", "esp-rtos/esp32c2", "esp-radio/esp32c2", ] @@ -46,6 +49,7 @@ esp32c3 = [ "esp-backtrace/esp32c3", "esp-bootloader-esp-idf/esp32c3", "esp-hal/esp32c3", + "esp-metadata-generated/esp32c3", "esp-rtos/esp32c3", "esp-radio/esp32c3", ] @@ -54,6 +58,7 @@ esp32c5 = [ "esp-backtrace/esp32c5", "esp-bootloader-esp-idf/esp32c5", "esp-hal/esp32c5", + "esp-metadata-generated/esp32c5", "esp-rtos/esp32c5", "esp-radio/esp32c5", ] @@ -62,6 +67,7 @@ esp32c6 = [ "esp-backtrace/esp32c6", "esp-bootloader-esp-idf/esp32c6", "esp-hal/esp32c6", + "esp-metadata-generated/esp32c6", "esp-rtos/esp32c6", "esp-radio/esp32c6", ] @@ -70,14 +76,25 @@ esp32c61 = [ "esp-backtrace/esp32c61", "esp-bootloader-esp-idf/esp32c61", "esp-hal/esp32c61", + "esp-metadata-generated/esp32c61", "esp-rtos/esp32c61", "esp-radio/esp32c61", ] +esp32s31 = [ + "esp-alloc/esp32s31", + "esp-backtrace/esp32s31", + "esp-bootloader-esp-idf/esp32s31", + "esp-hal/esp32s31", + "esp-metadata-generated/esp32s31", + "esp-rtos/esp32s31", + "esp-radio/esp32s31", +] esp32s2 = [ "esp-alloc/esp32s2", "esp-backtrace/esp32s2", "esp-bootloader-esp-idf/esp32s2", "esp-hal/esp32s2", + "esp-metadata-generated/esp32s2", "esp-rtos/esp32s2", "esp-radio/esp32s2", ] @@ -86,6 +103,7 @@ esp32s3 = [ "esp-backtrace/esp32s3", "esp-bootloader-esp-idf/esp32s3", "esp-hal/esp32s3", + "esp-metadata-generated/esp32s3", "esp-rtos/esp32s3", "esp-radio/esp32s3", ] diff --git a/examples/esp-now/embassy_esp_now/src/main.rs b/examples/esp-now/embassy_esp_now/src/main.rs index e1544c9e18c..bfbc53791ce 100644 --- a/examples/esp-now/embassy_esp_now/src/main.rs +++ b/examples/esp-now/embassy_esp_now/src/main.rs @@ -12,22 +12,29 @@ use embassy_futures::select::{Either, select}; use embassy_time::{Duration, Ticker}; use esp_alloc as _; use esp_backtrace as _; -use esp_hal::{clock::CpuClock, timer::timg::TimerGroup}; +use esp_hal::{clock::CpuClock, ram, timer::timg::TimerGroup}; use esp_println::println; use esp_radio::esp_now::{BROADCAST_ADDRESS, PeerInfo}; esp_bootloader_esp_idf::esp_app_desc!(); +// Full `.dram2_uninit` region for this chip. +const DRAM2_UNINIT_SIZE: usize = { + let range: core::ops::Range = esp_metadata_generated::memory_range!("DRAM2_UNINIT"); + range.end - range.start +}; + #[esp_hal::main] async fn main(_spawner: Spawner) -> ! { esp_println::logger::init_logger_from_env(); let config = esp_hal::Config::default().with_cpu_clock(CpuClock::max()); let peripherals = esp_hal::init(config); - esp_alloc::heap_allocator!(size: 72 * 1024); + esp_alloc::heap_allocator!(#[ram(reclaimed)] size: DRAM2_UNINIT_SIZE); + esp_alloc::heap_allocator!(size: 36 * 1024); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let wifi = peripherals.WIFI; let controller = esp_radio::wifi::WifiController::new(wifi, Default::default()).unwrap(); diff --git a/examples/esp-now/embassy_esp_now_duplex/Cargo.toml b/examples/esp-now/embassy_esp_now_duplex/Cargo.toml index 7904e19739a..a4ec7a50c8d 100644 --- a/examples/esp-now/embassy_esp_now_duplex/Cargo.toml +++ b/examples/esp-now/embassy_esp_now_duplex/Cargo.toml @@ -15,6 +15,7 @@ esp-backtrace = { path = "../../../esp-backtrace", features = [ ] } esp-bootloader-esp-idf = { path = "../../../esp-bootloader-esp-idf" } esp-hal = { path = "../../../esp-hal", features = ["log-04", "unstable"] } +esp-metadata-generated = { path = "../../../esp-metadata-generated" } esp-println = { path = "../../../esp-println", features = ["log-04"] } esp-rtos = { path = "../../../esp-rtos", features = ["esp-radio", "embassy", "log-04"] } esp-radio = { path = "../../../esp-radio", features = [ @@ -31,6 +32,7 @@ esp32 = [ "esp-backtrace/esp32", "esp-bootloader-esp-idf/esp32", "esp-hal/esp32", + "esp-metadata-generated/esp32", "esp-rtos/esp32", "esp-radio/esp32", ] @@ -39,6 +41,7 @@ esp32c2 = [ "esp-backtrace/esp32c2", "esp-bootloader-esp-idf/esp32c2", "esp-hal/esp32c2", + "esp-metadata-generated/esp32c2", "esp-rtos/esp32c2", "esp-radio/esp32c2", ] @@ -47,6 +50,7 @@ esp32c3 = [ "esp-backtrace/esp32c3", "esp-bootloader-esp-idf/esp32c3", "esp-hal/esp32c3", + "esp-metadata-generated/esp32c3", "esp-rtos/esp32c3", "esp-radio/esp32c3", ] @@ -55,6 +59,7 @@ esp32c5 = [ "esp-backtrace/esp32c5", "esp-bootloader-esp-idf/esp32c5", "esp-hal/esp32c5", + "esp-metadata-generated/esp32c5", "esp-rtos/esp32c5", "esp-radio/esp32c5", ] @@ -63,6 +68,7 @@ esp32c6 = [ "esp-backtrace/esp32c6", "esp-bootloader-esp-idf/esp32c6", "esp-hal/esp32c6", + "esp-metadata-generated/esp32c6", "esp-rtos/esp32c6", "esp-radio/esp32c6", ] @@ -71,14 +77,25 @@ esp32c61 = [ "esp-backtrace/esp32c61", "esp-bootloader-esp-idf/esp32c61", "esp-hal/esp32c61", + "esp-metadata-generated/esp32c61", "esp-rtos/esp32c61", "esp-radio/esp32c61", ] +esp32s31 = [ + "esp-alloc/esp32s31", + "esp-backtrace/esp32s31", + "esp-bootloader-esp-idf/esp32s31", + "esp-hal/esp32s31", + "esp-metadata-generated/esp32s31", + "esp-rtos/esp32s31", + "esp-radio/esp32s31", +] esp32s2 = [ "esp-alloc/esp32s2", "esp-backtrace/esp32s2", "esp-bootloader-esp-idf/esp32s2", "esp-hal/esp32s2", + "esp-metadata-generated/esp32s2", "esp-rtos/esp32s2", "esp-radio/esp32s2", ] @@ -87,6 +104,7 @@ esp32s3 = [ "esp-backtrace/esp32s3", "esp-bootloader-esp-idf/esp32s3", "esp-hal/esp32s3", + "esp-metadata-generated/esp32s3", "esp-rtos/esp32s3", "esp-radio/esp32s3", ] diff --git a/examples/esp-now/embassy_esp_now_duplex/src/main.rs b/examples/esp-now/embassy_esp_now_duplex/src/main.rs index 44041ed6f14..99f0dd55fb6 100644 --- a/examples/esp-now/embassy_esp_now_duplex/src/main.rs +++ b/examples/esp-now/embassy_esp_now_duplex/src/main.rs @@ -13,7 +13,7 @@ use embassy_sync::{blocking_mutex::raw::NoopRawMutex, mutex::Mutex}; use embassy_time::{Duration, Ticker}; use esp_alloc as _; use esp_backtrace as _; -use esp_hal::{clock::CpuClock, timer::timg::TimerGroup}; +use esp_hal::{clock::CpuClock, ram, timer::timg::TimerGroup}; use esp_println::println; use esp_radio::esp_now::{ BROADCAST_ADDRESS, @@ -25,6 +25,12 @@ use esp_radio::esp_now::{ esp_bootloader_esp_idf::esp_app_desc!(); +// Full `.dram2_uninit` region for this chip. +const DRAM2_UNINIT_SIZE: usize = { + let range: core::ops::Range = esp_metadata_generated::memory_range!("DRAM2_UNINIT"); + range.end - range.start +}; + // When you are okay with using a nightly compiler it's better to use https://docs.rs/static_cell/2.1.0/static_cell/macro.make_static.html macro_rules! mk_static { ($t:ty,$val:expr) => {{ @@ -41,26 +47,26 @@ async fn main(spawner: Spawner) -> ! { let config = esp_hal::Config::default().with_cpu_clock(CpuClock::max()); let peripherals = esp_hal::init(config); - esp_alloc::heap_allocator!(size: 72 * 1024); + esp_alloc::heap_allocator!(#[ram(reclaimed)] size: DRAM2_UNINIT_SIZE); + esp_alloc::heap_allocator!(size: 36 * 1024); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let wifi = peripherals.WIFI; - let controller = mk_static!( - esp_radio::wifi::WifiController<'static>, - esp_radio::wifi::WifiController::new(wifi, Default::default()).unwrap() - ); + let controller = esp_radio::wifi::WifiController::new(wifi, Default::default()).unwrap(); let esp_now = controller.esp_now(); + // For demonstration purposes - you _may_ drop the controller, you don't _have to_. + drop(controller); esp_now.set_channel(11).unwrap(); println!("esp-now version {}", esp_now.version().unwrap()); let (manager, sender, receiver) = esp_now.split(); - let manager = mk_static!(EspNowManager<'static>, manager); + let manager = mk_static!(EspNowManager, manager); let sender = mk_static!( - Mutex::>, + Mutex::, Mutex::::new(sender) ); @@ -89,7 +95,7 @@ async fn main(spawner: Spawner) -> ! { } #[embassy_executor::task] -async fn broadcaster(sender: &'static Mutex>) { +async fn broadcaster(sender: &'static Mutex) { let mut ticker = Ticker::every(Duration::from_secs(1)); loop { ticker.next().await; @@ -102,7 +108,7 @@ async fn broadcaster(sender: &'static Mutex> } #[embassy_executor::task] -async fn listener(manager: &'static EspNowManager<'static>, mut receiver: EspNowReceiver<'static>) { +async fn listener(manager: &'static EspNowManager, mut receiver: EspNowReceiver) { loop { let r = receiver.receive_async().await; println!("Received {:?}", r.data()); diff --git a/examples/hello_world/Cargo.toml b/examples/hello_world/Cargo.toml index d8a22866d46..ee0d085d11d 100644 --- a/examples/hello_world/Cargo.toml +++ b/examples/hello_world/Cargo.toml @@ -49,6 +49,11 @@ esp32h2 = [ "esp-bootloader-esp-idf/esp32h2", "esp-hal/esp32h2", ] +esp32h4 = [ + "esp-backtrace/esp32h4", + "esp-bootloader-esp-idf/esp32h4", + "esp-hal/esp32h4", +] esp32p4 = [ "esp-backtrace/esp32p4", "esp-bootloader-esp-idf/esp32p4", diff --git a/examples/ieee802154/ieee802154_receive_all_frames/Cargo.toml b/examples/ieee802154/ieee802154_receive_all_frames/Cargo.toml index f834c4ce2b8..7c71e54f551 100644 --- a/examples/ieee802154/ieee802154_receive_all_frames/Cargo.toml +++ b/examples/ieee802154/ieee802154_receive_all_frames/Cargo.toml @@ -40,6 +40,20 @@ esp32h2 = [ "esp-hal/esp32h2", "esp-radio/esp32h2", ] +esp32h4 = [ + "esp-alloc/esp32h4", + "esp-backtrace/esp32h4", + "esp-bootloader-esp-idf/esp32h4", + "esp-hal/esp32h4", + "esp-radio/esp32h4", +] +esp32s31 = [ + "esp-alloc/esp32s31", + "esp-backtrace/esp32s31", + "esp-bootloader-esp-idf/esp32s31", + "esp-hal/esp32s31", + "esp-radio/esp32s31", +] [profile.release] debug = true diff --git a/examples/ieee802154/ieee802154_receive_frame/Cargo.toml b/examples/ieee802154/ieee802154_receive_frame/Cargo.toml index 3d6a239ff51..c9062f1c22c 100644 --- a/examples/ieee802154/ieee802154_receive_frame/Cargo.toml +++ b/examples/ieee802154/ieee802154_receive_frame/Cargo.toml @@ -40,6 +40,20 @@ esp32h2 = [ "esp-hal/esp32h2", "esp-radio/esp32h2", ] +esp32h4 = [ + "esp-alloc/esp32h4", + "esp-backtrace/esp32h4", + "esp-bootloader-esp-idf/esp32h4", + "esp-hal/esp32h4", + "esp-radio/esp32h4", +] +esp32s31 = [ + "esp-alloc/esp32s31", + "esp-backtrace/esp32s31", + "esp-bootloader-esp-idf/esp32s31", + "esp-hal/esp32s31", + "esp-radio/esp32s31", +] [profile.release] debug = true diff --git a/examples/ieee802154/ieee802154_send_broadcast_frame/Cargo.toml b/examples/ieee802154/ieee802154_send_broadcast_frame/Cargo.toml index d43a795c8ba..09b5361a560 100644 --- a/examples/ieee802154/ieee802154_send_broadcast_frame/Cargo.toml +++ b/examples/ieee802154/ieee802154_send_broadcast_frame/Cargo.toml @@ -41,6 +41,20 @@ esp32h2 = [ "esp-hal/esp32h2", "esp-radio/esp32h2", ] +esp32h4 = [ + "esp-alloc/esp32h4", + "esp-backtrace/esp32h4", + "esp-bootloader-esp-idf/esp32h4", + "esp-hal/esp32h4", + "esp-radio/esp32h4", +] +esp32s31 = [ + "esp-alloc/esp32s31", + "esp-backtrace/esp32s31", + "esp-bootloader-esp-idf/esp32s31", + "esp-hal/esp32s31", + "esp-radio/esp32s31", +] [profile.release] debug = true diff --git a/examples/ieee802154/ieee802154_send_frame/Cargo.toml b/examples/ieee802154/ieee802154_send_frame/Cargo.toml index bd889279179..eda1079a9c3 100644 --- a/examples/ieee802154/ieee802154_send_frame/Cargo.toml +++ b/examples/ieee802154/ieee802154_send_frame/Cargo.toml @@ -41,6 +41,20 @@ esp32h2 = [ "esp-hal/esp32h2", "esp-radio/esp32h2", ] +esp32h4 = [ + "esp-alloc/esp32h4", + "esp-backtrace/esp32h4", + "esp-bootloader-esp-idf/esp32h4", + "esp-hal/esp32h4", + "esp-radio/esp32h4", +] +esp32s31 = [ + "esp-alloc/esp32s31", + "esp-backtrace/esp32s31", + "esp-bootloader-esp-idf/esp32s31", + "esp-hal/esp32s31", + "esp-radio/esp32s31", +] [profile.release] debug = true diff --git a/examples/ieee802154/ieee802154_sniffer/Cargo.toml b/examples/ieee802154/ieee802154_sniffer/Cargo.toml index 51e3f51757f..7ce1cdbcc42 100644 --- a/examples/ieee802154/ieee802154_sniffer/Cargo.toml +++ b/examples/ieee802154/ieee802154_sniffer/Cargo.toml @@ -41,6 +41,20 @@ esp32h2 = [ "esp-hal/esp32h2", "esp-radio/esp32h2", ] +esp32h4 = [ + "esp-alloc/esp32h4", + "esp-backtrace/esp32h4", + "esp-bootloader-esp-idf/esp32h4", + "esp-hal/esp32h4", + "esp-radio/esp32h4", +] +esp32s31 = [ + "esp-alloc/esp32s31", + "esp-backtrace/esp32s31", + "esp-bootloader-esp-idf/esp32s31", + "esp-hal/esp32s31", + "esp-radio/esp32s31", +] [profile.release] debug = true diff --git a/examples/ieee802154/ieee802154_sniffer/src/main.rs b/examples/ieee802154/ieee802154_sniffer/src/main.rs index a19347c3bcf..9dfa4f1d42c 100644 --- a/examples/ieee802154/ieee802154_sniffer/src/main.rs +++ b/examples/ieee802154/ieee802154_sniffer/src/main.rs @@ -30,9 +30,11 @@ fn main() -> ! { // Default pins for Uart communication let (tx_pin, rx_pin) = cfg_select! { + feature = "esp32c5" => (peripherals.GPIO11, peripherals.GPIO12), feature = "esp32c6" => (peripherals.GPIO16, peripherals.GPIO17), feature = "esp32h2" => (peripherals.GPIO24, peripherals.GPIO23), - feature = "esp32c5" => (peripherals.GPIO11, peripherals.GPIO12), + feature = "esp32h4" => (peripherals.GPIO24, peripherals.GPIO23), + feature = "esp32s31" => (peripherals.GPIO3, peripherals.GPIO2), }; let mut uart0 = Uart::new(peripherals.UART0, uart::Config::default()) diff --git a/examples/interrupt/gpio/Cargo.toml b/examples/interrupt/gpio/Cargo.toml index b537e67ee57..2b77a98d504 100644 --- a/examples/interrupt/gpio/Cargo.toml +++ b/examples/interrupt/gpio/Cargo.toml @@ -46,6 +46,11 @@ esp32h2 = [ "esp-bootloader-esp-idf/esp32h2", "esp-hal/esp32h2", ] +esp32h4 = [ + "esp-backtrace/esp32h4", + "esp-bootloader-esp-idf/esp32h4", + "esp-hal/esp32h4", +] esp32p4 = [ "esp-backtrace/esp32p4", "esp-bootloader-esp-idf/esp32p4", diff --git a/examples/interrupt/gpio/src/main.rs b/examples/interrupt/gpio/src/main.rs index c934f1dd170..c0e9d43f65a 100644 --- a/examples/interrupt/gpio/src/main.rs +++ b/examples/interrupt/gpio/src/main.rs @@ -9,6 +9,7 @@ //! - ESP32, ESP32-S2, ESP32-S3: GPIO0 //! - ESP32-C5: GPIO28 //! - ESP32-P4: GPIO35 +//! - ESP32-H4: GPIO34 //! - ESP32-S31: GPIO61 //! - Others: GPIO9 @@ -44,14 +45,14 @@ fn main() -> ! { let mut led = Output::new(peripherals.GPIO2, Level::Low, OutputConfig::default()); - let button = - cfg_select! { - any(feature = "esp32", feature = "esp32s2", feature = "esp32s3") => peripherals.GPIO0, - feature = "esp32c5" => peripherals.GPIO28, - feature = "esp32p4" => peripherals.GPIO35, - feature = "esp32s31" => peripherals.GPIO61, - _ => peripherals.GPIO9, - }; + let button = cfg_select! { + any(feature = "esp32", feature = "esp32s2", feature = "esp32s3") => peripherals.GPIO0, + feature = "esp32c5" => peripherals.GPIO28, + feature = "esp32p4" => peripherals.GPIO35, + feature = "esp32h4" => peripherals.GPIO34, + feature = "esp32s31" => peripherals.GPIO61, + _ => peripherals.GPIO9, + }; let config = InputConfig::default().with_pull(Pull::Up); let mut button = Input::new(button, config); diff --git a/examples/interrupt/uart/Cargo.toml b/examples/interrupt/uart/Cargo.toml index f8e2092fb0e..46e6df4b143 100644 --- a/examples/interrupt/uart/Cargo.toml +++ b/examples/interrupt/uart/Cargo.toml @@ -36,6 +36,11 @@ esp32h2 = [ "esp-bootloader-esp-idf/esp32h2", "esp-hal/esp32h2", ] +esp32h4 = [ + "esp-backtrace/esp32h4", + "esp-bootloader-esp-idf/esp32h4", + "esp-hal/esp32h4", +] esp32s2 = [ "esp-backtrace/esp32s2", "esp-bootloader-esp-idf/esp32s2", diff --git a/examples/interrupt/uart/src/main.rs b/examples/interrupt/uart/src/main.rs index 43ada67be32..c3e13a08af1 100644 --- a/examples/interrupt/uart/src/main.rs +++ b/examples/interrupt/uart/src/main.rs @@ -57,11 +57,10 @@ fn main() -> ! { feature = "esp32c6" => (peripherals.GPIO16, peripherals.GPIO17), feature = "esp32c61" => (peripherals.GPIO3, peripherals.GPIO2), feature = "esp32h2" => (peripherals.GPIO24, peripherals.GPIO23), + feature = "esp32h4" => (peripherals.GPIO24, peripherals.GPIO23), feature = "esp32p4" => (peripherals.GPIO6, peripherals.GPIO5), feature = "esp32s31" => (peripherals.GPIO3, peripherals.GPIO2), - any(feature = "esp32s2", feature = "esp32s3") => { - (peripherals.GPIO43, peripherals.GPIO44) - } + any(feature = "esp32s2", feature = "esp32s3") => (peripherals.GPIO43, peripherals.GPIO44), }; let uart_config = UartConfig::default() diff --git a/examples/ota/update/Cargo.toml b/examples/ota/update/Cargo.toml index f1e66eaf72b..a9db2556d27 100644 --- a/examples/ota/update/Cargo.toml +++ b/examples/ota/update/Cargo.toml @@ -12,74 +12,67 @@ esp-backtrace = { path = "../../../esp-backtrace", features = [ esp-bootloader-esp-idf = { path = "../../../esp-bootloader-esp-idf" } esp-hal = { path = "../../../esp-hal", features = ["log-04", "unstable"] } esp-println = { path = "../../../esp-println", features = ["log-04"] } -esp-storage = { path = "../../../esp-storage" } [features] esp32 = [ "esp-backtrace/esp32", "esp-bootloader-esp-idf/esp32", "esp-hal/esp32", - "esp-storage/esp32", ] esp32c2 = [ "esp-backtrace/esp32c2", "esp-bootloader-esp-idf/esp32c2", "esp-hal/esp32c2", - "esp-storage/esp32c2", ] esp32c3 = [ "esp-backtrace/esp32c3", "esp-bootloader-esp-idf/esp32c3", "esp-hal/esp32c3", - "esp-storage/esp32c3", ] esp32c5 = [ "esp-backtrace/esp32c5", "esp-bootloader-esp-idf/esp32c5", "esp-hal/esp32c5", - "esp-storage/esp32c5", ] esp32c6 = [ "esp-backtrace/esp32c6", "esp-bootloader-esp-idf/esp32c6", "esp-hal/esp32c6", - "esp-storage/esp32c6", ] esp32c61 = [ "esp-backtrace/esp32c61", "esp-bootloader-esp-idf/esp32c61", "esp-hal/esp32c61", - "esp-storage/esp32c61", ] esp32h2 = [ "esp-backtrace/esp32h2", "esp-bootloader-esp-idf/esp32h2", "esp-hal/esp32h2", - "esp-storage/esp32h2", +] +esp32h4 = [ + "esp-backtrace/esp32h4", + "esp-bootloader-esp-idf/esp32h4", + "esp-hal/esp32h4", ] esp32p4 = [ "esp-backtrace/esp32p4", "esp-bootloader-esp-idf/esp32p4", "esp-hal/esp32p4", - "esp-storage/esp32p4", ] esp32s2 = [ "esp-backtrace/esp32s2", "esp-bootloader-esp-idf/esp32s2", "esp-hal/esp32s2", - "esp-storage/esp32s2", ] esp32s3 = [ "esp-backtrace/esp32s3", "esp-bootloader-esp-idf/esp32s3", "esp-hal/esp32s3", - "esp-storage/esp32s3", ] esp32s31 = [ "esp-backtrace/esp32s31", "esp-bootloader-esp-idf/esp32s31", "esp-hal/esp32s31", - "esp-storage/esp32s31", ] [profile.release] diff --git a/examples/ota/update/src/main.rs b/examples/ota/update/src/main.rs index 24388f5661e..c35a4b86199 100644 --- a/examples/ota/update/src/main.rs +++ b/examples/ota/update/src/main.rs @@ -5,18 +5,19 @@ //! the binary. In a real world application you can get the image via HTTP(S), //! UART or from an sd-card etc. //! -//! Adjust the target and the chip in the following commands according to the -//! chip used! +//! When these instructions are shown by `cargo xtask run`, `{CHIP}` and +//! `{TARGET}` are already replaced for the selected chip, so the commands can +//! be copy-pasted as shown. //! //! ```ignore,bash -//! cargo xtask build examples gpio --chip=esp32 -//! espflash save-image --chip=esp32 target/xtensa-esp32-none-elf/release/gpio_interrupt target/ota_image -//! cargo xtask build examples update --chip=esp32 -//! espflash save-image --chip=esp32 target/xtensa-esp32-none-elf/release/ota_update target/ota_image -//! cargo xtask build examples update --chip=esp32 -//! espflash save-image --chip=esp32 target/xtensa-esp32-none-elf/release/ota_update target/ota_image +//! cargo xtask build gpio {CHIP} +//! espflash save-image --chip={CHIP} target/{TARGET}/release/gpio_interrupt target/ota_image +//! cargo xtask build ota/update {CHIP} +//! espflash save-image --chip={CHIP} target/{TARGET}/release/ota_update target/ota_image +//! cargo xtask build ota/update {CHIP} +//! espflash save-image --chip={CHIP} target/{TARGET}/release/ota_update target/ota_image //! espflash erase-flash -//! cargo xtask run example update --chip=esp32 +//! cargo xtask run ota/update {CHIP} //! ``` //! //! On first boot notice the firmware partition gets booted ("Loaded app from @@ -31,27 +32,31 @@ //! //! See +//% CHIP_FILTER: flash_driver_supported + #![no_std] #![no_main] use esp_backtrace as _; use esp_hal::{ + flash::{Config, Flash}, gpio::{Input, InputConfig, Pull}, main, }; use esp_println::println; -use esp_storage::FlashStorage; esp_bootloader_esp_idf::esp_app_desc!(); static OTA_IMAGE: &[u8] = include_bytes!("../../../../target/ota_image"); +const SECTOR_SIZE: usize = 4096; + #[main] fn main() -> ! { esp_println::logger::init_logger_from_env(); let peripherals = esp_hal::init(esp_hal::Config::default()); - let mut flash = FlashStorage::new(peripherals.FLASH); + let mut flash = Flash::new(peripherals.FLASH, Config::default()).unwrap(); let mut buffer = [0u8; esp_bootloader_esp_idf::partitions::PARTITION_TABLE_MAX_LEN]; let pt = @@ -93,14 +98,14 @@ fn main() -> ! { } } - let button = - cfg_select! { - any(feature = "esp32", feature = "esp32s2", feature = "esp32s3") => peripherals.GPIO0, - feature = "esp32c5" => peripherals.GPIO28, - feature = "esp32p4" => peripherals.GPIO35, - feature = "esp32s31" => peripherals.GPIO61, - _ => peripherals.GPIO9, - }; + let button = cfg_select! { + any(feature = "esp32", feature = "esp32s2", feature = "esp32s3") => peripherals.GPIO0, + feature = "esp32c5" => peripherals.GPIO28, + feature = "esp32p4" => peripherals.GPIO35, + feature = "esp32h4" => peripherals.GPIO34, + feature = "esp32s31" => peripherals.GPIO61, + _ => peripherals.GPIO9, + }; let boot_button = Input::new(button, InputConfig::default().with_pull(Pull::Up)); @@ -114,12 +119,24 @@ fn main() -> ! { println!("Flashing image to {:?}", part_type); - // write to the app partition - for (sector, chunk) in OTA_IMAGE.chunks(4096).enumerate() { + // Write to the app partition. The region is encrypted if flash + // encryption is enabled. + let mut sector_buffer = [0xff; SECTOR_SIZE]; + for (sector, chunk) in OTA_IMAGE.chunks(SECTOR_SIZE).enumerate() { println!("Writing sector {sector}..."); + let offset = (sector * SECTOR_SIZE) as u32; + next_app_partition + .erase(offset, offset + SECTOR_SIZE as u32) + .unwrap(); + + // Encrypted writes must be a multiple of 16 bytes, so pad the + // last chunk with erased bytes. + sector_buffer.fill(0xff); + sector_buffer[..chunk.len()].copy_from_slice(chunk); + let len = chunk.len().next_multiple_of(16); next_app_partition - .write((sector * 4096) as u32, chunk) + .write(offset, §or_buffer[..len]) .unwrap(); } diff --git a/examples/peripheral/canfd/.cargo/config.toml b/examples/peripheral/canfd/.cargo/config.toml new file mode 100644 index 00000000000..44dacc4278b --- /dev/null +++ b/examples/peripheral/canfd/.cargo/config.toml @@ -0,0 +1,24 @@ +[target.'cfg(target_arch = "riscv32")'] +runner = "espflash flash --monitor" +rustflags = [ + "-C", "link-arg=-Tlinkall.x", + "-C", "force-frame-pointers", +] + +[target.'cfg(target_arch = "xtensa")'] +runner = "espflash flash --monitor" +rustflags = [ + # GNU LD + "-C", "link-arg=-Wl,-Tlinkall.x", + "-C", "link-arg=-nostartfiles", + + # LLD + # "-C", "link-arg=-Tlinkall.x", + # "-C", "linker=rust-lld", +] + +[env] +ESP_LOG = "info" + +[unstable] +build-std = ["core", "alloc"] diff --git a/examples/peripheral/canfd/Cargo.toml b/examples/peripheral/canfd/Cargo.toml new file mode 100644 index 00000000000..73208fb0190 --- /dev/null +++ b/examples/peripheral/canfd/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "canfd" +version = "0.0.0" +edition = "2024" +publish = false + +[dependencies] +esp-backtrace = { path = "../../../esp-backtrace", features = [ + "panic-handler", + "println", +] } +esp-bootloader-esp-idf = { path = "../../../esp-bootloader-esp-idf" } +esp-hal = { path = "../../../esp-hal", features = ["log-04", "unstable"] } +esp-println = { path = "../../../esp-println", features = ["log-04"] } + +[features] +esp32c5 = [ + "esp-backtrace/esp32c5", + "esp-bootloader-esp-idf/esp32c5", + "esp-hal/esp32c5", +] + +[profile.release] +debug = true +debug-assertions = true +lto = "fat" +codegen-units = 1 diff --git a/examples/peripheral/canfd/src/main.rs b/examples/peripheral/canfd/src/main.rs new file mode 100644 index 00000000000..186d3132138 --- /dev/null +++ b/examples/peripheral/canfd/src/main.rs @@ -0,0 +1,106 @@ +//! This example sends a CAN FD frame to another ESP and receives it back. +//! +//! `IS_FIRST_SENDER` below must be set to false on one of the ESPs. +//! +//! The following wiring is assumed: +//! - TX/RX => GPIO2, connected internally and with a pull-up resistor. +//! +//! ESP1/GND --- ESP2/GND +//! ESP1/GPIO2 --- ESP2/GPIO2 +//! +//! Without a transceiver, the two controllers drive one wire open-drain and a +//! pull-up makes it recessive. The internal pull-up is enough for the 500 kbit/s +//! arbitration phase, but the rising edges of the 2 Mbit/s data phase need an +//! external pull-up of a few kilo-ohms to 3V3. +//! +//! Notes for external transceiver use: +//! +//! The default setup assumes that two microcontrollers are connected directly +//! without an external transceiver. If you want to use an external transceiver, +//! you need to: +//! * remove the `with_no_transceiver` call from the configuration +//! * use separate pins for `rx_pin` and `tx_pin`, and change them to the appropriate pins for your +//! boards. + +//% CHIP_FILTER: canfd_driver_supported + +#![no_std] +#![no_main] + +const IS_FIRST_SENDER: bool = true; + +use esp_backtrace as _; +use esp_hal::{ + canfd::{CanFd, Config, Frame, StandardId, TxBufferState}, + delay::Delay, + main, +}; +use esp_println::println; + +esp_bootloader_esp_idf::esp_app_desc!(); + +#[main] +fn main() -> ! { + esp_println::logger::init_logger_from_env(); + let peripherals = esp_hal::init(esp_hal::Config::default()); + + // Without an external transceiver, we only need a single line between the two + // MCUs. + let (rx_pin, tx_pin) = unsafe { peripherals.GPIO2.split() }; + // Use these if you want to use an external transceiver: + // let tx_pin = peripherals.GPIO2; + // let rx_pin = peripherals.GPIO0; + + // The default configuration runs the arbitration phase at 500 kbit/s and + // the data phase at 2 Mbit/s from the 80 MHz function clock. Other bit + // rates are set with `with_nominal_timing` and `with_fd_timing`. + let config = Config::default().with_no_transceiver(true); + + // The controller is configured but stays off the bus until it is started. + let mut canfd = CanFd::new(peripherals.TWAI0, config) + .unwrap() + .with_rx(rx_pin) + .with_tx(tx_pin); + + // Join the bus. This waits for the bus to be idle long enough for the + // controller to become error-active. + canfd.start().unwrap(); + + // A CAN FD frame with 64 bytes of payload, sent with the data phase at the + // FD bit rate. + let payload: [u8; 64] = core::array::from_fn(|i| i as u8); + let id = StandardId::new(0x123).unwrap(); + let frame = Frame::new_fd(id, &payload) + .unwrap() + .with_bit_rate_switch(true); + + if IS_FIRST_SENDER { + send(&mut canfd, &frame); + } + + let delay = Delay::new(); + loop { + // Wait for a frame to be received. + while canfd.rx_frame_count() == 0 {} + let received = canfd.receive().unwrap(); + + println!("Received a frame: {received:?}"); + delay.delay_millis(250); + + // Transmit a new frame back to the other ESP. + send(&mut canfd, &frame); + } +} + +/// Queues a frame and waits until the hardware is done with it. +fn send(canfd: &mut CanFd<'_>, frame: &Frame) { + let index = canfd.transmit(frame).unwrap(); + loop { + match canfd.tx_buffer_state(index) { + TxBufferState::Ready | TxBufferState::InProgress => {} + TxBufferState::Ok => break, + state => panic!("transmission failed: {state:?}"), + } + } + println!("Sent a frame"); +} diff --git a/examples/peripheral/dma/mem2mem/Cargo.toml b/examples/peripheral/dma/mem2mem/Cargo.toml index f565936216e..3d3798300b8 100644 --- a/examples/peripheral/dma/mem2mem/Cargo.toml +++ b/examples/peripheral/dma/mem2mem/Cargo.toml @@ -45,6 +45,11 @@ esp32h2 = [ "esp-bootloader-esp-idf/esp32h2", "esp-hal/esp32h2", ] +esp32h4 = [ + "esp-backtrace/esp32h4", + "esp-bootloader-esp-idf/esp32h4", + "esp-hal/esp32h4", +] esp32p4 = [ "esp-backtrace/esp32p4", "esp-bootloader-esp-idf/esp32p4", diff --git a/examples/peripheral/flash/.cargo/config.toml b/examples/peripheral/flash/.cargo/config.toml new file mode 100644 index 00000000000..44dacc4278b --- /dev/null +++ b/examples/peripheral/flash/.cargo/config.toml @@ -0,0 +1,24 @@ +[target.'cfg(target_arch = "riscv32")'] +runner = "espflash flash --monitor" +rustflags = [ + "-C", "link-arg=-Tlinkall.x", + "-C", "force-frame-pointers", +] + +[target.'cfg(target_arch = "xtensa")'] +runner = "espflash flash --monitor" +rustflags = [ + # GNU LD + "-C", "link-arg=-Wl,-Tlinkall.x", + "-C", "link-arg=-nostartfiles", + + # LLD + # "-C", "link-arg=-Tlinkall.x", + # "-C", "linker=rust-lld", +] + +[env] +ESP_LOG = "info" + +[unstable] +build-std = ["core", "alloc"] diff --git a/examples/peripheral/flash/Cargo.toml b/examples/peripheral/flash/Cargo.toml new file mode 100644 index 00000000000..4d3adf88bfe --- /dev/null +++ b/examples/peripheral/flash/Cargo.toml @@ -0,0 +1,82 @@ +[package] +name = "flash" +version = "0.0.0" +edition = "2024" +publish = false + +[dependencies] +esp-backtrace = { path = "../../../esp-backtrace", features = [ + "panic-handler", + "println", +] } +esp-bootloader-esp-idf = { path = "../../../esp-bootloader-esp-idf" } +esp-hal = { path = "../../../esp-hal", features = ["log-04", "unstable"] } +esp-println = { path = "../../../esp-println", features = ["log-04"] } + +[features] +esp32 = [ + "esp-backtrace/esp32", + "esp-bootloader-esp-idf/esp32", + "esp-hal/esp32", +] +esp32c2 = [ + "esp-backtrace/esp32c2", + "esp-bootloader-esp-idf/esp32c2", + "esp-hal/esp32c2", +] +esp32c3 = [ + "esp-backtrace/esp32c3", + "esp-bootloader-esp-idf/esp32c3", + "esp-hal/esp32c3", +] +esp32c5 = [ + "esp-backtrace/esp32c5", + "esp-bootloader-esp-idf/esp32c5", + "esp-hal/esp32c5", +] +esp32c6 = [ + "esp-backtrace/esp32c6", + "esp-bootloader-esp-idf/esp32c6", + "esp-hal/esp32c6", +] +esp32c61 = [ + "esp-backtrace/esp32c61", + "esp-bootloader-esp-idf/esp32c61", + "esp-hal/esp32c61", +] +esp32h2 = [ + "esp-backtrace/esp32h2", + "esp-bootloader-esp-idf/esp32h2", + "esp-hal/esp32h2", +] +esp32h4 = [ + "esp-backtrace/esp32h4", + "esp-bootloader-esp-idf/esp32h4", + "esp-hal/esp32h4", +] +esp32p4 = [ + "esp-backtrace/esp32p4", + "esp-bootloader-esp-idf/esp32p4", + "esp-hal/esp32p4", +] +esp32s2 = [ + "esp-backtrace/esp32s2", + "esp-bootloader-esp-idf/esp32s2", + "esp-hal/esp32s2", +] +esp32s3 = [ + "esp-backtrace/esp32s3", + "esp-bootloader-esp-idf/esp32s3", + "esp-hal/esp32s3", +] +esp32s31 = [ + "esp-backtrace/esp32s31", + "esp-bootloader-esp-idf/esp32s31", + "esp-hal/esp32s31", +] + +[profile.release] +debug = true +debug-assertions = true +lto = "fat" +codegen-units = 1 diff --git a/examples/peripheral/flash/src/main.rs b/examples/peripheral/flash/src/main.rs new file mode 100644 index 00000000000..214b9d53b90 --- /dev/null +++ b/examples/peripheral/flash/src/main.rs @@ -0,0 +1,93 @@ +//! Writes and reads internal SPI flash via [`esp_hal::flash`]. +//! +//! Assumes the default factory layout (app at `0x1_0000`, NVS at `0x9000`). +//! Write and erase are unsafe NOR operations: there is no auto-erase, and they +//! can overwrite the running application. This example only mutates the first +//! NVS sector. Buffers are word slices in DRAM. + +//% CHIP_FILTER: flash_driver_supported + +#![no_std] +#![no_main] + +use esp_backtrace as _; +use esp_hal::{ + flash::{Config, Flash}, + main, +}; +use esp_println::println; + +esp_bootloader_esp_idf::esp_app_desc!(); + +/// Default factory-app image: `0x1_0000` plus the 24-byte image header and +/// 8-byte first section header. +const APP_DESC_OFFSET: u32 = 0x10_020; +/// Default NVS data partition. +const NVS_OFFSET: u32 = 0x9000; + +fn as_bytes(words: &[u32]) -> &[u8] { + // SAFETY: inspecting the in-memory bytes of `u32` words. + unsafe { core::slice::from_raw_parts(words.as_ptr().cast(), size_of_val(words)) } +} + +fn as_bytes_mut(words: &mut [u32]) -> &mut [u8] { + // SAFETY: mutating the in-memory bytes of `u32` words. + unsafe { core::slice::from_raw_parts_mut(words.as_mut_ptr().cast(), size_of_val(words)) } +} + +#[main] +fn main() -> ! { + esp_println::logger::init_logger_from_env(); + let peripherals = esp_hal::init(esp_hal::Config::default()); + + let mut flash = Flash::new(peripherals.FLASH, Config::default()).unwrap(); + let info = flash.chip_info(); + println!( + "Flash chip_id = {:#08x}, capacity = {}", + info.chip_id, info.capacity + ); + println!("Flash capacity = {}", flash.capacity()); + println!(); + // The app descriptor sits in the first 256 bytes of an app image, after the + // 24-byte image header and the 8-byte first section header. + let mut app_desc = [0u32; 64]; + flash.read(APP_DESC_OFFSET, &mut app_desc).unwrap(); + println!("App descriptor dump {:02x?}", as_bytes(&app_desc)); + println!(); + + let mut words = [0u32; 8]; + flash.read(NVS_OFFSET, &mut words).unwrap(); + println!("Read from {:x}: {:02x?}", NVS_OFFSET, as_bytes(&words)); + + { + let bytes = as_bytes_mut(&mut words); + bytes[0x00] = bytes[0x00].wrapping_add(1); + bytes[0x01] = bytes[0x01].wrapping_add(2); + bytes[0x02] = bytes[0x02].wrapping_add(3); + bytes[0x03] = bytes[0x03].wrapping_add(4); + bytes[0x04] = bytes[0x04].wrapping_add(1); + bytes[0x05] = bytes[0x05].wrapping_add(2); + bytes[0x06] = bytes[0x06].wrapping_add(3); + bytes[0x07] = bytes[0x07].wrapping_add(4); + } + + // NOR flash can only program 1→0; erase the sector first so the new pattern + // can include 1-bits. + // SAFETY: NVS is a data partition, not mapped firmware. + unsafe { + flash + .erase(NVS_OFFSET, NVS_OFFSET + Flash::SECTOR_SIZE) + .unwrap(); + flash.write(NVS_OFFSET, &words).unwrap(); + } + println!("Written to {:x}: {:02x?}", NVS_OFFSET, as_bytes(&words)); + + let mut reread = [0u32; 8]; + flash.read(NVS_OFFSET, &mut reread).unwrap(); + println!("Read from {:x}: {:02x?}", NVS_OFFSET, as_bytes(&reread)); + + println!(); + println!("Reset (CTRL-R in espflash) to re-read the persisted data."); + + loop {} +} diff --git a/examples/peripheral/flash_read_write/Cargo.toml b/examples/peripheral/flash_read_write/Cargo.toml index 0e7ad8303da..7d485906263 100644 --- a/examples/peripheral/flash_read_write/Cargo.toml +++ b/examples/peripheral/flash_read_write/Cargo.toml @@ -12,74 +12,67 @@ esp-backtrace = { path = "../../../esp-backtrace", features = [ esp-bootloader-esp-idf = { path = "../../../esp-bootloader-esp-idf" } esp-hal = { path = "../../../esp-hal", features = ["log-04", "unstable"] } esp-println = { path = "../../../esp-println", features = ["log-04"] } -esp-storage = { path = "../../../esp-storage" } [features] esp32 = [ "esp-backtrace/esp32", "esp-bootloader-esp-idf/esp32", "esp-hal/esp32", - "esp-storage/esp32", ] esp32c2 = [ "esp-backtrace/esp32c2", "esp-bootloader-esp-idf/esp32c2", "esp-hal/esp32c2", - "esp-storage/esp32c2", ] esp32c3 = [ "esp-backtrace/esp32c3", "esp-bootloader-esp-idf/esp32c3", "esp-hal/esp32c3", - "esp-storage/esp32c3", ] esp32c5 = [ "esp-backtrace/esp32c5", "esp-bootloader-esp-idf/esp32c5", "esp-hal/esp32c5", - "esp-storage/esp32c5", ] esp32c6 = [ "esp-backtrace/esp32c6", "esp-bootloader-esp-idf/esp32c6", "esp-hal/esp32c6", - "esp-storage/esp32c6", ] esp32c61 = [ "esp-backtrace/esp32c61", "esp-bootloader-esp-idf/esp32c61", "esp-hal/esp32c61", - "esp-storage/esp32c61", ] esp32h2 = [ "esp-backtrace/esp32h2", "esp-bootloader-esp-idf/esp32h2", "esp-hal/esp32h2", - "esp-storage/esp32h2", +] +esp32h4 = [ + "esp-backtrace/esp32h4", + "esp-bootloader-esp-idf/esp32h4", + "esp-hal/esp32h4", ] esp32p4 = [ "esp-backtrace/esp32p4", "esp-bootloader-esp-idf/esp32p4", "esp-hal/esp32p4", - "esp-storage/esp32p4", ] esp32s2 = [ "esp-backtrace/esp32s2", "esp-bootloader-esp-idf/esp32s2", "esp-hal/esp32s2", - "esp-storage/esp32s2", ] esp32s3 = [ "esp-backtrace/esp32s3", "esp-bootloader-esp-idf/esp32s3", "esp-hal/esp32s3", - "esp-storage/esp32s3", ] esp32s31 = [ "esp-backtrace/esp32s31", "esp-bootloader-esp-idf/esp32s31", "esp-hal/esp32s31", - "esp-storage/esp32s31", ] [profile.release] diff --git a/examples/peripheral/flash_read_write/src/main.rs b/examples/peripheral/flash_read_write/src/main.rs index 5d33a2ae517..2cccf519ccf 100644 --- a/examples/peripheral/flash_read_write/src/main.rs +++ b/examples/peripheral/flash_read_write/src/main.rs @@ -2,14 +2,18 @@ //! //! See https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-guides/partition-tables.html#built-in-partition-tables +//% CHIP_FILTER: flash_driver_supported + #![no_std] #![no_main] use esp_backtrace as _; use esp_bootloader_esp_idf::partitions; -use esp_hal::main; +use esp_hal::{ + flash::{Config, Flash}, + main, +}; use esp_println::println; -use esp_storage::FlashStorage; esp_bootloader_esp_idf::esp_app_desc!(); @@ -18,7 +22,7 @@ fn main() -> ! { esp_println::logger::init_logger_from_env(); let peripherals = esp_hal::init(esp_hal::Config::default()); - let mut flash = FlashStorage::new(peripherals.FLASH); + let mut flash = Flash::new(peripherals.FLASH, Config::default()).unwrap(); println!("Flash size = {}", flash.capacity()); let mut pt_mem = [0u8; partitions::PARTITION_TABLE_MAX_LEN]; @@ -40,10 +44,13 @@ fn main() -> ! { // The app descriptor (if present) is contained in the first 256 bytes // of an app image, right after the image header (24 bytes) and the first - // section header (8 bytes) + // section header (8 bytes). + // + // App partitions are encrypted when flash encryption is enabled, so access + // them through an `AutoFlashRegion` which handles both cases. let mut app_desc = [0u8; 256]; factory - .as_flash_region(&mut flash) + .as_auto_flash_region(&mut flash) .read(32, &mut app_desc) .unwrap(); println!("App descriptor dump {:02x?}", app_desc); @@ -62,7 +69,8 @@ fn main() -> ! { )) .unwrap() .unwrap(); - let mut nvs_partition = nvs.as_flash_region(&mut flash); + // NVS partitions are not flash-encrypted, so access them as a plain `FlashRegion`. + let mut nvs_partition = nvs.as_flash_region(&mut flash).unwrap(); let mut bytes = [0u8; 32]; println!("NVS partition size = {}", nvs_partition.capacity()); @@ -88,6 +96,11 @@ fn main() -> ! { bytes[0x06] = bytes[0x06].wrapping_add(3); bytes[0x07] = bytes[0x07].wrapping_add(4); + // Writes can only clear bits, so erase the sector before writing new data. + // This also erases the rest of the sector. + nvs_partition + .erase(offset_in_nvs_partition, offset_in_nvs_partition + 4096) + .unwrap(); nvs_partition .write(offset_in_nvs_partition, &bytes) .unwrap(); diff --git a/examples/peripheral/i2c/src/main.rs b/examples/peripheral/i2c/src/main.rs index 85fa97646c8..515f8abcd31 100644 --- a/examples/peripheral/i2c/src/main.rs +++ b/examples/peripheral/i2c/src/main.rs @@ -5,6 +5,8 @@ //! - When the master writes to the slave, the slave prints the received data. //! - When the master reads from the slave, the slave responds by sending back a message. +//% CHIP_FILTER: i2c_slave_driver_supported + #![no_std] #![no_main] diff --git a/examples/peripheral/lp_core/lp_blinky/src/main.rs b/examples/peripheral/lp_core/lp_blinky/src/main.rs index e045f5e6715..2e713f0f48e 100644 --- a/examples/peripheral/lp_core/lp_blinky/src/main.rs +++ b/examples/peripheral/lp_core/lp_blinky/src/main.rs @@ -42,9 +42,7 @@ fn main() -> ! { .unwrap(); let mut lp_core = cfg_select! { - any(feature = "esp32s2", feature = "esp32s3") => { - UlpCore::new(peripherals.ULP_RISCV_CORE) - } + any(feature = "esp32s2", feature = "esp32s3") => UlpCore::new(peripherals.ULP_RISCV_CORE), _ => LpCore::new(peripherals.LP_CORE), }; @@ -65,11 +63,10 @@ fn main() -> ! { }; // start LP core - let wakeup_source = - cfg_select! { - any(feature = "esp32s2", feature = "esp32s3") => UlpCoreWakeupSource::HpCpu, - _ => LpCoreWakeupSource::HpCpu, - }; + let wakeup_source = cfg_select! { + any(feature = "esp32s2", feature = "esp32s3") => UlpCoreWakeupSource::HpCpu, + _ => LpCoreWakeupSource::HpCpu, + }; lp_core_code.run(&mut lp_core, wakeup_source, lp_pin); println!("lp core run"); diff --git a/examples/peripheral/spi/loopback/Cargo.toml b/examples/peripheral/spi/loopback/Cargo.toml index 01bdf9f3201..8bd3bba3476 100644 --- a/examples/peripheral/spi/loopback/Cargo.toml +++ b/examples/peripheral/spi/loopback/Cargo.toml @@ -45,6 +45,11 @@ esp32h2 = [ "esp-bootloader-esp-idf/esp32h2", "esp-hal/esp32h2", ] +esp32h4 = [ + "esp-backtrace/esp32h4", + "esp-bootloader-esp-idf/esp32h4", + "esp-hal/esp32h4", +] esp32s2 = [ "esp-backtrace/esp32s2", "esp-bootloader-esp-idf/esp32s2", diff --git a/examples/peripheral/spi/loopback_dma_psram/src/main.rs b/examples/peripheral/spi/loopback_dma_psram/src/main.rs index 99f426bb72b..23b17c6e1e1 100644 --- a/examples/peripheral/spi/loopback_dma_psram/src/main.rs +++ b/examples/peripheral/spi/loopback_dma_psram/src/main.rs @@ -57,12 +57,11 @@ fn main() -> ! { esp_alloc::psram_allocator!(peripherals.PSRAM, esp_hal::psram); let delay = Delay::new(); - let (sclk, mosi, cs) = - cfg_select! { - feature = "esp32s3" => (peripherals.GPIO42, peripherals.GPIO48, peripherals.GPIO38), - feature = "esp32s31" => (peripherals.GPIO11, peripherals.GPIO12, peripherals.GPIO13), - _ => (peripherals.GPIO6, peripherals.GPIO7, peripherals.GPIO10), - }; + let (sclk, mosi, cs) = cfg_select! { + feature = "esp32s3" => (peripherals.GPIO42, peripherals.GPIO48, peripherals.GPIO38), + feature = "esp32s31" => (peripherals.GPIO11, peripherals.GPIO12, peripherals.GPIO13), + _ => (peripherals.GPIO6, peripherals.GPIO7, peripherals.GPIO10), + }; let (miso, mosi) = unsafe { mosi.split() }; diff --git a/qa-test/.cargo/config.toml b/examples/qa/.cargo/config.toml similarity index 100% rename from qa-test/.cargo/config.toml rename to examples/qa/.cargo/config.toml diff --git a/qa-test/.clippy.toml b/examples/qa/.clippy.toml similarity index 100% rename from qa-test/.clippy.toml rename to examples/qa/.clippy.toml diff --git a/qa-test/Cargo.toml b/examples/qa/Cargo.toml similarity index 73% rename from qa-test/Cargo.toml rename to examples/qa/Cargo.toml index 38b169382aa..d9488031504 100644 --- a/qa-test/Cargo.toml +++ b/examples/qa/Cargo.toml @@ -5,8 +5,11 @@ edition = "2024" license = "MIT OR Apache-2.0" publish = false +[package.metadata.espressif] +aliases = ["qa"] + [build-dependencies] -esp-metadata-generated = { path = "../esp-metadata-generated", features = ["build-script"] } +esp-metadata-generated = { path = "../../esp-metadata-generated", features = ["build-script"] } [dependencies] embassy-executor = "0.10.0" @@ -17,23 +20,23 @@ embassy-sync = "0.8.0" embedded-graphics = "0.8.1" embedded-hal-async = "1.0.0" embedded-io-async = "0.7.0" -esp-alloc = { path = "../esp-alloc" } -esp-backtrace = { path = "../esp-backtrace", features = [ +esp-alloc = { path = "../../esp-alloc" } +esp-backtrace = { path = "../../esp-backtrace", features = [ "panic-handler", "println", ] } -esp-bootloader-esp-idf = { path = "../esp-bootloader-esp-idf" } -esp-hal = { path = "../esp-hal", features = ["log-04", "unstable"] } -esp-rtos = { path = "../esp-rtos", optional = true, features = [ +esp-bootloader-esp-idf = { path = "../../esp-bootloader-esp-idf" } +esp-hal = { path = "../../esp-hal", features = ["log-04", "unstable"] } +esp-metadata-generated = { path = "../../esp-metadata-generated" } +esp-rtos = { path = "../../esp-rtos", optional = true, features = [ "log-04", "embassy", ] } -esp-println = { path = "../esp-println", features = ["log-04"] } -esp-radio = { path = "../esp-radio", features = [ +esp-println = { path = "../../esp-println", features = ["log-04"] } +esp-radio = { path = "../../esp-radio", features = [ "log-04", "unstable", ], optional = true } -esp-storage = { path = "../esp-storage", optional = true } ieee802154 = "0.6.1" lis3dh-async = "0.9.3" ssd1306 = "0.10.0" @@ -43,14 +46,13 @@ block-device-adapters = "0.2.0" embedded-fatfs = { git = "https://github.com/MabezDev/embedded-fatfs", rev = "518528cc111fcf65c48abbdeb80735a38eada112", default-features = false } embedded-partitions = { git = "https://github.com/MabezDev/embedded-fatfs", rev = "518528cc111fcf65c48abbdeb80735a38eada112" } rtos-trace = { version = "0.2.0", optional = true } -trouble-host = { version = "0.7.0", features = [ +trouble-host = { version = "0.8.0", features = [ "default-packet-pool-mtu-255", "derive", "scan", ] } log = "0.4" libm = "0.2" -nb = "0" [features] unstable = [] @@ -65,109 +67,119 @@ esp32 = [ "esp-backtrace/esp32", "esp-bootloader-esp-idf/esp32", "esp-hal/esp32", + "esp-metadata-generated/esp32", "esp-rtos/esp32", "esp-println/esp32", "esp-radio?/esp32", - "esp-storage?/esp32", ] esp32c2 = [ "esp-alloc/esp32c2", "esp-backtrace/esp32c2", "esp-bootloader-esp-idf/esp32c2", "esp-hal/esp32c2", + "esp-metadata-generated/esp32c2", "esp-rtos/esp32c2", "esp-println/esp32c2", "esp-radio?/esp32c2", - "esp-storage?/esp32c2", ] esp32c3 = [ "esp-alloc/esp32c3", "esp-backtrace/esp32c3", "esp-bootloader-esp-idf/esp32c3", "esp-hal/esp32c3", + "esp-metadata-generated/esp32c3", "esp-rtos/esp32c3", "esp-println/esp32c3", "esp-radio?/esp32c3", - "esp-storage?/esp32c3", ] esp32c5 = [ "esp-alloc/esp32c5", "esp-backtrace/esp32c5", "esp-bootloader-esp-idf/esp32c5", "esp-hal/esp32c5", + "esp-metadata-generated/esp32c5", "esp-rtos/esp32c5", "esp-println/esp32c5", "esp-radio?/esp32c5", - "esp-storage?/esp32c5", ] esp32c6 = [ "esp-alloc/esp32c6", "esp-backtrace/esp32c6", "esp-bootloader-esp-idf/esp32c6", "esp-hal/esp32c6", + "esp-metadata-generated/esp32c6", "esp-rtos/esp32c6", "esp-println/esp32c6", "esp-radio?/esp32c6", - "esp-storage?/esp32c6", ] esp32c61 = [ "esp-alloc/esp32c61", "esp-backtrace/esp32c61", "esp-bootloader-esp-idf/esp32c61", "esp-hal/esp32c61", + "esp-metadata-generated/esp32c61", "esp-rtos/esp32c61", "esp-println/esp32c61", "esp-radio?/esp32c61", - "esp-storage?/esp32c61", ] esp32h2 = [ "esp-alloc/esp32h2", "esp-backtrace/esp32h2", "esp-bootloader-esp-idf/esp32h2", "esp-hal/esp32h2", + "esp-metadata-generated/esp32h2", "esp-rtos/esp32h2", "esp-println/esp32h2", "esp-radio?/esp32h2", - "esp-storage?/esp32h2", +] +esp32h4 = [ + "esp-alloc/esp32h4", + "esp-backtrace/esp32h4", + "esp-bootloader-esp-idf/esp32h4", + "esp-hal/esp32h4", + "esp-metadata-generated/esp32h4", + "esp-rtos/esp32h4", + "esp-println/esp32h4", + "esp-radio?/esp32h4", ] esp32p4 = [ "esp-alloc/esp32p4", "esp-backtrace/esp32p4", "esp-bootloader-esp-idf/esp32p4", "esp-hal/esp32p4", + "esp-metadata-generated/esp32p4", "esp-rtos/esp32p4", "esp-println/esp32p4", - "esp-storage?/esp32p4", ] esp32s2 = [ "esp-alloc/esp32s2", "esp-backtrace/esp32s2", "esp-bootloader-esp-idf/esp32s2", "esp-hal/esp32s2", + "esp-metadata-generated/esp32s2", "esp-rtos/esp32s2", "esp-println/esp32s2", "esp-radio?/esp32s2", - "esp-storage?/esp32s2", ] esp32s3 = [ "esp-alloc/esp32s3", "esp-backtrace/esp32s3", "esp-bootloader-esp-idf/esp32s3", "esp-hal/esp32s3", + "esp-metadata-generated/esp32s3", "esp-rtos/esp32s3", "esp-println/esp32s3", "esp-radio?/esp32s3", - "esp-storage?/esp32s3", ] esp32s31 = [ "esp-alloc/esp32s31", "esp-backtrace/esp32s31", "esp-bootloader-esp-idf/esp32s31", "esp-hal/esp32s31", + "esp-metadata-generated/esp32s31", "esp-rtos/esp32s31", "esp-println/esp32s31", - # "esp-radio?/esp32s31", - "esp-storage?/esp32s31", + "esp-radio?/esp32s31", ] rtos-trace = ["esp-rtos/rtos-trace", "dep:rtos-trace"] diff --git a/qa-test/README.md b/examples/qa/README.md similarity index 79% rename from qa-test/README.md rename to examples/qa/README.md index 1bee0404966..e14d80f7e55 100644 --- a/qa-test/README.md +++ b/examples/qa/README.md @@ -4,7 +4,7 @@ This package contains a number of binary applications intended for manual/qualit Each device has its own unique set of peripherals, and as such not every test will run on every device. We recommend building and flashing the tests using the `xtask` method documented below, which will greatly simplify the process. -To check if a device is compatible with a given test, check the metadata comments above the imports, which describe the supported devices following the `//% CHIP_FILTER:` designator. The expression can use boolean cfg symbols, key-value cfg comparisons (e.g. `interrupt_controller != "clic"`), and chip names — see [`xtask/README.md`](../xtask/README.md) for details. If this metadata is not present, then the test will work on any device supported by `esp-hal`. +To check if a device is compatible with a given test, check the metadata comments above the imports, which describe the supported devices following the `//% CHIP_FILTER:` designator. The expression can use boolean cfg symbols, key-value cfg comparisons (e.g. `interrupt_controller != "clic"`), and chip names — see [`xtask/README.md`](../../xtask/README.md) for details. If this metadata is not present, then the test will work on any device supported by `esp-hal`. As previously stated, we use the [cargo-xtask] pattern for automation. Commands invoking this tool must be run from the root of the repository. @@ -12,14 +12,12 @@ As previously stated, we use the [cargo-xtask] pattern for automation. Commands ## Running Tests -You can build and then subsequently flash and run a test using the `run example` subcommand. With a target device connected to your host system, run: +You can build and then subsequently flash and run a test with a target device connected: ```shell -cargo xtask run example --package qa-test --chip esp32c6 sleep_timer +esp-devtool run sleep_timer ``` -Again, note that we must specify which package to build the test from, plus which test to build and flash to the target device. - ## Adding Tests If you are contributing to `esp-hal` and would like to add a test, the process is generally the same as any other project. diff --git a/qa-test/build.rs b/examples/qa/build.rs similarity index 100% rename from qa-test/build.rs rename to examples/qa/build.rs diff --git a/qa-test/src/bin/ble_advertise_after_sleep.rs b/examples/qa/src/bin/ble-advertise-after-sleep.rs similarity index 97% rename from qa-test/src/bin/ble_advertise_after_sleep.rs rename to examples/qa/src/bin/ble-advertise-after-sleep.rs index 3a5a6cb1a51..e6e64162c5c 100644 --- a/qa-test/src/bin/ble_advertise_after_sleep.rs +++ b/examples/qa/src/bin/ble-advertise-after-sleep.rs @@ -23,6 +23,7 @@ use esp_hal::{ use esp_println::println; use esp_radio::ble::controller::BleConnector; use log::{info, warn}; +use qa_test::DRAM2_UNINIT_SIZE; use trouble_host::prelude::*; esp_bootloader_esp_idf::esp_app_desc!(); @@ -57,11 +58,11 @@ async fn main(_s: Spawner) { let config = esp_hal::Config::default().with_cpu_clock(CpuClock::max()); let peripherals = esp_hal::init(config); - esp_alloc::heap_allocator!(#[esp_hal::ram(reclaimed)] size: 64 * 1024); + esp_alloc::heap_allocator!(#[esp_hal::ram(reclaimed)] size: DRAM2_UNINIT_SIZE); esp_alloc::heap_allocator!(size: 72 * 1024); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let mut lpwr = LowPower::new(peripherals.LPWR); @@ -71,7 +72,7 @@ async fn main(_s: Spawner) { let address: Address = Address::random([0xff, 0x8f, 0x1a, 0x05, 0xe4, 0xff]); info!("our address = {:?}", address); - let mut resources: HostResources<_, DefaultPacketPool, CONNECTIONS_MAX, L2CAP_CHANNELS_MAX> = + let mut resources: HostResources = HostResources::new(); let stack = trouble_host::new(controller, &mut resources) .set_random_address(address) diff --git a/examples/qa/src/bin/ble-periodic-adv.rs b/examples/qa/src/bin/ble-periodic-adv.rs new file mode 100644 index 00000000000..1dbb6d7c2dc --- /dev/null +++ b/examples/qa/src/bin/ble-periodic-adv.rs @@ -0,0 +1,288 @@ +//! Regression / verification test for . +//! +//! Directly writes and reads HCI packets to/from the BLE controller (without a +//! BLE host stack) to verify `LE Set Periodic Advertising Data` (0x203F) with a +//! non-empty payload and `Operation = 0x03` (Complete periodic advertising data). +//! +//! In #6506, `bt-hci`'s `WriteHci::write_hci_async` for `&[u8]` encoded the +//! `Advertising_Data_Length` parameter as `self.size()` (`len + 1`) instead of +//! `self.len()`, causing the controller to reject the command with status `0x12` +//! (`Invalid HCI Command Parameters`) because the total parameter length did not +//! match `3 + Advertising_Data_Length`. + +//% FEATURES: esp-radio esp-radio/ble esp-radio/unstable esp-hal/unstable +//% CHIP_FILTER: bt_driver_supported && bt_controller == "npl" + +#![no_std] +#![no_main] + +use esp_alloc as _; +use esp_backtrace as _; +use esp_hal::{clock::CpuClock, delay::Delay, timer::timg::TimerGroup}; +use esp_println::println; +use esp_radio::ble::controller::BleConnector; + +esp_bootloader_esp_idf::esp_app_desc!(); + +const H4_TYPE_COMMAND: u8 = 0x01; +const H4_TYPE_EVENT: u8 = 0x04; +const EVT_COMMAND_COMPLETE: u8 = 0x0E; + +const OGF_CONTROLLER_BASEBAND: u8 = 0x03; +const OGF_LE_CONTROLLER: u8 = 0x08; + +const OCF_RESET: u16 = 0x0003; +const OCF_LE_SET_ADV_SET_RANDOM_ADDR: u16 = 0x0035; +const OCF_LE_SET_EXT_ADV_PARAMS: u16 = 0x0036; +const OCF_LE_SET_EXT_ADV_DATA: u16 = 0x0037; +const OCF_LE_SET_EXT_ADV_ENABLE: u16 = 0x0039; +const OCF_LE_SET_PERIODIC_ADV_PARAMS: u16 = 0x003E; +const OCF_LE_SET_PERIODIC_ADV_DATA: u16 = 0x003F; +const OCF_LE_SET_PERIODIC_ADV_ENABLE: u16 = 0x0040; + +const fn opcode(ogf: u8, ocf: u16) -> [u8; 2] { + (((ogf as u16) << 10) | ocf).to_le_bytes() +} + +fn read_all(connector: &mut BleConnector, mut buf: &mut [u8]) { + while !buf.is_empty() { + let len = connector.read(buf).unwrap(); + buf = &mut buf[len..]; + } +} + +fn read_packet(connector: &mut BleConnector, buf: &mut [u8]) -> usize { + read_all(connector, &mut buf[..3]); + let payload_len = buf[2] as usize; + read_all(connector, &mut buf[3..][..payload_len]); + 3 + payload_len +} + +/// Sends an HCI command and waits for its `Command Complete` event, returning the status byte. +fn send_cmd(connector: &mut BleConnector, name: &str, ogf: u8, ocf: u16, params: &[u8]) -> u8 { + let op = opcode(ogf, ocf); + let mut cmd = [0u8; 260]; + cmd[0] = H4_TYPE_COMMAND; + cmd[1] = op[0]; + cmd[2] = op[1]; + cmd[3] = params.len() as u8; + cmd[4..][..params.len()].copy_from_slice(params); + + connector.write(&cmd[..4 + params.len()]).unwrap(); + + let mut evt = [0u8; 260]; + loop { + let len = read_packet(connector, &mut evt); + if len >= 7 + && evt[0] == H4_TYPE_EVENT + && evt[1] == EVT_COMMAND_COMPLETE + && evt[4] == op[0] + && evt[5] == op[1] + { + println!( + "[{}] (0x{:04x}) complete: status=0x{:02x} payload={:02x?}", + name, + u16::from_le_bytes(op), + evt[6], + &evt[3..len] + ); + return evt[6]; + } + } +} + +#[esp_hal::main] +fn main() -> ! { + esp_println::logger::init_logger_from_env(); + let peripherals = esp_hal::init(esp_hal::Config::default().with_cpu_clock(CpuClock::max())); + + esp_alloc::heap_allocator!(size: 72 * 1024); + + let timg0 = TimerGroup::new(peripherals.TIMG0); + esp_rtos::start(timg0.timer0); + + let config = esp_radio::ble::Config::default().with_ext_adv_max_size(255); + let mut connector = BleConnector::new(peripherals.BT, config).unwrap(); + + // 1. HCI Reset + let status = send_cmd( + &mut connector, + "HCI Reset", + OGF_CONTROLLER_BASEBAND, + OCF_RESET, + &[], + ); + assert_eq!(status, 0x00, "HCI Reset failed"); + + // 2. LE Set Extended Advertising Parameters (7.8.53) + // Adv_Handle = 0, Adv_Event_Properties = 0x0000 (non-connectable, non-scannable), + // Primary_Adv_Interval_Min = 0x0000A0 (100ms), Primary_Adv_Interval_Max = 0x000140 (200ms), + // Primary_Adv_Channel_Map = 0x07 (all), Own_Address_Type = 0x01 (Random), + // Peer_Address_Type = 0x00, Peer_Address = [0; 6], Adv_Filter_Policy = 0x00, + // Adv_Tx_Power = 0x7F (no preference), Primary_Adv_PHY = 0x01 (LE 1M), + // Secondary_Adv_Max_Skip = 0x00, Secondary_Adv_PHY = 0x01 (LE 1M), + // Adv_SID = 0x00, Scan_Request_Notification_Enable = 0x00 + let ext_adv_params = [ + 0x00, // Advertising_Handle + 0x00, 0x00, // Advertising_Event_Properties + 0xA0, 0x00, 0x00, // Primary_Advertising_Interval_Min (160 * 0.625ms = 100ms) + 0x40, 0x01, 0x00, // Primary_Advertising_Interval_Max (320 * 0.625ms = 200ms) + 0x07, // Primary_Advertising_Channel_Map + 0x01, // Own_Address_Type (Random) + 0x00, // Peer_Address_Type + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Peer_Address + 0x00, // Advertising_Filter_Policy + 0x7F, // Advertising_Tx_Power + 0x01, // Primary_Advertising_PHY (LE 1M) + 0x00, // Secondary_Advertising_Max_Skip + 0x01, // Secondary_Advertising_PHY (LE 1M) + 0x00, // Advertising_SID + 0x00, // Scan_Request_Notification_Enable + ]; + let status = send_cmd( + &mut connector, + "LE Set Extended Advertising Parameters", + OGF_LE_CONTROLLER, + OCF_LE_SET_EXT_ADV_PARAMS, + &ext_adv_params, + ); + assert_eq!( + status, 0x00, + "LE Set Extended Advertising Parameters failed" + ); + + // 3. LE Set Advertising Set Random Address (7.8.52) + let rand_addr_params = [ + 0x00, // Advertising_Handle + 0xFF, 0x8F, 0x1A, 0x05, 0xE4, 0xFF, // Random_Address (static random: top 2 bits = 11) + ]; + let status = send_cmd( + &mut connector, + "LE Set Advertising Set Random Address", + OGF_LE_CONTROLLER, + OCF_LE_SET_ADV_SET_RANDOM_ADDR, + &rand_addr_params, + ); + assert_eq!(status, 0x00, "LE Set Advertising Set Random Address failed"); + + // 4. LE Set Extended Advertising Data (7.8.54) so the device shows up with a name in a BLE + // scanner app ("ESP Periodic Adv"). + // AD Structure 1: Flags (0x01) = LE General Discoverable (0x02) | BR/EDR Not Supported (0x04) + // AD Structure 2: Complete Local Name (0x09) = "ESP Periodic Adv" + const LOCAL_NAME: &[u8] = b"ESP Periodic Adv"; + let mut ext_adv_data = [0u8; 4 + 3 + 2 + LOCAL_NAME.len()]; + ext_adv_data[0] = 0x00; // Advertising_Handle + ext_adv_data[1] = 0x03; // Operation (Complete extended advertising data) + ext_adv_data[2] = 0x01; // Fragment_Preference (Should not fragment) + ext_adv_data[3] = (3 + 2 + LOCAL_NAME.len()) as u8; // Advertising_Data_Length + ext_adv_data[4..9].copy_from_slice(&[ + 0x02, + 0x01, + 0x06, // Flags: LE General Discoverable | BR/EDR Not Supported + (1 + LOCAL_NAME.len()) as u8, + 0x09, // Complete Local Name + ]); + ext_adv_data[9..].copy_from_slice(LOCAL_NAME); + let status = send_cmd( + &mut connector, + "LE Set Extended Advertising Data", + OGF_LE_CONTROLLER, + OCF_LE_SET_EXT_ADV_DATA, + &ext_adv_data, + ); + assert_eq!(status, 0x00, "LE Set Extended Advertising Data failed"); + + // 5. LE Set Periodic Advertising Parameters (7.8.61) + // Adv_Handle = 0, Periodic_Adv_Interval_Min = 0x0050 (100ms), + // Periodic_Adv_Interval_Max = 0x0050 (100ms), Periodic_Adv_Properties = 0x0000 + let per_adv_params = [ + 0x00, // Advertising_Handle + 0x50, 0x00, // Periodic_Advertising_Interval_Min (80 * 1.25ms = 100ms) + 0x50, 0x00, // Periodic_Advertising_Interval_Max (80 * 1.25ms = 100ms) + 0x00, 0x00, // Periodic_Advertising_Properties + ]; + let status = send_cmd( + &mut connector, + "LE Set Periodic Advertising Parameters", + OGF_LE_CONTROLLER, + OCF_LE_SET_PERIODIC_ADV_PARAMS, + &per_adv_params, + ); + assert_eq!( + status, 0x00, + "LE Set Periodic Advertising Parameters failed" + ); + + // 6. LE Set Periodic Advertising Data (7.8.62) + // AD Structure: Manufacturer Specific Data (0xFF), Company ID 0xFFFF, counter byte + let adv_payload = [0x04, 0xFF, 0xFF, 0xFF, 0x00]; + let mut per_adv_data = [0u8; 3 + 5]; + per_adv_data[0] = 0x00; // Advertising_Handle + per_adv_data[1] = 0x03; // Operation (Complete periodic advertising data) + per_adv_data[2] = adv_payload.len() as u8; // Advertising_Data_Length + per_adv_data[3..].copy_from_slice(&adv_payload); + + let status = send_cmd( + &mut connector, + "LE Set Periodic Advertising Data", + OGF_LE_CONTROLLER, + OCF_LE_SET_PERIODIC_ADV_DATA, + &per_adv_data, + ); + assert_eq!(status, 0x00, "LE Set Periodic Advertising Data failed"); + + // 7. LE Set Periodic Advertising Enable (7.8.63) + let per_adv_enable = [ + 0x01, // Enable = 0x01 (Periodic advertising enabled) + 0x00, // Advertising_Handle + ]; + let status = send_cmd( + &mut connector, + "LE Set Periodic Advertising Enable", + OGF_LE_CONTROLLER, + OCF_LE_SET_PERIODIC_ADV_ENABLE, + &per_adv_enable, + ); + assert_eq!(status, 0x00, "LE Set Periodic Advertising Enable failed"); + + // 8. LE Set Extended Advertising Enable (7.8.56) + let ext_adv_enable = [ + 0x01, // Enable = 0x01 + 0x01, // Number_of_Sets = 1 + 0x00, // Advertising_Handle[0] = 0 + 0x00, 0x00, // Duration[0] = 0 (no duration limit) + 0x00, // Max_Extended_Advertising_Events[0] = 0 + ]; + let status = send_cmd( + &mut connector, + "LE Set Extended Advertising Enable", + OGF_LE_CONTROLLER, + OCF_LE_SET_EXT_ADV_ENABLE, + &ext_adv_enable, + ); + assert_eq!(status, 0x00, "LE Set Extended Advertising Enable failed"); + + println!( + "PASS: Advertising as \"ESP Periodic Adv\" (FF:E4:05:1A:8F:FF), updating periodic payload every second..." + ); + + // 9. Continuously update periodic advertising data while advertising + let delay = Delay::new(); + let mut counter: u8 = 0; + loop { + delay.delay_millis(1000); + counter = counter.wrapping_add(1); + per_adv_data[7] = counter; + let status = send_cmd( + &mut connector, + "LE Set Periodic Advertising Data (update)", + OGF_LE_CONTROLLER, + OCF_LE_SET_PERIODIC_ADV_DATA, + &per_adv_data, + ); + assert_eq!( + status, 0x00, + "Updating LE Periodic Advertising Data while enabled failed" + ); + } +} diff --git a/qa-test/src/bin/ble_reinit_scan.rs b/examples/qa/src/bin/ble-reinit-scan.rs similarity index 96% rename from qa-test/src/bin/ble_reinit_scan.rs rename to examples/qa/src/bin/ble-reinit-scan.rs index da9d2c47692..2c99e8f77d7 100644 --- a/qa-test/src/bin/ble_reinit_scan.rs +++ b/examples/qa/src/bin/ble-reinit-scan.rs @@ -58,7 +58,7 @@ async fn main(_spawner: Spawner) { esp_alloc::heap_allocator!(size: 72 * 1024); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); println!( "Waiting {}s (baseline power, radio never initialized)", @@ -83,7 +83,6 @@ async fn main(_spawner: Spawner) { let address: Address = Address::random([0xff, 0x8f, 0x1b, 0x05, 0xe4, 0xff]); let mut resources: HostResources< - _, DefaultPacketPool, CONNECTIONS_MAX, L2CAP_CHANNELS_MAX, @@ -91,11 +90,11 @@ async fn main(_spawner: Spawner) { let stack = trouble_host::new(controller, &mut resources) .set_random_address(address) .build(); - let central = stack.central(); + let mut central = stack.central(); let mut runner = stack.runner(); let printer = Printer; - let mut scanner = Scanner::new(central); + let mut scanner = Scanner::new(&mut central); println!( "Iteration {iteration}: active for {}s", ACTIVE_PHASE.as_secs() diff --git a/qa-test/src/bin/embassy_adc_async_abstraction.rs b/examples/qa/src/bin/embassy-adc-async-abstraction.rs similarity index 88% rename from qa-test/src/bin/embassy_adc_async_abstraction.rs rename to examples/qa/src/bin/embassy-adc-async-abstraction.rs index 43c31296555..e89790f4480 100644 --- a/qa-test/src/bin/embassy_adc_async_abstraction.rs +++ b/examples/qa/src/bin/embassy-adc-async-abstraction.rs @@ -4,9 +4,7 @@ //! PINS //! GPIO4 for ADC1, GPIO20 on the ESP32-P4 -// The ESP32-S31 is excluded because this example calibrates the pin, and no -// calibration scheme is implemented for that chip. -//% CHIP_FILTER: adc_driver_supported && !esp32 && !esp32s31 +//% CHIP_FILTER: adc_basic_calibration #![no_std] #![no_main] @@ -65,7 +63,7 @@ where MC: Converter, { async fn measure(&mut self) -> u16 { - let raw_value = self.adc.read_oneshot(&mut self.pin).await; + let raw_value = self.adc.read_oneshot(&mut self.pin).await.unwrap(); MC::raw_to_metering(raw_value) } @@ -85,7 +83,7 @@ async fn main(_spawner: Spawner) { esp_println::logger::init_logger_from_env(); let peripherals = esp_hal::init(esp_hal::Config::default()); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let mut adc1_config = AdcConfig::new(); let analog_pin1 = cfg_select! { @@ -96,8 +94,11 @@ async fn main(_spawner: Spawner) { .enable_pin_with_cal::<_, AdcCalBasic>>( analog_pin1, Attenuation::_11dB, - ); - let adc1 = Adc::new(peripherals.ADC1, adc1_config).into_async(); + ) + .unwrap(); + let adc1 = Adc::new(peripherals.ADC1, adc1_config) + .unwrap() + .into_async(); let mut id = AdcSensor::<_, _, _, Identity>::new(adc1, pin1); let delay = Delay::new(); diff --git a/qa-test/src/bin/embassy_adc.rs b/examples/qa/src/bin/embassy-adc.rs similarity index 62% rename from qa-test/src/bin/embassy_adc.rs rename to examples/qa/src/bin/embassy-adc.rs index 30c8a4ab3bf..fd714f2d3c5 100644 --- a/qa-test/src/bin/embassy_adc.rs +++ b/examples/qa/src/bin/embassy-adc.rs @@ -2,7 +2,6 @@ //! //! PINS //! GPIO4 for ADC1, GPIO43 on the ESP32-S31, GPIO20 on the ESP32-P4 -//! ONLY ESP32-C3: GPIO5 for ADC2 //! //! Note that the S31 ADC is differential with a maximum raw value of 4393, //! so measuring GND will return about 2198. @@ -14,7 +13,7 @@ use embassy_executor::Spawner; use esp_backtrace as _; -#[cfg(not(feature = "esp32s31"))] +#[cfg(adc_line_calibration)] use esp_hal::analog::adc::AdcCalLine; use esp_hal::{ analog::adc::{Adc, AdcConfig, Attenuation}, @@ -30,7 +29,7 @@ async fn main(_spawner: Spawner) { esp_println::logger::init_logger_from_env(); let peripherals = esp_hal::init(esp_hal::Config::default()); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let mut adc1_config = AdcConfig::new(); @@ -42,38 +41,24 @@ async fn main(_spawner: Spawner) { // The ESP32-S31 has no calibration scheme implemented. let mut pin1 = cfg_select! { - feature = "esp32s31" => adc1_config.enable_pin(adc1_pin, Attenuation::_11dB), - _ => adc1_config + adc_line_calibration => adc1_config .enable_pin_with_cal::<_, AdcCalLine>>( adc1_pin, Attenuation::_11dB, - ), + ) + .unwrap(), + _ => adc1_config.enable_pin(adc1_pin, Attenuation::_11dB), }; - let mut adc1 = Adc::new(peripherals.ADC1, adc1_config).into_async(); - - cfg_select! { - feature = "esp32c3" => { - let mut adc2_config = AdcConfig::new(); - let analog_pin2 = peripherals.GPIO5; - let mut pin2 = adc2_config.enable_pin(analog_pin2, Attenuation::_11dB); - let mut adc2 = Adc::new(peripherals.ADC2, adc2_config).into_async(); - } - _ => {} - } + let mut adc1 = Adc::new(peripherals.ADC1, adc1_config) + .unwrap() + .into_async(); let delay = Delay::new(); loop { - let adc1_value: u16 = adc1.read_oneshot(&mut pin1).await; + let adc1_value: u16 = adc1.read_oneshot(&mut pin1).await.unwrap(); println!("ADC1 value: {}", adc1_value); - cfg_select! { - feature = "esp32c3" => { - let adc2_value: u16 = adc2.read_oneshot(&mut pin2).await; - println!("ADC2 value: {}", adc2_value); - } - _ => {} - } delay.delay_millis(1000); } } diff --git a/qa-test/src/bin/embassy_executor_benchmark.rs b/examples/qa/src/bin/embassy-executor-benchmark.rs similarity index 98% rename from qa-test/src/bin/embassy_executor_benchmark.rs rename to examples/qa/src/bin/embassy-executor-benchmark.rs index 2bc67c9573a..bb10946f9bc 100644 --- a/qa-test/src/bin/embassy_executor_benchmark.rs +++ b/examples/qa/src/bin/embassy-executor-benchmark.rs @@ -88,7 +88,7 @@ async fn main(spawner: Spawner) { Hooks::init(); let systimer = SystemTimer::new(peripherals.SYSTIMER); - esp_rtos::start(systimer.alarm0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(systimer.alarm0); println!("Embassy initialized!"); spawner.spawn(TASK1.spawn(|| Task1 {}).unwrap()); diff --git a/qa-test/src/bin/embassy_i2c_bmp180_calibration_data.rs b/examples/qa/src/bin/embassy-i2c-bmp180-calibration-data.rs similarity index 96% rename from qa-test/src/bin/embassy_i2c_bmp180_calibration_data.rs rename to examples/qa/src/bin/embassy-i2c-bmp180-calibration-data.rs index 9fa906faeab..5a28c6ab59a 100644 --- a/qa-test/src/bin/embassy_i2c_bmp180_calibration_data.rs +++ b/examples/qa/src/bin/embassy-i2c-bmp180-calibration-data.rs @@ -31,7 +31,7 @@ esp_bootloader_esp_idf::esp_app_desc!(); async fn main(_spawner: Spawner) { let peripherals = esp_hal::init(esp_hal::Config::default()); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let mut i2c = I2c::new( peripherals.I2C0, diff --git a/qa-test/src/bin/embassy_i2c.rs b/examples/qa/src/bin/embassy-i2c.rs similarity index 95% rename from qa-test/src/bin/embassy_i2c.rs rename to examples/qa/src/bin/embassy-i2c.rs index 0035a7788b5..1119f8eac0a 100644 --- a/qa-test/src/bin/embassy_i2c.rs +++ b/examples/qa/src/bin/embassy-i2c.rs @@ -31,7 +31,7 @@ esp_bootloader_esp_idf::esp_app_desc!(); async fn main(_spawner: Spawner) { let peripherals = esp_hal::init(esp_hal::Config::default()); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let i2c0 = I2c::new( peripherals.I2C0, diff --git a/qa-test/src/bin/embassy_i2s_pdm_rx.rs b/examples/qa/src/bin/embassy-i2s-pdm-rx.rs similarity index 93% rename from qa-test/src/bin/embassy_i2s_pdm_rx.rs rename to examples/qa/src/bin/embassy-i2s-pdm-rx.rs index 110152cb0aa..6db704e651f 100644 --- a/qa-test/src/bin/embassy_i2s_pdm_rx.rs +++ b/examples/qa/src/bin/embassy-i2s-pdm-rx.rs @@ -10,8 +10,9 @@ //! 3V3 ────────────── VCC //! ``` //! -//! Reads 16 kHz mono PCM on chips with a hardware PDM2PCM filter (ESP32, ESP32-S3, …), -//! or 2.048 MHz raw PDM oversampling on chips without one (ESP32-C6, …), matching ESP-IDF. +//! Reads 16 kHz mono PCM on chips with a hardware PDM2PCM filter (ESP32, ESP32-S3, +//! ESP32-S31, …), or 2.048 MHz raw PDM oversampling on chips without one +//! (ESP32-C6, …), matching ESP-IDF. //! Values are printed as `i16` like IDF's example — on raw-PDM targets that means line //! bitstream words, not decoded PCM. @@ -71,7 +72,7 @@ async fn main(_spawner: Spawner) { let peripherals = esp_hal::init(esp_hal::Config::default()); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let dma_channel = cfg_select! { i2s_dma_engine = "I2S_DMA" => peripherals.DMA_I2S0, @@ -79,7 +80,7 @@ async fn main(_spawner: Spawner) { }; cfg_select! { - any(feature = "esp32", feature = "esp32s3", feature = "esp32p4") => { + i2s_supports_pdm2pcm => { println!("embassy_i2s_pdm_rx: PDM RX in PCM format"); } _ => { @@ -88,7 +89,7 @@ async fn main(_spawner: Spawner) { } let rx_cfg = cfg_select! { - any(feature = "esp32", feature = "esp32s3", feature = "esp32p4") => { + i2s_supports_pdm2pcm => { PdmRxConfig::new_pcm_default(Rate::from_hz(16_000), PdmSlotMode::Mono) } _ => PdmRxConfig::new_raw_default(Rate::from_hz(2_048_000), PdmSlotMode::Mono), diff --git a/qa-test/src/bin/embassy_i2s_pdm.rs b/examples/qa/src/bin/embassy-i2s-pdm.rs similarity index 99% rename from qa-test/src/bin/embassy_i2s_pdm.rs rename to examples/qa/src/bin/embassy-i2s-pdm.rs index d78fa97addf..d1ab6fd9ea3 100644 --- a/qa-test/src/bin/embassy_i2s_pdm.rs +++ b/examples/qa/src/bin/embassy-i2s-pdm.rs @@ -165,7 +165,7 @@ async fn main(_spawner: Spawner) { let peripherals = esp_hal::init(esp_hal::Config::default()); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let dma_channel = cfg_select! { i2s_dma_engine = "I2S_DMA" => peripherals.DMA_I2S0, diff --git a/qa-test/src/bin/embassy_i2s_read.rs b/examples/qa/src/bin/embassy-i2s-read.rs similarity index 97% rename from qa-test/src/bin/embassy_i2s_read.rs rename to examples/qa/src/bin/embassy-i2s-read.rs index 2be77cdf9a4..4cb906a0534 100644 --- a/qa-test/src/bin/embassy_i2s_read.rs +++ b/examples/qa/src/bin/embassy-i2s-read.rs @@ -34,7 +34,7 @@ async fn main(_spawner: Spawner) { println!("Init!"); let peripherals = esp_hal::init(esp_hal::Config::default()); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let dma_channel = cfg_select! { i2s_dma_engine = "I2S_DMA" => peripherals.DMA_I2S0, diff --git a/qa-test/src/bin/embassy_i2s_sound.rs b/examples/qa/src/bin/embassy-i2s-sound.rs similarity index 98% rename from qa-test/src/bin/embassy_i2s_sound.rs rename to examples/qa/src/bin/embassy-i2s-sound.rs index 7b67dbe0c05..26f2e5e5a59 100644 --- a/qa-test/src/bin/embassy_i2s_sound.rs +++ b/examples/qa/src/bin/embassy-i2s-sound.rs @@ -55,7 +55,7 @@ async fn main(_spawner: Spawner) { println!("Init!"); let peripherals = esp_hal::init(esp_hal::Config::default()); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let dma_channel = cfg_select! { i2s_dma_engine = "I2S_DMA" => peripherals.DMA_I2S0, diff --git a/qa-test/src/bin/embassy_scan_after_sleep.rs b/examples/qa/src/bin/embassy-scan-after-sleep.rs similarity index 90% rename from qa-test/src/bin/embassy_scan_after_sleep.rs rename to examples/qa/src/bin/embassy-scan-after-sleep.rs index 9d07152cd50..d2785c22abf 100644 --- a/qa-test/src/bin/embassy_scan_after_sleep.rs +++ b/examples/qa/src/bin/embassy-scan-after-sleep.rs @@ -1,7 +1,5 @@ -// ESP32 has some serious (light-)sleep issues - so don't include it here until that is fixed. - //% FEATURES: esp-radio esp-radio/wifi esp-hal/unstable -//% CHIP_FILTER: wifi_driver_supported && sleep_driver_supported && !esp32 +//% CHIP_FILTER: wifi_driver_supported && sleep_driver_supported #![no_std] #![no_main] @@ -17,6 +15,7 @@ use esp_hal::{ timer::timg::TimerGroup, }; use esp_println::println; +use qa_test::DRAM2_UNINIT_SIZE; esp_bootloader_esp_idf::esp_app_desc!(); @@ -28,11 +27,11 @@ async fn main(_spawner: Spawner) { let peripherals = esp_hal::init(esp_hal::Config::default()); // Provide a heap for components that allocate (esp-rtos/esp-radio, etc.) - esp_alloc::heap_allocator!(#[esp_hal::ram(reclaimed)] size: 64 * 1024); + esp_alloc::heap_allocator!(#[esp_hal::ram(reclaimed)] size: DRAM2_UNINIT_SIZE); // Preempt scheduler (WiFi) let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let delay = esp_hal::delay::Delay::new(); delay.delay_millis(100); diff --git a/examples/qa/src/bin/embassy-twai-interrupt-executor.rs b/examples/qa/src/bin/embassy-twai-interrupt-executor.rs new file mode 100644 index 00000000000..df0e0345a6a --- /dev/null +++ b/examples/qa/src/bin/embassy-twai-interrupt-executor.rs @@ -0,0 +1,102 @@ +//! TWAI: `transmit_async` from a task on a higher priority executor +//! +//! The transmitting task runs on an `InterruptExecutor` at priority 2, above +//! the TWAI interrupt (esp-hal's default priority 1), so a task the interrupt +//! handler wakes runs before the handler returns. The handler must not undo +//! what that task does meanwhile: when it did, the transmit interrupt the next +//! frame had just enabled was disabled again, and every frame after the first +//! waited for some other wake-up (esp-rs/esp-hal#6421). +//! +//! Self-test mode with TX and RX on the same pin, so nothing needs to be +//! connected: the controller sends without an acknowledgement. The test sends +//! 100 frames back to back and prints PASS when they all go out within +//! 100 ms (about 10 ms of bus time at 1 Mbit/s), FAIL otherwise. +//! +//! The following pins are used: +//! - TX/RX => GPIO2 + +//% CHIP_FILTER: twai_driver_supported + +#![no_std] +#![no_main] + +use embassy_executor::Spawner; +use embassy_time::{Duration, Instant, Timer, with_timeout}; +use esp_backtrace as _; +use esp_hal::{ + Blocking, + interrupt::Priority, + timer::timg::TimerGroup, + twai::{BaudRate, EspTwaiFrame, StandardId, TwaiConfiguration, TwaiMode}, +}; +use esp_println::println; +use esp_rtos::embassy::InterruptExecutor; +use static_cell::StaticCell; + +esp_bootloader_esp_idf::esp_app_desc!(); + +const FRAMES: usize = 100; +const DEADLINE: Duration = Duration::from_millis(100); + +static EXECUTOR: StaticCell> = StaticCell::new(); + +#[embassy_executor::task] +async fn transmit(config: TwaiConfiguration<'static, Blocking>) { + let mut twai = config.into_async().start(); + let frame = EspTwaiFrame::new(StandardId::new(0x123).unwrap(), &[1, 2, 3, 4]).unwrap(); + + let start = Instant::now(); + let mut sent = 0; + while sent < FRAMES { + // A frame whose completion wakes nobody is still picked up when the + // timeout's own timer wakes the task: a stall shows up as ~50 ms a + // frame, not as a hang + match with_timeout(Duration::from_millis(50), twai.transmit_async(&frame)).await { + Ok(Ok(())) => sent += 1, + Ok(Err(e)) => { + println!("FAIL: frame {} not sent: {:?}", sent, e); + return; + } + Err(_) => { + println!("FAIL: frame {} not sent within 50 ms", sent); + return; + } + } + } + let took = start.elapsed(); + + if took <= DEADLINE { + println!("PASS: {} frames in {} ms", sent, took.as_millis()); + } else { + println!( + "FAIL: {} frames took {} ms, expected at most {} ms", + sent, + took.as_millis(), + DEADLINE.as_millis() + ); + } +} + +#[esp_hal::main] +async fn main(_spawner: Spawner) { + let peripherals = esp_hal::init(esp_hal::Config::default()); + let timg0 = TimerGroup::new(peripherals.TIMG0); + esp_rtos::start(timg0.timer0); + + let (rx, tx) = unsafe { peripherals.GPIO2.split() }; + let config = TwaiConfiguration::new( + peripherals.TWAI0, + rx, + tx, + BaudRate::B1000K, + TwaiMode::SelfTest, + ); + + let executor = EXECUTOR.init(InterruptExecutor::new(peripherals.FROM_CPU_INTR2)); + let spawner = executor.start(Priority::Priority2); + spawner.spawn(transmit(config).unwrap()); + + loop { + Timer::after(Duration::from_secs(1)).await; + } +} diff --git a/qa-test/src/bin/embassy_wifi_bench.rs b/examples/qa/src/bin/embassy-wifi-bench.rs similarity index 98% rename from qa-test/src/bin/embassy_wifi_bench.rs rename to examples/qa/src/bin/embassy-wifi-bench.rs index 37ef49f4453..a426e10fcdb 100644 --- a/qa-test/src/bin/embassy_wifi_bench.rs +++ b/examples/qa/src/bin/embassy-wifi-bench.rs @@ -35,6 +35,7 @@ use esp_radio::wifi::{ WifiController, sta::StationConfig, }; +use qa_test::DRAM2_UNINIT_SIZE; esp_bootloader_esp_idf::esp_app_desc!(); @@ -71,12 +72,12 @@ async fn main(spawner: Spawner) -> ! { esp_alloc::heap_allocator!(size: 32 * 1024); // add some more RAM - esp_alloc::heap_allocator!(#[ram(reclaimed)] size: 64 * 1024); + esp_alloc::heap_allocator!(#[ram(reclaimed)] size: DRAM2_UNINIT_SIZE); let server_address: Ipv4Addr = HOST_IP.parse().expect("Invalid HOST_IP address"); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let station_config = Config::Station( StationConfig::default() diff --git a/qa-test/src/bin/embassy_wifi_csi.rs b/examples/qa/src/bin/embassy-wifi-csi.rs similarity index 96% rename from qa-test/src/bin/embassy_wifi_csi.rs rename to examples/qa/src/bin/embassy-wifi-csi.rs index df2f686ed6b..77d87619eb9 100644 --- a/qa-test/src/bin/embassy_wifi_csi.rs +++ b/examples/qa/src/bin/embassy-wifi-csi.rs @@ -25,6 +25,7 @@ use esp_radio::wifi::{ scan::ScanConfig, sta::StationConfig, }; +use qa_test::DRAM2_UNINIT_SIZE; esp_bootloader_esp_idf::esp_app_desc!(); // When you are okay with using a nightly compiler it's better to use https://docs.rs/static_cell/2.1.0/static_cell/macro.make_static.html @@ -46,11 +47,11 @@ async fn main(spawner: Spawner) -> ! { let config = esp_hal::Config::default().with_cpu_clock(CpuClock::max()); let peripherals = esp_hal::init(config); - esp_alloc::heap_allocator!(#[ram(reclaimed)] size: 64 * 1024); + esp_alloc::heap_allocator!(#[ram(reclaimed)] size: DRAM2_UNINIT_SIZE); esp_alloc::heap_allocator!(size: 36 * 1024); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let station_config = Config::Station( StationConfig::default() diff --git a/qa-test/src/bin/embassy_wifi_drop.rs b/examples/qa/src/bin/embassy-wifi-drop.rs similarity index 95% rename from qa-test/src/bin/embassy_wifi_drop.rs rename to examples/qa/src/bin/embassy-wifi-drop.rs index 89dc5fa17c4..daa817a8307 100644 --- a/qa-test/src/bin/embassy_wifi_drop.rs +++ b/examples/qa/src/bin/embassy-wifi-drop.rs @@ -12,6 +12,7 @@ use esp_backtrace as _; use esp_hal::{clock::CpuClock, ram, timer::timg::TimerGroup}; use esp_println::println; use esp_radio::wifi::{AuthenticationMethodConfig, Config, ControllerConfig, sta::StationConfig}; +use qa_test::DRAM2_UNINIT_SIZE; esp_bootloader_esp_idf::esp_app_desc!(); @@ -26,10 +27,10 @@ async fn main(_spawner: Spawner) { esp_alloc::heap_allocator!(size: 32 * 1024); // add some more RAM - esp_alloc::heap_allocator!(#[ram(reclaimed)] size: 64 * 1024); + esp_alloc::heap_allocator!(#[ram(reclaimed)] size: DRAM2_UNINIT_SIZE); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let mut wifi = peripherals.WIFI; { diff --git a/qa-test/src/bin/embassy_wifi_i2s.rs b/examples/qa/src/bin/embassy-wifi-i2s.rs similarity index 97% rename from qa-test/src/bin/embassy_wifi_i2s.rs rename to examples/qa/src/bin/embassy-wifi-i2s.rs index 5c206c6785d..aef80943d5e 100644 --- a/qa-test/src/bin/embassy_wifi_i2s.rs +++ b/examples/qa/src/bin/embassy-wifi-i2s.rs @@ -29,6 +29,7 @@ use esp_radio::wifi::{ WifiController, sta::StationConfig, }; +use qa_test::DRAM2_UNINIT_SIZE; use static_cell::StaticCell; esp_bootloader_esp_idf::esp_app_desc!(); @@ -140,11 +141,11 @@ async fn main(spawner: Spawner) { let peripherals = esp_hal::init(esp_hal::Config::default()); // Provide a heap for components that allocate (esp-rtos/esp-radio, etc.) - esp_alloc::heap_allocator!(#[ram(reclaimed)] size: 64 * 1024); + esp_alloc::heap_allocator!(#[ram(reclaimed)] size: DRAM2_UNINIT_SIZE); // Preempt scheduler (WiFi) let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); esp_rtos::CurrentThreadHandle::get().set_priority(30); diff --git a/qa-test/src/bin/embassy_wifi_stress.rs b/examples/qa/src/bin/embassy-wifi-stress.rs similarity index 97% rename from qa-test/src/bin/embassy_wifi_stress.rs rename to examples/qa/src/bin/embassy-wifi-stress.rs index f426f215025..2156c60e90e 100644 --- a/qa-test/src/bin/embassy_wifi_stress.rs +++ b/examples/qa/src/bin/embassy-wifi-stress.rs @@ -27,6 +27,7 @@ use esp_radio::wifi::{ scan::{ScanConfig, ScanTypeConfig}, sta::StationConfig, }; +use qa_test::DRAM2_UNINIT_SIZE; esp_bootloader_esp_idf::esp_app_desc!(); @@ -39,10 +40,10 @@ async fn main(_spawner: Spawner) { let mut peripherals = initialize_esp_hal(EspConfig::default().with_cpu_clock(CpuClock::max())); // only have one memory region to make it easier to spot leaks - esp_alloc::heap_allocator!(#[ram(reclaimed)] size: 64 * 1024); + esp_alloc::heap_allocator!(#[ram(reclaimed)] size: DRAM2_UNINIT_SIZE); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let mut i = 0; loop { diff --git a/qa-test/src/bin/ext_adv_scan.rs b/examples/qa/src/bin/ext-adv-scan.rs similarity index 92% rename from qa-test/src/bin/ext_adv_scan.rs rename to examples/qa/src/bin/ext-adv-scan.rs index 11bc2d11e21..882095e25fe 100644 --- a/qa-test/src/bin/ext_adv_scan.rs +++ b/examples/qa/src/bin/ext-adv-scan.rs @@ -33,7 +33,7 @@ async fn main(_s: Spawner) { esp_alloc::heap_allocator!(size: 72 * 1024); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let bluetooth = peripherals.BT; let connector = BleConnector::new(bluetooth, esp_radio::ble::Config::default()).unwrap(); @@ -45,16 +45,16 @@ async fn main(_s: Spawner) { println!("Our address = {:?}", address); - let mut resources: HostResources<_, DefaultPacketPool, CONNECTIONS_MAX, L2CAP_CHANNELS_MAX> = + let mut resources: HostResources = HostResources::new(); let stack = trouble_host::new(controller, &mut resources) .set_random_address(address) .build(); - let central = stack.central(); + let mut central = stack.central(); let mut runner = stack.runner(); let printer = Printer {}; - let mut scanner = Scanner::new(central); + let mut scanner = Scanner::new(&mut central); let _ = join(runner.run_with_handler(&printer), async { let config = ScanConfig { active: false, diff --git a/examples/qa/src/bin/flash_encrypted.rs b/examples/qa/src/bin/flash_encrypted.rs new file mode 100644 index 00000000000..0f46d942b69 --- /dev/null +++ b/examples/qa/src/bin/flash_encrypted.rs @@ -0,0 +1,120 @@ +//! Encrypted flash access on a device with flash encryption enabled. +//! +//! ATTENTION! +//! +//! Requires burned flash-encryption eFuses, an encryption-enabled second-stage +//! bootloader, and a matching partition table. Do not run this via xtask / +//! devtool. +//! +//! An encryption-enabled bootloader is larger than the default one and does not +//! fit below the usual 0x8000 partition table, so that table has to be moved. +//! This binary assumes the application image starts at 0x20000. 0xf000 is an +//! unused sector in the gap that layout leaves; it is erased as scratch. +//! +//! IF YOU HAVE NO IDEA WHAT ALL THIS MEANS, STOP HERE!!! +//! +//! `Flash::write_encrypted` can only be validated on hardware whose flash +//! encryption eFuses are burned: the ROM encrypts on write either way, but +//! `Flash::read_encrypted` only returns plaintext when the hardware decrypts. +//! HIL runners do not use encrypted boards, so this is a manual test. +//! +//! On ESP32 the ROM programs a 32-byte row of two AES blocks that share an +//! address-derived tweak. A 16-byte write at a 16- but not 32-byte aligned +//! boundary therefore has to decrypt the adjacent block and re-encrypt it to +//! the same ciphertext. Every row size and both boundary alignments are +//! covered below so that bridge is exercised. + +//% CHIP_FILTER: flash_driver_supported +//% FEATURES: unstable + +#![no_std] +#![no_main] + +use esp_backtrace as _; +use esp_hal::{ + Blocking, + flash::{Config, Error, Flash}, + main, +}; +use esp_println::println; + +esp_bootloader_esp_idf::esp_app_desc!(); + +/// Unused sector below the application image (see the crate-level docs). +const SCRATCH: u32 = 0xf000; + +/// `(offset into the sector, word count)` for every row size the driver +/// selects, at both a 32- and a 16-byte aligned offset. +const CASES: &[(u32, usize)] = &[(0, 4), (0, 8), (0, 12), (16, 4), (16, 8), (16, 12)]; + +#[main] +fn main() -> ! { + esp_println::logger::init_logger_from_env(); + let peripherals = esp_hal::init(esp_hal::Config::default()); + + assert!( + esp_hal::efuse::flash_encryption(), + "this device has no flash encryption key burned" + ); + + let mut flash = Flash::new(peripherals.FLASH, Config::default()).unwrap(); + let sector = flash.chip_info().sector_size; + + let mut plaintext = [0u32; 12]; + for (i, word) in plaintext.iter_mut().enumerate() { + *word = 0x0102_0304u32.wrapping_mul(i as u32 + 1); + } + + for &(offset, words) in CASES { + let data = &plaintext[..words]; + let len = (words * 4) as u32; + + // SAFETY: scratch is below the application image at 0x20000. + unsafe { flash.erase(SCRATCH, SCRATCH + sector).unwrap() }; + unsafe { flash.write_encrypted(SCRATCH + offset, data).unwrap() }; + + let mut plain = [0u32; 12]; + flash + .read_encrypted(SCRATCH + offset, &mut plain[..words]) + .unwrap(); + assert_eq!(data, &plain[..words], "{len} bytes at {offset} lost data"); + + let mut raw = [0u32; 12]; + flash.read(SCRATCH + offset, &mut raw[..words]).unwrap(); + assert_ne!(data, &raw[..words], "{len} bytes at {offset} not encrypted"); + + // Re-encrypting a bridged neighbor must reproduce erased flash. + if offset > 0 { + assert_erased(&mut flash, SCRATCH, offset); + } + assert_erased(&mut flash, SCRATCH + offset + len, 16); + + println!("ok: {len} bytes at offset {offset}"); + } + + assert_eq!( + unsafe { flash.write_encrypted(SCRATCH + 4, &plaintext[..4]) }, + Err(Error::NotAligned) + ); + assert_eq!( + unsafe { flash.write_encrypted(SCRATCH, &plaintext[..3]) }, + Err(Error::NotAligned) + ); + + unsafe { flash.erase(SCRATCH, SCRATCH + sector).unwrap() }; + + println!("Test passed"); + + loop {} +} + +/// Assert that up to 16 bytes of flash read back as erased. +fn assert_erased(flash: &mut Flash<'static, Blocking>, offset: u32, len: u32) { + let mut buf = [0u32; 4]; + let words = (len / 4) as usize; + flash.read(offset, &mut buf[..words]).unwrap(); + assert!( + buf[..words].iter().all(|&word| word == 0xFFFF_FFFF), + "{offset:#x} is not erased" + ); +} diff --git a/qa-test/src/bin/gpio_interrupt_latency.rs b/examples/qa/src/bin/gpio-interrupt-latency.rs similarity index 98% rename from qa-test/src/bin/gpio_interrupt_latency.rs rename to examples/qa/src/bin/gpio-interrupt-latency.rs index aadb44e8ad8..4a54c65e26b 100644 --- a/qa-test/src/bin/gpio_interrupt_latency.rs +++ b/examples/qa/src/bin/gpio-interrupt-latency.rs @@ -49,7 +49,7 @@ async fn main(spawner: Spawner) { enc_b.set_input_enable(true); let timg0 = TimerGroup::new(p.TIMG0); - esp_rtos::start(timg0.timer0, p.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); spawner.spawn(toggle(enc_a_clone, enc_b_clone, &SIGNAL).unwrap()); spawner.spawn(wait(enc_a, enc_b, &SIGNAL).unwrap()); diff --git a/qa-test/src/bin/i2c_bmp180_calibration_data.rs b/examples/qa/src/bin/i2c-bmp180-calibration-data.rs similarity index 100% rename from qa-test/src/bin/i2c_bmp180_calibration_data.rs rename to examples/qa/src/bin/i2c-bmp180-calibration-data.rs diff --git a/qa-test/src/bin/i2c_display.rs b/examples/qa/src/bin/i2c-display.rs similarity index 100% rename from qa-test/src/bin/i2c_display.rs rename to examples/qa/src/bin/i2c-display.rs diff --git a/qa-test/src/bin/i2c_ssd1306_length_test.rs b/examples/qa/src/bin/i2c-ssd1306-length-test.rs similarity index 100% rename from qa-test/src/bin/i2c_ssd1306_length_test.rs rename to examples/qa/src/bin/i2c-ssd1306-length-test.rs diff --git a/qa-test/src/bin/ieee802154_reinit_broadcast.rs b/examples/qa/src/bin/ieee802154-reinit-broadcast.rs similarity index 100% rename from qa-test/src/bin/ieee802154_reinit_broadcast.rs rename to examples/qa/src/bin/ieee802154-reinit-broadcast.rs diff --git a/qa-test/src/bin/lcd_cam_ov2640.rs b/examples/qa/src/bin/lcd-cam-ov2640.rs similarity index 99% rename from qa-test/src/bin/lcd_cam_ov2640.rs rename to examples/qa/src/bin/lcd-cam-ov2640.rs index bab0409003a..29689fc78d2 100644 --- a/qa-test/src/bin/lcd_cam_ov2640.rs +++ b/examples/qa/src/bin/lcd-cam-ov2640.rs @@ -20,7 +20,7 @@ //! - D8 => GPIO17 //! - D9 => GPIO16 -//% CHIP_FILTER: camera_driver_supported +//% CHIP_FILTER: camera_driver_supported && lcd_cam_dma_engine == "AHB_GDMA" #![no_std] #![no_main] diff --git a/examples/qa/src/bin/lcd-dpi.rs b/examples/qa/src/bin/lcd-dpi.rs new file mode 100644 index 00000000000..fd274d222c6 --- /dev/null +++ b/examples/qa/src/bin/lcd-dpi.rs @@ -0,0 +1,487 @@ +//! Drives a 16-bit parallel RGB display using the LCD_CAM peripheral. +//! +//! This example fills the screen with every color. +//! +//! Hardware setup: +//! +//! Signal | ESP32-S3-LCD-EV-Board v1.5 | ESP32-S31-Korvo-1-V1.1 +//! ---------- | -------------------------- | ---------------------- +//! LCD_VSYNC | GPIO3 | GPIO45 +//! LCD_HSYNC | GPIO46 | GPIO44 +//! LCD_DE | GPIO17 | GPIO43 +//! LCD_PCLK | GPIO9 | GPIO40 +//! LCD_DATA0 | GPIO10 | GPIO8 +//! LCD_DATA1 | GPIO11 | GPIO9 +//! LCD_DATA2 | GPIO12 | GPIO10 +//! LCD_DATA3 | GPIO13 | GPIO11 +//! LCD_DATA4 | GPIO14 | GPIO12 +//! LCD_DATA5 | GPIO21 | GPIO13 +//! LCD_DATA6 | GPIO8 | GPIO14 +//! LCD_DATA7 | GPIO18 | GPIO15 +//! LCD_DATA8 | GPIO45 | GPIO16 +//! LCD_DATA9 | GPIO38 | GPIO17 +//! LCD_DATA10 | GPIO39 | GPIO18 +//! LCD_DATA11 | GPIO40 | GPIO19 +//! LCD_DATA12 | GPIO41 | GPIO33 +//! LCD_DATA13 | GPIO42 | GPIO34 +//! LCD_DATA14 | GPIO2 | GPIO35 +//! LCD_DATA15 | GPIO1 | GPIO36 + +//% CHIP_FILTER: rgb_display_driver_supported && !esp32 + +#![no_std] +#![no_main] + +use core::iter::empty; + +use esp_backtrace as _; +use esp_hal::{ + dma_loop_buffer, + gpio::Level, + lcd_cam::{ + LcdCam, + lcd::{ + ClockMode, + Phase, + Polarity, + dpi::{Config, Dpi, Format, FrameTiming}, + }, + }, + main, + peripherals::Peripherals, + time::Rate, +}; +use esp_println::println; + +cfg_select! { + esp32s3 => { + use core::iter::once; + + use esp_hal::{ + Blocking, + delay::Delay, + gpio::{Output, OutputConfig}, + i2c::{self, master::I2c}, + }; + } + _ => {} +} + +esp_bootloader_esp_idf::esp_app_desc!(); + +#[main] +fn main() -> ! { + esp_println::logger::init_logger_from_env(); + + let peripherals: Peripherals = esp_hal::init(esp_hal::Config::default()); + + let tx_channel = cfg_select! { + lcd_cam_dma_engine = "AHB_GDMA" => peripherals.DMA_CH2, + lcd_cam_dma_engine = "AXI_GDMA" => peripherals.DMA_AXI_CH0, + }; + let lcd_cam = LcdCam::new(peripherals.LCD_CAM); + + cfg_select! { + esp32s3 => { + let i2c = I2c::new( + peripherals.I2C0, + i2c::master::Config::default().with_frequency(Rate::from_khz(400)), + ) + .unwrap() + .with_sda(peripherals.GPIO47) + .with_scl(peripherals.GPIO48); + + let mut expander = Tca9554::new(i2c); + expander.write_output_reg(0b1111_0011).unwrap(); + expander.write_direction_reg(0b1111_0001).unwrap(); + + let delay = Delay::new(); + + println!("Initialising"); + + let mut write_byte = |b: u8, is_cmd: bool| { + const SCS_BIT: u8 = 0b0000_0010; + const SCL_BIT: u8 = 0b0000_0100; + const SDA_BIT: u8 = 0b0000_1000; + + let mut output = 0b1111_0001 & !SCS_BIT; + expander.write_output_reg(output).unwrap(); + + for bit in once(!is_cmd).chain((0..8).map(|i| (b >> i) & 0b1 != 0).rev()) { + let prev = output; + if bit { + output |= SDA_BIT; + } else { + output &= !SDA_BIT; + } + if prev != output { + expander.write_output_reg(output).unwrap(); + } + + output &= !SCL_BIT; + expander.write_output_reg(output).unwrap(); + + output |= SCL_BIT; + expander.write_output_reg(output).unwrap(); + } + + output &= !SCL_BIT; + expander.write_output_reg(output).unwrap(); + + output &= !SDA_BIT; + expander.write_output_reg(output).unwrap(); + + output |= SCS_BIT; + expander.write_output_reg(output).unwrap(); + }; + + let vsync_pin = peripherals.GPIO3; + let hsync_pin = peripherals.GPIO46; + let de_pin = peripherals.GPIO17; + let pclk_pin = peripherals.GPIO9; + let data0_pin = peripherals.GPIO10; + let data1_pin = peripherals.GPIO11; + let data2_pin = peripherals.GPIO12; + let data3_pin = peripherals.GPIO13; + let data4_pin = peripherals.GPIO14; + let data5_pin = peripherals.GPIO21; + let data6_pin = peripherals.GPIO8; + let data7_pin = peripherals.GPIO18; + let data8_pin = peripherals.GPIO45; + let data9_pin = peripherals.GPIO38; + let data10_pin = peripherals.GPIO39; + let data11_pin = peripherals.GPIO40; + let data12_pin = peripherals.GPIO41; + let data13_pin = peripherals.GPIO42; + let data14_pin = peripherals.GPIO2; + let data15_pin = peripherals.GPIO1; + + let mut vsync_pin = vsync_pin; + + let vsync_must_be_high_during_setup = + Output::new(vsync_pin.reborrow(), Level::High, OutputConfig::default()); + + for &init in INIT_CMDS.iter() { + match init { + InitCmd::Cmd(cmd, args) => { + write_byte(cmd, true); + for &arg in args { + write_byte(arg, false); + } + } + InitCmd::Delay(ms) => { + delay.delay_millis(ms as _); + } + } + } + drop(vsync_must_be_high_during_setup); + + let config = Config::default() + .with_clock_mode(ClockMode { + polarity: Polarity::IdleLow, + phase: Phase::ShiftLow, + }) + .with_frequency(Rate::from_mhz(16)) + .with_format(Format { + enable_2byte_mode: true, + ..Default::default() + }) + .with_timing(FrameTiming { + horizontal_active_width: 480, + horizontal_total_width: 520, + horizontal_blank_front_porch: 10, + + vertical_active_height: 480, + vertical_total_height: 510, + vertical_blank_front_porch: 10, + + hsync_width: 10, + vsync_width: 10, + + hsync_position: 0, + }) + .with_vsync_idle_level(Level::High) + .with_hsync_idle_level(Level::High) + .with_de_idle_level(Level::Low) + .with_disable_black_region(false); + } + esp32s31 => { + let vsync_pin = peripherals.GPIO45; + let hsync_pin = peripherals.GPIO44; + let de_pin = peripherals.GPIO43; + let pclk_pin = peripherals.GPIO40; + let data0_pin = peripherals.GPIO8; + let data1_pin = peripherals.GPIO9; + let data2_pin = peripherals.GPIO10; + let data3_pin = peripherals.GPIO11; + let data4_pin = peripherals.GPIO12; + let data5_pin = peripherals.GPIO13; + let data6_pin = peripherals.GPIO14; + let data7_pin = peripherals.GPIO15; + let data8_pin = peripherals.GPIO16; + let data9_pin = peripherals.GPIO17; + let data10_pin = peripherals.GPIO18; + let data11_pin = peripherals.GPIO19; + let data12_pin = peripherals.GPIO33; + let data13_pin = peripherals.GPIO34; + let data14_pin = peripherals.GPIO35; + let data15_pin = peripherals.GPIO36; + + let config = Config::default() + .with_clock_mode(ClockMode { + polarity: Polarity::IdleLow, + phase: Phase::ShiftLow, + }) + .with_frequency(Rate::from_mhz(40)) + .with_format(Format { + enable_2byte_mode: true, + ..Default::default() + }) + .with_timing(FrameTiming { + horizontal_active_width: 800, + horizontal_total_width: 840, + horizontal_blank_front_porch: 10, + + vertical_active_height: 480, + vertical_total_height: 510, + vertical_blank_front_porch: 10, + + hsync_width: 10, + vsync_width: 10, + + hsync_position: 0, + }) + .with_vsync_idle_level(Level::High) + .with_hsync_idle_level(Level::High) + .with_de_idle_level(Level::Low) + .with_disable_black_region(false); + } + } + + let mut dma_buf = dma_loop_buffer!(2 * 16); + + let mut dpi = Dpi::new(lcd_cam.lcd, tx_channel, config) + .unwrap() + .with_vsync(vsync_pin) + .with_hsync(hsync_pin) + .with_de(de_pin) + .with_pclk(pclk_pin) + // Blue + .with_data0(data0_pin) + .with_data1(data1_pin) + .with_data2(data2_pin) + .with_data3(data3_pin) + .with_data4(data4_pin) + // Green + .with_data5(data5_pin) + .with_data6(data6_pin) + .with_data7(data7_pin) + .with_data8(data8_pin) + .with_data9(data9_pin) + .with_data10(data10_pin) + // Red + .with_data11(data11_pin) + .with_data12(data12_pin) + .with_data13(data13_pin) + .with_data14(data14_pin) + .with_data15(data15_pin); + + const MAX_RED: u16 = (1 << 5) - 1; + const MAX_GREEN: u16 = (1 << 6) - 1; + const MAX_BLUE: u16 = (1 << 5) - 1; + + fn rgb(r: u16, g: u16, b: u16) -> u16 { + (r << 11) | (g << 5) | (b << 0) + } + + let mut colors = empty() + // Start with red and gradually add green + .chain((0..=MAX_GREEN).map(|g| rgb(MAX_RED, g, 0))) + // Then remove the red + .chain((0..=MAX_RED).rev().map(|r| rgb(r, MAX_GREEN, 0))) + // Then add blue + .chain((0..=MAX_BLUE).map(|b| rgb(0, MAX_GREEN, b))) + // Then remove green + .chain((0..=MAX_GREEN).rev().map(|g| rgb(0, g, MAX_BLUE))) + // Then add red + .chain((0..=MAX_RED).map(|r| rgb(r, 0, MAX_BLUE))) + // Then remove blue + .chain((0..=MAX_BLUE).rev().map(|b| rgb(MAX_RED, 0, b))) + // Once we get we have red, and we can start again. + .cycle(); + + println!("Rendering"); + loop { + let transfer = dpi.send(false, dma_buf).map_err(|e| e.0).unwrap(); + (_, dpi, dma_buf) = transfer.wait(); + + if let Some(color) = colors.next() { + for chunk in dma_buf.chunks_mut(2) { + chunk.copy_from_slice(&color.to_le_bytes()); + } + } + } +} + +#[cfg(esp32s3)] +struct Tca9554 { + i2c: I2c<'static, Blocking>, + address: u8, +} + +#[cfg(esp32s3)] +impl Tca9554 { + pub fn new(i2c: I2c<'static, Blocking>) -> Self { + Self { i2c, address: 0x20 } + } + + pub fn write_direction_reg(&mut self, value: u8) -> Result<(), i2c::master::Error> { + self.i2c.write(self.address, &[0x03, value]) + } + + pub fn write_output_reg(&mut self, value: u8) -> Result<(), i2c::master::Error> { + self.i2c.write(self.address, &[0x01, value]) + } +} + +#[cfg(esp32s3)] +#[derive(Copy, Clone)] +enum InitCmd { + Cmd(u8, &'static [u8]), + Delay(u8), +} + +#[cfg(esp32s3)] +const INIT_CMDS: &[InitCmd] = &[ + InitCmd::Cmd(0xf0, &[0x55, 0xaa, 0x52, 0x08, 0x00]), + InitCmd::Cmd(0xf6, &[0x5a, 0x87]), + InitCmd::Cmd(0xc1, &[0x3f]), + InitCmd::Cmd(0xc2, &[0x0e]), + InitCmd::Cmd(0xc6, &[0xf8]), + InitCmd::Cmd(0xc9, &[0x10]), + InitCmd::Cmd(0xcd, &[0x25]), + InitCmd::Cmd(0xf8, &[0x8a]), + InitCmd::Cmd(0xac, &[0x45]), + InitCmd::Cmd(0xa0, &[0xdd]), + InitCmd::Cmd(0xa7, &[0x47]), + InitCmd::Cmd(0xfa, &[0x00, 0x00, 0x00, 0x04]), + InitCmd::Cmd(0x86, &[0x99, 0xa3, 0xa3, 0x51]), + InitCmd::Cmd(0xa3, &[0xee]), + InitCmd::Cmd(0xfd, &[0x3c, 0x3]), + InitCmd::Cmd(0x71, &[0x48]), + InitCmd::Cmd(0x72, &[0x48]), + InitCmd::Cmd(0x73, &[0x00, 0x44]), + InitCmd::Cmd(0x97, &[0xee]), + InitCmd::Cmd(0x83, &[0x93]), + InitCmd::Cmd(0x9a, &[0x72]), + InitCmd::Cmd(0x9b, &[0x5a]), + InitCmd::Cmd(0x82, &[0x2c, 0x2c]), + InitCmd::Cmd(0xB1, &[0x10]), + InitCmd::Cmd( + 0x6d, + &[ + 0x00, 0x1f, 0x19, 0x1a, 0x10, 0x0e, 0x0c, 0x0a, 0x02, 0x07, 0x1e, 0x1e, 0x1e, 0x1e, + 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x08, 0x01, 0x09, 0x0b, 0x0d, 0x0f, + 0x1a, 0x19, 0x1f, 0x00, + ], + ), + InitCmd::Cmd( + 0x64, + &[ + 0x38, 0x05, 0x01, 0xdb, 0x03, 0x03, 0x38, 0x04, 0x01, 0xdc, 0x03, 0x03, 0x7a, 0x7a, + 0x7a, 0x7a, + ], + ), + InitCmd::Cmd( + 0x65, + &[ + 0x38, 0x03, 0x01, 0xdd, 0x03, 0x03, 0x38, 0x02, 0x01, 0xde, 0x03, 0x03, 0x7a, 0x7a, + 0x7a, 0x7a, + ], + ), + InitCmd::Cmd( + 0x66, + &[ + 0x38, 0x01, 0x01, 0xdf, 0x03, 0x03, 0x38, 0x00, 0x01, 0xe0, 0x03, 0x03, 0x7a, 0x7a, + 0x7a, 0x7a, + ], + ), + InitCmd::Cmd( + 0x67, + &[ + 0x30, 0x01, 0x01, 0xe1, 0x03, 0x03, 0x30, 0x02, 0x01, 0xe2, 0x03, 0x03, 0x7a, 0x7a, + 0x7a, 0x7a, + ], + ), + InitCmd::Cmd( + 0x68, + &[ + 0x00, 0x08, 0x15, 0x08, 0x15, 0x7a, 0x7a, 0x08, 0x15, 0x08, 0x15, 0x7a, 0x7a, + ], + ), + InitCmd::Cmd(0x60, &[0x38, 0x08, 0x7a, 0x7a, 0x38, 0x09, 0x7a, 0x7a]), + InitCmd::Cmd(0x63, &[0x31, 0xe4, 0x7a, 0x7a, 0x31, 0xe5, 0x7a, 0x7a]), + InitCmd::Cmd(0x69, &[0x04, 0x22, 0x14, 0x22, 0x14, 0x22, 0x08]), + InitCmd::Cmd(0x6b, &[0x07]), + InitCmd::Cmd(0x7a, &[0x08, 0x13]), + InitCmd::Cmd(0x7b, &[0x08, 0x13]), + InitCmd::Cmd( + 0xd1, + &[ + 0x00, 0x00, 0x00, 0x04, 0x00, 0x12, 0x00, 0x18, 0x00, 0x21, 0x00, 0x2a, 0x00, 0x35, + 0x00, 0x47, 0x00, 0x56, 0x00, 0x90, 0x00, 0xe5, 0x01, 0x68, 0x01, 0xd5, 0x01, 0xd7, + 0x02, 0x36, 0x02, 0xa6, 0x02, 0xee, 0x03, 0x48, 0x03, 0xa0, 0x03, 0xba, 0x03, 0xc5, + 0x03, 0xd0, 0x03, 0xe0, 0x03, 0xea, 0x03, 0xfa, 0x03, 0xff, + ], + ), + InitCmd::Cmd( + 0xd2, + &[ + 0x00, 0x00, 0x00, 0x04, 0x00, 0x12, 0x00, 0x18, 0x00, 0x21, 0x00, 0x2a, 0x00, 0x35, + 0x00, 0x47, 0x00, 0x56, 0x00, 0x90, 0x00, 0xe5, 0x01, 0x68, 0x01, 0xd5, 0x01, 0xd7, + 0x02, 0x36, 0x02, 0xa6, 0x02, 0xee, 0x03, 0x48, 0x03, 0xa0, 0x03, 0xba, 0x03, 0xc5, + 0x03, 0xd0, 0x03, 0xe0, 0x03, 0xea, 0x03, 0xfa, 0x03, 0xff, + ], + ), + InitCmd::Cmd( + 0xd3, + &[ + 0x00, 0x00, 0x00, 0x04, 0x00, 0x12, 0x00, 0x18, 0x00, 0x21, 0x00, 0x2a, 0x00, 0x35, + 0x00, 0x47, 0x00, 0x56, 0x00, 0x90, 0x00, 0xe5, 0x01, 0x68, 0x01, 0xd5, 0x01, 0xd7, + 0x02, 0x36, 0x02, 0xa6, 0x02, 0xee, 0x03, 0x48, 0x03, 0xa0, 0x03, 0xba, 0x03, 0xc5, + 0x03, 0xd0, 0x03, 0xe0, 0x03, 0xea, 0x03, 0xfa, 0x03, 0xff, + ], + ), + InitCmd::Cmd( + 0xd4, + &[ + 0x00, 0x00, 0x00, 0x04, 0x00, 0x12, 0x00, 0x18, 0x00, 0x21, 0x00, 0x2a, 0x00, 0x35, + 0x00, 0x47, 0x00, 0x56, 0x00, 0x90, 0x00, 0xe5, 0x01, 0x68, 0x01, 0xd5, 0x01, 0xd7, + 0x02, 0x36, 0x02, 0xa6, 0x02, 0xee, 0x03, 0x48, 0x03, 0xa0, 0x03, 0xba, 0x03, 0xc5, + 0x03, 0xd0, 0x03, 0xe0, 0x03, 0xea, 0x03, 0xfa, 0x03, 0xff, + ], + ), + InitCmd::Cmd( + 0xd5, + &[ + 0x00, 0x00, 0x00, 0x04, 0x00, 0x12, 0x00, 0x18, 0x00, 0x21, 0x00, 0x2a, 0x00, 0x35, + 0x00, 0x47, 0x00, 0x56, 0x00, 0x90, 0x00, 0xe5, 0x01, 0x68, 0x01, 0xd5, 0x01, 0xd7, + 0x02, 0x36, 0x02, 0xa6, 0x02, 0xee, 0x03, 0x48, 0x03, 0xa0, 0x03, 0xba, 0x03, 0xc5, + 0x03, 0xd0, 0x03, 0xe0, 0x03, 0xea, 0x03, 0xfa, 0x03, 0xff, + ], + ), + InitCmd::Cmd( + 0xd6, + &[ + 0x00, 0x00, 0x00, 0x04, 0x00, 0x12, 0x00, 0x18, 0x00, 0x21, 0x00, 0x2a, 0x00, 0x35, + 0x00, 0x47, 0x00, 0x56, 0x00, 0x90, 0x00, 0xe5, 0x01, 0x68, 0x01, 0xd5, 0x01, 0xd7, + 0x02, 0x36, 0x02, 0xa6, 0x02, 0xee, 0x03, 0x48, 0x03, 0xa0, 0x03, 0xba, 0x03, 0xc5, + 0x03, 0xd0, 0x03, 0xe0, 0x03, 0xea, 0x03, 0xfa, 0x03, 0xff, + ], + ), + InitCmd::Cmd(0x3A, &[0x66]), + InitCmd::Cmd(0x11, &[]), + InitCmd::Delay(120), + InitCmd::Cmd(0x29, &[]), + InitCmd::Delay(20), +]; diff --git a/qa-test/src/bin/lcd_i8080.rs b/examples/qa/src/bin/lcd-i8080.rs similarity index 99% rename from qa-test/src/bin/lcd_i8080.rs rename to examples/qa/src/bin/lcd-i8080.rs index 1b9ac7fc198..bbaa82ed68b 100644 --- a/qa-test/src/bin/lcd_i8080.rs +++ b/examples/qa/src/bin/lcd-i8080.rs @@ -17,7 +17,7 @@ //! - D6 => GPIO16 //! - D7 => GPIO15 -//% CHIP_FILTER: rgb_display_driver_supported && soc_has_lcd_cam +//% CHIP_FILTER: rgb_display_driver_supported && soc_has_lcd_cam && lcd_cam_dma_engine == "AHB_GDMA" #![no_std] #![no_main] diff --git a/qa-test/src/bin/lcd_mipi_dsi.rs b/examples/qa/src/bin/lcd-mipi-dsi.rs similarity index 100% rename from qa-test/src/bin/lcd_mipi_dsi.rs rename to examples/qa/src/bin/lcd-mipi-dsi.rs diff --git a/qa-test/src/bin/lp_timer.rs b/examples/qa/src/bin/lp-timer.rs similarity index 100% rename from qa-test/src/bin/lp_timer.rs rename to examples/qa/src/bin/lp-timer.rs diff --git a/qa-test/src/bin/mcpwm.rs b/examples/qa/src/bin/mcpwm.rs similarity index 91% rename from qa-test/src/bin/mcpwm.rs rename to examples/qa/src/bin/mcpwm.rs index a8ecc3529a6..511246fb474 100644 --- a/qa-test/src/bin/mcpwm.rs +++ b/examples/qa/src/bin/mcpwm.rs @@ -26,9 +26,7 @@ fn main() -> ! { let pin = peripherals.GPIO0; let clock_cfg = cfg_select! { - feature = "esp32h2" => { - PeripheralClockConfig::with_frequency(Rate::from_mhz(40)).unwrap() - } + feature = "esp32h2" => PeripheralClockConfig::with_frequency(Rate::from_mhz(40)).unwrap(), _ => PeripheralClockConfig::with_frequency(Rate::from_mhz(32)).unwrap(), }; diff --git a/qa-test/src/bin/multicore_flash.rs b/examples/qa/src/bin/multicore-flash.rs similarity index 71% rename from qa-test/src/bin/multicore_flash.rs rename to examples/qa/src/bin/multicore-flash.rs index b3912514d17..3c2e60beb1c 100644 --- a/qa-test/src/bin/multicore_flash.rs +++ b/examples/qa/src/bin/multicore-flash.rs @@ -3,11 +3,11 @@ //! This test verifies that flash operations remain correct when running //! on one core while the other core creates significant cache pressure. //! -//! It tests the `multicore_auto_park()` and `multicore_ignore()` functionality based on the boolean -//! values of `FLASH_ON_CORE_0` and `USE_AUTO_PARK`. +//! It tests the `MultiCoreStrategy::AutoPark` and `MultiCoreStrategy::ignore()` strategies of +//! `esp_hal::flash::Flash` based on the boolean values of `FLASH_ON_CORE_0` and `USE_AUTO_PARK`. -//% CHIP_FILTER: multi_core && !esp32 && !esp32p4 -//% FEATURES: unstable esp-storage +//% CHIP_FILTER: multi_core && flash_driver_supported && !esp32 && !esp32p4 +//% FEATURES: unstable // TODO: Make esp32 work @@ -19,6 +19,7 @@ use core::ptr::addr_of_mut; use esp_backtrace as _; use esp_hal::{ clock::CpuClock, + flash::{Config, Flash, MultiCoreStrategy}, main, peripherals::FLASH, system::{CpuControl, Stack}, @@ -35,9 +36,9 @@ const CACHE_PRESSURE_BASE: u32 = 0x4200_0000; const CACHE_PRESSURE_SIZE: usize = 65536; // 64KB unsafe extern "C" { - #[cfg(feature = "esp32s31")] + #[cfg(any(feature = "esp32h4", feature = "esp32s31"))] fn Cache_Invalidate_All(cache_map: u32); - #[cfg(not(feature = "esp32s31"))] + #[cfg(not(any(feature = "esp32h4", feature = "esp32s31")))] fn Cache_Invalidate_ICache_All(); } @@ -91,10 +92,10 @@ fn read() { // Read through the entire region to stress cache for offset in (0..CACHE_PRESSURE_SIZE).step_by(32) { let ptr = base_ptr.add(offset / 4); - #[cfg(feature = "esp32s31")] + #[cfg(any(feature = "esp32h4", feature = "esp32s31"))] // CACHE_MAP_L1_ICACHE_0 | CACHE_MAP_L1_ICACHE_1 | CACHE_MAP_L1_DCACHE Cache_Invalidate_All(0x13); - #[cfg(not(feature = "esp32s31"))] + #[cfg(not(any(feature = "esp32h4", feature = "esp32s31")))] Cache_Invalidate_ICache_All(); core::ptr::read_volatile(ptr); } @@ -104,12 +105,15 @@ fn read() { fn flash_access(flash: esp_hal::peripherals::FLASH) { println!("flash access running"); - let flash = esp_storage::FlashStorage::new(flash); - let mut flash = if USE_AUTO_PARK { - flash.multicore_auto_park() + let strategy = if USE_AUTO_PARK { + MultiCoreStrategy::AutoPark } else { - unsafe { flash.multicore_ignore() } + // SAFETY: not sound, the other core reads from flash. This is what the + // test exercises. + unsafe { MultiCoreStrategy::ignore() } }; + let mut flash = + Flash::new(flash, Config::default().with_multi_core_strategy(strategy)).unwrap(); println!("flash created"); let d = esp_hal::delay::Delay::new(); @@ -120,9 +124,11 @@ fn flash_access(flash: esp_hal::peripherals::FLASH) { println!("write flash"); other2(); - let foo = [0u8; 0x4000]; + let foo = [0u32; 0x1000]; - let res = flash.write_nor(0x9000, &foo); + // SAFETY: 0x9000 is the NVS partition of the default partition table, + // which is not mapped. + let res = unsafe { flash.write(0x9000, &foo) }; println!("Writing to flash result: {:?}", res); } } diff --git a/qa-test/src/bin/nvs_partition_erase.rs b/examples/qa/src/bin/nvs-partition-erase.rs similarity index 74% rename from qa-test/src/bin/nvs_partition_erase.rs rename to examples/qa/src/bin/nvs-partition-erase.rs index f294a62e0d7..b21b41ed174 100644 --- a/qa-test/src/bin/nvs_partition_erase.rs +++ b/examples/qa/src/bin/nvs-partition-erase.rs @@ -7,12 +7,13 @@ //! Assumes the device is flashed with a partition table containing an NVS //! partition (which is the case for the default partition table). //! -//! Also exercises `esp_storage::FlashStorage::erase` on the last sector of the +//! Also exercises `esp_hal::flash::Flash::erase` on the last sector of the //! whole flash - an area nothing occupies with the default partition table. //! //! NOTE: This test erases the NVS partition and the last sector of the flash! -//% FEATURES: esp-storage +//% CHIP_FILTER: flash_driver_supported +//% FEATURES: unstable #![no_std] #![no_main] @@ -25,9 +26,11 @@ use esp_bootloader_esp_idf::partitions::{ PartitionType, read_partition_table, }; -use esp_hal::main; +use esp_hal::{ + flash::{self, Config, Flash}, + main, +}; use esp_println::println; -use esp_storage::FlashStorageError; esp_bootloader_esp_idf::esp_app_desc!(); @@ -38,7 +41,7 @@ fn main() -> ! { esp_println::logger::init_logger_from_env(); let peripherals = esp_hal::init(esp_hal::Config::default()); - let mut flash = esp_storage::FlashStorage::new(peripherals.FLASH); + let mut flash = Flash::new(peripherals.FLASH, Config::default()).unwrap(); let mut buffer = [0u8; PARTITION_TABLE_MAX_LEN]; let pt = read_partition_table(&mut flash, &mut buffer).unwrap(); @@ -48,7 +51,7 @@ fn main() -> ! { .unwrap() .expect("No NVS partition found"); - let mut region = nvs.as_flash_region(&mut flash); + let mut region = nvs.as_flash_region(&mut flash).unwrap(); let len = region.partition_size() as u32; println!("NVS partition: {} bytes", len); assert!(len >= 2 * SECTOR_SIZE); @@ -85,19 +88,21 @@ fn main() -> ! { ); assert_eq!(region.erase(SECTOR_SIZE, 0), Err(Error::OutOfBounds)); - // The same boundary conditions apply to `FlashStorage` itself: erasing the - // last sector of the flash must succeed + // The same boundary conditions apply to the flash driver itself: erasing + // the last sector of the flash must succeed let capacity = flash.capacity() as u32; - flash - .write(capacity - SECTOR_SIZE, &[0xa5; SECTOR_SIZE as usize]) - .unwrap(); - flash.erase(capacity - SECTOR_SIZE, capacity).unwrap(); - flash.read(capacity - SECTOR_SIZE, &mut sector).unwrap(); - assert!(sector.iter().all(|&b| b == 0xff)); + let mut words = [0xa5a5_a5a5u32; SECTOR_SIZE as usize / 4]; + // SAFETY: the last sector of the flash is not mapped. + unsafe { + flash.write(capacity - SECTOR_SIZE, &words).unwrap(); + flash.erase(capacity - SECTOR_SIZE, capacity).unwrap(); + } + flash.read(capacity - SECTOR_SIZE, &mut words).unwrap(); + assert!(words.iter().all(|&w| w == u32::MAX)); assert_eq!( - flash.erase(SECTOR_SIZE, 0), - Err(FlashStorageError::OutOfBounds) + unsafe { flash.erase(SECTOR_SIZE, 0) }, + Err(flash::Error::OutOfBounds) ); println!("Test passed"); diff --git a/examples/qa/src/bin/psram.rs b/examples/qa/src/bin/psram.rs new file mode 100644 index 00000000000..deee66dde77 --- /dev/null +++ b/examples/qa/src/bin/psram.rs @@ -0,0 +1,199 @@ +//! Uses PSRAM as heap memory and measures CPU-driven PSRAM throughput. +//! +//! You need a supported target with at least 2 MB of PSRAM memory. + +//% CHIP_FILTER: psram_driver_supported +//% FEATURES: esp-alloc/internal-heap-stats + +#![no_std] +#![no_main] + +extern crate alloc; + +use alloc::{string::String, vec::Vec}; + +use esp_alloc as _; +use esp_backtrace as _; +use esp_hal::{clock::CpuClock, main, ram, time::Instant}; +use esp_println::println; + +esp_bootloader_esp_idf::esp_app_desc!(); + +#[cfg(is_not_release)] +compile_error!("PSRAM example must be built in release mode!"); + +/// PSRAM buffer size for the functional check and the throughput measurements. +const PSRAM_BENCH_BYTES: usize = 512 * 1024; +/// Internal-RAM bounce buffer for SRAM <-> PSRAM copies. +const SRAM_CHUNK_BYTES: usize = 16 * 1024; +/// Repeats each timed transfer to reduce timer quantization error. +const ITERATIONS: u32 = 4; + +fn print_throughput(label: &str, bytes: u64, elapsed_us: u64) { + let us = elapsed_us.max(1); + let mib_x100 = bytes * 100_000_000 / us / (1024 * 1024); + println!( + "{label}: {bytes} bytes in {us} us ({}.{:02} MiB/s)", + mib_x100 / 100, + mib_x100 % 100 + ); +} + +#[ram] +fn write_u32(buf: &mut [u32], value: u32) { + for slot in buf.iter_mut() { + unsafe { + core::ptr::write_volatile(slot, value); + } + } +} + +#[ram] +fn read_u32(buf: &[u32]) -> u32 { + let mut acc = 0u32; + for slot in buf { + acc ^= unsafe { core::ptr::read_volatile(slot) }; + } + acc +} + +#[ram] +fn copy_sram_to_psram(dst: &mut [u8], src: &[u8]) { + for chunk in dst.chunks_exact_mut(src.len()) { + chunk.copy_from_slice(src); + } +} + +#[ram] +fn copy_psram_to_sram(dst: &mut [u8], src: &[u8]) { + for chunk in src.chunks_exact(dst.len()) { + dst.copy_from_slice(chunk); + } +} + +#[ram] +fn copy_psram_to_psram(dst: &mut [u8], src: &[u8]) { + dst.copy_from_slice(src); +} + +fn measure_write_u32(buf: &mut [u32]) { + write_u32(buf, 0xa5a5_5a5a); + let start = Instant::now(); + for i in 0..ITERATIONS { + write_u32(buf, 0x5a5a_a5a5 ^ i); + } + print_throughput( + "seq write u32 (PSRAM)", + PSRAM_BENCH_BYTES as u64 * u64::from(ITERATIONS), + start.elapsed().as_micros(), + ); +} + +fn measure_read_u32(buf: &[u32]) { + core::hint::black_box(read_u32(buf)); + let start = Instant::now(); + let mut acc = 0u32; + for _ in 0..ITERATIONS { + acc ^= read_u32(buf); + } + core::hint::black_box(acc); + print_throughput( + "seq read u32 (PSRAM)", + PSRAM_BENCH_BYTES as u64 * u64::from(ITERATIONS), + start.elapsed().as_micros(), + ); +} + +fn measure_sram_to_psram(dst: &mut [u8], src: &[u8]) { + copy_sram_to_psram(dst, src); + let start = Instant::now(); + for _ in 0..ITERATIONS { + copy_sram_to_psram(dst, src); + } + print_throughput( + "memcpy SRAM -> PSRAM", + PSRAM_BENCH_BYTES as u64 * u64::from(ITERATIONS), + start.elapsed().as_micros(), + ); +} + +fn measure_psram_to_sram(dst: &mut [u8], src: &[u8]) { + copy_psram_to_sram(dst, src); + let start = Instant::now(); + for _ in 0..ITERATIONS { + copy_psram_to_sram(dst, src); + } + core::hint::black_box(dst); + print_throughput( + "memcpy PSRAM -> SRAM", + PSRAM_BENCH_BYTES as u64 * u64::from(ITERATIONS), + start.elapsed().as_micros(), + ); +} + +fn measure_psram_to_psram(dst: &mut [u8], src: &[u8]) { + copy_psram_to_psram(dst, src); + let start = Instant::now(); + for _ in 0..ITERATIONS { + copy_psram_to_psram(dst, src); + } + print_throughput( + "memcpy PSRAM -> PSRAM", + PSRAM_BENCH_BYTES as u64 * u64::from(ITERATIONS), + start.elapsed().as_micros(), + ); +} + +#[main] +fn main() -> ! { + esp_println::logger::init_logger_from_env(); + let peripherals = esp_hal::init(esp_hal::Config::default().with_cpu_clock(CpuClock::max())); + + esp_alloc::psram_allocator!(peripherals.PSRAM, esp_hal::psram); + + println!("Going to access PSRAM"); + let mut psram_a = Vec::::with_capacity(PSRAM_BENCH_BYTES); + psram_a.resize(PSRAM_BENCH_BYTES, 0); + let mut psram_b = Vec::::with_capacity(PSRAM_BENCH_BYTES); + psram_b.resize(PSRAM_BENCH_BYTES, 0); + + for (i, byte) in psram_a.iter_mut().enumerate() { + *byte = (i & 0xff) as u8; + } + + println!("vec size = {} bytes", psram_a.len()); + println!("vec address = {:p}", psram_a.as_ptr()); + println!("vec[..100] = {:?}", &psram_a[..100]); + + let string = String::from("A string allocated in PSRAM"); + println!("'{}' allocated at {:p}", &string, string.as_ptr()); + + println!("{}", esp_alloc::HEAP.stats()); + + // Keep the bounce buffer in internal RAM, not on the stack. + let sram = { + static mut SRAM: [u8; SRAM_CHUNK_BYTES] = [0; SRAM_CHUNK_BYTES]; + // SAFETY: `main` is the only user of this buffer. + unsafe { &mut *core::ptr::addr_of_mut!(SRAM) } + }; + for (i, byte) in sram.iter_mut().enumerate() { + *byte = (i & 0xff) as u8; + } + + println!("PSRAM throughput (CPU, {ITERATIONS} iterations):"); + + let word_count = PSRAM_BENCH_BYTES / 4; + // SAFETY: The allocator returns a word-aligned heap block. + let psram_words = + unsafe { core::slice::from_raw_parts_mut(psram_a.as_mut_ptr().cast::(), word_count) }; + measure_write_u32(psram_words); + measure_read_u32(psram_words); + + measure_sram_to_psram(&mut psram_a, sram); + measure_psram_to_sram(sram, &psram_a); + measure_psram_to_psram(&mut psram_b, &psram_a); + + println!("done"); + + loop {} +} diff --git a/qa-test/src/bin/qspi_flash.rs b/examples/qa/src/bin/qspi-flash.rs similarity index 100% rename from qa-test/src/bin/qspi_flash.rs rename to examples/qa/src/bin/qspi-flash.rs diff --git a/qa-test/src/bin/ram.rs b/examples/qa/src/bin/ram.rs similarity index 99% rename from qa-test/src/bin/ram.rs rename to examples/qa/src/bin/ram.rs index 7ed6d4f9d88..fac1bfbe831 100644 --- a/qa-test/src/bin/ram.rs +++ b/examples/qa/src/bin/ram.rs @@ -11,7 +11,7 @@ //! //! We can also run code from RTC memory. -//% CHIP_FILTER: soc_has_lpwr && !esp32c2 && !esp32c61 && !esp32p4 +//% CHIP_FILTER: soc_has_lpwr && !esp32c2 && !esp32c61 && !esp32h4 #![allow(static_mut_refs)] #![no_std] diff --git a/qa-test/src/bin/sdmmc_sd_async.rs b/examples/qa/src/bin/sdmmc-sd-async.rs similarity index 75% rename from qa-test/src/bin/sdmmc_sd_async.rs rename to examples/qa/src/bin/sdmmc-sd-async.rs index 5713640951a..e7bde90ab11 100644 --- a/qa-test/src/bin/sdmmc_sd_async.rs +++ b/examples/qa/src/bin/sdmmc-sd-async.rs @@ -7,6 +7,9 @@ //! single-block (CMD24/CMD17) and multi-block (CMD25/CMD18, with auto-stop) //! transfer paths are written and read back. No raw blocks are overwritten. //! +//! Build with `SDMMC_FORMAT=1` to erase the card first: the test writes an MBR +//! with one FAT32 partition and formats it. This destroys all data on the card. +//! //! Pins: //! //! | Signal | ESP32-S3 (1-bit) | ESP32 (4-bit) | ESP32-S31 (4-bit) | ESP32-P4 (4-bit, slot 0) @@ -26,8 +29,8 @@ use block_device_adapters::BufStream; use embassy_executor::Spawner; use embassy_time::Delay; -use embedded_fatfs::{FileSystem, FsOptions, ReadWriteSeek}; -use embedded_io_async::{Read, Write}; +use embedded_fatfs::{FatType, FileSystem, FormatVolumeOptions, FsOptions, ReadWriteSeek}; +use embedded_io_async::{Read, Seek, SeekFrom, Write}; use embedded_partitions::mbr::Scheme; use esp_backtrace as _; #[cfg(any(feature = "esp32s3", feature = "esp32p4"))] @@ -38,7 +41,7 @@ use esp_hal::{ timer::timg::TimerGroup, }; use esp_println::println; -use sdio::{BlockDevice, sd::Card}; +use sdio::{Addressable, BlockDevice, sd::Card}; esp_bootloader_esp_idf::esp_app_desc!(); @@ -50,6 +53,12 @@ const CARD_HZ: u32 = 40_000_000; #[cfg(any(feature = "esp32s3", feature = "esp32p4"))] const INPUT_DELAY_PHASE: DelayPhase = DelayPhase::_0; +/// Erase and format the card before the test when set at compile time. +const FORMAT: bool = option_env!("SDMMC_FORMAT").is_some(); + +/// First block of the FAT32 partition that the format step creates. +const PART_START: u32 = 2048; + /// Test-owned file (8.3 name); assumed not to exist on the card. const TEST_FILE: &str = "ESPQA.TXT"; const MSG_CREATE: &[u8] = b"esp-hal sdmmc async create\n"; @@ -73,7 +82,7 @@ async fn main(_spawner: Spawner) { let peripherals = esp_hal::init(esp_hal::Config::default()); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let controller = SdHostController::new(peripherals.SDHOST, Config::default()).unwrap(); let slot_config = SlotConfig::default(); @@ -128,6 +137,41 @@ async fn main(_spawner: Spawner) { .unwrap(); println!("card initialized: {:?}", card.card()); + if FORMAT { + let blocks = card.card().block_count(); + println!("Formatting card ({blocks} blocks)"); + + let mut mbr = [0u8; 512]; + let entry = &mut mbr[446..462]; + entry[1..4].copy_from_slice(&[0xFE, 0xFF, 0xFF]); + entry[4] = 0x0C; // FAT32 (LBA) + entry[5..8].copy_from_slice(&[0xFE, 0xFF, 0xFF]); + entry[8..12].copy_from_slice(&PART_START.to_le_bytes()); + entry[12..16].copy_from_slice(&(blocks - PART_START).to_le_bytes()); + mbr[510] = 0x55; + mbr[511] = 0xAA; + + let mut stream = BufStream::<_, 512>::new(&mut card); + stream.write_all(&mbr).await.unwrap(); + stream.flush().await.unwrap(); + + let Ok(Scheme::Mbr(mut mbr)) = Scheme::open(stream).await else { + panic!("MBR not detected after write"); + }; + let mut part = RamWrites(mbr.open_partition(0).await.unwrap()); + embedded_fatfs::format_volume( + &mut part, + FormatVolumeOptions::new().fat_type(FatType::Fat32), + ) + .await + .unwrap(); + part.flush().await.unwrap(); + part.seek(SeekFrom::Start(0)).await.unwrap(); + let fs = FileSystem::new(&mut part, FsOptions::new()).await.unwrap(); + println!("Formatted: {:?}", fs.fat_type()); + fs.unmount().await.unwrap(); + } + let mut button = Input::new( cfg_select! { feature = "esp32p4" => peripherals.GPIO35, @@ -163,6 +207,42 @@ async fn main(_spawner: Spawner) { } } +/// Copies each write into RAM in pieces shorter than a block. +/// +/// `format_volume` writes zeros from a constant in flash, and the SDMMC DMA +/// cannot read flash. `BufStream` sends whole-block writes directly to the card +/// and does not update its cached block, so the cached block can overwrite them. +struct RamWrites(IO); + +impl embedded_io_async::ErrorType for RamWrites { + type Error = IO::Error; +} + +impl Read for RamWrites { + async fn read(&mut self, buf: &mut [u8]) -> Result { + self.0.read(buf).await + } +} + +impl Write for RamWrites { + async fn write(&mut self, buf: &[u8]) -> Result { + let mut ram = [0u8; 256]; + let len = buf.len().min(ram.len()); + ram[..len].copy_from_slice(&buf[..len]); + self.0.write(&ram[..len]).await + } + + async fn flush(&mut self) -> Result<(), Self::Error> { + self.0.flush().await + } +} + +impl Seek for RamWrites { + async fn seek(&mut self, pos: SeekFrom) -> Result { + self.0.seek(pos).await + } +} + /// Runs the CRUD cycle and reports the outcome. async fn fat_crud(io: IO) { match fat_crud_inner(io).await { diff --git a/qa-test/src/bin/sleep_timer_gpio.rs b/examples/qa/src/bin/sleep-timer-gpio.rs similarity index 87% rename from qa-test/src/bin/sleep_timer_gpio.rs rename to examples/qa/src/bin/sleep-timer-gpio.rs index eab3e900ca4..88e354915dd 100644 --- a/qa-test/src/bin/sleep_timer_gpio.rs +++ b/examples/qa/src/bin/sleep-timer-gpio.rs @@ -6,15 +6,15 @@ //! //! Wiring //! -//! | Function | ESP32 | ESP32-S2/S3 | ESP32-C2/C3 | ESP32-C5/C6/C61/P4 | ESP32-H2 | -//! | ------------------ | ----- | ----------- | ----------- | ------------------ | -------- | -//! | Wake on low level | GPIO2 | GPIO17 | GPIO2 | GPIO2 | GPIO9 | -//! | Wake on high level | GPIO4 | GPIO18 | GPIO3 | GPIO3 | GPIO10 | +//! | Function | ESP32 | ESP32-S2/S3 | ESP32-C2/C3/C5/C6/C61/P4/S31 | ESP32-H2 | +//! | ------------------ | ----- | ----------- | ---------------------------- | -------- | +//! | Wake on low level | GPIO2 | GPIO17 | GPIO2 | GPIO9 | +//! | Wake on high level | GPIO4 | GPIO18 | GPIO3 | GPIO10 | //! //! Each pin idles at the level that does not wake the chip. Pull the low-level pin to ground, or //! the high-level pin to 3V3, to end the sleep. -//% CHIP_FILTER: sleep_driver_supported +//% CHIP_FILTER: sleep_driver_supported && sleep_deep_sleep #![no_std] #![no_main] diff --git a/qa-test/src/bin/sleep_timer_oversleeping.rs b/examples/qa/src/bin/sleep-timer-oversleeping.rs similarity index 90% rename from qa-test/src/bin/sleep_timer_oversleeping.rs rename to examples/qa/src/bin/sleep-timer-oversleeping.rs index 90f1890a8a2..8adaf43948c 100644 --- a/qa-test/src/bin/sleep_timer_oversleeping.rs +++ b/examples/qa/src/bin/sleep-timer-oversleeping.rs @@ -2,9 +2,9 @@ //! //! Issue: -// esp32c2 and esp32c61 have no rtc-fast memory, which is required by the persistent BOOT_COUNT -// variable. -//% CHIP_FILTER: sleep_driver_supported && !esp32c2 && !esp32c61 +// esp32c2, esp32c61 and esp32h4 have no rtc-fast memory, which is required by the persistent +// BOOT_COUNT variable. +//% CHIP_FILTER: sleep_driver_supported && sleep_deep_sleep && !esp32c2 && !esp32c61 && !esp32h4 #![no_std] #![no_main] use embassy_executor::Spawner; @@ -19,6 +19,7 @@ use esp_hal::{ timer::timg::TimerGroup, }; use esp_println::println; +use qa_test::DRAM2_UNINIT_SIZE; extern crate alloc; @@ -42,10 +43,11 @@ async fn main(_spawner: Spawner) { let config = esp_hal::Config::default().with_cpu_clock(CpuClock::max()); let peripherals = esp_hal::init(config); - esp_alloc::heap_allocator!(#[esp_hal::ram(reclaimed)] size: 65536); + esp_alloc::heap_allocator!(size: 32768); + esp_alloc::heap_allocator!(#[esp_hal::ram(reclaimed)] size: DRAM2_UNINIT_SIZE); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let rtc = Rtc::new(peripherals.RTC_TIMER); let mut lpwr = LowPower::new(peripherals.LPWR); diff --git a/qa-test/src/bin/sleep_timer_wifi.rs b/examples/qa/src/bin/sleep-timer-wifi.rs similarity index 93% rename from qa-test/src/bin/sleep_timer_wifi.rs rename to examples/qa/src/bin/sleep-timer-wifi.rs index 0512980ebf2..f7fbb14a42e 100644 --- a/qa-test/src/bin/sleep_timer_wifi.rs +++ b/examples/qa/src/bin/sleep-timer-wifi.rs @@ -32,6 +32,7 @@ use esp_radio::wifi::{ scan::ScanConfig, sta::StationConfig, }; +use qa_test::DRAM2_UNINIT_SIZE; esp_bootloader_esp_idf::esp_app_desc!(); @@ -39,15 +40,15 @@ esp_bootloader_esp_idf::esp_app_desc!(); async fn main(_spawner: Spawner) -> ! { let peripherals = esp_hal::init(esp_hal::Config::default()); - esp_alloc::heap_allocator!(#[ram(reclaimed)] size: 64 * 1024); + esp_alloc::heap_allocator!(#[ram(reclaimed)] size: DRAM2_UNINIT_SIZE); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let delay = Delay::new(); let mut lpwr = LowPower::new(peripherals.LPWR); - println!("up and runnning!"); + println!("up and running!"); let reason = reset_reason(Cpu::ProCpu).unwrap_or(SocResetReason::ChipPowerOn); println!("reset reason: {:?}", reason); let wake_reason = wakeup_cause(); diff --git a/qa-test/src/bin/sleep_timer.rs b/examples/qa/src/bin/sleep-timer.rs similarity index 94% rename from qa-test/src/bin/sleep_timer.rs rename to examples/qa/src/bin/sleep-timer.rs index 067ce01c4d3..41b03347ddb 100644 --- a/qa-test/src/bin/sleep_timer.rs +++ b/examples/qa/src/bin/sleep-timer.rs @@ -1,6 +1,6 @@ //! Demonstrates waking from deep sleep with timer -//% CHIP_FILTER: sleep_driver_supported +//% CHIP_FILTER: sleep_driver_supported && sleep_deep_sleep #![no_std] #![no_main] diff --git a/examples/qa/src/bin/sleep_current.rs b/examples/qa/src/bin/sleep_current.rs new file mode 100644 index 00000000000..1c6203bd025 --- /dev/null +++ b/examples/qa/src/bin/sleep_current.rs @@ -0,0 +1,488 @@ +//! Walks CPU idle and sleep states so a current meter can record each path. +//! +//! The program holds every case for [`HOLD`], then moves to the next. The console +//! prints the case name before the hold, so you can align the meter with the +//! UART log. Use a UART port. USB Serial/JTAG stops across sleep. +//! +//! Active cases combine CPU clock (default and maximum), core count, and either a +//! busy loop or WAITI/WFI. Sleep cases are light sleep without CPU power-down, +//! light sleep with CPU power-down, the cache tag-memory subcase of that path, +//! and deep sleep. The only wakeup source is the LP timer. +//! +//! A chip whose default CPU clock is already the maximum skips the duplicate +//! maximum-clock active cases. Dual-core cases run only on multi-core chips. +//! CPU power-down and tag-memory cases run only where the hardware supports them. + +//% CHIP_FILTER: sleep_driver_supported && sleep_deep_sleep + +#![no_std] +#![no_main] +#![allow(static_mut_refs)] + +use esp_backtrace as _; +use esp_hal::{ + clock::CpuClock, + delay::Delay, + interrupt, + main, + rtc_cntl::{ + reset_reason, + sleep::{LowPower, RtcSleepConfig}, + wakeup_cause, + }, + system::Cpu, + time::{Duration, Instant}, + timer::{PeriodicTimer, timg::TimerGroup}, +}; +use esp_println::println; + +esp_bootloader_esp_idf::esp_app_desc!(); + +#[cfg(multi_core)] +use core::ptr::addr_of_mut; + +#[cfg(multi_core)] +use esp_hal::{interrupt::Priority, peripherals::Interrupt}; + +/// Time the program stays in each case, so a meter can settle and record. +const HOLD: Duration = Duration::from_secs(3); + +/// Interrupt period that lets WAITI/WFI return and check the hold deadline. +const WAITI_TICK: Duration = Duration::from_millis(250); + +#[cfg(not(any(feature = "esp32c2", feature = "esp32c61", feature = "esp32h4")))] +#[esp_hal::ram(unstable(rtc_fast, persistent))] +static mut PHASE: u32 = 0; + +fn load_phase() -> u32 { + cfg_select! { + feature = "esp32c2" => esp_hal::peripherals::LPWR::regs().store6().read().bits(), + any(feature = "esp32c61", feature = "esp32h4") => { + esp_hal::peripherals::LP_AON::regs().store6().read().bits() + } + _ => unsafe { PHASE }, + } +} + +fn store_phase(value: u32) { + cfg_select! { + feature = "esp32c2" => { + esp_hal::peripherals::LPWR::regs() + .store6() + .write(|w| unsafe { w.bits(value) }); + } + any(feature = "esp32c61", feature = "esp32h4") => { + esp_hal::peripherals::LP_AON::regs() + .store6() + .write(|w| unsafe { w.bits(value) }); + } + _ => unsafe { PHASE = value }, + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Case { + Active { + max_clock: bool, + two_cores: bool, + waiti: bool, + }, + LightSleep { + two_cores: bool, + cpu_pd: bool, + tagmem: bool, + }, + DeepSleep, +} + +const CASES: &[Case] = &[ + Case::Active { + max_clock: false, + two_cores: false, + waiti: false, + }, + Case::Active { + max_clock: false, + two_cores: false, + waiti: true, + }, + #[cfg(multi_core)] + Case::Active { + max_clock: false, + two_cores: true, + waiti: false, + }, + #[cfg(multi_core)] + Case::Active { + max_clock: false, + two_cores: true, + waiti: true, + }, + Case::Active { + max_clock: true, + two_cores: false, + waiti: false, + }, + Case::Active { + max_clock: true, + two_cores: false, + waiti: true, + }, + #[cfg(multi_core)] + Case::Active { + max_clock: true, + two_cores: true, + waiti: false, + }, + #[cfg(multi_core)] + Case::Active { + max_clock: true, + two_cores: true, + waiti: true, + }, + Case::LightSleep { + two_cores: false, + cpu_pd: false, + tagmem: false, + }, + #[cfg(multi_core)] + Case::LightSleep { + two_cores: true, + cpu_pd: false, + tagmem: false, + }, + #[cfg(supports_cpu_power_down)] + Case::LightSleep { + two_cores: false, + cpu_pd: true, + tagmem: false, + }, + #[cfg(all(supports_cpu_power_down, multi_core))] + Case::LightSleep { + two_cores: true, + cpu_pd: true, + tagmem: false, + }, + #[cfg(supports_tagmem_power_down)] + Case::LightSleep { + two_cores: false, + cpu_pd: true, + tagmem: true, + }, + #[cfg(all(supports_tagmem_power_down, multi_core))] + Case::LightSleep { + two_cores: true, + cpu_pd: true, + tagmem: true, + }, + Case::DeepSleep, +]; + +fn case_wants_max_clock(case: Case) -> Option { + match case { + Case::Active { max_clock, .. } => Some(max_clock), + _ => None, + } +} + +fn skip_duplicate_max_clock(case: Case) -> bool { + matches!( + case, + Case::Active { + max_clock: true, + .. + } + ) && CpuClock::default() == CpuClock::max() +} + +fn print_case(index: usize, case: Case) { + match case { + Case::Active { + max_clock, + two_cores, + waiti, + } => { + println!( + "=== [{}/{}] active CPU={} cores={} idle={} ({} s) ===", + index + 1, + CASES.len(), + if max_clock { "max" } else { "default" }, + if two_cores { 2 } else { 1 }, + if waiti { "WAITI/WFI" } else { "busy" }, + HOLD.as_secs(), + ); + } + Case::LightSleep { + two_cores, + cpu_pd, + tagmem, + } => { + println!( + "=== [{}/{}] light sleep cores={} cpu_pd={} tagmem={} ({} s) ===", + index + 1, + CASES.len(), + if two_cores { 2 } else { 1 }, + cpu_pd, + tagmem, + HOLD.as_secs(), + ); + } + Case::DeepSleep => { + println!( + "=== [{}/{}] deep sleep ({} s) ===", + index + 1, + CASES.len(), + HOLD.as_secs(), + ); + } + } +} + +static mut TIMER: *mut PeriodicTimer<'static, esp_hal::Blocking> = core::ptr::null_mut(); + +#[cfg(multi_core)] +static mut APP_WAITI: bool = true; + +#[cfg(multi_core)] +fn set_app_waiti(waiti: bool) { + unsafe { core::ptr::write_volatile(addr_of_mut!(APP_WAITI), waiti) }; +} + +#[cfg(multi_core)] +fn app_waiti() -> bool { + unsafe { core::ptr::read_volatile(&raw const APP_WAITI) } +} + +#[esp_hal::handler] +fn timer_handler() { + unsafe { + if let Some(timer) = TIMER.as_mut() { + timer.clear_interrupt(); + } + } +} + +#[cfg(multi_core)] +fn app_core_entry() -> ! { + cfg_select! { + xtensa => unsafe { + let _ = esp_hal::xtensa_lx::interrupt::enable(); + }, + riscv => unsafe { + let _ = esp_hal::riscv::interrupt::enable(); + }, + } + interrupt::enable(Interrupt::TG0_T0_LEVEL, Priority::min()); + + loop { + if app_waiti() { + interrupt::wait_for_interrupt(); + } else { + core::hint::spin_loop(); + } + } +} + +fn hold_active(waiti: bool) { + let end = Instant::now() + HOLD; + if waiti { + while Instant::now() < end { + interrupt::wait_for_interrupt(); + } + } else { + while Instant::now() < end { + core::hint::spin_loop(); + } + } +} + +fn deep_sleep_config() -> RtcSleepConfig { + cfg_select! { + any(esp32, esp32s2, esp32s3, esp32c3) => { + let mut config = RtcSleepConfig::deep(); + config.set_rtc_fastmem_pd_en(false); + config + } + _ => RtcSleepConfig::deep(), + } +} + +#[cfg(supports_cpu_power_down)] +#[esp_hal::ram(reclaimed, unstable(zeroed))] +static CPU_RETENTION_MEMORY: esp_hal::rtc_cntl::CpuRetentionStorage = + esp_hal::rtc_cntl::CpuRetentionStorage::new(); + +#[cfg(supports_tagmem_power_down)] +#[esp_hal::ram(reclaimed, unstable(zeroed))] +static CACHE_TAGMEM: esp_hal::rtc_cntl::CacheTagRetentionStorage = + esp_hal::rtc_cntl::CacheTagRetentionStorage::new(); + +#[main] +fn main() -> ! { + let mut phase = (load_phase() as usize) % CASES.len(); + while skip_duplicate_max_clock(CASES[phase]) { + phase = (phase + 1) % CASES.len(); + } + store_phase(phase as u32); + + let max_clock = case_wants_max_clock(CASES[phase]).unwrap_or(false); + let mut hal_config = esp_hal::Config::default(); + if max_clock { + hal_config = hal_config.with_cpu_clock(CpuClock::max()); + } + let peripherals = esp_hal::init(hal_config); + + let delay = Delay::new(); + let mut lpwr = LowPower::new(peripherals.LPWR); + + let timg0 = TimerGroup::new(peripherals.TIMG0); + let mut periodic = PeriodicTimer::new(timg0.timer0); + periodic.set_interrupt_handler(timer_handler); + periodic.listen(); + periodic.start(WAITI_TICK).unwrap(); + unsafe { + TIMER = (&raw mut periodic).cast(); + } + + #[cfg(multi_core)] + let mut cpu_control = { + use esp_hal::system::{CpuControl, Stack}; + + static mut APP_CORE_STACK: Stack<8192> = Stack::new(); + let mut cpu_control = CpuControl::new(peripherals.CPU_CTRL); + let guard = cpu_control + .start_app_core(unsafe { &mut *addr_of_mut!(APP_CORE_STACK) }, || { + app_core_entry() + }) + .unwrap(); + core::mem::forget(guard); + unsafe { cpu_control.park_core(Cpu::AppCpu) }; + cpu_control + }; + + #[cfg(supports_cpu_power_down)] + let mut cpu_pd_installed = false; + #[cfg(supports_tagmem_power_down)] + let mut tagmem_installed = false; + + println!( + "sleep_current: reset={:?} wake={:?} CPU={:?} phase={}/{}", + reset_reason(Cpu::ProCpu), + wakeup_cause(), + if max_clock { + CpuClock::max() + } else { + CpuClock::default() + }, + phase + 1, + CASES.len(), + ); + + loop { + while skip_duplicate_max_clock(CASES[phase]) { + phase = (phase + 1) % CASES.len(); + store_phase(phase as u32); + } + + if let Some(wants_max) = case_wants_max_clock(CASES[phase]) + && wants_max != max_clock + { + println!( + "reset to {} CPU clock", + if wants_max { "max" } else { "default" } + ); + delay.delay_millis(200); + store_phase(phase as u32); + esp_hal::system::software_reset(); + } + + let case = CASES[phase]; + print_case(phase, case); + delay.delay_millis(200); + + match case { + Case::Active { + two_cores, waiti, .. + } => { + #[cfg(multi_core)] + { + set_app_waiti(waiti); + if two_cores { + cpu_control.unpark_core(Cpu::AppCpu); + } else { + unsafe { cpu_control.park_core(Cpu::AppCpu) }; + } + delay.delay_millis(50); + } + #[cfg(not(multi_core))] + let _ = two_cores; + + hold_active(waiti); + } + Case::LightSleep { + two_cores, + cpu_pd, + tagmem, + } => { + periodic.unlisten(); + let _ = periodic.cancel(); + + #[cfg(multi_core)] + { + set_app_waiti(true); + if two_cores { + cpu_control.unpark_core(Cpu::AppCpu); + } else { + unsafe { cpu_control.park_core(Cpu::AppCpu) }; + } + delay.delay_millis(50); + } + #[cfg(not(multi_core))] + let _ = two_cores; + + #[cfg(supports_cpu_power_down)] + if cpu_pd && !cpu_pd_installed { + lpwr.install_cpu_retention_memory(CPU_RETENTION_MEMORY.take()) + .unwrap(); + cpu_pd_installed = true; + println!("installed CPU retention memory"); + } + #[cfg(not(supports_cpu_power_down))] + let _ = cpu_pd; + + #[cfg(supports_tagmem_power_down)] + if tagmem && !tagmem_installed { + lpwr.install_cache_tag_retention_memory(CACHE_TAGMEM.take()) + .unwrap(); + tagmem_installed = true; + println!("installed cache tag retention memory"); + } + #[cfg(not(supports_tagmem_power_down))] + let _ = tagmem; + + delay.delay_millis(100); + lpwr.set_wakeup_deadline(Instant::now() + HOLD); + lpwr.sleep_light(RtcSleepConfig::default()); + println!("woke from light sleep, cause={:?}", wakeup_cause()); + } + Case::DeepSleep => { + periodic.unlisten(); + let _ = periodic.cancel(); + + #[cfg(multi_core)] + unsafe { + cpu_control.park_core(Cpu::AppCpu); + } + + let next = ((phase + 1) % CASES.len()) as u32; + store_phase(next); + delay.delay_millis(100); + lpwr.set_wakeup_deadline(Instant::now() + HOLD); + lpwr.sleep_deep(deep_sleep_config()); + } + } + + phase = (phase + 1) % CASES.len(); + store_phase(phase as u32); + } +} diff --git a/qa-test/src/bin/software_reset.rs b/examples/qa/src/bin/software-reset.rs similarity index 100% rename from qa-test/src/bin/software_reset.rs rename to examples/qa/src/bin/software-reset.rs diff --git a/qa-test/src/bin/spi_halfduplex_read_manufacturer_id.rs b/examples/qa/src/bin/spi-halfduplex-read-manufacturer-id.rs similarity index 100% rename from qa-test/src/bin/spi_halfduplex_read_manufacturer_id.rs rename to examples/qa/src/bin/spi-halfduplex-read-manufacturer-id.rs diff --git a/qa-test/src/bin/sw_int_timer.rs b/examples/qa/src/bin/sw-int-timer.rs similarity index 86% rename from qa-test/src/bin/sw_int_timer.rs rename to examples/qa/src/bin/sw-int-timer.rs index 342663a7c2e..c4640b3bbce 100644 --- a/qa-test/src/bin/sw_int_timer.rs +++ b/examples/qa/src/bin/sw-int-timer.rs @@ -10,7 +10,7 @@ use esp_hal::{ delay::Delay, interrupt::software::SoftwareInterrupt, main, - peripherals::FROM_CPU_INTR0, + peripherals::FROM_CPU_INTR2, }; esp_bootloader_esp_idf::esp_app_desc!(); @@ -20,7 +20,7 @@ fn main() -> ! { esp_println::logger::init_logger_from_env(); let peripherals = esp_hal::init(esp_hal::Config::default()); - let mut sw_int = SoftwareInterrupt::new(peripherals.FROM_CPU_INTR0); + let mut sw_int = SoftwareInterrupt::new(peripherals.FROM_CPU_INTR2); sw_int.set_interrupt_handler(sw_int_handler); @@ -34,6 +34,6 @@ fn main() -> ! { #[esp_hal::handler] fn sw_int_handler() { - unsafe { SoftwareInterrupt::new(FROM_CPU_INTR0::steal()) }.reset(); + unsafe { SoftwareInterrupt::new(FROM_CPU_INTR2::steal()) }.reset(); log::info!("Triggered"); } diff --git a/qa-test/src/bin/temperature_sensor.rs b/examples/qa/src/bin/temperature-sensor.rs similarity index 91% rename from qa-test/src/bin/temperature_sensor.rs rename to examples/qa/src/bin/temperature-sensor.rs index 6adf83bb307..e4e4e128f3f 100644 --- a/qa-test/src/bin/temperature_sensor.rs +++ b/examples/qa/src/bin/temperature-sensor.rs @@ -1,7 +1,7 @@ //! This example uses the internal temperature sensor to measure the chip's //! temperature -//% CHIP_FILTER: soc_has_tsens +//% CHIP_FILTER: temp_sensor_driver_supported #![no_std] #![no_main] @@ -25,7 +25,7 @@ fn main() -> ! { let delay = Delay::new(); // Wait for the sensor to stabilize - delay.delay_micros(200); + delay.delay_micros(300); loop { let temp = temperature_sensor.get_temperature(); diff --git a/qa-test/src/bin/wifi_ble_modem_handoff.rs b/examples/qa/src/bin/wifi-ble-modem-handoff.rs similarity index 97% rename from qa-test/src/bin/wifi_ble_modem_handoff.rs rename to examples/qa/src/bin/wifi-ble-modem-handoff.rs index e8c663293dd..e28ebc94af6 100644 --- a/qa-test/src/bin/wifi_ble_modem_handoff.rs +++ b/examples/qa/src/bin/wifi-ble-modem-handoff.rs @@ -22,6 +22,7 @@ use esp_radio::{ wifi::{Config, ControllerConfig, WifiController, ap::AccessPointConfig}, }; use log::{info, warn}; +use qa_test::DRAM2_UNINIT_SIZE; use trouble_host::prelude::*; esp_bootloader_esp_idf::esp_app_desc!(); @@ -89,11 +90,11 @@ struct BatteryService { fn init_heap() { cfg_select! { feature = "esp32" => { - esp_alloc::heap_allocator!(#[ram(reclaimed)] size: 96 * 1024); + esp_alloc::heap_allocator!(#[ram(reclaimed)] size: DRAM2_UNINIT_SIZE); esp_alloc::heap_allocator!(size: 24 * 1024); } _ => { - esp_alloc::heap_allocator!(#[ram(reclaimed)] size: 64 * 1024); + esp_alloc::heap_allocator!(#[ram(reclaimed)] size: DRAM2_UNINIT_SIZE); esp_alloc::heap_allocator!(size: 64 * 1024); } } @@ -109,7 +110,7 @@ async fn main(_s: Spawner) -> ! { init_heap(); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); // Read the iteration left behind by the previous boot, then bump it so the // next boot (after our software reset) runs the other radio. @@ -176,7 +177,7 @@ where let address: Address = Address::random([0xff, 0x8f, 0x1a, 0x05, 0xe4, 0xff]); info!("[BLE] our address = {:?}", address); - let mut resources: HostResources<_, DefaultPacketPool, CONNECTIONS_MAX, L2CAP_CHANNELS_MAX> = + let mut resources: HostResources = HostResources::new(); let stack = trouble_host::new(controller, &mut resources) .set_random_address(address) diff --git a/examples/qa/src/bin/wifi-light-sleep.rs b/examples/qa/src/bin/wifi-light-sleep.rs new file mode 100644 index 00000000000..f0e4e6c1e55 --- /dev/null +++ b/examples/qa/src/bin/wifi-light-sleep.rs @@ -0,0 +1,172 @@ +//! Wi-Fi station in power save with automatic light sleep. +//! +//! Set SSID and PASSWORD env variable before running this example. +//! +//! The station connects with `PowerSaveMode::Minimum`, and the chip light-sleeps between beacons. +//! Every 30 seconds, the example opens a TCP connection to port 80 of the gateway, which needs both +//! receive and transmit to work. It counts beacon timeouts and disconnects. A disconnect with +//! reason 200 is a beacon timeout. +//! +//! Use the UART port. USB Serial/JTAG stops when the chip sleeps. + +//% FEATURES: esp-radio esp-radio/wifi esp-radio/unstable esp-hal/unstable +//% CHIP_FILTER: wifi_driver_supported && sleep_light_sleep + +#![no_std] +#![no_main] + +use embassy_executor::Spawner; +use embassy_net::{IpEndpoint, Runner, StackResources, tcp::TcpSocket}; +use embassy_time::{Duration, Instant, Timer, with_timeout}; +use esp_alloc as _; +use esp_backtrace as _; +use esp_hal::{ram, rng::Rng, timer::timg::TimerGroup}; +use esp_println::println; +use esp_radio::wifi::{ + AuthenticationMethodConfig, + Config, + ControllerConfig, + Interface, + PowerSaveMode, + WifiController, + event::{EventInfo, WifiEvent, enable_wifi_events}, + sta::StationConfig, +}; +use qa_test::DRAM2_UNINIT_SIZE; + +esp_bootloader_esp_idf::esp_app_desc!(); + +macro_rules! mk_static { + ($t:ty,$val:expr) => {{ + static STATIC_CELL: static_cell::StaticCell<$t> = static_cell::StaticCell::new(); + #[deny(unused_attributes)] + let x = STATIC_CELL.uninit().write(($val)); + x + }}; +} + +const SSID: &str = env!("SSID"); +const PASSWORD: &str = env!("PASSWORD"); + +const PROBE_INTERVAL: Duration = Duration::from_secs(30); + +#[esp_hal::main] +async fn main(spawner: Spawner) -> ! { + esp_println::logger::init_logger_from_env(); + let peripherals = esp_hal::init(esp_hal::Config::default()); + + esp_alloc::heap_allocator!(#[ram(reclaimed)] size: DRAM2_UNINIT_SIZE); + esp_alloc::heap_allocator!(size: 36 * 1024); + + let timg0 = TimerGroup::new(peripherals.TIMG0); + let sleep = esp_rtos::sleep::configure(peripherals.LPWR); + esp_rtos::start_with_idle_hook(timg0.timer0, sleep.light_sleep_hook); + + let station_config = Config::Station( + StationConfig::default() + .with_ssid(SSID.try_into().unwrap()) + .with_authentication(AuthenticationMethodConfig::Wpa2Personal( + PASSWORD.try_into().unwrap(), + )), + ); + + let wifi_interface = Interface::station(); + let mut controller = WifiController::new( + peripherals.WIFI, + ControllerConfig::default().with_initial_config(station_config), + ) + .unwrap(); + controller.set_power_saving(PowerSaveMode::Minimum).unwrap(); + enable_wifi_events(WifiEvent::StationBeaconTimeout.into()); + + let rng = Rng::new(); + let seed = (rng.random() as u64) << 32 | rng.random() as u64; + + let (stack, runner) = embassy_net::new( + wifi_interface, + embassy_net::Config::dhcpv4(Default::default()), + mk_static!(StackResources<3>, StackResources::<3>::new()), + seed, + ); + + spawner.spawn(connection(controller).unwrap()); + spawner.spawn(net_task(runner).unwrap()); + stack.wait_config_up().await; + let config = stack.config_v4().unwrap(); + let gateway = config.gateway.unwrap(); + println!("Got IP {}, gateway {}", config.address, gateway); + + let mut rx_buffer = [0u8; 1536]; + let mut tx_buffer = [0u8; 1536]; + let mut probes = 0u32; + let mut failures = 0u32; + + loop { + Timer::after(PROBE_INTERVAL).await; + + let mut socket = TcpSocket::new(stack, &mut rx_buffer, &mut tx_buffer); + let started = Instant::now(); + let result = with_timeout( + Duration::from_secs(5), + socket.connect(IpEndpoint::new(gateway.into(), 80)), + ) + .await; + let elapsed = started.elapsed().as_millis(); + socket.abort(); + let _ = socket.flush().await; + + probes += 1; + let ok = matches!(result, Ok(Ok(()))); + if !ok { + failures += 1; + } + println!( + "[{} s] probe {}: {} in {} ms, {} failed so far", + Instant::now().as_secs(), + probes, + if ok { "connected" } else { "failed" }, + elapsed, + failures, + ); + } +} + +#[embassy_executor::task] +async fn connection(mut controller: WifiController<'static>) { + let mut beacon_timeouts = 0u32; + let mut disconnects = 0u32; + + loop { + match controller.connect_async().await { + Ok(info) => { + println!("Connected to {:?}", info); + + // Subscribe only while connected. A subscriber that nobody reads fills the event + // channel, and `connect_async` then misses its events. + let mut events = controller.subscribe().unwrap(); + loop { + match events.next_event_pure().await { + EventInfo::StationBeaconTimeout => { + beacon_timeouts += 1; + println!("Beacon timeout, {beacon_timeouts} in total"); + } + EventInfo::StationDisconnected { reason, .. } => { + disconnects += 1; + println!("Disconnected, reason {reason}, {disconnects} in total"); + break; + } + _ => {} + } + } + } + Err(e) => println!("Failed to connect: {e:?}"), + } + + Timer::after(Duration::from_secs(5)).await; + } +} + +#[embassy_executor::task] +async fn net_task(mut runner: Runner<'static, Interface>) { + runner.run().await +} diff --git a/qa-test/src/bin/wifi_reinit_scan.rs b/examples/qa/src/bin/wifi-reinit-scan.rs similarity index 95% rename from qa-test/src/bin/wifi_reinit_scan.rs rename to examples/qa/src/bin/wifi-reinit-scan.rs index 2d3221b4231..619b6ecbdb9 100644 --- a/qa-test/src/bin/wifi_reinit_scan.rs +++ b/examples/qa/src/bin/wifi-reinit-scan.rs @@ -26,6 +26,7 @@ use esp_backtrace as _; use esp_hal::{clock::CpuClock, ram, timer::timg::TimerGroup}; use esp_println::println; use esp_radio::wifi::{ControllerConfig, WifiController, scan::ScanConfig}; +use qa_test::DRAM2_UNINIT_SIZE; esp_bootloader_esp_idf::esp_app_desc!(); @@ -44,10 +45,10 @@ async fn main(_spawner: Spawner) { esp_alloc::heap_allocator!(size: 32 * 1024); // add some more RAM - esp_alloc::heap_allocator!(#[ram(reclaimed)] size: 64 * 1024); + esp_alloc::heap_allocator!(#[ram(reclaimed)] size: DRAM2_UNINIT_SIZE); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); println!( "Waiting {}s (baseline power, radio never initialized)", diff --git a/qa-test/src/bin/wifi_survives_ble_drop.rs b/examples/qa/src/bin/wifi-survives-ble-drop.rs similarity index 96% rename from qa-test/src/bin/wifi_survives_ble_drop.rs rename to examples/qa/src/bin/wifi-survives-ble-drop.rs index 71f182c91ff..5f5732938b0 100644 --- a/qa-test/src/bin/wifi_survives_ble_drop.rs +++ b/examples/qa/src/bin/wifi-survives-ble-drop.rs @@ -32,6 +32,7 @@ use esp_radio::{ sta::StationConfig, }, }; +use qa_test::DRAM2_UNINIT_SIZE; esp_bootloader_esp_idf::esp_app_desc!(); // When you are okay with using a nightly compiler it's better to use https://docs.rs/static_cell/2.1.0/static_cell/macro.make_static.html @@ -56,17 +57,17 @@ async fn main(spawner: Spawner) -> ! { // COEX needs more RAM - add some more #[cfg(feature = "esp32")] { - esp_alloc::heap_allocator!(#[ram(reclaimed)] size: 96 * 1024); + esp_alloc::heap_allocator!(#[ram(reclaimed)] size: DRAM2_UNINIT_SIZE); esp_alloc::heap_allocator!(size: 24 * 1024); } #[cfg(not(feature = "esp32"))] { - esp_alloc::heap_allocator!(#[ram(reclaimed)] size: 64 * 1024); + esp_alloc::heap_allocator!(#[ram(reclaimed)] size: DRAM2_UNINIT_SIZE); esp_alloc::heap_allocator!(size: 64 * 1024); } let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let bluetooth = peripherals.BT; let ble_controller = BleConnector::new(bluetooth, Default::default()).unwrap(); diff --git a/qa-test/src/bin/wifi_syslog.rs b/examples/qa/src/bin/wifi-syslog.rs similarity index 92% rename from qa-test/src/bin/wifi_syslog.rs rename to examples/qa/src/bin/wifi-syslog.rs index e3b33c5fabc..6d5f039fa67 100644 --- a/qa-test/src/bin/wifi_syslog.rs +++ b/examples/qa/src/bin/wifi-syslog.rs @@ -14,6 +14,7 @@ use esp_backtrace as _; use esp_hal::{clock::CpuClock, ram, timer::timg::TimerGroup}; use esp_println::println; use esp_radio::wifi::{AuthenticationMethodConfig, Config, ControllerConfig, sta::StationConfig}; +use qa_test::DRAM2_UNINIT_SIZE; esp_bootloader_esp_idf::esp_app_desc!(); @@ -27,10 +28,10 @@ async fn main(_spawner: Spawner) { let peripherals = esp_hal::init(config); esp_alloc::heap_allocator!(size: 32 * 1024); - esp_alloc::heap_allocator!(#[ram(reclaimed)] size: 64 * 1024); + esp_alloc::heap_allocator!(#[ram(reclaimed)] size: DRAM2_UNINIT_SIZE); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let station_config = Config::Station( StationConfig::default() diff --git a/examples/qa/src/lib.rs b/examples/qa/src/lib.rs new file mode 100644 index 00000000000..e271af80e30 --- /dev/null +++ b/examples/qa/src/lib.rs @@ -0,0 +1,7 @@ +#![no_std] + +/// Bytes in `.dram2_uninit` for the selected chip. +pub const DRAM2_UNINIT_SIZE: usize = { + let range: core::ops::Range = esp_metadata_generated::memory_range!("DRAM2_UNINIT"); + range.end - range.start +}; diff --git a/examples/wifi/80211_tx/Cargo.toml b/examples/wifi/80211_tx/Cargo.toml index de52e793b97..c80e19ee0ed 100644 --- a/examples/wifi/80211_tx/Cargo.toml +++ b/examples/wifi/80211_tx/Cargo.toml @@ -13,6 +13,7 @@ esp-backtrace = { path = "../../../esp-backtrace", features = [ ] } esp-bootloader-esp-idf = { path = "../../../esp-bootloader-esp-idf" } esp-hal = { path = "../../../esp-hal", features = ["log-04", "unstable"] } +esp-metadata-generated = { path = "../../../esp-metadata-generated" } esp-println = { path = "../../../esp-println", features = ["log-04"] } esp-rtos = { path = "../../../esp-rtos", features = ["esp-radio", "log-04", "embassy"] } esp-radio = { path = "../../../esp-radio", features = [ @@ -29,6 +30,7 @@ esp32 = [ "esp-backtrace/esp32", "esp-bootloader-esp-idf/esp32", "esp-hal/esp32", + "esp-metadata-generated/esp32", "esp-rtos/esp32", "esp-radio/esp32", ] @@ -37,6 +39,7 @@ esp32c2 = [ "esp-backtrace/esp32c2", "esp-bootloader-esp-idf/esp32c2", "esp-hal/esp32c2", + "esp-metadata-generated/esp32c2", "esp-rtos/esp32c2", "esp-radio/esp32c2", ] @@ -45,6 +48,7 @@ esp32c3 = [ "esp-backtrace/esp32c3", "esp-bootloader-esp-idf/esp32c3", "esp-hal/esp32c3", + "esp-metadata-generated/esp32c3", "esp-rtos/esp32c3", "esp-radio/esp32c3", ] @@ -53,6 +57,7 @@ esp32c5 = [ "esp-backtrace/esp32c5", "esp-bootloader-esp-idf/esp32c5", "esp-hal/esp32c5", + "esp-metadata-generated/esp32c5", "esp-rtos/esp32c5", "esp-radio/esp32c5", ] @@ -61,6 +66,7 @@ esp32c6 = [ "esp-backtrace/esp32c6", "esp-bootloader-esp-idf/esp32c6", "esp-hal/esp32c6", + "esp-metadata-generated/esp32c6", "esp-rtos/esp32c6", "esp-radio/esp32c6", ] @@ -69,14 +75,25 @@ esp32c61 = [ "esp-backtrace/esp32c61", "esp-bootloader-esp-idf/esp32c61", "esp-hal/esp32c61", + "esp-metadata-generated/esp32c61", "esp-rtos/esp32c61", "esp-radio/esp32c61", ] +esp32s31 = [ + "esp-alloc/esp32s31", + "esp-backtrace/esp32s31", + "esp-bootloader-esp-idf/esp32s31", + "esp-hal/esp32s31", + "esp-metadata-generated/esp32s31", + "esp-rtos/esp32s31", + "esp-radio/esp32s31", +] esp32s2 = [ "esp-alloc/esp32s2", "esp-backtrace/esp32s2", "esp-bootloader-esp-idf/esp32s2", "esp-hal/esp32s2", + "esp-metadata-generated/esp32s2", "esp-rtos/esp32s2", "esp-radio/esp32s2", ] @@ -85,6 +102,7 @@ esp32s3 = [ "esp-backtrace/esp32s3", "esp-bootloader-esp-idf/esp32s3", "esp-hal/esp32s3", + "esp-metadata-generated/esp32s3", "esp-rtos/esp32s3", "esp-radio/esp32s3", ] diff --git a/examples/wifi/80211_tx/src/main.rs b/examples/wifi/80211_tx/src/main.rs index b702b30f83f..e0942115958 100644 --- a/examples/wifi/80211_tx/src/main.rs +++ b/examples/wifi/80211_tx/src/main.rs @@ -24,6 +24,12 @@ use ieee80211::{ esp_bootloader_esp_idf::esp_app_desc!(); +// Full `.dram2_uninit` region for this chip. +const DRAM2_UNINIT_SIZE: usize = { + let range: core::ops::Range = esp_metadata_generated::memory_range!("DRAM2_UNINIT"); + range.end - range.start +}; + const SSID: &str = "esp-radio 802.11 injection"; /// This is an arbitrary MAC address, used for the fake beacon frames. const MAC_ADDRESS: [u8; 6] = [0x00, 0x80, 0x41, 0x13, 0x37, 0x42]; @@ -34,16 +40,16 @@ async fn main(_spawner: embassy_executor::Spawner) -> ! { let config = esp_hal::Config::default().with_cpu_clock(CpuClock::max()); let peripherals = esp_hal::init(config); - esp_alloc::heap_allocator!(#[ram(reclaimed)] size: 64 * 1024); + esp_alloc::heap_allocator!(#[ram(reclaimed)] size: DRAM2_UNINIT_SIZE); esp_alloc::heap_allocator!(size: 36 * 1024); let delay = Delay::new(); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); - // The sniffer borrows the controller, so we only need the controller here — - // no station/AP `Interface` is required for raw 802.11 transmit. + // Wi-Fi stays initialized while the sniffer is alive — no station/AP + // `Interface` is required for raw 802.11 transmit. let controller = esp_radio::wifi::WifiController::new(peripherals.WIFI, Default::default()).unwrap(); diff --git a/examples/wifi/embassy_access_point/Cargo.toml b/examples/wifi/embassy_access_point/Cargo.toml index aeaa734d9a1..fcc4d465fba 100644 --- a/examples/wifi/embassy_access_point/Cargo.toml +++ b/examples/wifi/embassy_access_point/Cargo.toml @@ -24,6 +24,7 @@ esp-backtrace = { path = "../../../esp-backtrace", features = [ ] } esp-bootloader-esp-idf = { path = "../../../esp-bootloader-esp-idf" } esp-hal = { path = "../../../esp-hal", features = ["log-04", "unstable"] } +esp-metadata-generated = { path = "../../../esp-metadata-generated" } esp-println = { path = "../../../esp-println", features = ["log-04"] } esp-rtos = { path = "../../../esp-rtos", features = ["esp-radio", "embassy", "log-04"] } esp-radio = { path = "../../../esp-radio", features = [ @@ -39,6 +40,7 @@ esp32 = [ "esp-backtrace/esp32", "esp-bootloader-esp-idf/esp32", "esp-hal/esp32", + "esp-metadata-generated/esp32", "esp-rtos/esp32", "esp-radio/esp32", ] @@ -47,6 +49,7 @@ esp32c2 = [ "esp-backtrace/esp32c2", "esp-bootloader-esp-idf/esp32c2", "esp-hal/esp32c2", + "esp-metadata-generated/esp32c2", "esp-rtos/esp32c2", "esp-radio/esp32c2", ] @@ -55,6 +58,7 @@ esp32c3 = [ "esp-backtrace/esp32c3", "esp-bootloader-esp-idf/esp32c3", "esp-hal/esp32c3", + "esp-metadata-generated/esp32c3", "esp-rtos/esp32c3", "esp-radio/esp32c3", ] @@ -63,6 +67,7 @@ esp32c5 = [ "esp-backtrace/esp32c5", "esp-bootloader-esp-idf/esp32c5", "esp-hal/esp32c5", + "esp-metadata-generated/esp32c5", "esp-rtos/esp32c5", "esp-radio/esp32c5", ] @@ -71,6 +76,7 @@ esp32c6 = [ "esp-backtrace/esp32c6", "esp-bootloader-esp-idf/esp32c6", "esp-hal/esp32c6", + "esp-metadata-generated/esp32c6", "esp-rtos/esp32c6", "esp-radio/esp32c6", ] @@ -79,14 +85,25 @@ esp32c61 = [ "esp-backtrace/esp32c61", "esp-bootloader-esp-idf/esp32c61", "esp-hal/esp32c61", + "esp-metadata-generated/esp32c61", "esp-rtos/esp32c61", "esp-radio/esp32c61", ] +esp32s31 = [ + "esp-alloc/esp32s31", + "esp-backtrace/esp32s31", + "esp-bootloader-esp-idf/esp32s31", + "esp-hal/esp32s31", + "esp-metadata-generated/esp32s31", + "esp-rtos/esp32s31", + "esp-radio/esp32s31", +] esp32s2 = [ "esp-alloc/esp32s2", "esp-backtrace/esp32s2", "esp-bootloader-esp-idf/esp32s2", "esp-hal/esp32s2", + "esp-metadata-generated/esp32s2", "esp-rtos/esp32s2", "esp-radio/esp32s2", ] @@ -95,6 +112,7 @@ esp32s3 = [ "esp-backtrace/esp32s3", "esp-bootloader-esp-idf/esp32s3", "esp-hal/esp32s3", + "esp-metadata-generated/esp32s3", "esp-rtos/esp32s3", "esp-radio/esp32s3", ] diff --git a/examples/wifi/embassy_access_point/src/main.rs b/examples/wifi/embassy_access_point/src/main.rs index 1af06fd94e0..0903f62ed2d 100644 --- a/examples/wifi/embassy_access_point/src/main.rs +++ b/examples/wifi/embassy_access_point/src/main.rs @@ -33,6 +33,12 @@ use esp_println::{print, println}; use esp_radio::wifi::{Config, ControllerConfig, Interface, WifiController, ap::AccessPointConfig}; esp_bootloader_esp_idf::esp_app_desc!(); +// Full `.dram2_uninit` region for this chip. +const DRAM2_UNINIT_SIZE: usize = { + let range: core::ops::Range = esp_metadata_generated::memory_range!("DRAM2_UNINIT"); + range.end - range.start +}; + // When you are okay with using a nightly compiler it's better to use https://docs.rs/static_cell/2.1.0/static_cell/macro.make_static.html macro_rules! mk_static { ($t:ty,$val:expr) => {{ @@ -51,11 +57,11 @@ async fn main(spawner: Spawner) -> ! { let config = esp_hal::Config::default().with_cpu_clock(CpuClock::max()); let peripherals = esp_hal::init(config); - esp_alloc::heap_allocator!(#[ram(reclaimed)] size: 64 * 1024); + esp_alloc::heap_allocator!(#[ram(reclaimed)] size: DRAM2_UNINIT_SIZE); esp_alloc::heap_allocator!(size: 36 * 1024); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let access_point_config = Config::AccessPoint( AccessPointConfig::default().with_ssid("esp-radio".try_into().unwrap()), diff --git a/examples/wifi/embassy_access_point_with_sta/Cargo.toml b/examples/wifi/embassy_access_point_with_sta/Cargo.toml index b02b8a51481..03f5547d3f8 100644 --- a/examples/wifi/embassy_access_point_with_sta/Cargo.toml +++ b/examples/wifi/embassy_access_point_with_sta/Cargo.toml @@ -22,6 +22,7 @@ esp-backtrace = { path = "../../../esp-backtrace", features = [ ] } esp-bootloader-esp-idf = { path = "../../../esp-bootloader-esp-idf" } esp-hal = { path = "../../../esp-hal", features = ["log-04", "unstable"] } +esp-metadata-generated = { path = "../../../esp-metadata-generated" } esp-println = { path = "../../../esp-println", features = ["log-04"] } esp-rtos = { path = "../../../esp-rtos", features = ["esp-radio", "embassy", "log-04"] } esp-radio = { path = "../../../esp-radio", features = [ @@ -37,6 +38,7 @@ esp32 = [ "esp-backtrace/esp32", "esp-bootloader-esp-idf/esp32", "esp-hal/esp32", + "esp-metadata-generated/esp32", "esp-rtos/esp32", "esp-radio/esp32", ] @@ -45,6 +47,7 @@ esp32c2 = [ "esp-backtrace/esp32c2", "esp-bootloader-esp-idf/esp32c2", "esp-hal/esp32c2", + "esp-metadata-generated/esp32c2", "esp-rtos/esp32c2", "esp-radio/esp32c2", ] @@ -53,6 +56,7 @@ esp32c3 = [ "esp-backtrace/esp32c3", "esp-bootloader-esp-idf/esp32c3", "esp-hal/esp32c3", + "esp-metadata-generated/esp32c3", "esp-rtos/esp32c3", "esp-radio/esp32c3", ] @@ -61,6 +65,7 @@ esp32c5 = [ "esp-backtrace/esp32c5", "esp-bootloader-esp-idf/esp32c5", "esp-hal/esp32c5", + "esp-metadata-generated/esp32c5", "esp-rtos/esp32c5", "esp-radio/esp32c5", ] @@ -69,6 +74,7 @@ esp32c6 = [ "esp-backtrace/esp32c6", "esp-bootloader-esp-idf/esp32c6", "esp-hal/esp32c6", + "esp-metadata-generated/esp32c6", "esp-rtos/esp32c6", "esp-radio/esp32c6", ] @@ -77,14 +83,25 @@ esp32c61 = [ "esp-backtrace/esp32c61", "esp-bootloader-esp-idf/esp32c61", "esp-hal/esp32c61", + "esp-metadata-generated/esp32c61", "esp-rtos/esp32c61", "esp-radio/esp32c61", ] +esp32s31 = [ + "esp-alloc/esp32s31", + "esp-backtrace/esp32s31", + "esp-bootloader-esp-idf/esp32s31", + "esp-hal/esp32s31", + "esp-metadata-generated/esp32s31", + "esp-rtos/esp32s31", + "esp-radio/esp32s31", +] esp32s2 = [ "esp-alloc/esp32s2", "esp-backtrace/esp32s2", "esp-bootloader-esp-idf/esp32s2", "esp-hal/esp32s2", + "esp-metadata-generated/esp32s2", "esp-rtos/esp32s2", "esp-radio/esp32s2", ] @@ -93,6 +110,7 @@ esp32s3 = [ "esp-backtrace/esp32s3", "esp-bootloader-esp-idf/esp32s3", "esp-hal/esp32s3", + "esp-metadata-generated/esp32s3", "esp-rtos/esp32s3", "esp-radio/esp32s3", ] diff --git a/examples/wifi/embassy_access_point_with_sta/src/main.rs b/examples/wifi/embassy_access_point_with_sta/src/main.rs index 009a25bde42..b1b92187eee 100644 --- a/examples/wifi/embassy_access_point_with_sta/src/main.rs +++ b/examples/wifi/embassy_access_point_with_sta/src/main.rs @@ -58,6 +58,12 @@ use reqwless::{ }; esp_bootloader_esp_idf::esp_app_desc!(); +// Full `.dram2_uninit` region for this chip. +const DRAM2_UNINIT_SIZE: usize = { + let range: core::ops::Range = esp_metadata_generated::memory_range!("DRAM2_UNINIT"); + range.end - range.start +}; + const SSID: &str = env!("SSID"); const PASSWORD: &str = env!("PASSWORD"); @@ -77,11 +83,11 @@ async fn main(spawner: Spawner) -> ! { let config = esp_hal::Config::default().with_cpu_clock(CpuClock::max()); let peripherals = esp_hal::init(config); - esp_alloc::heap_allocator!(#[ram(reclaimed)] size: 64 * 1024); + esp_alloc::heap_allocator!(#[ram(reclaimed)] size: DRAM2_UNINIT_SIZE); esp_alloc::heap_allocator!(size: 36 * 1024); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let access_point_station_config = Config::AccessPointStation( StationConfig::default() diff --git a/examples/wifi/embassy_coex/Cargo.toml b/examples/wifi/embassy_coex/Cargo.toml index 1553264accc..bddb54953ec 100644 --- a/examples/wifi/embassy_coex/Cargo.toml +++ b/examples/wifi/embassy_coex/Cargo.toml @@ -22,6 +22,7 @@ esp-backtrace = { path = "../../../esp-backtrace", features = [ ] } esp-bootloader-esp-idf = { path = "../../../esp-bootloader-esp-idf" } esp-hal = { path = "../../../esp-hal", features = ["log-04", "unstable"] } +esp-metadata-generated = { path = "../../../esp-metadata-generated" } esp-println = { path = "../../../esp-println", features = ["log-04"] } esp-rtos = { path = "../../../esp-rtos", features = ["esp-radio", "embassy", "log-04"] } esp-radio = { path = "../../../esp-radio", features = [ @@ -33,7 +34,7 @@ esp-radio = { path = "../../../esp-radio", features = [ ] } reqwless = { version = "0.14.0", default-features = false } static_cell = "2.1.0" -trouble-host = { version = "0.7.0", features = [ +trouble-host = { version = "0.8.0", features = [ "default-packet-pool-mtu-255", "derive", "scan", @@ -45,6 +46,7 @@ esp32 = [ "esp-backtrace/esp32", "esp-bootloader-esp-idf/esp32", "esp-hal/esp32", + "esp-metadata-generated/esp32", "esp-rtos/esp32", "esp-radio/esp32", ] @@ -53,6 +55,7 @@ esp32c2 = [ "esp-backtrace/esp32c2", "esp-bootloader-esp-idf/esp32c2", "esp-hal/esp32c2", + "esp-metadata-generated/esp32c2", "esp-rtos/esp32c2", "esp-radio/esp32c2", ] @@ -61,6 +64,7 @@ esp32c3 = [ "esp-backtrace/esp32c3", "esp-bootloader-esp-idf/esp32c3", "esp-hal/esp32c3", + "esp-metadata-generated/esp32c3", "esp-rtos/esp32c3", "esp-radio/esp32c3", ] @@ -69,6 +73,7 @@ esp32c5 = [ "esp-backtrace/esp32c5", "esp-bootloader-esp-idf/esp32c5", "esp-hal/esp32c5", + "esp-metadata-generated/esp32c5", "esp-rtos/esp32c5", "esp-radio/esp32c5", ] @@ -77,6 +82,7 @@ esp32c6 = [ "esp-backtrace/esp32c6", "esp-bootloader-esp-idf/esp32c6", "esp-hal/esp32c6", + "esp-metadata-generated/esp32c6", "esp-rtos/esp32c6", "esp-radio/esp32c6", ] @@ -85,14 +91,25 @@ esp32c61 = [ "esp-backtrace/esp32c61", "esp-bootloader-esp-idf/esp32c61", "esp-hal/esp32c61", + "esp-metadata-generated/esp32c61", "esp-rtos/esp32c61", "esp-radio/esp32c61", ] +esp32s31 = [ + "esp-alloc/esp32s31", + "esp-backtrace/esp32s31", + "esp-bootloader-esp-idf/esp32s31", + "esp-hal/esp32s31", + "esp-metadata-generated/esp32s31", + "esp-rtos/esp32s31", + "esp-radio/esp32s31", +] esp32s3 = [ "esp-alloc/esp32s3", "esp-backtrace/esp32s3", "esp-bootloader-esp-idf/esp32s3", "esp-hal/esp32s3", + "esp-metadata-generated/esp32s3", "esp-rtos/esp32s3", "esp-radio/esp32s3", ] diff --git a/examples/wifi/embassy_coex/src/main.rs b/examples/wifi/embassy_coex/src/main.rs index 004f7080d2b..5cc8bbc3daf 100644 --- a/examples/wifi/embassy_coex/src/main.rs +++ b/examples/wifi/embassy_coex/src/main.rs @@ -4,6 +4,20 @@ //! - gets an ip address via DHCP //! - performs an HTTP get request to some "random" server //! - does BLE advertising and allows to connect +//! +//! The example also shows how to save power. Change these constants to compare: +//! +//! - `POWER_SAVE` selects the Wi-Fi modem power save mode. With power save, the radio is off +//! between beacons. +//! - `MODEM_SLEEP` lets the BLE controller turn the radio off between its events. +//! - `LIGHT_SLEEP` lets the chip enter automatic light sleep when all tasks are idle. The chip +//! sleeps only while both radios allow it. +//! - `CPU_POWERDOWN` lets light sleep power the CPU down, and retains its state in RAM. This saves +//! more current, but it makes the sleep and the wake slower. Only the ESP32-C3, -C5, -C6, -C61, +//! -S3 and -S31 support this. On other chips the constant has no effect. +//! +//! The USB Serial/JTAG console stops while the chip is in light sleep. Use the UART port to see +//! the output. //% CHIP_FILTER: wifi_driver_supported && bt_driver_supported @@ -11,7 +25,7 @@ #![no_main] use embassy_executor::Spawner; -use embassy_futures::join::join; +use embassy_futures::{join::join, select::select}; use embassy_net::{ Runner, StackResources, @@ -21,7 +35,12 @@ use embassy_net::{ use embassy_time::{Duration, Timer}; use esp_alloc as _; use esp_backtrace as _; -use esp_hal::{clock::CpuClock, ram, rng::Rng, timer::timg::TimerGroup}; +use esp_hal::{ + clock::{ClockConfig, CpuClock}, + ram, + rng::Rng, + timer::timg::TimerGroup, +}; use esp_println::println; use esp_radio::{ ble::controller::BleConnector, @@ -30,6 +49,7 @@ use esp_radio::{ Config, ControllerConfig, Interface, + PowerSaveMode, WifiController, scan::ScanConfig, sta::StationConfig, @@ -42,6 +62,12 @@ use reqwless::{ use trouble_host::prelude::*; esp_bootloader_esp_idf::esp_app_desc!(); +// Full `.dram2_uninit` region for this chip. +const DRAM2_UNINIT_SIZE: usize = { + let range: core::ops::Range = esp_metadata_generated::memory_range!("DRAM2_UNINIT"); + range.end - range.start +}; + // When you are okay with using a nightly compiler it's better to use https://docs.rs/static_cell/2.1.0/static_cell/macro.make_static.html macro_rules! mk_static { ($t:ty,$val:expr) => {{ @@ -55,6 +81,67 @@ macro_rules! mk_static { const SSID: &str = env!("SSID"); const PASSWORD: &str = env!("PASSWORD"); +/// The Wi-Fi modem power save mode. [`PowerSaveMode::None`] keeps the radio on and prevents +/// light-sleep. +const POWER_SAVE: PowerSaveMode = PowerSaveMode::Minimum; +/// Whether the BLE controller turns the radio off between its events. +const MODEM_SLEEP: bool = true; +/// Whether the chip enters automatic light sleep when all tasks are idle. Requires [`POWER_SAVE`] +/// and [`MODEM_SLEEP`] to be enabled. +const LIGHT_SLEEP: bool = true; +/// Whether light sleep powers the CPU down. Requires [`LIGHT_SLEEP`] to be enabled. +const CPU_POWERDOWN: bool = true; + +// An example reads no chip capability, so this condition lists the chips that support CPU +// power-down. +cfg_select! { + any( + feature = "esp32c3", + feature = "esp32c5", + feature = "esp32c6", + feature = "esp32c61", + feature = "esp32s3", + feature = "esp32s31", + ) => { + use esp_hal::rtc_cntl::CpuRetentionStorage; + + // The memory that the bootloader used is otherwise unused after boot. + #[ram(reclaimed, unstable(zeroed))] + static CPU_RETENTION_MEMORY: CpuRetentionStorage = CpuRetentionStorage::new(); + + // Keeping the cache tags makes the wake faster, because the cache stays warm. + #[cfg(feature = "esp32s3")] + #[ram(reclaimed, unstable(zeroed))] + static CACHE_TAGMEM: esp_hal::rtc_cntl::CacheTagRetentionStorage = + esp_hal::rtc_cntl::CacheTagRetentionStorage::new(); + + /// The reclaimed RAM that CPU power-down takes from the heap. The 16 bytes per buffer + /// cover its alignment. + const CPU_POWERDOWN_RAM: usize = size_of::() + + 16 + + cfg_select! { + feature = "esp32s3" => { + size_of::() + 16 + } + _ => 0, + }; + + fn enable_cpu_powerdown(sleep: &mut esp_rtos::sleep::Sleep) { + sleep + .enable_cpu_powerdown(CPU_RETENTION_MEMORY.take()) + .unwrap(); + + #[cfg(feature = "esp32s3")] + sleep.keep_cache_tags(CACHE_TAGMEM.take()).unwrap(); + } + } + _ => { + const CPU_POWERDOWN_RAM: usize = 0; + + fn enable_cpu_powerdown(_sleep: &mut esp_rtos::sleep::Sleep) {} + } +} + /// Max number of connections const CONNECTIONS_MAX: usize = 1; /// Max number of L2CAP channels. @@ -81,26 +168,50 @@ struct BatteryService { #[esp_hal::main] async fn main(spawner: Spawner) -> ! { esp_println::logger::init_logger_from_env(); - let config = esp_hal::Config::default().with_cpu_clock(CpuClock::max()); - let peripherals = esp_hal::init(config); + let peripherals = esp_hal::init(esp_hal::Config::default().with_cpu_clock({ + #[cfg_attr(feature = "esp32c2", allow(unused_mut))] + let mut config = ClockConfig::from(CpuClock::max()); + + #[cfg(not(feature = "esp32c2"))] + { + use esp_hal::clock::ll::BleLpClkConfig; + + // `Xtal` is the default, and a safe choice even in light sleep, although keeping the + // main crystal running raises the sleep current compared to an RC oscillator. + config.ble_lp_clk = Some(BleLpClkConfig::Xtal); + } + + config + })); // COEX needs more RAM - add some more #[cfg(feature = "esp32")] { - esp_alloc::heap_allocator!(#[ram(reclaimed)] size: 96 * 1024); + esp_alloc::heap_allocator!(#[ram(reclaimed)] size: DRAM2_UNINIT_SIZE); esp_alloc::heap_allocator!(size: 24 * 1024); } #[cfg(not(feature = "esp32"))] { - esp_alloc::heap_allocator!(#[ram(reclaimed)] size: 64 * 1024); - esp_alloc::heap_allocator!(size: 64 * 1024); + esp_alloc::heap_allocator!(#[ram(reclaimed)] size: DRAM2_UNINIT_SIZE - CPU_POWERDOWN_RAM); + esp_alloc::heap_allocator!(size: 64 * 1024 + CPU_POWERDOWN_RAM); } let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + if LIGHT_SLEEP { + let mut sleep = esp_rtos::sleep::configure(peripherals.LPWR); + if CPU_POWERDOWN { + enable_cpu_powerdown(&mut sleep); + } + esp_rtos::start_with_idle_hook(timg0.timer0, sleep.light_sleep_hook); + } else { + esp_rtos::start(timg0.timer0); + } - let bluetooth = peripherals.BT; - let connector = BleConnector::new(bluetooth, Default::default()).unwrap(); + let connector = BleConnector::new( + peripherals.BT, + esp_radio::ble::Config::default().with_modem_sleep(MODEM_SLEEP), + ) + .unwrap(); let ble_controller: ExternalController<_, 1> = ExternalController::new(connector); let station_config = Config::Station( @@ -118,6 +229,7 @@ async fn main(spawner: Spawner) -> ! { ControllerConfig::default().with_initial_config(station_config), ) .unwrap(); + controller.set_power_saving(POWER_SAVE).unwrap(); println!("Wifi started!"); let config = embassy_net::Config::dhcpv4(Default::default()); @@ -192,7 +304,7 @@ pub async fn ble_task(controller: ExternalController, 1>) println!("Our address = {:?}", address); - let mut resources: HostResources<_, DefaultPacketPool, CONNECTIONS_MAX, L2CAP_CHANNELS_MAX> = + let mut resources: HostResources = HostResources::new(); let stack = trouble_host::new(controller, &mut resources) .set_random_address(address) @@ -233,13 +345,20 @@ pub async fn ble_task(controller: ExternalController, 1>) ) .await { - Ok(adv) => match adv.accept().await.unwrap().with_attribute_server(&server) { - Ok(conn) => { - println!("got connection"); - gatt_events_task(&server, &conn).await.unwrap(); + Ok(adv) => { + match adv.accept().await.unwrap().with_attribute_server(&server) { + Ok(conn) => { + println!("got connection"); + let a = gatt_events_task(&server, &conn); + let b = custom_task(&server, &conn, &stack); + // run until any task ends (usually because the connection has been + // closed), then return to advertising + // state. + select(a, b).await; + } + Err(err) => println!("Error occurred: {:?}", err), } - Err(err) => println!("Error occurred: {:?}", err), - }, + } Err(e) => { panic!("[adv] error: {:?}", e); } @@ -323,3 +442,32 @@ async fn connection(mut controller: WifiController<'static>) { async fn net_task(mut runner: Runner<'static, Interface>) { runner.run().await } + +/// Example task to use the BLE notifier interface. +/// This task will notify the connected central of a counter value every 2 seconds. +/// It will also read the RSSI value every 2 seconds. +/// and will stop when the connection is closed by the central or an error occurs. +async fn custom_task( + server: &Server<'_>, + conn: &GattConnection<'_, '_, P>, + stack: &Stack<'_, C, P>, +) { + let mut tick: u8 = 0; + let level = server.battery_service.level; + loop { + tick = tick.wrapping_add(1); + println!("[custom_task] notifying connection of tick {}", tick); + if level.notify(conn, &tick, true).await.is_err() { + println!("[custom_task] error notifying connection"); + break; + }; + // read RSSI (Received Signal Strength Indicator) of the connection. + if let Ok(rssi) = conn.raw().rssi(stack).await { + println!("[custom_task] RSSI: {:?}", rssi); + } else { + println!("[custom_task] error getting RSSI"); + break; + }; + Timer::after_secs(2).await; + } +} diff --git a/examples/wifi/embassy_dhcp/.cargo/config.toml b/examples/wifi/embassy_dhcp/.cargo/config.toml index 8dff03101fb..9cce66c1f43 100644 --- a/examples/wifi/embassy_dhcp/.cargo/config.toml +++ b/examples/wifi/embassy_dhcp/.cargo/config.toml @@ -19,6 +19,7 @@ rustflags = [ [env] ESP_LOG = "info" +ESP_RADIO_CONFIG_WIFI_SOFTAP_SUPPORT = "false" SSID = "SSID" PASSWORD = "PASSWORD" STATIC_IP = "1.1.1.1 " diff --git a/examples/wifi/embassy_dhcp/Cargo.toml b/examples/wifi/embassy_dhcp/Cargo.toml index f2517e1ce2d..dcb3c4b6a63 100644 --- a/examples/wifi/embassy_dhcp/Cargo.toml +++ b/examples/wifi/embassy_dhcp/Cargo.toml @@ -21,10 +21,12 @@ esp-backtrace = { path = "../../../esp-backtrace", features = [ ] } esp-bootloader-esp-idf = { path = "../../../esp-bootloader-esp-idf" } esp-hal = { path = "../../../esp-hal", features = ["log-04", "unstable"] } +esp-metadata-generated = { path = "../../../esp-metadata-generated" } esp-println = { path = "../../../esp-println", features = ["log-04"] } esp-rtos = { path = "../../../esp-rtos", features = ["esp-radio", "embassy", "log-04"] } esp-radio = { path = "../../../esp-radio", features = [ "log-04", + "unstable", "wifi", ] } reqwless = { version = "0.14.0", default-features = false } @@ -36,6 +38,7 @@ esp32 = [ "esp-backtrace/esp32", "esp-bootloader-esp-idf/esp32", "esp-hal/esp32", + "esp-metadata-generated/esp32", "esp-rtos/esp32", "esp-radio/esp32", ] @@ -44,6 +47,7 @@ esp32c2 = [ "esp-backtrace/esp32c2", "esp-bootloader-esp-idf/esp32c2", "esp-hal/esp32c2", + "esp-metadata-generated/esp32c2", "esp-rtos/esp32c2", "esp-radio/esp32c2", ] @@ -52,6 +56,7 @@ esp32c3 = [ "esp-backtrace/esp32c3", "esp-bootloader-esp-idf/esp32c3", "esp-hal/esp32c3", + "esp-metadata-generated/esp32c3", "esp-rtos/esp32c3", "esp-radio/esp32c3", ] @@ -60,6 +65,7 @@ esp32c5 = [ "esp-backtrace/esp32c5", "esp-bootloader-esp-idf/esp32c5", "esp-hal/esp32c5", + "esp-metadata-generated/esp32c5", "esp-rtos/esp32c5", "esp-radio/esp32c5", ] @@ -68,6 +74,7 @@ esp32c6 = [ "esp-backtrace/esp32c6", "esp-bootloader-esp-idf/esp32c6", "esp-hal/esp32c6", + "esp-metadata-generated/esp32c6", "esp-rtos/esp32c6", "esp-radio/esp32c6", ] @@ -76,14 +83,25 @@ esp32c61 = [ "esp-backtrace/esp32c61", "esp-bootloader-esp-idf/esp32c61", "esp-hal/esp32c61", + "esp-metadata-generated/esp32c61", "esp-rtos/esp32c61", "esp-radio/esp32c61", ] +esp32s31 = [ + "esp-alloc/esp32s31", + "esp-backtrace/esp32s31", + "esp-bootloader-esp-idf/esp32s31", + "esp-hal/esp32s31", + "esp-metadata-generated/esp32s31", + "esp-rtos/esp32s31", + "esp-radio/esp32s31", +] esp32s2 = [ "esp-alloc/esp32s2", "esp-backtrace/esp32s2", "esp-bootloader-esp-idf/esp32s2", "esp-hal/esp32s2", + "esp-metadata-generated/esp32s2", "esp-rtos/esp32s2", "esp-radio/esp32s2", ] @@ -92,6 +110,7 @@ esp32s3 = [ "esp-backtrace/esp32s3", "esp-bootloader-esp-idf/esp32s3", "esp-hal/esp32s3", + "esp-metadata-generated/esp32s3", "esp-rtos/esp32s3", "esp-radio/esp32s3", ] diff --git a/examples/wifi/embassy_dhcp/src/main.rs b/examples/wifi/embassy_dhcp/src/main.rs index 0555bf3516d..9b6baf5f649 100644 --- a/examples/wifi/embassy_dhcp/src/main.rs +++ b/examples/wifi/embassy_dhcp/src/main.rs @@ -5,6 +5,19 @@ //! //! This gets an IP address via DHCP and performs an HTTP GET request //! using the reqwless HTTP client. +//! +//! The example also shows how to save power. Change these constants to compare: +//! +//! - `POWER_SAVE` selects the Wi-Fi modem power save mode. With power save, the radio is off +//! between beacons. +//! - `LIGHT_SLEEP` lets the chip enter automatic light sleep when all tasks are idle. The chip +//! sleeps only while the station is in power save. +//! - `CPU_POWERDOWN` lets light sleep power the CPU down, and retains its state in RAM. This saves +//! more current, but it makes the sleep and the wake slower. Only the ESP32-C3, -C5, -C6, -C61, +//! -S3 and -S31 support this. On other chips the constant has no effect. +//! +//! The USB Serial/JTAG console stops while the chip is in light sleep. Use the UART port to see +//! the output. //% CHIP_FILTER: wifi_driver_supported @@ -28,6 +41,7 @@ use esp_radio::wifi::{ Config, ControllerConfig, Interface, + PowerSaveMode, WifiController, scan::ScanConfig, sta::StationConfig, @@ -39,6 +53,12 @@ use reqwless::{ esp_bootloader_esp_idf::esp_app_desc!(); +// Full `.dram2_uninit` region for this chip. +const DRAM2_UNINIT_SIZE: usize = { + let range: core::ops::Range = esp_metadata_generated::memory_range!("DRAM2_UNINIT"); + range.end - range.start +}; + #[cfg(feature = "alloc-hooks")] use enumset::EnumSet; #[cfg(feature = "alloc-hooks")] @@ -74,17 +94,84 @@ macro_rules! mk_static { const SSID: &str = env!("SSID"); const PASSWORD: &str = env!("PASSWORD"); +/// The Wi-Fi modem power save mode. [`PowerSaveMode::None`] keeps the radio on and prevents +/// light-sleep. +const POWER_SAVE: PowerSaveMode = PowerSaveMode::Minimum; +/// Whether the chip enters automatic light sleep when all tasks are idle. Requires [`POWER_SAVE`] +/// to be enabled. The chip sleeps only while the station is in power save. +const LIGHT_SLEEP: bool = true; +/// Whether light sleep powers the CPU down. Requires [`LIGHT_SLEEP`] to be enabled. +const CPU_POWERDOWN: bool = true; + +// An example reads no chip capability, so this condition lists the chips that support CPU +// power-down. +cfg_select! { + any( + feature = "esp32c3", + feature = "esp32c5", + feature = "esp32c6", + feature = "esp32c61", + feature = "esp32s3", + feature = "esp32s31", + ) => { + use esp_hal::rtc_cntl::CpuRetentionStorage; + + // The memory that the bootloader used is otherwise unused after boot. + #[ram(reclaimed, unstable(zeroed))] + static CPU_RETENTION_MEMORY: CpuRetentionStorage = CpuRetentionStorage::new(); + + // Keeping the cache tags makes the wake faster, because the cache stays warm. + #[cfg(feature = "esp32s3")] + #[ram(reclaimed, unstable(zeroed))] + static CACHE_TAGMEM: esp_hal::rtc_cntl::CacheTagRetentionStorage = + esp_hal::rtc_cntl::CacheTagRetentionStorage::new(); + + /// The reclaimed RAM that CPU power-down takes from the heap. The 16 bytes per buffer + /// cover its alignment. + const CPU_POWERDOWN_RAM: usize = size_of::() + + 16 + + cfg_select! { + feature = "esp32s3" => { + size_of::() + 16 + } + _ => 0, + }; + + fn enable_cpu_powerdown(sleep: &mut esp_rtos::sleep::Sleep) { + sleep + .enable_cpu_powerdown(CPU_RETENTION_MEMORY.take()) + .unwrap(); + + #[cfg(feature = "esp32s3")] + sleep.keep_cache_tags(CACHE_TAGMEM.take()).unwrap(); + } + } + _ => { + const CPU_POWERDOWN_RAM: usize = 0; + + fn enable_cpu_powerdown(_sleep: &mut esp_rtos::sleep::Sleep) {} + } +} + #[esp_hal::main] async fn main(spawner: Spawner) -> ! { esp_println::logger::init_logger_from_env(); let config = esp_hal::Config::default().with_cpu_clock(CpuClock::max()); let peripherals = esp_hal::init(config); - esp_alloc::heap_allocator!(#[ram(reclaimed)] size: 64 * 1024); - esp_alloc::heap_allocator!(size: 36 * 1024); + esp_alloc::heap_allocator!(#[ram(reclaimed)] size: DRAM2_UNINIT_SIZE - CPU_POWERDOWN_RAM); + esp_alloc::heap_allocator!(size: 36 * 1024 + CPU_POWERDOWN_RAM); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + if LIGHT_SLEEP { + let mut sleep = esp_rtos::sleep::configure(peripherals.LPWR); + if CPU_POWERDOWN { + enable_cpu_powerdown(&mut sleep); + } + esp_rtos::start_with_idle_hook(timg0.timer0, sleep.light_sleep_hook); + } else { + esp_rtos::start(timg0.timer0); + } let station_config = Config::Station( StationConfig::default() @@ -101,6 +188,7 @@ async fn main(spawner: Spawner) -> ! { ControllerConfig::default().with_initial_config(station_config), ) .unwrap(); + controller.set_power_saving(POWER_SAVE).unwrap(); println!("Wifi configured and started!"); let config = embassy_net::Config::dhcpv4(Default::default()); diff --git a/examples/wifi/embassy_sntp/Cargo.toml b/examples/wifi/embassy_sntp/Cargo.toml index f24b8af774f..d6f80fe5723 100644 --- a/examples/wifi/embassy_sntp/Cargo.toml +++ b/examples/wifi/embassy_sntp/Cargo.toml @@ -20,6 +20,7 @@ esp-backtrace = { path = "../../../esp-backtrace", features = [ ] } esp-bootloader-esp-idf = { path = "../../../esp-bootloader-esp-idf" } esp-hal = { path = "../../../esp-hal", features = ["log-04", "unstable"] } +esp-metadata-generated = { path = "../../../esp-metadata-generated" } esp-println = { path = "../../../esp-println", features = ["log-04"] } esp-rtos = { path = "../../../esp-rtos", features = ["esp-radio", "embassy", "log-04"] } log = "0.4.17" @@ -38,6 +39,7 @@ esp32 = [ "esp-backtrace/esp32", "esp-bootloader-esp-idf/esp32", "esp-hal/esp32", + "esp-metadata-generated/esp32", "esp-rtos/esp32", "esp-radio/esp32", ] @@ -46,6 +48,7 @@ esp32c2 = [ "esp-backtrace/esp32c2", "esp-bootloader-esp-idf/esp32c2", "esp-hal/esp32c2", + "esp-metadata-generated/esp32c2", "esp-rtos/esp32c2", "esp-radio/esp32c2", ] @@ -54,6 +57,7 @@ esp32c3 = [ "esp-backtrace/esp32c3", "esp-bootloader-esp-idf/esp32c3", "esp-hal/esp32c3", + "esp-metadata-generated/esp32c3", "esp-rtos/esp32c3", "esp-radio/esp32c3", ] @@ -62,6 +66,7 @@ esp32c6 = [ "esp-backtrace/esp32c6", "esp-bootloader-esp-idf/esp32c6", "esp-hal/esp32c6", + "esp-metadata-generated/esp32c6", "esp-rtos/esp32c6", "esp-radio/esp32c6", ] @@ -70,6 +75,7 @@ esp32s2 = [ "esp-backtrace/esp32s2", "esp-bootloader-esp-idf/esp32s2", "esp-hal/esp32s2", + "esp-metadata-generated/esp32s2", "esp-rtos/esp32s2", "esp-radio/esp32s2", ] @@ -78,6 +84,7 @@ esp32s3 = [ "esp-backtrace/esp32s3", "esp-bootloader-esp-idf/esp32s3", "esp-hal/esp32s3", + "esp-metadata-generated/esp32s3", "esp-rtos/esp32s3", "esp-radio/esp32s3", ] @@ -86,6 +93,7 @@ esp32c5 = [ "esp-backtrace/esp32c5", "esp-bootloader-esp-idf/esp32c5", "esp-hal/esp32c5", + "esp-metadata-generated/esp32c5", "esp-rtos/esp32c5", "esp-radio/esp32c5", ] @@ -94,9 +102,19 @@ esp32c61 = [ "esp-backtrace/esp32c61", "esp-bootloader-esp-idf/esp32c61", "esp-hal/esp32c61", + "esp-metadata-generated/esp32c61", "esp-rtos/esp32c61", "esp-radio/esp32c61", ] +esp32s31 = [ + "esp-alloc/esp32s31", + "esp-backtrace/esp32s31", + "esp-bootloader-esp-idf/esp32s31", + "esp-hal/esp32s31", + "esp-metadata-generated/esp32s31", + "esp-rtos/esp32s31", + "esp-radio/esp32s31", +] [profile.release] debug = true diff --git a/examples/wifi/embassy_sntp/src/main.rs b/examples/wifi/embassy_sntp/src/main.rs index b817fcfe015..9e354c43ca6 100644 --- a/examples/wifi/embassy_sntp/src/main.rs +++ b/examples/wifi/embassy_sntp/src/main.rs @@ -41,6 +41,12 @@ use sntpc_net_embassy::UdpSocketWrapper; esp_bootloader_esp_idf::esp_app_desc!(); +// Full `.dram2_uninit` region for this chip. +const DRAM2_UNINIT_SIZE: usize = { + let range: core::ops::Range = esp_metadata_generated::memory_range!("DRAM2_UNINIT"); + range.end - range.start +}; + // When you are okay with using a nightly compiler it's better to use https://docs.rs/static_cell/2.1.0/static_cell/macro.make_static.html macro_rules! mk_static { ($t:ty,$val:expr) => {{ @@ -86,11 +92,11 @@ async fn main(spawner: Spawner) -> ! { let peripherals = esp_hal::init(config); let rtc = Rtc::new(peripherals.RTC_TIMER); - esp_alloc::heap_allocator!(#[ram(reclaimed)] size: 64 * 1024); + esp_alloc::heap_allocator!(#[ram(reclaimed)] size: DRAM2_UNINIT_SIZE); esp_alloc::heap_allocator!(size: 36 * 1024); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let station_config = Config::Station( StationConfig::default() diff --git a/examples/wifi/sniffer/Cargo.toml b/examples/wifi/sniffer/Cargo.toml index bc395a3648f..f9228a5e58b 100644 --- a/examples/wifi/sniffer/Cargo.toml +++ b/examples/wifi/sniffer/Cargo.toml @@ -14,6 +14,7 @@ esp-backtrace = { path = "../../../esp-backtrace", features = [ ] } esp-bootloader-esp-idf = { path = "../../../esp-bootloader-esp-idf" } esp-hal = { path = "../../../esp-hal", features = ["log-04", "unstable"] } +esp-metadata-generated = { path = "../../../esp-metadata-generated" } esp-println = { path = "../../../esp-println", features = ["log-04"] } esp-rtos = { path = "../../../esp-rtos", features = ["esp-radio", "log-04", "embassy"] } esp-radio = { path = "../../../esp-radio", features = [ @@ -30,6 +31,7 @@ esp32 = [ "esp-backtrace/esp32", "esp-bootloader-esp-idf/esp32", "esp-hal/esp32", + "esp-metadata-generated/esp32", "esp-rtos/esp32", "esp-radio/esp32", ] @@ -38,6 +40,7 @@ esp32c2 = [ "esp-backtrace/esp32c2", "esp-bootloader-esp-idf/esp32c2", "esp-hal/esp32c2", + "esp-metadata-generated/esp32c2", "esp-rtos/esp32c2", "esp-radio/esp32c2", ] @@ -46,6 +49,7 @@ esp32c3 = [ "esp-backtrace/esp32c3", "esp-bootloader-esp-idf/esp32c3", "esp-hal/esp32c3", + "esp-metadata-generated/esp32c3", "esp-rtos/esp32c3", "esp-radio/esp32c3", ] @@ -54,6 +58,7 @@ esp32c5 = [ "esp-backtrace/esp32c5", "esp-bootloader-esp-idf/esp32c5", "esp-hal/esp32c5", + "esp-metadata-generated/esp32c5", "esp-rtos/esp32c5", "esp-radio/esp32c5", ] @@ -62,6 +67,7 @@ esp32c6 = [ "esp-backtrace/esp32c6", "esp-bootloader-esp-idf/esp32c6", "esp-hal/esp32c6", + "esp-metadata-generated/esp32c6", "esp-rtos/esp32c6", "esp-radio/esp32c6", ] @@ -70,14 +76,25 @@ esp32c61 = [ "esp-backtrace/esp32c61", "esp-bootloader-esp-idf/esp32c61", "esp-hal/esp32c61", + "esp-metadata-generated/esp32c61", "esp-rtos/esp32c61", "esp-radio/esp32c61", ] +esp32s31 = [ + "esp-alloc/esp32s31", + "esp-backtrace/esp32s31", + "esp-bootloader-esp-idf/esp32s31", + "esp-hal/esp32s31", + "esp-metadata-generated/esp32s31", + "esp-rtos/esp32s31", + "esp-radio/esp32s31", +] esp32s2 = [ "esp-alloc/esp32s2", "esp-backtrace/esp32s2", "esp-bootloader-esp-idf/esp32s2", "esp-hal/esp32s2", + "esp-metadata-generated/esp32s2", "esp-rtos/esp32s2", "esp-radio/esp32s2", ] @@ -86,6 +103,7 @@ esp32s3 = [ "esp-backtrace/esp32s3", "esp-bootloader-esp-idf/esp32s3", "esp-hal/esp32s3", + "esp-metadata-generated/esp32s3", "esp-rtos/esp32s3", "esp-radio/esp32s3", ] diff --git a/examples/wifi/sniffer/src/main.rs b/examples/wifi/sniffer/src/main.rs index 3037a6eea64..18be3a10104 100644 --- a/examples/wifi/sniffer/src/main.rs +++ b/examples/wifi/sniffer/src/main.rs @@ -17,12 +17,18 @@ use core::cell::RefCell; use critical_section::Mutex; use esp_backtrace as _; -use esp_hal::{clock::CpuClock, timer::timg::TimerGroup}; +use esp_hal::{clock::CpuClock, ram, timer::timg::TimerGroup}; use esp_println::println; use ieee80211::{match_frames, mgmt_frame::BeaconFrame}; esp_bootloader_esp_idf::esp_app_desc!(); +// Full `.dram2_uninit` region for this chip. +const DRAM2_UNINIT_SIZE: usize = { + let range: core::ops::Range = esp_metadata_generated::memory_range!("DRAM2_UNINIT"); + range.end - range.start +}; + static KNOWN_SSIDS: Mutex>> = Mutex::new(RefCell::new(BTreeSet::new())); #[esp_hal::main] @@ -31,13 +37,14 @@ async fn main(_spawner: embassy_executor::Spawner) -> ! { let config = esp_hal::Config::default().with_cpu_clock(CpuClock::max()); let peripherals = esp_hal::init(config); - esp_alloc::heap_allocator!(size: 72 * 1024); + esp_alloc::heap_allocator!(#[ram(reclaimed)] size: DRAM2_UNINIT_SIZE); + esp_alloc::heap_allocator!(size: 36 * 1024); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); - // The sniffer borrows the controller, so we only need the controller here — - // no station/AP `Interface` is required for promiscuous capture. + // Wi-Fi stays initialized while the sniffer is alive — no station/AP + // `Interface` is required for promiscuous capture. let controller = esp_radio::wifi::WifiController::new(peripherals.WIFI, Default::default()).unwrap(); diff --git a/hil-test-radio/.cargo/config.toml b/hil-test-radio/.cargo/config.toml index 69a1b14939e..1ae7d0ba218 100644 --- a/hil-test-radio/.cargo/config.toml +++ b/hil-test-radio/.cargo/config.toml @@ -20,6 +20,9 @@ rustflags = [ "-C", "link-arg=-Wl,-Tlinkall.x", ] +[env] +DEFMT_LOG = "info,embedded_test=warn" + [unstable] build-std = ["core", "alloc"] diff --git a/hil-test-radio/Cargo.toml b/hil-test-radio/Cargo.toml index c9dea910214..773b34d2e87 100644 --- a/hil-test-radio/Cargo.toml +++ b/hil-test-radio/Cargo.toml @@ -58,7 +58,6 @@ esp-bootloader-esp-idf = { path = "../esp-bootloader-esp-idf" } esp-hal = { path = "../esp-hal" } esp-metadata-generated = { path = "../esp-metadata-generated" } esp-rtos = { path = "../esp-rtos", optional = true } -esp-storage = { path = "../esp-storage", optional = true } esp-radio = { path = "../esp-radio", optional = true } esp-radio-rtos-driver = { path = "../esp-radio-rtos-driver", optional = true } static_cell = { version = "2.1.0" } @@ -76,7 +75,7 @@ reqwless = { version = "0.14.0", default-features = false } edge-dhcp = "0.8.0" edge-nal = "0.7.0" edge-nal-embassy = "0.9.0" -trouble-host = { version = "0.7.0", default-features = false, features = [ +trouble-host = { version = "0.8.0", default-features = false, features = [ "central", "default-packet-pool-mtu-255", "derive", @@ -102,7 +101,6 @@ esp32c6 = [ "esp-hal/esp32c6", "esp-alloc?/esp32c6", "esp-radio?/esp32c6", - "esp-storage?/esp32c6", "esp-bootloader-esp-idf/esp32c6", "esp-metadata-generated/esp32c6", "esp-rtos?/esp32c6", @@ -112,7 +110,6 @@ esp32s3 = [ "esp-hal/esp32s3", "esp-alloc?/esp32s3", "esp-radio?/esp32s3", - "esp-storage?/esp32s3", "esp-bootloader-esp-idf/esp32s3", "esp-metadata-generated/esp32s3", "esp-rtos?/esp32s3", diff --git a/hil-test-radio/src/bin/support/ble_peripheral_support.rs b/hil-test-radio/src/bin/support/ble_peripheral_support.rs index 5da3cf09d31..72bf1107060 100644 --- a/hil-test-radio/src/bin/support/ble_peripheral_support.rs +++ b/hil-test-radio/src/bin/support/ble_peripheral_support.rs @@ -57,7 +57,7 @@ async fn main(_spawner: Spawner) { let p = esp_hal::init(config); let timg0 = TimerGroup::new(p.TIMG0); - esp_rtos::start(timg0.timer0, p.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let connector = BleConnector::new(p.BT, Default::default()).unwrap(); let controller: ExternalController<_, 1> = ExternalController::new(connector); @@ -71,7 +71,7 @@ where { let address = Address::random(PERIPHERAL_ADDRESS); - let mut resources: HostResources<_, DefaultPacketPool, 1, 2> = HostResources::new(); + let mut resources: HostResources = HostResources::new(); let stack = trouble_host::new(controller, &mut resources) .set_random_address(address) .build(); diff --git a/hil-test-radio/src/bin/support/wifi_ap_support.rs b/hil-test-radio/src/bin/support/wifi_ap_support.rs index bbcdfe99891..b8dd2f98f07 100644 --- a/hil-test-radio/src/bin/support/wifi_ap_support.rs +++ b/hil-test-radio/src/bin/support/wifi_ap_support.rs @@ -27,7 +27,7 @@ use esp_radio::wifi::{ ControllerConfig, Interface, WifiController, - ap::AccessPointConfig, + ap::{AccessPointConfig, EventInfo}, }; use hil_test as _; use hil_test::mk_static; @@ -57,7 +57,7 @@ async fn main(spawner: Spawner) -> ! { let p = esp_hal::init(config); let timg0 = TimerGroup::new(p.TIMG0); - esp_rtos::start(timg0.timer0, p.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let access_point_config = Config::AccessPoint( AccessPointConfig::default() @@ -68,7 +68,7 @@ async fn main(spawner: Spawner) -> ! { let device = esp_radio::wifi::Interface::access_point(); let controller = esp_radio::wifi::WifiController::new( p.WIFI, - ControllerConfig::default().with_initial_config(access_point_config), + ControllerConfig::default().with_initial_config(access_point_config.clone()), ) .unwrap(); @@ -91,7 +91,7 @@ async fn main(spawner: Spawner) -> ! { seed, ); - spawner.spawn(connection(controller).unwrap()); + spawner.spawn(connection(controller, access_point_config).unwrap()); spawner.spawn(net_task(runner).unwrap()); spawner.spawn(run_dhcp(stack, gw_ip_addr_str).unwrap()); @@ -191,11 +191,17 @@ async fn run_dhcp(stack: Stack<'static>, gw_ip_addr: &'static str) { } } +/// After each station connects, applies the unchanged configuration again. The station must stay +/// connected (`unchanged_access_point_config_keeps_the_station`). #[embassy_executor::task] -async fn connection(controller: WifiController<'static>) { +async fn connection(mut controller: WifiController<'static>, config: Config) { loop { - let _ = controller + if let Ok(EventInfo::Connected(_)) = controller .wait_for_access_point_connected_event_async() - .await; + .await + { + Timer::after(Duration::from_secs(1)).await; + controller.set_config(&config).unwrap(); + } } } diff --git a/hil-test-radio/src/bin/tests/ble.rs b/hil-test-radio/src/bin/tests/ble.rs index 0d15fb4a986..cbd75c7a952 100644 --- a/hil-test-radio/src/bin/tests/ble.rs +++ b/hil-test-radio/src/bin/tests/ble.rs @@ -3,12 +3,16 @@ //! The support firmware is a BLE peripheral; this test binary acts as the //! central device and validates that scanning and connection establishment work //! against real peer hardware. +//! +//! On chips with an IEEE 802.15.4 radio, it also checks that BLE still works when +//! the 802.15.4 driver was brought up first. //% CHIP_FILTER(has_wifi_ble): esp32c6 || esp32s3 //% HARNESS-FIRMWARE(has_wifi_ble): ble_peripheral_support //% FEATURES: unstable esp-alloc embassy //% FEATURES(has_wifi_ble): esp-radio/ble esp-radio esp-radio-unstable +//% FEATURES-IF(soc_has_ieee802154): esp-radio/ieee802154 //% ENV: ESP_HAL_CONFIG_STACK_GUARD_OFFSET=4 diff --git a/hil-test-radio/src/bin/tests/ble/gatt.rs b/hil-test-radio/src/bin/tests/ble/gatt.rs index c47e76cdb50..b40105f13b9 100644 --- a/hil-test-radio/src/bin/tests/ble/gatt.rs +++ b/hil-test-radio/src/bin/tests/ble/gatt.rs @@ -2,7 +2,11 @@ mod tests { use embassy_futures::select::select; use embassy_time::{Duration, Timer, with_timeout}; - use esp_hal::{clock::CpuClock, peripherals::Peripherals, timer::timg::TimerGroup}; + use esp_hal::{ + clock::CpuClock, + peripherals::{BT, Peripherals}, + timer::timg::TimerGroup, + }; use esp_radio::ble::controller::BleConnector; use trouble_host::prelude::*; @@ -17,13 +21,41 @@ mod tests { #[test] async fn ble_central_connects_to_peripheral(p: Peripherals) { let timg0 = TimerGroup::new(p.TIMG0); - esp_rtos::start(timg0.timer0, p.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); - let connector = BleConnector::new(p.BT, Default::default()).unwrap(); + connect_and_read_battery_level(p.BT).await; + } + + /// The 802.15.4 driver is brought up (and kept receiving) before the BLE controller is + /// created, the way a Thread device that commissions over BLE does it. Initializing BLE must + /// not reset the RF frontend under the PHY that 802.15.4 already initialized, or the + /// controller cannot transmit: no scan request, no connection request, no GATT. + #[cfg(soc_has_ieee802154)] + #[test] + async fn ble_central_connects_while_ieee802154_is_up(p: Peripherals) { + use esp_radio::ieee802154::{Config, Ieee802154}; + + let timg0 = TimerGroup::new(p.TIMG0); + esp_rtos::start(timg0.timer0); + + let mut ieee802154 = Ieee802154::new(p.IEEE802154); + ieee802154.set_config(Config { + rx_when_idle: true, + ..Default::default() + }); + ieee802154.start_receive(); + + connect_and_read_battery_level(p.BT).await; + + drop(ieee802154); + } + + async fn connect_and_read_battery_level(bt: BT<'_>) { + let connector = BleConnector::new(bt, Default::default()).unwrap(); let controller: ExternalController<_, 1> = ExternalController::new(connector); let address = Address::random(crate::PERIPHERAL_ADDRESS); - let mut resources: HostResources<_, DefaultPacketPool, 1, 2> = HostResources::new(); + let mut resources: HostResources = HostResources::new(); let stack = trouble_host::new(controller, &mut resources) .set_random_address(Address::random([0xff, 0x48, 0x49, 0x4c, 0x43, 0xff])) .build(); diff --git a/hil-test-radio/src/bin/tests/ieee802154.rs b/hil-test-radio/src/bin/tests/ieee802154.rs index 3944abe3215..90204469812 100644 --- a/hil-test-radio/src/bin/tests/ieee802154.rs +++ b/hil-test-radio/src/bin/tests/ieee802154.rs @@ -6,13 +6,14 @@ //! //! The support firmware (`ieee802154_echo_support`) runs on a second board and //! echoes back every frame it receives, so this binary can exercise both the -//! transmit/ACK and the receive paths against real peer hardware. +//! transmit/ACK and the receive paths against real peer hardware - also while +//! a BLE controller is created and dropped next to the running 802.15.4 driver. //% CHIP_FILTER(has_ieee802154): esp32c6 //% HARNESS-FIRMWARE(has_ieee802154): ieee802154_echo_support //% FEATURES: unstable esp-alloc embassy -//% FEATURES(has_ieee802154): esp-radio/ieee802154 esp-radio esp-radio-unstable +//% FEATURES(has_ieee802154): esp-radio/ieee802154 esp-radio/ble esp-radio esp-radio-unstable //% ENV: ESP_HAL_CONFIG_STACK_GUARD_OFFSET=4 diff --git a/hil-test-radio/src/bin/tests/ieee802154/loopback.rs b/hil-test-radio/src/bin/tests/ieee802154/loopback.rs index 02c8abbdd8a..e1f52363694 100644 --- a/hil-test-radio/src/bin/tests/ieee802154/loopback.rs +++ b/hil-test-radio/src/bin/tests/ieee802154/loopback.rs @@ -1,7 +1,11 @@ #[embedded_test::tests(default_timeout = 30, executor = esp_rtos::embassy::Executor::new())] mod tests { use embassy_time::{Duration, Timer}; - use esp_hal::{clock::CpuClock, peripherals::Peripherals, timer::timg::TimerGroup}; + use esp_hal::{ + clock::CpuClock, + peripherals::{IEEE802154, Peripherals, TIMG0}, + timer::timg::TimerGroup, + }; use esp_radio::ieee802154::{Config, Frame, Ieee802154}; use hil_test::ieee802154::{CHANNEL, DUT_ADDRESS, PAN_ID, PAYLOAD, SUPPORT_ADDRESS}; use ieee802154::mac::{ @@ -55,11 +59,11 @@ mod tests { } } - fn start_radio(p: Peripherals) -> Ieee802154<'static> { - let timg0 = TimerGroup::new(p.TIMG0); - esp_rtos::start(timg0.timer0, p.FROM_CPU_INTR0); + fn start_radio(timg0: TIMG0<'static>, radio: IEEE802154<'static>) -> Ieee802154<'static> { + let timg0 = TimerGroup::new(timg0); + esp_rtos::start(timg0.timer0); - let mut ieee802154 = Ieee802154::new(p.IEEE802154); + let mut ieee802154 = Ieee802154::new(radio); ieee802154.set_config(dut_config()); ieee802154.start_receive(); ieee802154 @@ -69,7 +73,7 @@ mod tests { /// should be able to observe the received ACK frame. #[test] async fn transmit_is_acknowledged(p: Peripherals) { - let mut ieee802154 = start_radio(p); + let mut ieee802154 = start_radio(p.TIMG0, p.IEEE802154); let mut acked = false; for seq in 0..30u8 { @@ -92,10 +96,39 @@ mod tests { /// the DUT should receive a frame carrying the payload it sent. #[test] async fn receives_echoed_frame(p: Peripherals) { - let mut ieee802154 = start_radio(p); + let mut ieee802154 = start_radio(p.TIMG0, p.IEEE802154); + + assert!( + receives_echo(&mut ieee802154).await, + "did not receive an echoed frame from the peer board" + ); + } + + /// A BLE controller created after the 802.15.4 driver, and dropped before it, must leave the + /// running driver alone: creating it must not reset the 802.15.4 MAC (and the RF frontend + /// under the PHY), and dropping it must not power down or gate what the driver still uses. + #[test] + async fn survives_ble_init_and_drop(p: Peripherals) { + use esp_radio::ble::controller::BleConnector; + + let mut ieee802154 = start_radio(p.TIMG0, p.IEEE802154); + + let ble = BleConnector::new(p.BT, Default::default()).unwrap(); + assert!( + receives_echo(&mut ieee802154).await, + "802.15.4 stopped working once BLE was initialized" + ); + + drop(ble); + assert!( + receives_echo(&mut ieee802154).await, + "802.15.4 stopped working once BLE was dropped" + ); + } - let mut echoed = false; - 'outer: for seq in 0..30u8 { + /// Sends frames to the peer board until it echoes one back. + async fn receives_echo(ieee802154: &mut Ieee802154<'_>) -> bool { + for seq in 0..30u8 { ieee802154.transmit(&data_frame(seq, true), false).ok(); // Wait for the peer to auto-ACK and echo the frame back to us. @@ -104,15 +137,11 @@ mod tests { if let Some(Ok(received)) = ieee802154.received() && received.frame.payload.as_slice() == PAYLOAD { - echoed = true; - break 'outer; + return true; } } } - assert!( - echoed, - "did not receive an echoed frame from the peer board" - ); + false } } diff --git a/hil-test-radio/src/bin/tests/wifi/dhcp.rs b/hil-test-radio/src/bin/tests/wifi/dhcp.rs index 39a8f2f05a3..8dccc67541d 100644 --- a/hil-test-radio/src/bin/tests/wifi/dhcp.rs +++ b/hil-test-radio/src/bin/tests/wifi/dhcp.rs @@ -1,5 +1,6 @@ #[embedded_test::tests(default_timeout = 45, executor = esp_rtos::embassy::Executor::new())] mod tests { + use embassy_futures::select::{Either, select}; use embassy_net::{ Runner, StackResources, @@ -132,7 +133,7 @@ mod tests { let spawner = unsafe { embassy_executor::Spawner::for_current_executor().await }; let timg0 = TimerGroup::new(p.TIMG0); - esp_rtos::start(timg0.timer0, p.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let wifi_interface = Interface::station(); let controller = esp_radio::wifi::WifiController::new( @@ -144,10 +145,33 @@ mod tests { run_http_smoke_test(spawner, controller, wifi_interface).await; } + #[test] + async fn unchanged_access_point_config_keeps_the_station(p: Peripherals) { + let timg0 = TimerGroup::new(p.TIMG0); + esp_rtos::start(timg0.timer0); + + let mut controller = esp_radio::wifi::WifiController::new( + p.WIFI, + ControllerConfig::default().with_initial_config(station_config()), + ) + .unwrap(); + + connect_with_retry(&mut controller).await; + + // The support firmware applies its unchanged configuration again 1 s after a station + // connects. + let disconnect = controller.wait_for_disconnect_async(); + let result = select(disconnect, Timer::after(Duration::from_secs(5))).await; + assert!( + matches!(result, Either::Second(())), + "The station was disconnected" + ); + } + #[test] async fn wifi_drop(p: Peripherals) { let timg0 = TimerGroup::new(p.TIMG0); - esp_rtos::start(timg0.timer0, p.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let spawner = unsafe { embassy_executor::Spawner::for_current_executor().await }; let mut wifi = p.WIFI; diff --git a/hil-test/Cargo.toml b/hil-test/Cargo.toml index b10a8625a77..2a3c735ed00 100644 --- a/hil-test/Cargo.toml +++ b/hil-test/Cargo.toml @@ -4,9 +4,16 @@ version = "0.0.0" edition = "2024" publish = false +[package.metadata.espressif] +aliases = ["test", "tests"] + [lib] name = "hil_test" +[[bin]] +name = "adc" +harness = false + [[bin]] name = "alloc_psram" harness = false @@ -25,6 +32,11 @@ name = "radio_basic" harness = false required-features = ["esp-alloc"] +[[bin]] +name = "ieee802154" +harness = false +required-features = ["esp-alloc"] + [[bin]] name = "gpio" harness = false @@ -49,6 +61,10 @@ harness = false name = "lcd_cam" harness = false +[[bin]] +name = "canfd" +harness = false + [[bin]] name = "misc_drivers" harness = false @@ -76,7 +92,7 @@ name = "spi" harness = false [[bin]] -name = "storage" +name = "flash" harness = false [[bin]] @@ -102,15 +118,14 @@ esp-bootloader-esp-idf = { path = "../esp-bootloader-esp-idf" } esp-hal = { path = "../esp-hal" } esp-metadata-generated = { path = "../esp-metadata-generated" } esp-rtos = { path = "../esp-rtos", optional = true } -esp-storage = { path = "../esp-storage", optional = true } esp-sync = { path = "../esp-sync" } esp-radio = { path = "../esp-radio", optional = true } esp-radio-rtos-driver = { path = "../esp-radio-rtos-driver", optional = true } portable-atomic = "1.11" -static_cell = { version = "2.1.0" } +static_cell = { version = "2.1.1" } semihosting = { version = "0.1", features= ["stdio", "panic-handler"] } -trouble-host = { version = "0.7.0", features = [ +trouble-host = { version = "0.8.0", features = [ "default-packet-pool-mtu-255", "derive", "scan", @@ -126,11 +141,18 @@ nb = "1.1.0" p192 = { version = "0.13.0", default-features = false, features = ["arithmetic"] } p256 = { version = "0.13.2", default-features = false, features = ["arithmetic"] } p384 = { version = "0.13.1", default-features = false, features = ["arithmetic"] } +sm2 = { version = "0.13.3", default-features = false, features = ["arithmetic"] } sha1 = { version = "0.11", default-features = false } sha2 = { version = "0.11", default-features = false } +sm3 = { version = "0.5", default-features = false } paste = "1.0.15" +sdio = "0.5" +block-device-adapters = "0.2.0" +embedded-fatfs = { git = "https://github.com/MabezDev/embedded-fatfs", rev = "518528cc111fcf65c48abbdeb80735a38eada112", default-features = false } +embedded-partitions = { git = "https://github.com/MabezDev/embedded-fatfs", rev = "518528cc111fcf65c48abbdeb80735a38eada112" } + [build-dependencies] esp-metadata-generated = { path = "../esp-metadata-generated", features = ["build-script"] } @@ -139,7 +161,7 @@ default = [] unstable = ["esp-hal/unstable"] # Add the `embedded-test/defmt` feature for more verbose testing -defmt = ["dep:defmt-rtt", "embedded-test/defmt", "esp-hal/defmt", "esp-rtos?/defmt", "esp-radio?/defmt"] +defmt = ["dep:defmt-rtt", "embedded-test/defmt", "esp-hal/defmt", "esp-rtos?/defmt", "esp-radio?/defmt", "esp-radio-rtos-driver?/defmt"] esp-radio = ["dep:esp-radio", "dep:esp-rtos", "dep:esp-radio-rtos-driver", "esp-rtos/esp-radio"] esp-radio-unstable = ["esp-radio/unstable"] embassy = ["dep:esp-rtos", "esp-rtos/embassy"] @@ -151,7 +173,6 @@ esp32 = [ "esp-hal/esp32", "esp-alloc?/esp32", "esp-radio?/esp32", - "esp-storage?/esp32", "esp-bootloader-esp-idf/esp32", "esp-metadata-generated/esp32", "esp-rtos?/esp32", @@ -160,7 +181,6 @@ esp32c2 = [ "esp-hal/esp32c2", "esp-alloc?/esp32c2", "esp-radio?/esp32c2", - "esp-storage?/esp32c2", "esp-bootloader-esp-idf/esp32c2", "esp-metadata-generated/esp32c2", "esp-rtos?/esp32c2" @@ -169,7 +189,6 @@ esp32c3 = [ "esp-hal/esp32c3", "esp-alloc?/esp32c3", "esp-radio?/esp32c3", - "esp-storage?/esp32c3", "esp-bootloader-esp-idf/esp32c3", "esp-metadata-generated/esp32c3", "esp-rtos?/esp32c3", @@ -178,7 +197,6 @@ esp32c5 = [ "esp-hal/esp32c5", "esp-alloc?/esp32c5", "esp-radio?/esp32c5", - "esp-storage?/esp32c5", "esp-bootloader-esp-idf/esp32c5", "esp-metadata-generated/esp32c5", "esp-rtos?/esp32c5", @@ -187,7 +205,6 @@ esp32c6 = [ "esp-hal/esp32c6", "esp-alloc?/esp32c6", "esp-radio?/esp32c6", - "esp-storage?/esp32c6", "esp-bootloader-esp-idf/esp32c6", "esp-metadata-generated/esp32c6", "esp-rtos?/esp32c6", @@ -196,7 +213,6 @@ esp32c61 = [ "esp-hal/esp32c61", "esp-alloc?/esp32c61", "esp-radio?/esp32c61", - "esp-storage?/esp32c61", "esp-bootloader-esp-idf/esp32c61", "esp-metadata-generated/esp32c61", "esp-rtos?/esp32c61", @@ -205,25 +221,30 @@ esp32h2 = [ "esp-hal/esp32h2", "esp-alloc?/esp32h2", "esp-radio?/esp32h2", - "esp-storage?/esp32h2", "esp-bootloader-esp-idf/esp32h2", "esp-metadata-generated/esp32h2", "esp-rtos?/esp32h2", ] +esp32h4 = [ + "esp-hal/esp32h4", + "esp-alloc?/esp32h4", + "esp-radio?/esp32h4", + "esp-bootloader-esp-idf/esp32h4", + "esp-metadata-generated/esp32h4", + "esp-rtos?/esp32h4", +] esp32p4 = [ "esp-hal/esp32p4", "esp-alloc?/esp32p4", "esp-bootloader-esp-idf/esp32p4", "esp-metadata-generated/esp32p4", "esp-rtos?/esp32p4", - "esp-storage?/esp32p4", ] esp32s2 = [ "embedded-test/xtensa-semihosting", "esp-hal/esp32s2", "esp-alloc?/esp32s2", "esp-radio?/esp32s2", - "esp-storage?/esp32s2", "esp-bootloader-esp-idf/esp32s2", "esp-metadata-generated/esp32s2", "esp-rtos?/esp32s2" @@ -233,7 +254,6 @@ esp32s3 = [ "esp-hal/esp32s3", "esp-alloc?/esp32s3", "esp-radio?/esp32s3", - "esp-storage?/esp32s3", "esp-bootloader-esp-idf/esp32s3", "esp-metadata-generated/esp32s3", "esp-rtos?/esp32s3", @@ -241,8 +261,7 @@ esp32s3 = [ esp32s31 = [ "esp-hal/esp32s31", "esp-alloc?/esp32s31", - # "esp-radio?/esp32s31", - "esp-storage?/esp32s31", + "esp-radio?/esp32s31", "esp-bootloader-esp-idf/esp32s31", "esp-metadata-generated/esp32s31", "esp-rtos?/esp32s31", @@ -269,3 +288,7 @@ lto = false # LTO (thin or fat) miscompiles some tests on RISC-V overflow-checks = true # We rarely debug HIL binaries, so let's shrink the .ELF size debug = 0 + +[patch.crates-io] +block-device-driver = { git = "https://github.com/MabezDev/embedded-fatfs", rev = "518528cc111fcf65c48abbdeb80735a38eada112" } +block-device-adapters = { git = "https://github.com/MabezDev/embedded-fatfs", rev = "518528cc111fcf65c48abbdeb80735a38eada112" } diff --git a/hil-test/README.md b/hil-test/README.md index 3096661155b..f977527ed8f 100644 --- a/hil-test/README.md +++ b/hil-test/README.md @@ -23,21 +23,21 @@ Target device **MUST** be connected via its USB-Serial-JTAG port, or if unavaila You can run all tests for a given device by running the following command from the workspace root: ```shell -cargo xtask run tests $CHIP +cargo xtask test $CHIP ``` To run a single test on a target, run the following command from the workspace root: ```shell # Run GPIO tests for ESP32-C6 -cargo xtask run tests esp32c6 --test gpio +cargo xtask test esp32c6 gpio ``` If you want to run a test multiple times: ```shell # Run GPIO tests for ESP32-C6 -cargo xtask run tests esp32c6 --test gpio --repeat 10 +cargo xtask test esp32c6 gpio --repeat 10 ``` Some tests will require physical connections, please see the current [configuration in our runners]. @@ -49,64 +49,85 @@ Some tests will require physical connections, please see the current [configurat ### Running Tests Remotely (ie. on Self-Hosted Runners) The [`hil.yml`] workflow builds the test suite for all our available targets and executes them. +Every board carries a pair of connected LP pads and, except for the ESP32, a pair of connected HP +pads. LP and HP pads hold their level through different registers, so the GPIO tests need a +connected pair of each. + Our self-hosted runners have the following setup: - ESP32-C2 (`esp32c2-jtag`): - Devkit: `ESP8684-DevKitM-1` connected via UART (`UART` port). - `GPIO18` and `GPIO9` are I2C pins. - - `GPIO2` and `GPIO3` are connected. + - `GPIO2` and `GPIO3` are connected (LP pads). + - `GPIO10` and `GPIO0` are connected (`GPIO10` is an HP pad, `GPIO0` an LP one - the board + has no second free HP pad). - Probe: `ESP-Prog` connected with the [following connections][connection_c2] - RPi: Raspbian 12 configured with the following [setup] - ESP32-C3 (`rustboard`): - Devkit: `ESP32-C3-DevKit-RUST-1` connected via USB-Serial-JTAG (`USB` port). - `GPIO4` and `GPIO5` are I2C pins. - - `GPIO2` and `GPIO3` are connected. + - `GPIO2` and `GPIO3` are connected (LP pads). + - `GPIO6` and `GPIO7` are connected (HP pads). - RPi: Raspbian 12 configured with the following [setup] - ESP32-C5 (`esp32c5-usb`): - Devkit: `ESP32-C5-DevKitC-1` connected via USB-Serial-JTAG (`USB` port) and UART (`UART` port). - `GPIO2` and `GPIO3` are I2C pins. - - `GPIO9` and `GPIO10` are connected. + - `GPIO9` and `GPIO10` are connected (HP pads). + - `GPIO4` and `GPIO5` are connected (LP pads). - RPi: Raspbian 12 configured with the following [setup] - ESP32-C6 (`esp32c6-usb`): - Devkit: `ESP32-C6-DevKitC-1 V1.2` connected via USB-Serial-JTAG (`USB` port) and UART (`UART` port). - `GPIO6` and `GPIO7` are I2C pins. - - `GPIO2` and `GPIO3` are connected. + - `GPIO2` and `GPIO3` are connected (LP pads). + - `GPIO22` and `GPIO23` are connected (HP pads). - RPi: Raspbian 12 configured with the following [setup] - ESP32-C61 (`esp32c61-usb`): - Devkit: `ESP32-C61-DevKitC-1 V2.0` connected via USB-Serial-JTAG (`USB` port) and UART (`UART` port). - `GPIO6` and `GPIO7` are I2C pins. - - `GPIO2` and `GPIO3` are connected. + - `GPIO2` and `GPIO3` are connected (LP pads). + - `GPIO22` and `GPIO23` are connected (HP pads). - RPi: Raspbian 12 configured with the following [setup] - ESP32-H2 (`esp32h2-usb`): - Devkit: `ESP32-H2-DevKitM-1` connected via USB-Serial-JTAG (`USB` port) and UART (`UART` port). - `GPIO12` and `GPIO22` are I2C pins. - - `GPIO2` and `GPIO3` are connected. + - `GPIO2` and `GPIO3` are connected (HP pads). + - `GPIO10` and `GPIO11` are connected (LP pads). + - RPi: Raspbian 12 configured with the following [setup] +- ESP32-H4 (`esp32h4-usb`): + - Devkit: `ESP32-H4-DevKitC-1` connected via USB-Serial-JTAG (`USB` port) and UART (`UART` port). + - `GPIO26` and `GPIO27` are I2C pins. + - `GPIO2` and `GPIO3` are connected (LP pads). + - `GPIO19` and `GPIO20` are connected (HP pads). - RPi: Raspbian 12 configured with the following [setup] - ESP32-P4 (`esp32p4`): - Devkit: `ESP32-P4 EV Board 1.6 (rev 3.1)` connected via USB-Serial-JTAG (`USB` port). - `GPIO2` and `GPIO3` are I2C pins. - - `GPIO5` and `GPIO6` are connected. + - `GPIO5` and `GPIO6` are connected (LP pads). + - `GPIO46` and `GPIO53` are connected (HP pads). - RPi: Raspbian 12 configured with the following [setup] - ESP32-S2 (`esp32s2-jtag`): - Devkit: `ESP32-S2-Saola-1` connected via UART (`UART` port). - `GPIO2` and `GPIO3` are I2C pins. - - `GPIO9` and `GPIO10` are connected. + - `GPIO9` and `GPIO10` are connected (LP pads). + - `GPIO37` and `GPIO38` are connected (HP pads). - Probe: `ESP-Prog` connected with the [following connections][connection_s2] - RPi: Raspbian 12 configured with the following [setup] - ESP32-S3 (`esp32s3-usb`): - Devkit: `ESP32-S3-DevKitC-1` connected via USB-Serial-JTAG (`USB` port) and UART (`UART` port). - `GPIO2` and `GPIO3` are I2C pins. - - `GPIO9` and `GPIO10` are connected. + - `GPIO9` and `GPIO10` are connected (LP pads). + - `GPIO40` and `GPIO41` are connected (HP pads). - RPi: Raspbian 12 configured with the following [setup] - ESP32-S31 (`esp32s31-jtag`): - Devkit: `ESP32-S31_QFN80_Test_Board` connected via UART (`USB-UART` port). - `GPIO6` and `GPIO7` are I2C pins. - - `GPIO2` and `GPIO3` are connected. + - `GPIO2` and `GPIO3` are connected (LP pads). + - `GPIO8` and `GPIO44` are connected (HP pads). - Probe: `ESP-Prog` connected with the [following connections][connection_s31] - RPi: Raspbian 12 configured with the following [setup] - ESP32 (`esp32-jtag`): - Devkit: `ESP32-ETHERNET-A-v1.2` connected via USB-Serial-JTAG (`USB` port). - `GPIO32` and `GPIO33` are I2C pins. - - `GPIO2` and `GPIO4` are connected. + - `GPIO2` and `GPIO4` are connected (LP pads). The used devkit exposes no free HP pad, so the HP tests do not run on this chip. - RPi: Raspbian 12 configured with the following [setup] [connection_s31]: https://docs.espressif.com/projects/esp-idf/en/latest/esp32s31/api-guides/jtag-debugging/configure-other-jtag.html#configure-hardware diff --git a/hil-test/src/bin/adc.rs b/hil-test/src/bin/adc.rs new file mode 100644 index 00000000000..5728dfa48ef --- /dev/null +++ b/hil-test/src/bin/adc.rs @@ -0,0 +1,313 @@ +//! ADC Tests +//! +//! Nothing drives the ADC pins to a known voltage yet, so these tests only check that conversions +//! complete and stay within the ADC's output range, not that the readings are accurate. +//! +//! The `self_cal` configuration ignores the eFuse init code, forcing `Adc::new` to measure it at +//! runtime the way it has to on chips without calibration eFuses. + +//% CHIP_FILTER: adc_driver_supported +//% FEATURES: unstable +//% FEATURES(efuse): +//% CHIP_FILTER(self_cal): adc_calibration_v1_scheme_supported && !esp32c5 +//% CARGO-CONFIG(self_cal): target.'cfg(target_os="none")'.rustflags=["--cfg=__test_adc_self_cal"] + +#![no_std] +#![no_main] + +use hil_test as _; + +// A pad of a connected test pair where one exists, so the other pad can drive it once the tests +// check the readings. Neither LP pad is on ADC1 on the ESP32, ESP32-H2, ESP32-P4 and ESP32-S31, so +// those use their HP pair where it has an ADC1 pad, or an unconnected ADC1 pad. +macro_rules! adc_pin { + ($peripherals:expr) => {{ + cfg_select! { + esp32 => $peripherals.GPIO36, + esp32h2 => hil_test::hp_test_pins!($peripherals).0, + esp32p4 => $peripherals.GPIO20, + esp32s31 => hil_test::hp_test_pins!($peripherals).1, + esp32c61 => hil_test::lp_test_pins!($peripherals).1, + // esp32c2, esp32c3, esp32c5, esp32c6, esp32s2, esp32s3 + _ => hil_test::lp_test_pins!($peripherals).0, + } + }}; +} + +const READS: usize = 16; + +// The ESP32-S2 SAR is 13 bits wide. The ESP32-S31 SAR is differential, see the `analog::adc` +// module documentation. +const MAX_RAW: u16 = if cfg!(esp32s2) { + 0x1fff +} else if cfg!(esp32s31) { + 4393 +} else { + 0xfff +}; + +macro_rules! assert_reads_complete { + ($adc:expr, $pin:expr) => {{ + for _ in 0..READS { + let value = nb::block!($adc.read_oneshot(&mut $pin)).unwrap(); + hil_test::assert!(value <= MAX_RAW, "reading {} exceeds {}", value, MAX_RAW); + } + }}; +} + +#[embedded_test::tests(default_timeout = 3, executor = hil_test::Executor::new())] +mod tests { + use esp_hal::{ + analog::adc::{Adc, AdcConfig, Attenuation}, + peripherals::Peripherals, + }; + + use super::*; + + #[init] + fn init() -> Peripherals { + esp_hal::init(esp_hal::Config::default()) + } + + #[test] + fn blocking_reads_complete(p: Peripherals) { + let mut config = AdcConfig::new(); + let mut pin = config.enable_pin(adc_pin!(p), Attenuation::_11dB); + let mut adc = Adc::new(p.ADC1, config).unwrap(); + + assert_reads_complete!(adc, pin); + } + + // Every attenuation has its own init code, so each one goes through calibration separately. + #[test] + fn every_attenuation_reads_complete(mut p: Peripherals) { + let mut gpio = adc_pin!(p); + + for attenuation in [ + Attenuation::_0dB, + Attenuation::_2p5dB, + Attenuation::_6dB, + Attenuation::_11dB, + ] { + let mut config = AdcConfig::new(); + let mut pin = config.enable_pin(gpio.reborrow(), attenuation); + let mut adc = Adc::new(p.ADC1.reborrow(), config).unwrap(); + + assert_reads_complete!(adc, pin); + } + } + + #[test] + #[cfg(adc_basic_calibration)] + fn basic_calibration_reads_complete(p: Peripherals) { + use esp_hal::{analog::adc::AdcCalBasic, peripherals::ADC1}; + + let mut config = AdcConfig::new(); + let mut pin = config + .enable_pin_with_cal::<_, AdcCalBasic>(adc_pin!(p), Attenuation::_11dB) + .unwrap(); + let mut adc = Adc::new(p.ADC1, config).unwrap(); + + assert_reads_complete!(adc, pin); + } + + // Line fitting needs a factory reference point from eFuse, which the ESP32-H2 dev kits on the + // HIL runners do not have burnt - `AdcCalLine` (and `AdcCalCurve`, built on it) returns + // `Err(Error::MissingCalibrationData)` there. + #[test] + #[cfg(all(adc_line_calibration, not(esp32h2)))] + fn line_calibration_reads_complete(p: Peripherals) { + use esp_hal::{analog::adc::AdcCalLine, peripherals::ADC1}; + + let mut config = AdcConfig::new(); + let mut pin = config + .enable_pin_with_cal::<_, AdcCalLine>(adc_pin!(p), Attenuation::_11dB) + .unwrap(); + let mut adc = Adc::new(p.ADC1, config).unwrap(); + + for _ in 0..READS { + nb::block!(adc.read_oneshot(&mut pin)).unwrap(); + } + } + + // The ESP32-H2 dev kits on the HIL runners have no line-fitting eFuse data, so calibration + // reports `MissingCalibrationData` there instead of reading. + #[test] + #[cfg(esp32h2)] + fn line_calibration_missing_data_reports_error(p: Peripherals) { + use esp_hal::{ + analog::adc::{AdcCalLine, Error}, + peripherals::ADC1, + }; + + let (failed_pin, good_pin) = hil_test::hp_test_pins!(p); + + let mut config = AdcConfig::new(); + let result = + config.enable_pin_with_cal::<_, AdcCalLine>(failed_pin, Attenuation::_11dB); + hil_test::assert!( + matches!(result, Err(Error::MissingCalibrationData)), + "line calibration without eFuse data must report MissingCalibrationData" + ); + + // The failed call must not have configured anything: enabling another channel still works. + let mut pin = config.enable_pin(good_pin, Attenuation::_11dB); + let mut adc = Adc::new(p.ADC1, config).unwrap(); + + assert_reads_complete!(adc, pin); + } + + // The ESP32-C2 only characterizes line fitting at 0 dB and 11 dB; the other attenuations have + // no reference point. + #[test] + #[cfg(esp32c2)] + fn line_calibration_unsupported_attenuation_reports_error(p: Peripherals) { + use esp_hal::{ + analog::adc::{AdcCalLine, Error}, + peripherals::ADC1, + }; + + let (failed_pin, good_pin) = hil_test::lp_test_pins!(p); + + let mut config = AdcConfig::new(); + let result = + config.enable_pin_with_cal::<_, AdcCalLine>(failed_pin, Attenuation::_6dB); + hil_test::assert!( + matches!( + result, + Err(Error::UnsupportedAttenuation(Attenuation::_6dB)) + ), + "line calibration at 6 dB must report UnsupportedAttenuation" + ); + + // The failed call must not have configured anything: enabling another channel still works. + let mut pin = config.enable_pin(good_pin, Attenuation::_11dB); + let mut adc = Adc::new(p.ADC1, config).unwrap(); + + assert_reads_complete!(adc, pin); + } + + // Not on the ESP32-H2 HIL dev kits, see `line_calibration_reads_complete`. + #[test] + #[cfg(all(adc_curve_calibration, not(esp32h2)))] + fn curve_calibration_reads_complete(p: Peripherals) { + use esp_hal::{analog::adc::AdcCalCurve, peripherals::ADC1}; + + let mut config = AdcConfig::new(); + let mut pin = config + .enable_pin_with_cal::<_, AdcCalCurve>(adc_pin!(p), Attenuation::_11dB) + .unwrap(); + let mut adc = Adc::new(p.ADC1, config).unwrap(); + + for _ in 0..READS { + nb::block!(adc.read_oneshot(&mut pin)).unwrap(); + } + } + + #[test] + #[cfg(not(esp32))] + async fn async_reads_complete(p: Peripherals) { + let mut config = AdcConfig::new(); + let mut pin = config.enable_pin(adc_pin!(p), Attenuation::_11dB); + let mut adc = Adc::new(p.ADC1, config).unwrap().into_async(); + + for _ in 0..READS { + let value = adc.read_oneshot(&mut pin).await.unwrap(); + hil_test::assert!(value <= MAX_RAW, "reading {} exceeds {}", value, MAX_RAW); + } + } + #[test] + fn unconfigured_channel_returns_error(p: Peripherals) { + use esp_hal::analog::adc::{AdcChannel, Error}; + + let mut config = AdcConfig::new(); + let mut pin = config.enable_pin(adc_pin!(p), Attenuation::_11dB); + + let empty = AdcConfig::new(); + let mut adc = Adc::new(p.ADC1, empty).unwrap(); + + let channel = pin.pin.adc_channel(); + let result = nb::block!(adc.read_oneshot(&mut pin)); + hil_test::assert!( + matches!( + result, + Err(Error::ChannelNotConfigured(ch)) if ch == channel + ), + "reading an unconfigured channel must report ChannelNotConfigured" + ); + } + + #[test] + #[cfg(not(esp32))] + async fn async_unconfigured_channel_returns_error(p: Peripherals) { + use esp_hal::analog::adc::{AdcChannel, Error}; + + let mut config = AdcConfig::new(); + let mut pin = config.enable_pin(adc_pin!(p), Attenuation::_11dB); + + let empty = AdcConfig::new(); + let mut adc = Adc::new(p.ADC1, empty).unwrap().into_async(); + + let channel = pin.pin.adc_channel(); + let result = adc.read_oneshot(&mut pin).await; + hil_test::assert!( + matches!( + result, + Err(Error::ChannelNotConfigured(ch)) if ch == channel + ), + "reading an unconfigured channel must report ChannelNotConfigured" + ); + } + + // ADC2 ownership is tracked by a global claim flag, driven here the same + // way the radio drives it: dropping a never-claimed handle or failing to + // claim must not release a live owner, while dropping a live driver must. + #[test] + #[cfg(esp32)] + fn adc2_contention_keeps_claim_and_allows_retry(mut p: Peripherals) { + use esp_hal::{ + Internal, + analog::adc::{Adc, AdcConfig, Error, release_adc2, try_claim_adc2}, + }; + + // Simulate the radio holding ADC2. + try_claim_adc2(unsafe { Internal::conjure() }).unwrap(); + + // Dropping a never-claimed handle must not release the live owner. + // (`Drop for ADC2` used to wipe the radio's claim here.) + drop(p.ADC2.reborrow()); + hil_test::assert!( + try_claim_adc2(unsafe { Internal::conjure() }).is_err(), + "dropping an unused ADC2 handle must not release the live owner" + ); + + hil_test::assert!( + matches!( + Adc::new(p.ADC2.reborrow(), AdcConfig::new()), + Err(Error::Adc2InUse) + ), + "ADC2 claim must fail while the radio holds it" + ); + // The failed claim above must not have released the live owner. + hil_test::assert!( + matches!( + Adc::new(p.ADC2.reborrow(), AdcConfig::new()), + Err(Error::Adc2InUse) + ), + "failed claim must not release the live ADC2 owner" + ); + + // Simulate radio deinit, then retry with the owned token. + release_adc2(unsafe { Internal::conjure() }); + let adc = Adc::new(p.ADC2, AdcConfig::new()).unwrap(); + + // Dropping the live driver releases the claim again. + drop(adc); + hil_test::assert!( + try_claim_adc2(unsafe { Internal::conjure() }).is_ok(), + "dropping a live ADC2 driver must release the claim" + ); + // Leave the flag unclaimed for later tests. + release_adc2(unsafe { Internal::conjure() }); + } +} diff --git a/hil-test/src/bin/alloc_dcache_reclaimed.rs b/hil-test/src/bin/alloc_dcache_reclaimed.rs deleted file mode 100644 index 56e5ac96ce8..00000000000 --- a/hil-test/src/bin/alloc_dcache_reclaimed.rs +++ /dev/null @@ -1,40 +0,0 @@ -//! Allocator tests in DCache-reclaimed memory - -//% CHIP_FILTER: esp32s3 -//% ENV(esp32s3): ESP_HAL_CONFIG_DATA_CACHE_SIZE=32KB -//% FEATURES: esp-alloc - -#![no_std] -#![no_main] - -use hil_test as _; - -extern crate alloc; - -#[embedded_test::tests] -mod dcache_reclaimed { - use esp_hal::{clock::CpuClock, ram}; - - #[init] - fn init() { - let config = esp_hal::Config::default().with_cpu_clock(CpuClock::max()); - let _p = esp_hal::init(config); - - esp_alloc::heap_allocator!(#[ram(unstable(dcache_reclaimed))] size: 32 * 1024); - } - - // alloc::vec::Vec tests - - #[test] - fn test_simple() { - let mut vec = alloc::vec::Vec::with_capacity(16384); - - for i in 0..16384 { - vec.push((i % 256) as u8); - } - - for i in 0..16384 { - assert_eq!(vec[i], (i % 256) as u8); - } - } -} diff --git a/hil-test/src/bin/alloc_psram.rs b/hil-test/src/bin/alloc_psram.rs index 59e32580911..35e4e332477 100644 --- a/hil-test/src/bin/alloc_psram.rs +++ b/hil-test/src/bin/alloc_psram.rs @@ -1,11 +1,11 @@ //! Allocator and PSRAM-related tests -//% CHIP_FILTER(llff, tlsf): psram_driver_supported && !soc_has_flash -//% CHIP_FILTER(llff_with_storage, tlsf_with_storage): psram_driver_supported && soc_has_flash -//% ENV(llff, llff_with_storage): ESP_ALLOC_CONFIG_HEAP_ALGORITHM=LLFF -//% ENV(tlsf, tlsf_with_storage): ESP_ALLOC_CONFIG_HEAP_ALGORITHM=TLSF +//% CHIP_FILTER(llff, tlsf): psram_driver_supported +//% ENV(llff): ESP_ALLOC_CONFIG_HEAP_ALGORITHM=LLFF +//% ENV(tlsf): ESP_ALLOC_CONFIG_HEAP_ALGORITHM=TLSF +// The default 64KB leaves nothing to reclaim, see the dcache_reclaimed tests below. +//% ENV-IF(esp32s3): ESP_HAL_CONFIG_DATA_CACHE_SIZE=32KB //% FEATURES: unstable esp-alloc/nightly -//% FEATURES(llff_with_storage, tlsf_with_storage): esp-storage #![no_std] #![no_main] @@ -140,12 +140,96 @@ mod tests { } } -#[cfg(feature = "esp-storage")] +/// Only the ESP32-S3 can hand unused data cache to the allocator, and only as much of it +/// as `ESP_HAL_CONFIG_DATA_CACHE_SIZE` leaves unused. +#[cfg(feature = "esp32s3")] #[embedded_test::tests] -mod storage_tests { +mod dcache_reclaimed { + use esp_hal::{clock::CpuClock, ram}; + + #[init] + fn init() { + let config = esp_hal::Config::default().with_cpu_clock(CpuClock::max()); + let _p = esp_hal::init(config); + + esp_alloc::heap_allocator!(#[ram(unstable(dcache_reclaimed))] size: 32 * 1024); + } + + #[test] + fn reclaimed_dcache_is_usable() { + let mut vec = alloc::vec::Vec::with_capacity(16384); + + for i in 0..16384 { + vec.push((i % 256) as u8); + } + + for i in 0..16384 { + assert_eq!(vec[i], (i % 256) as u8); + } + } +} + +#[cfg(multi_core)] +#[embedded_test::tests] +mod multi_core_tests { + use core::sync::atomic::{AtomicBool, Ordering}; + + use allocator_api2::boxed::Box; + use esp_alloc::ExternalMemory; + use esp_hal::{ + clock::CpuClock, + peripherals::CPU_CTRL, + system::{CpuControl, Stack}, + time::{Duration, Instant}, + }; + use hil_test::mk_static; + + #[init] + fn init() -> CPU_CTRL<'static> { + let config = esp_hal::Config::default().with_cpu_clock(CpuClock::max()); + let p = esp_hal::init(config); + esp_alloc::psram_allocator!(p.PSRAM, esp_hal::psram); + + p.CPU_CTRL + } + + #[test] + fn test_other_core_writes_psram(cpu_ctrl: CPU_CTRL<'static>) { + const PATTERN: u32 = 0xA5C3_5A3C; + static WRITTEN: AtomicBool = AtomicBool::new(false); + + let word = Box::into_raw(Box::new_in(0u32, ExternalMemory)) as usize; + + let mut cpu_control = CpuControl::new(cpu_ctrl); + let stack = mk_static!(Stack<8192>, Stack::new()); + let _guard = cpu_control + .start_app_core(stack, move || { + unsafe { (word as *mut u32).write_volatile(PATTERN) }; + WRITTEN.store(true, Ordering::Release); + loop {} + }) + .unwrap(); + + let deadline = Instant::now() + Duration::from_millis(100); + while !WRITTEN.load(Ordering::Acquire) { + assert!( + Instant::now() < deadline, + "the other core did not finish its write" + ); + } + assert_eq!(unsafe { (word as *const u32).read_volatile() }, PATTERN); + } +} + +#[cfg(flash_driver_supported)] +#[embedded_test::tests] +mod flash_tests { use esp_bootloader_esp_idf::partitions; - use esp_hal::{clock::CpuClock, peripherals::FLASH}; - use esp_storage::FlashStorage; + use esp_hal::{ + clock::CpuClock, + flash::{Config, Flash}, + peripherals::FLASH, + }; struct Context<'a> { flash: FLASH<'a>, @@ -161,8 +245,8 @@ mod storage_tests { } #[test] - fn test_with_accessing_flash_storage(ctx: Context<'static>) { - let mut flash = FlashStorage::new(ctx.flash); + fn test_with_accessing_flash(ctx: Context<'static>) { + let mut flash = Flash::new(ctx.flash, Config::default()).unwrap(); let mut pt_mem = [0u8; partitions::PARTITION_TABLE_MAX_LEN]; let pt = partitions::read_partition_table(&mut flash, &mut pt_mem).unwrap(); @@ -176,7 +260,7 @@ mod storage_tests { )) .unwrap() .unwrap() - .as_flash_region(&mut flash) + .as_auto_flash_region(&mut flash) .read(32, &mut app_desc) .unwrap(); @@ -191,14 +275,12 @@ mod storage_tests { } #[test] - fn test_spiram_is_reliable_when_using_esp_storage() { + fn test_spiram_is_reliable_when_writing_flash(ctx: Context<'static>) { // adapted from the reproducer in https://github.com/esp-rs/esp-hal/issues/3642 - const NVS_PART_FLASH_ADDR: usize = 0x9000; - - #[repr(C, align(4))] - struct AlignedBuf([u8; N]); + const NVS_PART_FLASH_ADDR: u32 = 0x9000; + let mut flash = Flash::new(ctx.flash, Config::default()).unwrap(); let rng = esp_hal::rng::Rng::new(); for _ in 0..100 { @@ -206,15 +288,9 @@ mod storage_tests { let mut heap_buf = alloc::vec![0u8; 1024]; rng.read(&mut buf); heap_buf.copy_from_slice(&buf); - let mut flash_buf = AlignedBuf([0; 4096]); - unsafe { - esp_storage::ll::spiflash_write( - NVS_PART_FLASH_ADDR as u32, - flash_buf.0.as_mut_ptr() as *const u32, - 1024, - ) - .unwrap(); - } + let flash_buf = [0u32; 256]; + // SAFETY: the NVS partition is not mapped. + unsafe { flash.write(NVS_PART_FLASH_ADDR, &flash_buf) }.unwrap(); for i in 0..1024 { assert_eq!(buf[i], heap_buf[i], "buf != heap_buf at index {}", i); @@ -222,3 +298,82 @@ mod storage_tests { } } } + +/// PSRAM at the default 200 MHz with the MPLL at 400 MHz, and at 250 MHz with the MPLL at +/// 500 MHz. +#[cfg(feature = "esp32s31")] +#[embedded_test::tests] +mod mpll { + use esp_hal::{ + clock::{ + ClockConfig, + CpuClock, + ll::{MpllClkConfig, mpll_clk_frequency}, + }, + peripherals::{HP_SYS_CLKRST, LP_AON_CLK_RST}, + psram::{Psram, PsramConfig, PsramTimingParams}, + }; + + fn assert_mpll_programmed(expected_hz: u32) { + let div = unsafe { LP_AON_CLK_RST::steal() } + .register_block() + .mspi_div() + .read(); + let fb_div = div.mspi_fb_div().bits() as u32; + let ref_div = div.mspi_ref_div().bits() as u32; + let mpll_hz = 40_000_000 * (fb_div + 1) / (ref_div + 1); + + hil_test::assert_eq!(mpll_hz, expected_hz); + hil_test::assert_eq!(mpll_hz, mpll_clk_frequency()); + + let cal = unsafe { HP_SYS_CLKRST::steal() } + .register_block() + .ana_pll_ctrl0() + .read(); + hil_test::assert!( + cal.mspi_cal_stop().bit_is_set(), + "esp-hal's MPLL calibration did not run" + ); + } + + fn assert_psram_holds_a_pattern(psram: &Psram) { + let (start, size) = psram.raw_parts(); + hil_test::assert!(size > 0); + + let words = size / 4; + let psram = unsafe { core::slice::from_raw_parts_mut(start as *mut u32, words) }; + + for (i, word) in psram.iter_mut().enumerate() { + *word = (i as u32).wrapping_mul(0x9E37_79B9); + } + for (i, word) in psram.iter().enumerate() { + hil_test::assert_eq!(*word, (i as u32).wrapping_mul(0x9E37_79B9)); + } + } + + #[test] + fn default_mpll_400_psram_200() { + let p = esp_hal::init( + esp_hal::Config::default().with_cpu_clock(ClockConfig::from(CpuClock::max())), + ); + let psram = Psram::new(p.PSRAM, PsramConfig::default()); + + assert_mpll_programmed(400_000_000); + assert_psram_holds_a_pattern(&psram); + } + + #[test] + fn mpll_500_psram_250() { + let mut clocks = ClockConfig::from(CpuClock::max()); + clocks.mpll_clk = Some(MpllClkConfig::_500); + let p = esp_hal::init(esp_hal::Config::default().with_cpu_clock(clocks)); + let config = PsramConfig { + timing: PsramTimingParams::MHZ_250, + ..Default::default() + }; + let psram = Psram::new(p.PSRAM, config); + + assert_mpll_programmed(500_000_000); + assert_psram_holds_a_pattern(&psram); + } +} diff --git a/hil-test/src/bin/canfd.rs b/hil-test/src/bin/canfd.rs new file mode 100644 index 00000000000..e6a1623ce1c --- /dev/null +++ b/hil-test/src/bin/canfd.rs @@ -0,0 +1,1617 @@ +//! CAN FD Tests +//! +//! The two common test pins are wired together. The single-node tests drive +//! one pin push-pull and listen on the other. Tests with two nodes, or with a +//! fault injector, on the wire use open-drain outputs with the internal +//! pull-ups, which is a minimal CAN bus with no transceivers. + +//% CHIP_FILTER: canfd_driver_supported +//% FEATURES: unstable embassy + +#![no_std] +#![no_main] + +use esp_hal::{ + Async, + Blocking, + DriverMode, + canfd::{ + CanFd, + CanFdInterrupt, + ClockSource, + Config, + ConfigError, + Error, + ExtendedId, + Frame, + FrameError, + FrameFormats, + Id, + MaskFilter, + MaskFilterConfig, + Mode, + RangeFilterConfig, + StandardId, + Timing, + TxBufferState, + }, + rtc_cntl::WakeLock, + timer::timg::TimerGroup, +}; +use hil_test as _; + +struct Context { + canfd: CanFd<'static, D>, +} + +// The blocking driver has to be movable into a task and shareable through a +// static. The async driver is `!Send` by design; see `esp_hal::Async`. +const _: () = { + const fn send_and_sync() {} + const fn sync() {} + send_and_sync::>(); + sync::>(); +}; + +fn std(id: u16) -> StandardId { + StandardId::new(id).unwrap() +} + +fn ext(id: u32) -> ExtendedId { + ExtendedId::new(id).unwrap() +} + +/// Loopback plus self test lets one controller exercise itself without an +/// acknowledging peer. +fn config() -> Config { + Config::default().with_mode(Mode::LoopbackSelfTest) +} + +/// Waits for a queued frame to leave the in-progress states. +fn wait_tx(canfd: &CanFd<'static, D>, index: u8) -> TxBufferState { + // The slowest bit rate these tests configure needs over a hundred + // milliseconds for one frame. + let deadline = esp_hal::time::Instant::now() + esp_hal::time::Duration::from_millis(500); + loop { + let state = canfd.tx_buffer_state(index); + if !matches!( + state, + TxBufferState::Ready | TxBufferState::InProgress | TxBufferState::AbortInProgress + ) { + return state; + } + assert!( + esp_hal::time::Instant::now() < deadline, + "TX buffer {} never finished, stuck in {:?}", + index, + state + ); + } +} + +/// Sends `frame` and returns what came back out of the RX buffer. +fn round_trip(canfd: &mut CanFd<'static, Blocking>, frame: &Frame) -> Frame { + canfd.flush_rx(); + let index = canfd.transmit(frame).unwrap(); + assert_eq!(wait_tx(canfd, index), TxBufferState::Ok, "transmit failed"); + canfd.receive().unwrap() +} + +/// Sends a one-byte frame and reports whether the filters let it through. +fn accepted(canfd: &mut CanFd<'static, Blocking>, id: impl Into) -> bool { + canfd.flush_rx(); + let frame = Frame::new(id, &[0xAA]).unwrap(); + let index = canfd.transmit(&frame).unwrap(); + assert_eq!(wait_tx(canfd, index), TxBufferState::Ok, "transmit failed"); + canfd.rx_frame_count() > 0 +} + +#[embedded_test::tests(default_timeout = 3)] +mod blocking_tests { + use esp_hal::time::{Duration, Instant}; + + use super::*; + + /// Checks the timestamp counter advances at `rate` counts per second, + /// timed against the system timer. + fn measure_rate(canfd: &CanFd<'static, Blocking>, rate: u32) { + let rate = u64::from(rate); + let start = canfd.timestamp(); + let began = Instant::now(); + while began.elapsed() < Duration::from_millis(5) {} + let elapsed = began.elapsed(); + let ticks = canfd.timestamp() - start; + + let expected = rate * elapsed.as_micros() / 1_000_000; + assert!( + ticks.abs_diff(expected) < expected / 10, + "counter advanced {} in {} us, expected about {}", + ticks, + elapsed.as_micros(), + expected + ); + } + + #[init] + fn init() -> Context { + let peripherals = esp_hal::init(esp_hal::Config::default()); + + let (rx, tx) = hil_test::common_test_pins!(peripherals); + + let mut canfd = CanFd::new(peripherals.TWAI0, config()) + .unwrap() + .with_rx(rx) + .with_tx(tx); + canfd.start().unwrap(); + + Context { canfd } + } + + #[test] + fn reports_the_ctu_can_fd_core(ctx: Context) { + assert!(ctx.canfd.identity().is_ctu_can_fd()); + assert_eq!(ctx.canfd.tx_buffer_count(), 4); + } + + #[test] + fn classic_frames_round_trip(mut ctx: Context) { + for (id, payload) in [ + (Id::from(std(0x123)), &b"12345678"[..]), + (Id::from(ext(0x1AB_CDEF)), &b"abcd"[..]), + (Id::from(std(0x7FF)), &[][..]), + ] { + let sent = Frame::new(id, payload).unwrap(); + let got = round_trip(&mut ctx.canfd, &sent); + + assert_eq!(got.id(), id); + assert!(!got.is_fd()); + assert_eq!(got.payload(), payload); + } + } + + #[test] + fn fd_frames_round_trip_at_every_payload_length(mut ctx: Context) { + for len in [0usize, 1, 8, 12, 16, 20, 24, 32, 48, 64] { + let mut payload = [0u8; 64]; + for (i, byte) in payload.iter_mut().enumerate().take(len) { + *byte = i as u8; + } + + let sent = Frame::new_fd(std(0x100 + len as u16), &payload[..len]) + .unwrap() + .with_bit_rate_switch(true); + let got = round_trip(&mut ctx.canfd, &sent); + + assert!(got.is_fd(), "len {}", len); + assert!(got.is_bit_rate_switched(), "len {}", len); + assert_eq!(got.payload(), &payload[..len], "len {}", len); + } + } + + #[test] + fn extended_id_fd_frame_round_trips(mut ctx: Context) { + let sent = Frame::new_fd(ext(0x1FF_FFFF), &[0x5A; 64]) + .unwrap() + .with_bit_rate_switch(true); + let got = round_trip(&mut ctx.canfd, &sent); + + assert_eq!(got.id(), ext(0x1FF_FFFF).into()); + assert!(got.is_extended()); + assert!(got.is_fd()); + assert_eq!(got.payload(), &[0x5A; 64]); + } + + #[test] + fn max_identifiers_round_trip(mut ctx: Context) { + for id in [Id::from(StandardId::MAX), Id::from(ExtendedId::MAX)] { + let got = round_trip(&mut ctx.canfd, &Frame::new(id, &[0x5A]).unwrap()); + assert_eq!(got.id(), id); + } + } + + #[test] + fn frames_speak_embedded_can(mut ctx: Context) { + // Code written against the `embedded-can` traits is entitled to the + // promise that a frame holds at most 8 bytes. + use embedded_can::Frame as _; + use esp_hal::canfd::ClassicFrame; + + fn eight_byte_consumer(frame: &F) -> [u8; 8] { + let data = frame.data(); + let mut bytes = [0u8; 8]; + bytes[..data.len()].copy_from_slice(data); + bytes + } + + let standard = std(0x123); + let sent = ClassicFrame::new(standard, &[1, 2, 3]).unwrap(); + let got = ClassicFrame::try_from(round_trip(&mut ctx.canfd, &sent.into())).unwrap(); + assert_eq!(embedded_can::Frame::id(&got), Id::Standard(standard)); + assert!(got.is_standard()); + assert!(got.is_data_frame()); + assert_eq!(got.dlc(), 3); + assert_eq!(got.data(), &[1, 2, 3]); + assert_eq!(eight_byte_consumer(&got), [1, 2, 3, 0, 0, 0, 0, 0]); + assert!(!got.is_fd()); + + assert!(ClassicFrame::new(standard, &[0; 9]).is_none()); + + let extended = ext(0x1AB_CDEF); + let request = ClassicFrame::new_remote(extended, 4).unwrap(); + let got = ClassicFrame::try_from(round_trip(&mut ctx.canfd, &request.into())).unwrap(); + assert_eq!(embedded_can::Frame::id(&got), Id::Extended(extended)); + assert!(embedded_can::Frame::is_extended(&got)); + assert!(got.is_remote_frame()); + assert_eq!(got.dlc(), 4); + assert_eq!(got.data(), &[]); + assert_eq!(eight_byte_consumer(&got), [0; 8]); + assert!(ClassicFrame::new_remote(extended, 9).is_none()); + + // A received FD frame must never reach that consumer. + let fd = Frame::new_fd(std(0x124), &[0x5A; 64]) + .unwrap() + .with_bit_rate_switch(true); + let got = round_trip(&mut ctx.canfd, &fd); + assert_eq!( + ClassicFrame::try_from(got).unwrap_err(), + FrameError::NotClassic + ); + } + + #[test] + fn timing_rejects_what_the_hardware_cannot_sample(_ctx: Context) { + use esp_hal::canfd::{FD_TIMING_LIMITS, NOMINAL_TIMING_LIMITS}; + + // TRM 38.3.7.7 states its limits in system clock periods, so each + // parameter here is in range and the combination is still invalid. + let too_short_phase2 = Timing { + baud_rate_prescaler: 1, + propagation_segment: 5, + phase_segment_1: 5, + phase_segment_2: 1, + sync_jump_width: 1, + }; + assert!(!too_short_phase2.is_valid(&NOMINAL_TIMING_LIMITS)); + assert!(!too_short_phase2.is_valid(&FD_TIMING_LIMITS)); + + let ok = Timing { + baud_rate_prescaler: 2, + ..too_short_phase2 + }; + assert!(ok.is_valid(&NOMINAL_TIMING_LIMITS)); + + let too_short_before_sample = Timing { + baud_rate_prescaler: 1, + propagation_segment: 1, + phase_segment_1: 0, + phase_segment_2: 2, + sync_jump_width: 1, + }; + assert!(!too_short_before_sample.is_valid(&NOMINAL_TIMING_LIMITS)); + } + + #[test] + fn frames_report_their_data_length_code(_ctx: Context) { + for (len, dlc) in [ + (0, 0), + (8, 8), + (9, 9), + (12, 9), + (13, 10), + (24, 12), + (25, 13), + (32, 13), + (33, 14), + (48, 14), + (49, 15), + (64, 15), + ] { + let frame = Frame::new_fd(std(1), &[0; 64][..len]).unwrap(); + assert_eq!(frame.dlc(), dlc, "len {}", len); + assert_eq!(frame.len(), len); + } + assert_eq!(Frame::new_request(std(1), 5).unwrap().dlc(), 5); + assert_eq!( + Frame::new_fd(std(1), &[0; 65]).unwrap_err(), + FrameError::PayloadTooLong + ); + } + + #[test] + fn mask_filter_accepts_and_rejects(mut ctx: Context) { + // Accept 0x220..=0x22F. + ctx.canfd.set_mask_filter( + MaskFilter::A, + &MaskFilterConfig::standard(std(0x220), std(0x7F0)), + ); + ctx.canfd.disable_mask_filter(MaskFilter::B); + ctx.canfd.disable_mask_filter(MaskFilter::C); + ctx.canfd.disable_range_filter(); + + assert!(accepted(&mut ctx.canfd, std(0x225)), "0x225 must pass"); + assert!(!accepted(&mut ctx.canfd, std(0x235)), "0x235 must not"); + + ctx.canfd.accept_all(); + } + + #[test] + fn range_filter_accepts_and_rejects(mut ctx: Context) { + ctx.canfd.disable_mask_filter(MaskFilter::A); + ctx.canfd + .set_range_filter(&RangeFilterConfig::standard(std(0x400), std(0x40F))); + + assert!(accepted(&mut ctx.canfd, std(0x400)), "0x400 must pass"); + assert!(accepted(&mut ctx.canfd, std(0x408)), "0x408 must pass"); + assert!(accepted(&mut ctx.canfd, std(0x40F)), "0x40F must pass"); + assert!(!accepted(&mut ctx.canfd, std(0x3FF)), "0x3FF must not"); + assert!(!accepted(&mut ctx.canfd, std(0x410)), "0x410 must not"); + + ctx.canfd.accept_all(); + } + + #[test] + fn filters_can_reject_fd_frames_alone(mut ctx: Context) { + ctx.canfd.set_mask_filter( + MaskFilter::A, + &MaskFilterConfig::standard(std(0), std(0)).with_formats(FrameFormats::Classic), + ); + ctx.canfd.disable_range_filter(); + + assert!(accepted(&mut ctx.canfd, std(0x123)), "classic must pass"); + + ctx.canfd.flush_rx(); + let fd = Frame::new_fd(std(0x123), &[0; 12]).unwrap(); + let index = ctx.canfd.transmit(&fd).unwrap(); + assert_eq!(wait_tx(&ctx.canfd, index), TxBufferState::Ok); + assert_eq!(ctx.canfd.rx_frame_count(), 0, "FD frame must be filtered"); + + ctx.canfd.accept_all(); + } + + #[test] + fn the_timestamp_counter_runs_at_the_rate_it_reports(mut ctx: Context) { + let resolution = ctx.canfd.start_timestamp_timer(1_000_000).unwrap(); + assert_eq!(resolution, 1_000_000); + assert_eq!(ctx.canfd.timestamp_bit_width(), 32); + measure_rate(&ctx.canfd, resolution); + + // A restart at a lower divider can stall the prescaler for up to + // 65536 clock periods, about a third of the time; alternate to catch it. + for round in 0..6 { + let wanted = if round % 2 == 0 { 2_000_000 } else { 1_000_000 }; + + ctx.canfd.stop_timestamp_timer(); + let got = ctx.canfd.start_timestamp_timer(wanted).unwrap(); + assert_eq!(got, wanted); + assert!( + ctx.canfd.timestamp() < u64::from(wanted) / 100, + "restarting the timer did not clear the counter" + ); + measure_rate(&ctx.canfd, got); + } + + ctx.canfd.stop_timestamp_timer(); + } + + #[test] + fn timestamps_are_captured(mut ctx: Context) { + ctx.canfd.start_timestamp_timer(1_000_000).unwrap(); + + // Let the counter climb past anything another frame field could hold. + let deadline = Instant::now() + Duration::from_millis(500); + while ctx.canfd.timestamp() < 0x1_0000 { + assert!( + Instant::now() < deadline, + "timestamp counter never reached a usable value" + ); + } + + let before = ctx.canfd.timestamp(); + let got = round_trip( + &mut ctx.canfd, + &Frame::new(std(0x555), &[1, 2, 3, 4]).unwrap(), + ); + let after = ctx.canfd.timestamp(); + + assert!( + got.timestamp() > before && got.timestamp() <= after, + "timestamp {} outside the window [{}, {}] of the transfer", + got.timestamp(), + before, + after + ); + + ctx.canfd.stop_timestamp_timer(); + } + + #[test] + fn a_clean_bus_reports_no_errors(mut ctx: Context) { + round_trip(&mut ctx.canfd, &Frame::new(std(0x321), &[7; 8]).unwrap()); + + assert_eq!(ctx.canfd.receive_error_count(), 0); + assert_eq!(ctx.canfd.transmit_error_count(), 0); + assert_eq!(ctx.canfd.error_state(), esp_hal::canfd::ErrorState::Active); + } + + #[test] + fn leaving_the_bus_waits_out_a_frame_at_a_low_bit_rate(mut ctx: Context) { + // 5 kbit/s: a 64-byte frame takes over a hundred milliseconds. + let slow = Timing { + baud_rate_prescaler: 200, + propagation_segment: 40, + phase_segment_1: 24, + phase_segment_2: 15, + sync_jump_width: 8, + }; + ctx.canfd + .apply_config(&config().with_nominal_timing(slow)) + .unwrap(); + ctx.canfd.start().unwrap(); + + let frame = Frame::new_fd(std(0x100), &[0xA5; 64]).unwrap(); + let index = ctx.canfd.transmit(&frame).unwrap(); + + let deadline = Instant::now() + Duration::from_millis(100); + while ctx.canfd.tx_buffer_state(index) != TxBufferState::InProgress { + assert!(Instant::now() < deadline, "the frame never started"); + } + + let began = Instant::now(); + ctx.canfd + .stop() + .expect("leaving the bus cut the frame short"); + let waited = began.elapsed(); + + assert!( + waited > Duration::from_millis(60), + "stopped after {} us, which is too soon to have waited for the frame", + waited.as_micros() + ); + assert!( + !matches!( + ctx.canfd.tx_buffer_state(index), + TxBufferState::Ready | TxBufferState::InProgress | TxBufferState::AbortInProgress + ), + "the buffer was still in flight after stopping" + ); + } + + #[test] + fn the_chip_stays_awake_exactly_while_the_controller_is_on_the_bus(mut ctx: Context) { + assert!(ctx.canfd.is_started()); + assert!(WakeLock::is_active(), "started in init, yet asleep"); + + ctx.canfd.stop().unwrap(); + assert!(!ctx.canfd.is_started()); + assert!(!WakeLock::is_active(), "stopped, yet held awake"); + + ctx.canfd.start().unwrap(); + assert!(ctx.canfd.is_started()); + assert!(WakeLock::is_active(), "restarted, yet asleep"); + + ctx.canfd.apply_config(&config()).unwrap(); + assert!(!ctx.canfd.is_started()); + assert!(!WakeLock::is_active(), "reconfigured, yet held awake"); + + ctx.canfd.start().unwrap(); + ctx.canfd.start().unwrap(); + ctx.canfd.stop().unwrap(); + assert!( + !WakeLock::is_active(), + "a repeated start left a lock behind" + ); + + ctx.canfd.start().unwrap(); + drop(ctx.canfd); + assert!(!WakeLock::is_active(), "dropped, yet held awake"); + } + + #[test] + fn the_transceiver_mode_cannot_change_once_the_pins_are_bound(mut ctx: Context) { + assert_eq!( + ctx.canfd.apply_config(&config().with_no_transceiver(true)), + Err(ConfigError::TransceiverModeLocked) + ); + assert!(!ctx.canfd.config().no_transceiver()); + + ctx.canfd + .apply_config(&config().with_retransmit_limit(1)) + .unwrap(); + } + + #[test] + fn the_slowest_bit_rate_still_joins_the_bus(mut ctx: Context) { + // Every field at its maximum from the 40 MHz crystal is about 741 + // bit/s, where joining takes over a hundred milliseconds. + let slowest = Timing { + baud_rate_prescaler: 255, + propagation_segment: 127, + phase_segment_1: 63, + phase_segment_2: 63, + sync_jump_width: 31, + }; + ctx.canfd + .apply_config( + &config() + .with_clock_source(ClockSource::Xtal) + .with_nominal_timing(slowest), + ) + .unwrap(); + + let began = Instant::now(); + ctx.canfd + .start() + .expect("the controller gave up before the bus could integrate"); + + assert!( + began.elapsed() > Duration::from_millis(10), + "joined in {} us, which is faster than this bit rate allows", + began.elapsed().as_micros() + ); + } + + #[test] + fn changing_the_clock_source_stops_the_timestamp_timer(mut ctx: Context) { + let resolution = ctx.canfd.start_timestamp_timer(1_000_000).unwrap(); + measure_rate(&ctx.canfd, resolution); + + ctx.canfd + .apply_config(&config().with_clock_source(ClockSource::Xtal)) + .unwrap(); + + let stopped_at = ctx.canfd.timestamp(); + let began = Instant::now(); + while began.elapsed() < Duration::from_millis(5) {} + assert_eq!( + ctx.canfd.timestamp(), + stopped_at, + "the timer kept counting across a clock source change" + ); + + let resolution = ctx.canfd.start_timestamp_timer(1_000_000).unwrap(); + measure_rate(&ctx.canfd, resolution); + ctx.canfd.stop_timestamp_timer(); + } + + #[test] + fn transmitting_while_off_the_bus_is_refused(mut ctx: Context) { + let frame = Frame::new(std(0x1A5), &[9]).unwrap(); + + // A stopped controller ignores the arming command, so success here + // would be a lost frame. Every path off the bus is covered. + ctx.canfd.stop().unwrap(); + assert_eq!(ctx.canfd.transmit(&frame), Err(Error::ControllerStopped)); + + let (_, mut tx) = ctx.canfd.split(); + assert_eq!(tx.transmit(&frame), Err(Error::ControllerStopped)); + + ctx.canfd.apply_config(&config()).unwrap(); + assert_eq!(ctx.canfd.transmit(&frame), Err(Error::ControllerStopped)); + + ctx.canfd.start().unwrap(); + let got = round_trip(&mut ctx.canfd, &frame); + assert_eq!(got.id(), std(0x1A5).into()); + assert_eq!(got.payload(), &[9]); + } + + #[test] + fn a_filter_matches_only_its_identifier_format(mut ctx: Context) { + // A base identifier sits in the top 11 bits of the identifier word, so + // an extended identifier with the same top bits matches the same code + // and mask. Only the format the filter was set up for tells them apart. + let top_bits = ext(0x7FF << 18); + + ctx.canfd.set_mask_filter( + MaskFilter::A, + &MaskFilterConfig::standard(std(0x7FF), StandardId::MAX), + ); + ctx.canfd.disable_mask_filter(MaskFilter::B); + ctx.canfd.disable_mask_filter(MaskFilter::C); + ctx.canfd.disable_range_filter(); + + assert!(accepted(&mut ctx.canfd, std(0x7FF)), "0x7FF must pass"); + assert!(!accepted(&mut ctx.canfd, std(0x000)), "0x000 must not"); + assert!( + !accepted(&mut ctx.canfd, top_bits), + "an extended identifier must not pass a standard filter" + ); + + ctx.canfd.set_mask_filter( + MaskFilter::A, + &MaskFilterConfig::extended(top_bits, ExtendedId::MAX), + ); + assert!( + accepted(&mut ctx.canfd, top_bits), + "the extended one must pass" + ); + assert!( + !accepted(&mut ctx.canfd, std(0x7FF)), + "a standard identifier must not pass an extended filter" + ); + + ctx.canfd.disable_mask_filter(MaskFilter::A); + ctx.canfd + .set_range_filter(&RangeFilterConfig::standard(std(0x7FF), std(0x7FF))); + assert!(accepted(&mut ctx.canfd, std(0x7FF)), "0x7FF must pass"); + assert!( + !accepted(&mut ctx.canfd, top_bits), + "an extended identifier must not pass a standard range" + ); + + ctx.canfd.accept_all(); + } + + #[test] + fn tx_buffer_indices_the_hardware_does_not_have_are_refused(mut ctx: Context) { + let frame = Frame::new(std(0x111), &[1]).unwrap(); + let index = ctx.canfd.transmit(&frame).unwrap(); + assert_eq!(wait_tx(&ctx.canfd, index), TxBufferState::Ok); + + let count = ctx.canfd.tx_buffer_count(); + for index in [count, count + 1, 2 * count, u8::MAX] { + assert_eq!( + ctx.canfd.tx_buffer_state(index), + TxBufferState::NotExist, + "index {} reported a buffer that does not exist", + index + ); + + // The commands must not land on a real buffer either. + ctx.canfd.abort_transmit(index); + ctx.canfd.release_tx_buffer(index); + ctx.canfd.set_tx_priority(index, 7); + assert_eq!( + ctx.canfd.tx_buffer_state(0), + TxBufferState::Ok, + "a command with index {} reached buffer 0", + index + ); + } + } + + #[test] + fn the_secondary_sample_point_leaves_room_for_the_measured_delay(mut ctx: Context) { + // The default data phase is four quanta of ten clock periods, so an + // offset of 16 quanta lands exactly on the four-bit-time limit of + // TRM 38.3.7.3, and the measured delay comes on top. + assert_eq!( + ctx.canfd + .apply_config(&config().with_secondary_sample_point_offset(16)), + Err(ConfigError::UnsupportedSecondarySamplePoint) + ); + assert_eq!(ctx.canfd.config().secondary_sample_point_offset(), None); + + ctx.canfd + .apply_config(&config().with_secondary_sample_point_offset(15)) + .unwrap(); + assert_eq!(ctx.canfd.config().secondary_sample_point_offset(), Some(15)); + } +} + +/// Two controllers on one wire, so a peer acknowledges frames and arbitrates. +#[embedded_test::tests(default_timeout = 5)] +mod two_node_tests { + use super::*; + + struct Nodes { + node0: CanFd<'static, Blocking>, + node1: CanFd<'static, Blocking>, + } + + #[init] + fn init() -> Nodes { + let peripherals = esp_hal::init(esp_hal::Config::default()); + + // Each controller needs both signals on its own end of the wire. + let (pin0, pin1) = hil_test::common_test_pins!(peripherals); + let (rx0, tx0) = unsafe { pin0.split() }; + let (rx1, tx1) = unsafe { pin1.split() }; + + let config = Config::default().with_no_transceiver(true); + + let mut node0 = CanFd::new(peripherals.TWAI0, config) + .unwrap() + .with_rx(rx0) + .with_tx(tx0); + let mut node1 = CanFd::new(peripherals.TWAI1, config) + .unwrap() + .with_rx(rx1) + .with_tx(tx1); + + node0.start().unwrap(); + node1.start().unwrap(); + + Nodes { node0, node1 } + } + + /// Sends from `from`, expects it on `to`, and returns what arrived. + fn cross( + from: &mut CanFd<'static, Blocking>, + to: &mut CanFd<'static, Blocking>, + frame: &Frame, + ) -> Frame { + to.flush_rx(); + let index = from.transmit(frame).unwrap(); + assert_eq!(wait_tx(from, index), TxBufferState::Ok, "transmit failed"); + to.receive().unwrap() + } + + #[test] + fn frames_cross_in_both_directions(mut ctx: Nodes) { + // TX OK here means the peer acknowledged. + let sent = Frame::new(std(0x301), &[9, 8, 7, 6, 5, 4, 3, 2]).unwrap(); + let got = cross(&mut ctx.node0, &mut ctx.node1, &sent); + assert_eq!(got.id(), std(0x301).into()); + assert_eq!(got.payload(), sent.payload()); + + let sent = Frame::new(std(0x401), &[0xC0, 0xFF, 0xEE]).unwrap(); + let got = cross(&mut ctx.node1, &mut ctx.node0, &sent); + assert_eq!(got.id(), std(0x401).into()); + assert_eq!(got.payload(), sent.payload()); + } + + #[test] + fn fd_frames_cross_at_the_data_bit_rate(mut ctx: Nodes) { + let sent = Frame::new_fd(ext(0x1AB_CDEF), &[0x3C; 64]) + .unwrap() + .with_bit_rate_switch(true); + let got = cross(&mut ctx.node0, &mut ctx.node1, &sent); + + assert_eq!(got.id(), ext(0x1AB_CDEF).into()); + assert!(got.is_fd()); + assert!(got.is_bit_rate_switched()); + assert_eq!(got.payload(), &[0x3C; 64]); + } + + #[test] + fn simultaneous_transmissions_arbitrate(mut ctx: Nodes) { + ctx.node0.flush_rx(); + ctx.node1.flush_rx(); + + // No handler is registered, so listening only latches the flag. + ctx.node0.clear_interrupts(CanFdInterrupt::ArbitrationLost); + ctx.node1.clear_interrupts(CanFdInterrupt::ArbitrationLost); + ctx.node0.listen(CanFdInterrupt::ArbitrationLost); + ctx.node1.listen(CanFdInterrupt::ArbitrationLost); + + // Both nodes become ready while the filler occupies the bus, so they + // start together at the next intermission and arbitrate. + let filler = Frame::new(std(0x7FF), &[0; 8]).unwrap(); + let filler_idx = ctx.node0.transmit(&filler).unwrap(); + + let low = Frame::new(std(0x100), &[1]).unwrap(); + let high = Frame::new(std(0x200), &[2]).unwrap(); + let i0 = ctx.node0.transmit(&low).unwrap(); + let i1 = ctx.node1.transmit(&high).unwrap(); + + assert_eq!(wait_tx(&ctx.node0, filler_idx), TxBufferState::Ok); + assert_eq!(wait_tx(&ctx.node0, i0), TxBufferState::Ok); + assert_eq!(wait_tx(&ctx.node1, i1), TxBufferState::Ok); + + assert_eq!(ctx.node1.receive().unwrap().id(), std(0x7FF).into()); + assert_eq!(ctx.node1.receive().unwrap().id(), std(0x100).into()); + assert_eq!(ctx.node0.receive().unwrap().id(), std(0x200).into()); + + // The higher identifier is the one that backed off. + assert!( + ctx.node1 + .interrupts() + .contains(CanFdInterrupt::ArbitrationLost), + "0x200 should have lost arbitration to 0x100" + ); + assert!( + !ctx.node0 + .interrupts() + .contains(CanFdInterrupt::ArbitrationLost), + "0x100 has the lower identifier and should have won" + ); + + assert_eq!(ctx.node0.receive_error_count(), 0, "node0 REC"); + assert_eq!(ctx.node0.transmit_error_count(), 0, "node0 TEC"); + assert_eq!(ctx.node1.receive_error_count(), 0, "node1 REC"); + assert_eq!(ctx.node1.transmit_error_count(), 0, "node1 TEC"); + } +} + +#[embedded_test::tests(default_timeout = 3, executor = hil_test::Executor::new())] +mod async_tests { + use core::{ + sync::atomic::{AtomicUsize, Ordering}, + task::{Poll, RawWaker, RawWakerVTable, Waker}, + }; + + use embassy_time::{Duration, Instant, Timer}; + + use super::*; + + static WAKES: AtomicUsize = AtomicUsize::new(0); + + /// A waker belonging to no executor, so a wake can only come from the + /// driver. + fn counting_waker() -> Waker { + fn clone(_: *const ()) -> RawWaker { + RawWaker::new(core::ptr::null(), &VTABLE) + } + fn wake(_: *const ()) { + WAKES.fetch_add(1, Ordering::SeqCst); + } + static VTABLE: RawWakerVTable = RawWakerVTable::new(clone, wake, wake, |_| {}); + + WAKES.store(0, Ordering::SeqCst); + + unsafe { Waker::from_raw(RawWaker::new(core::ptr::null(), &VTABLE)) } + } + + /// The async driver plus a peer that delivers a frame on demand. + struct AsyncContext { + canfd: CanFd<'static, Async>, + peer: CanFd<'static, Blocking>, + } + + #[init] + async fn init() -> AsyncContext { + let peripherals = esp_hal::init(esp_hal::Config::default()); + + let (pin0, pin1) = hil_test::common_test_pins!(peripherals); + let (rx0, tx0) = unsafe { pin0.split() }; + let (rx1, tx1) = unsafe { pin1.split() }; + + let timg0 = TimerGroup::new(peripherals.TIMG0); + esp_rtos::start(timg0.timer0); + + let mut canfd = CanFd::new(peripherals.TWAI0, config().with_no_transceiver(true)) + .unwrap() + .with_rx(rx0) + .with_tx(tx0) + .into_async(); + canfd.start().unwrap(); + + let peer_config = Config::default() + .with_mode(Mode::SelfTest) + .with_no_transceiver(true); + let mut peer = CanFd::new(peripherals.TWAI1, peer_config) + .unwrap() + .with_rx(rx1) + .with_tx(tx1); + peer.start().unwrap(); + + AsyncContext { canfd, peer } + } + + #[test] + async fn frames_round_trip(mut ctx: AsyncContext) { + for frame in [ + Frame::new(std(0x201), &[1, 2, 3, 4, 5, 6, 7, 8]).unwrap(), + Frame::new_fd(std(0x202), &[0x77; 64]) + .unwrap() + .with_bit_rate_switch(true), + ] { + ctx.canfd.flush_rx(); + ctx.canfd.transmit_async(&frame).await.unwrap(); + + let got = ctx.canfd.receive_async().await; + assert_eq!(got.id(), frame.id()); + assert_eq!(got.is_fd(), frame.is_fd()); + assert_eq!(got.payload(), frame.payload()); + } + } + + #[test] + async fn receive_async_waits_instead_of_spinning(mut ctx: AsyncContext) { + ctx.canfd.flush_rx(); + + let waker = counting_waker(); + let mut cx = core::task::Context::from_waker(&waker); + let mut receive = core::pin::pin!(ctx.canfd.receive_async()); + + assert!( + receive.as_mut().poll(&mut cx).is_pending(), + "received a frame from an idle bus" + ); + assert!(WakeLock::is_active(), "waiting for a frame while asleep"); + + // A future that wakes itself on every poll is still Pending, so only + // the wake count tells spinning apart from parking. + Timer::after(Duration::from_millis(50)).await; + + assert_eq!( + WAKES.load(Ordering::SeqCst), + 0, + "the future woke itself while the bus was idle" + ); + assert!( + receive.as_mut().poll(&mut cx).is_pending(), + "received a frame from an idle bus" + ); + } + + #[test] + async fn receive_async_wakes_on_the_rx_interrupt(mut ctx: AsyncContext) { + ctx.canfd.flush_rx(); + + let waker = counting_waker(); + let mut cx = core::task::Context::from_waker(&waker); + + let mut receive = core::pin::pin!(ctx.canfd.receive_async()); + + assert!( + receive.as_mut().poll(&mut cx).is_pending(), + "receive_async returned before any frame was sent" + ); + assert_eq!( + WAKES.load(Ordering::SeqCst), + 0, + "nothing should have woken the future yet" + ); + + ctx.peer + .transmit(&Frame::new(std(0x203), &[0xEE; 2]).unwrap()) + .unwrap(); + + // This waker belongs to no executor, so the wake can only come from + // the RX interrupt. + let deadline = Instant::now() + Duration::from_millis(500); + while WAKES.load(Ordering::SeqCst) == 0 { + assert!( + Instant::now() < deadline, + "the RX interrupt never woke the future" + ); + } + + match receive.as_mut().poll(&mut cx) { + Poll::Ready(frame) => assert_eq!(frame.id(), std(0x203).into()), + Poll::Pending => panic!("the frame arrived but the future did not complete"), + } + } +} + +/// Two nodes exchanging real traffic, with the driver under test in async +/// mode. +#[embedded_test::tests(default_timeout = 5, executor = hil_test::Executor::new())] +mod contention_tests { + use core::{ + sync::atomic::{AtomicUsize, Ordering}, + task::{Poll, RawWaker, RawWakerVTable, Waker}, + }; + + use embassy_time::Timer; + use esp_hal::time::{Duration, Instant}; + + use super::*; + + static WAKES: AtomicUsize = AtomicUsize::new(0); + + fn counting_waker() -> Waker { + fn clone(_: *const ()) -> RawWaker { + RawWaker::new(core::ptr::null(), &VTABLE) + } + fn wake(_: *const ()) { + WAKES.fetch_add(1, Ordering::SeqCst); + } + static VTABLE: RawWakerVTable = RawWakerVTable::new(clone, wake, wake, |_| {}); + + WAKES.store(0, Ordering::SeqCst); + + unsafe { Waker::from_raw(RawWaker::new(core::ptr::null(), &VTABLE)) } + } + + struct Nodes { + node: CanFd<'static, Async>, + peer: CanFd<'static, Blocking>, + } + + #[init] + async fn init() -> Nodes { + let peripherals = esp_hal::init(esp_hal::Config::default()); + + let (pin0, pin1) = hil_test::common_test_pins!(peripherals); + let (rx0, tx0) = unsafe { pin0.split() }; + let (rx1, tx1) = unsafe { pin1.split() }; + + let timg0 = TimerGroup::new(peripherals.TIMG0); + esp_rtos::start(timg0.timer0); + + let config = Config::default().with_no_transceiver(true); + let mut node = CanFd::new(peripherals.TWAI0, config) + .unwrap() + .with_rx(rx0) + .with_tx(tx0) + .into_async(); + let mut peer = CanFd::new(peripherals.TWAI1, config) + .unwrap() + .with_rx(rx1) + .with_tx(tx1); + node.start().unwrap(); + peer.start().unwrap(); + + Nodes { node, peer } + } + + /// 5 kbit/s in the arbitration phase: a 64-byte frame takes over a hundred + /// milliseconds, leaving room to interrupt it. + fn slow_nominal() -> Config { + Config::default() + .with_no_transceiver(true) + .with_nominal_timing(Timing { + baud_rate_prescaler: 200, + propagation_segment: 40, + phase_segment_1: 24, + phase_segment_2: 15, + sync_jump_width: 8, + }) + } + + /// The same rate in the data phase only. A data phase slower than the + /// arbitration phase is unusual but legal (TRM 38.3.7.1). + fn slow_data() -> Config { + Config::default() + .with_no_transceiver(true) + .with_fd_timing(Timing { + baud_rate_prescaler: 200, + propagation_segment: 40, + phase_segment_1: 24, + phase_segment_2: 15, + sync_jump_width: 8, + }) + } + + #[test] + async fn rx_and_tx_halves_work_at_the_same_time(mut ctx: Nodes) { + let (mut rx, mut tx) = ctx.node.split(); + + let outgoing = Frame::new_fd(std(0x150), &[0x5A; 64]) + .unwrap() + .with_bit_rate_switch(true); + let mut receive = core::pin::pin!(rx.receive_async()); + let mut transmit = core::pin::pin!(tx.transmit_async(&outgoing)); + + let waker = counting_waker(); + let mut cx = core::task::Context::from_waker(&waker); + + assert!(receive.as_mut().poll(&mut cx).is_pending()); + assert!(transmit.as_mut().poll(&mut cx).is_pending()); + + let deadline = Instant::now() + Duration::from_millis(500); + let mut sent = false; + loop { + if !sent && transmit.as_mut().poll(&mut cx).is_ready() { + sent = true; + assert_eq!(ctx.peer.receive().unwrap().id(), std(0x150).into()); + let index = ctx + .peer + .transmit(&Frame::new(std(0x151), &[0xC3; 8]).unwrap()) + .unwrap(); + assert_eq!(wait_tx(&ctx.peer, index), TxBufferState::Ok); + } + if sent && let Poll::Ready(frame) = receive.as_mut().poll(&mut cx) { + assert_eq!(frame.id(), std(0x151).into()); + assert_eq!(frame.payload(), &[0xC3; 8]); + break; + } + assert!( + Instant::now() < deadline, + "split halves did not both complete" + ); + } + } + + #[test] + async fn tx_buffer_priority_controls_the_local_queue(mut ctx: Nodes) { + // Buffer zero goes first because it was armed on an idle bus; the rest + // follow in descending priority. Buffer one is ranked above the + // three-bit field, which must saturate rather than wrap to zero. + let priorities = [0u8, 9, 2, 3]; + for (index, &priority) in priorities.iter().enumerate() { + ctx.node.set_tx_priority(index as u8, priority); + } + + let first = Frame::new_fd(std(0x777), &[0; 64]).unwrap(); + assert_eq!(ctx.node.transmit(&first).unwrap(), 0); + for index in 1..4u8 { + assert_eq!( + ctx.node + .transmit(&Frame::new(std(0x100), &[index]).unwrap()) + .unwrap(), + index + ); + } + for index in 0..4 { + assert_eq!(wait_tx(&ctx.node, index), TxBufferState::Ok); + } + + assert_eq!(ctx.peer.receive().unwrap().id(), std(0x777).into()); + for index in [1u8, 3, 2] { + assert_eq!( + ctx.peer.receive().unwrap().payload(), + &[index], + "buffers left in the wrong order" + ); + } + } + + #[test] + async fn a_full_rx_buffer_drains_in_order_and_rearms(mut ctx: Nodes) { + let waker = counting_waker(); + let mut cx = core::task::Context::from_waker(&waker); + + { + let mut receive = core::pin::pin!(ctx.node.receive_async()); + assert!(receive.as_mut().poll(&mut cx).is_pending()); + + // More frames than the 128-word buffer can hold, never read. + for seq in 0..40u8 { + let frame = Frame::new_fd(std(0x123), &[seq; 64]) + .unwrap() + .with_bit_rate_switch(true); + let index = ctx.peer.transmit(&frame).unwrap(); + assert_eq!(wait_tx(&ctx.peer, index), TxBufferState::Ok); + } + assert!(WAKES.load(Ordering::SeqCst) > 0, "no frame ever woke RX"); + } + + assert!(ctx.node.rx_overrun(), "overrun was not reported"); + let queued = ctx.node.rx_frame_count(); + assert!(queued > 0 && queued < 40, "queued {} frames", queued); + + // An overrun drops what does not fit, not what is already held. + for seq in 0..queued { + let mut receive = core::pin::pin!(ctx.node.receive_async()); + match receive.as_mut().poll(&mut cx) { + Poll::Ready(frame) => assert_eq!(frame.payload(), &[seq as u8; 64]), + Poll::Pending => panic!("a queued frame was lost"), + } + } + assert_eq!(ctx.node.rx_frame_count(), 0); + + ctx.node.clear_rx_overrun(); + assert!(!ctx.node.rx_overrun()); + + WAKES.store(0, Ordering::SeqCst); + let mut receive = core::pin::pin!(ctx.node.receive_async()); + assert!(receive.as_mut().poll(&mut cx).is_pending()); + + // One spurious wake left over from the drained buffer is allowed. + Timer::after_millis(10).await; + WAKES.store(0, Ordering::SeqCst); + assert!(receive.as_mut().poll(&mut cx).is_pending()); + Timer::after_millis(10).await; + assert_eq!( + WAKES.load(Ordering::SeqCst), + 0, + "the future kept waking itself on an idle bus" + ); + + let index = ctx + .peer + .transmit(&Frame::new(std(0x456), &[42]).unwrap()) + .unwrap(); + assert_eq!(wait_tx(&ctx.peer, index), TxBufferState::Ok); + + let deadline = Instant::now() + Duration::from_millis(100); + while WAKES.load(Ordering::SeqCst) == 0 { + assert!(Instant::now() < deadline, "RX never rearmed"); + } + match receive.as_mut().poll(&mut cx) { + Poll::Ready(frame) => assert_eq!(frame.id(), std(0x456).into()), + Poll::Pending => panic!("the fresh frame did not complete the future"), + } + } + + #[test] + async fn a_cancelled_transmission_reuses_its_buffer_without_losing_a_wake(mut ctx: Nodes) { + ctx.node.apply_config(&slow_nominal()).unwrap(); + ctx.peer.apply_config(&slow_nominal()).unwrap(); + ctx.node.start().unwrap(); + ctx.peer.start().unwrap(); + + let waker = counting_waker(); + let mut cx = core::task::Context::from_waker(&waker); + + // Drop a transmit future while its frame is on the wire; the hardware + // keeps sending it. + let first = Frame::new_fd(std(0x100), &[0xA5; 64]).unwrap(); + { + let mut transmit = core::pin::pin!(ctx.node.transmit_async(&first)); + assert!(transmit.as_mut().poll(&mut cx).is_pending()); + Timer::after_millis(5).await; + } + assert_eq!(ctx.node.tx_buffer_state(0), TxBufferState::InProgress); + assert!( + WakeLock::is_active(), + "cancelling the future let the chip sleep on a frame in flight" + ); + ctx.node.abort_transmit(0); + assert_eq!(wait_tx(&ctx.node, 0), TxBufferState::Ok); + assert_eq!(ctx.peer.receive().unwrap().id(), std(0x100).into()); + + // The next future takes the buffer the cancelled one left behind. + WAKES.store(0, Ordering::SeqCst); + let second = Frame::new_fd(std(0x101), &[0x3C; 64]).unwrap(); + { + let mut transmit = core::pin::pin!(ctx.node.transmit_async(&second)); + assert!(transmit.as_mut().poll(&mut cx).is_pending()); + + let deadline = Instant::now() + Duration::from_millis(500); + loop { + if WAKES.swap(0, Ordering::SeqCst) > 0 + && let Poll::Ready(result) = transmit.as_mut().poll(&mut cx) + { + result.unwrap(); + break; + } + assert!( + Instant::now() < deadline, + "the reused buffer never delivered its wake" + ); + Timer::after_millis(1).await; + } + } + + assert_eq!(ctx.peer.receive().unwrap().payload(), second.payload()); + assert_eq!(ctx.node.receive_error_count(), 0); + assert_eq!(ctx.node.transmit_error_count(), 0); + assert_eq!(ctx.peer.receive_error_count(), 0); + assert_eq!(ctx.peer.transmit_error_count(), 0); + } + + #[test] + async fn dropping_an_async_driver_with_a_pending_interrupt_returns(mut ctx: Nodes) { + let waker = counting_waker(); + let mut cx = core::task::Context::from_waker(&waker); + + // Arm the RX interrupt and cancel the future. + { + let mut receive = core::pin::pin!(ctx.node.receive_async()); + assert!(receive.as_mut().poll(&mut cx).is_pending()); + } + + // Tear the driver down while its interrupt is pending. The critical + // section keeps the request pending until teardown is over. + critical_section::with(|_| { + let index = ctx + .peer + .transmit(&Frame::new(std(0x2A), &[7]).unwrap()) + .unwrap(); + assert_eq!(wait_tx(&ctx.peer, index), TxBufferState::Ok); + + let deadline = Instant::now() + Duration::from_millis(100); + while ctx.node.rx_frame_count() == 0 { + assert!(Instant::now() < deadline, "the frame never arrived"); + } + + drop(ctx.node); + }); + + // Reaching this line is the assertion. + assert_eq!(ctx.peer.receive_error_count(), 0); + assert_eq!(ctx.peer.transmit_error_count(), 0); + } + + #[test] + async fn joining_the_bus_waits_out_a_frame_in_flight(mut ctx: Nodes) { + ctx.node.apply_config(&slow_nominal()).unwrap(); + ctx.peer.apply_config(&slow_nominal()).unwrap(); + ctx.node.start().unwrap(); + ctx.peer.start().unwrap(); + + ctx.peer.stop().unwrap(); + + let frame = Frame::new_fd(ext(0x1234567), &[0x55; 64]).unwrap(); + let index = ctx.node.transmit(&frame).unwrap(); + let deadline = Instant::now() + Duration::from_millis(100); + while ctx.node.tx_buffer_state(index) != TxBufferState::InProgress { + assert!(Instant::now() < deadline, "the frame never started"); + } + + let began = Instant::now(); + ctx.peer + .start() + .expect("joining the bus during a legal frame timed out"); + let waited = began.elapsed(); + + assert!( + waited > Duration::from_millis(10), + "joined in {} us, which is too soon to have waited for the frame", + waited.as_micros() + ); + + assert_eq!(wait_tx(&ctx.node, index), TxBufferState::Ok); + assert_eq!(ctx.peer.receive().unwrap().payload(), frame.payload()); + } + + #[test] + async fn joining_the_bus_waits_out_a_slow_data_phase(mut ctx: Nodes) { + // 50 kbit/s nominal with 6.25 kbit/s data makes a 64-byte frame last + // about 105 ms, while 2048 nominal bit times is 41 ms. + let slow_payload = Config::default() + .with_no_transceiver(true) + .with_nominal_timing(Timing { + baud_rate_prescaler: 100, + propagation_segment: 7, + phase_segment_1: 5, + phase_segment_2: 3, + sync_jump_width: 3, + }) + .with_fd_timing(Timing { + baud_rate_prescaler: 128, + propagation_segment: 63, + phase_segment_1: 15, + phase_segment_2: 21, + sync_jump_width: 3, + }); + + ctx.node.apply_config(&slow_payload).unwrap(); + // Self test on the sender: the peer is off the bus and cannot ACK. + ctx.peer + .apply_config(&slow_payload.with_mode(Mode::SelfTest)) + .unwrap(); + ctx.node.start().unwrap(); + ctx.peer.start().unwrap(); + + ctx.node.stop().unwrap(); + + let frame = Frame::new_fd(std(0x321), &[0; 64]) + .unwrap() + .with_bit_rate_switch(true); + let index = ctx.peer.transmit(&frame).unwrap(); + let deadline = Instant::now() + Duration::from_millis(100); + while ctx.peer.tx_buffer_state(index) != TxBufferState::InProgress { + assert!(Instant::now() < deadline, "the frame never started"); + } + Timer::after_millis(5).await; + + let began = Instant::now(); + ctx.node + .start() + .expect("joining timed out inside a frame with a slow data phase"); + let waited = began.elapsed(); + + assert!( + waited > Duration::from_millis(10), + "joined in {} us, too soon to have waited for the frame", + waited.as_micros() + ); + assert_eq!(wait_tx(&ctx.peer, index), TxBufferState::Ok); + } + + #[test] + async fn leaving_the_bus_waits_out_a_slow_data_phase(mut ctx: Nodes) { + ctx.node.apply_config(&slow_data()).unwrap(); + ctx.peer.apply_config(&slow_data()).unwrap(); + ctx.node.start().unwrap(); + ctx.peer.start().unwrap(); + + let frame = Frame::new_fd(std(0x321), &[0x55; 64]) + .unwrap() + .with_bit_rate_switch(true); + + let index = ctx.node.transmit(&frame).unwrap(); + assert_eq!(wait_tx(&ctx.node, index), TxBufferState::Ok); + assert_eq!(ctx.peer.receive().unwrap().payload(), frame.payload()); + + let index = ctx.node.transmit(&frame).unwrap(); + Timer::after_millis(5).await; + assert_eq!(ctx.node.tx_buffer_state(index), TxBufferState::InProgress); + + let began = Instant::now(); + let result = ctx.node.stop(); + let waited = began.elapsed(); + + assert_eq!( + result, + Ok(()), + "stopping gave up after {} us, so the bound ignored the data phase", + waited.as_micros() + ); + assert!( + waited > Duration::from_millis(50), + "stopped after {} us, too soon to have waited for the frame", + waited.as_micros() + ); + } + + #[test] + async fn dropping_a_transmitter_does_not_corrupt_a_slow_data_frame(mut ctx: Nodes) { + ctx.node.apply_config(&slow_data()).unwrap(); + ctx.peer.apply_config(&slow_data()).unwrap(); + ctx.node.start().unwrap(); + ctx.peer.start().unwrap(); + + let frame = Frame::new_fd(std(0x321), &[0x55; 64]) + .unwrap() + .with_bit_rate_switch(true); + let index = ctx.node.transmit(&frame).unwrap(); + Timer::after_millis(5).await; + assert_eq!(ctx.node.tx_buffer_state(index), TxBufferState::InProgress); + + drop(ctx.node); + Timer::after_millis(150).await; + + assert_eq!( + ctx.peer.receive_error_count(), + 0, + "dropping the transmitter corrupted the frame the peer was receiving" + ); + assert_eq!(ctx.peer.transmit_error_count(), 0); + assert_eq!(ctx.peer.receive().unwrap().payload(), &[0x55; 64]); + } +} + +/// Faults injected on the wire: the second pin drives a dominant pulse into a +/// frame being transmitted, which is a bit error against the controller's own +/// output. +#[embedded_test::tests(default_timeout = 5)] +mod fault_tests { + use esp_hal::{ + canfd::ErrorState, + delay::Delay, + gpio::{DriveMode, Level, Output, OutputConfig, Pull}, + time::{Duration, Instant}, + }; + + use super::*; + + struct Context { + node: CanFd<'static, Blocking>, + injector: Output<'static>, + } + + #[init] + fn init() -> Context { + let peripherals = esp_hal::init(esp_hal::Config::default()); + + let (pin0, pin1) = hil_test::common_test_pins!(peripherals); + let injector = Output::new( + pin1, + Level::High, + OutputConfig::default() + .with_drive_mode(DriveMode::OpenDrain) + .with_pull(Pull::Up), + ); + let (rx, tx) = unsafe { pin0.split() }; + + // One shot, so each corrupted frame counts exactly once. + let mut node = CanFd::new( + peripherals.TWAI0, + Config::default() + .with_mode(Mode::SelfTest) + .with_retransmit_limit(0) + .with_no_transceiver(true), + ) + .unwrap() + .with_rx(rx) + .with_tx(tx); + node.start().unwrap(); + + Context { node, injector } + } + + /// Corrupts frames until the transmit error counter reaches `target`. + fn drive_to(ctx: &mut Context, target_tec: u16) { + let frame = Frame::new(ext(0x1234567), &[0xFF; 8]).unwrap(); + let mut seen_passive = false; + + for _ in 0..40 { + let index = ctx.node.transmit(&frame).unwrap(); + + let deadline = Instant::now() + Duration::from_millis(5); + while ctx.node.tx_buffer_state(index) != TxBufferState::InProgress { + assert!(Instant::now() < deadline, "the frame never started"); + } + + // 120 us into a 500 kbit/s frame is inside its payload. + Delay::new().delay_micros(120); + ctx.injector.set_low(); + Delay::new().delay_micros(20); + ctx.injector.set_high(); + + assert_eq!(wait_tx(&ctx.node, index), TxBufferState::Failed); + + let state = ctx.node.error_state(); + let tec = ctx.node.transmit_error_count(); + + if state == ErrorState::Passive { + seen_passive = true; + } + if state == ErrorState::BusOff { + assert!(seen_passive, "went bus-off without passing through passive"); + assert!(tec >= 256, "bus-off at TEC {}", tec); + return; + } + if tec >= target_tec { + return; + } + } + + panic!( + "injection never reached TEC {}: {}", + target_tec, + ctx.node.transmit_error_count() + ); + } + + #[test] + fn injected_faults_reach_bus_off_and_recover(mut ctx: Context) { + drive_to(&mut ctx, 256); + + let capture = ctx.node.error_capture(); + assert_eq!(capture.kind, esp_hal::canfd::BusErrorKind::Bit); + assert_eq!( + embedded_can::Error::kind(&capture.kind), + embedded_can::ErrorKind::Bit + ); + + // Bus-off is not left on its own. + Delay::new().delay_millis(10); + assert_eq!(ctx.node.error_state(), ErrorState::BusOff); + + let began = Instant::now(); + ctx.node.request_bus_off_recovery(); + while ctx.node.error_state() != ErrorState::Active { + assert!( + began.elapsed() < Duration::from_millis(100), + "the controller never rejoined the bus" + ); + } + + // 128 occurrences of 11 recessive bits at 500 kbit/s is about 2.8 ms. + assert!( + began.elapsed() > Duration::from_micros(2500), + "rejoined in {} us, too fast to have waited out reintegration", + began.elapsed().as_micros() + ); + assert_eq!(ctx.node.receive_error_count(), 0); + assert_eq!(ctx.node.transmit_error_count(), 0); + + let index = ctx + .node + .transmit(&Frame::new(std(0x123), &[0xAB; 8]).unwrap()) + .unwrap(); + assert_eq!(wait_tx(&ctx.node, index), TxBufferState::Ok); + } + + #[test] + fn a_split_transmitter_sees_bus_off_and_recovers(mut ctx: Context) { + drive_to(&mut ctx, 256); + + let (rx, mut tx) = ctx.node.split(); + assert_eq!(tx.error_state(), ErrorState::BusOff); + assert_eq!(rx.error_state(), ErrorState::BusOff); + assert!(tx.transmit_error_count() >= 256); + + let began = Instant::now(); + tx.request_bus_off_recovery(); + while tx.error_state() != ErrorState::Active { + assert!( + began.elapsed() < Duration::from_millis(100), + "the controller never rejoined the bus" + ); + } + assert_eq!(rx.receive_error_count(), 0); + assert_eq!(rx.transmit_error_count(), 0); + + let index = tx + .transmit(&Frame::new(std(0x123), &[0xAB; 8]).unwrap()) + .unwrap(); + let deadline = Instant::now() + Duration::from_millis(100); + while !tx.tx_buffer_state(index).is_writable() { + assert!(Instant::now() < deadline, "the frame never finished"); + } + assert_eq!(tx.tx_buffer_state(index), TxBufferState::Ok); + } + + #[test] + fn a_recovery_request_made_while_active_does_nothing(mut ctx: Context) { + // The hardware would remember an early request and rejoin on its own. + ctx.node.request_bus_off_recovery(); + + drive_to(&mut ctx, 256); + Delay::new().delay_millis(10); + + assert_eq!( + ctx.node.error_state(), + ErrorState::BusOff, + "an early recovery request armed an automatic recovery" + ); + } +} diff --git a/hil-test/src/bin/crypto/aes.rs b/hil-test/src/bin/crypto/aes.rs index 38369dec89d..10ed53440fa 100644 --- a/hil-test/src/bin/crypto/aes.rs +++ b/hil-test/src/bin/crypto/aes.rs @@ -358,6 +358,44 @@ mod tests { ); } + /// The crypto accelerators and the MCPWM peripherals share a clock, and its reference count. + #[test] + #[cfg(soc_has_clock_node_crypto_pwm_clk)] + fn test_crypto_clock_shared_with_mcpwm() { + use esp_hal::{ + clock::ll::{ClockTree, CryptoPwmClkConfig, McpwmInstance, crypto_pwm_clk_frequency}, + mcpwm::{McPwm, PeripheralClockConfig}, + time::Rate, + }; + + let p = esp_hal::init(Config::default().with_cpu_clock(CpuClock::max())); + let mut aes = Aes::new(p.AES); + + let clock_config = PeripheralClockConfig::with_frequency(Rate::from_mhz(32)).unwrap(); + let mcpwm = McPwm::new(p.MCPWM0, clock_config); + + hil_test::assert!( + ClockTree::with(|clocks| clocks.crypto_pwm_clk()) == Some(CryptoPwmClkConfig::Pll) + ); + hil_test::assert_eq!( + McpwmInstance::Mcpwm0.function_clock_frequency(), + crypto_pwm_clk_frequency() + ); + aes_ll_roundtrip::<16>( + &mut aes, + PLAINTEXT[0..16].try_into().unwrap(), + CIPHERTEXT_ECB_128[0..16].try_into().unwrap(), + ); + + core::mem::drop(mcpwm); + + aes_ll_roundtrip::<16>( + &mut aes, + PLAINTEXT[0..16].try_into().unwrap(), + CIPHERTEXT_ECB_128[0..16].try_into().unwrap(), + ); + } + #[test] #[cfg(aes_supports_dma)] fn test_aes_dma_ecb() { diff --git a/hil-test/src/bin/crypto/ecc.rs b/hil-test/src/bin/crypto/ecc.rs index d86066a43b4..2902ab4677d 100644 --- a/hil-test/src/bin/crypto/ecc.rs +++ b/hil-test/src/bin/crypto/ecc.rs @@ -180,29 +180,58 @@ const P384_TEST_DATA: TestData<48> = TestData { ], }; +#[cfg(all( + any(ecc_has_point_addition, ecc_has_modular_arithmetic), + ecc_has_curve_sm2 +))] +const SM2_TEST_DATA: TestData<32> = TestData { + curve: EllipticCurve::Sm2, + mod_base: EccModBase::OrderOfCurve, + x: hex!("c7744c3389455a71e10b66f2bf0be38f94c9396a4604995f1981191f2caec432"), + y: hex!("a0f03921e532df0240472ac67c87a9d05321696be3cebd599c77f6f4a23637bc"), + num: hex!("c7744c3389455a71e10b66f2bf0be38f94c9396a4604995f1981191f2caec432"), + den: hex!("a0f03921e532df0240472ac67c87a9d05321696be3cebd599c77f6f4a23637bc"), + expected_sum: hex!("676586546e783974215390b83c938c60e8eaa2d529d356b9b5f80f14cfe4fbee"), + expected_diff: hex!("4ac5e74bad0637c2ccc9014eae633d3140a8d0fe6235db057d09232a88778d76"), + expected_prod: hex!("23669ddfa03452818d9c8e031cb479c7e96249291ba1e9b54bb6f0cbd59672cf"), + expected_div: hex!("ef1d8483cd699edb733c44bdc1021b2635f984c95a03b04d837cbbfe07187e80"), +}; + +#[cfg(all(ecc_has_modular_arithmetic, ecc_has_curve_sm2))] +const SM2_PRIME_TEST_DATA: TestData<32> = TestData { + mod_base: EccModBase::PrimeModulus, + expected_sum: hex!("676586546e783974215390b83c938c60e8eaa2d529d356b9b5f80f14cfe4fbee"), + expected_diff: hex!("26841212a4127b6ea2c43b2c428439bf40a8d0fe6235db057d09232a88778d76"), + expected_prod: hex!("6ae7ac91993431c4f382f002f2db4653523a035710daa1cf0c63c4bd45e7d7ed"), + expected_div: hex!("f1d46363a49c41f0f3a1b502bb1b6ccd5daf4a857eedfaa8a22e877b8d325f32"), + ..SM2_TEST_DATA +}; + fn for_each_test_case(mut test: impl FnMut(&[u8], EllipticCurve)) { - let prime_fields: &[&[u8]] = &[ - &hex!("fffffffffffffffffffffffffffffffeffffffffffffffff"), - &hex!("ffffffff00000001000000000000000000000000ffffffffffffffffffffffff"), + let test_cases: &[(&[u8], EllipticCurve)] = &[ + ( + &hex!("fffffffffffffffffffffffffffffffeffffffffffffffff"), + EllipticCurve::P192, + ), + ( + &hex!("ffffffff00000001000000000000000000000000ffffffffffffffffffffffff"), + EllipticCurve::P256, + ), #[cfg(ecc_has_curve_p384)] - &hex!( - "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff" + ( + &hex!( + "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff" + ), + EllipticCurve::P384, + ), + #[cfg(ecc_has_curve_sm2)] + ( + &hex!("fffffffeffffffffffffffffffffffffffffffff00000000ffffffffffffffff"), + EllipticCurve::Sm2, ), ]; - for &prime_field in prime_fields { - let curve; - for_each_ecc_curve! { - (all $(($_id:tt, $name:tt, $bits:literal)),*) => { - curve = match prime_field.len() { - $( - v if v == $bits / 8 => EllipticCurve::$name, - )* - _ => unimplemented!(), - } - }; - }; - + for &(prime_field, curve) in test_cases { test(prime_field, curve) } } @@ -243,6 +272,9 @@ macro_rules! curve_crate { (P384 $($rest:tt)*) => { p384 $($rest)* }; + (Sm2 $($rest:tt)*) => { + sm2 $($rest)* + }; } macro_rules! uint { @@ -255,6 +287,9 @@ macro_rules! uint { (P384) => { crypto_bigint::U384 }; + (Sm2) => { + crypto_bigint::U256 + }; } fn affine_point_coords(curve: EllipticCurve, x: &mut [u8], y: &mut [u8]) { @@ -717,6 +752,12 @@ mod tests { test_ecc_point_addition(ctx, P384_TEST_DATA); } + #[test] + #[cfg(all(ecc_has_point_addition, ecc_has_curve_sm2))] + fn test_ecc_point_addition_sm2(ctx: Context<'static>) { + test_ecc_point_addition(ctx, SM2_TEST_DATA); + } + #[cfg(ecc_has_modular_arithmetic)] fn run_mod_tests(mut ctx: Context<'static>, test_case: TestData) { let result = &mut [0; N][..]; @@ -787,6 +828,18 @@ mod tests { fn test_ecc_mod_operations_384(ctx: Context<'static>) { run_mod_tests(ctx, P384_TEST_DATA); } + + #[test] + #[cfg(all(ecc_has_modular_arithmetic, ecc_has_curve_sm2))] + fn test_ecc_mod_operations_sm2(ctx: Context<'static>) { + run_mod_tests(ctx, SM2_TEST_DATA); + } + + #[test] + #[cfg(all(ecc_has_modular_arithmetic, ecc_has_curve_sm2))] + fn test_ecc_mod_operations_sm2_prime(ctx: Context<'static>) { + run_mod_tests(ctx, SM2_PRIME_TEST_DATA); + } } #[embedded_test::tests(default_timeout = 10)] @@ -902,4 +955,18 @@ mod work_queue_tests { let _backend = ctx.ecc.start(); run_backend_mod_tests(P384_TEST_DATA); } + + #[test] + #[cfg(all(ecc_has_modular_arithmetic, ecc_has_curve_sm2))] + fn test_ecc_backend_mod_operations_sm2(mut ctx: Context<'static>) { + let _backend = ctx.ecc.start(); + run_backend_mod_tests(SM2_TEST_DATA); + } + + #[test] + #[cfg(all(ecc_has_modular_arithmetic, ecc_has_curve_sm2))] + fn test_ecc_backend_mod_operations_sm2_prime(mut ctx: Context<'static>) { + let _backend = ctx.ecc.start(); + run_backend_mod_tests(SM2_PRIME_TEST_DATA); + } } diff --git a/hil-test/src/bin/crypto/rsa.rs b/hil-test/src/bin/crypto/rsa.rs index 9912365174d..a61d43c77f6 100644 --- a/hil-test/src/bin/crypto/rsa.rs +++ b/hil-test/src/bin/crypto/rsa.rs @@ -66,14 +66,7 @@ mod tests { fn init() -> Context<'static> { let peripherals = esp_hal::init(esp_hal::Config::default().with_cpu_clock(CpuClock::max())); - #[allow(unused_mut)] - let mut rsa = Rsa::new(peripherals.RSA); - - #[cfg(not(esp32))] - { - rsa.disable_constant_time(true); - rsa.search_acceleration(true); - } + let rsa = Rsa::new(peripherals.RSA, esp_hal::rsa::Config::default()).unwrap(); Context { rsa } } @@ -222,6 +215,46 @@ mod tests { hil_test::assert_eq!(EXPECTED_EXPONENTIATION_OUTPUT, outbuf); } + #[test] + #[cfg(not(esp32))] + fn test_constant_time_off_speeds_up_exponentiation(mut ctx: Context<'static>) { + // 65537 has only two 1 bits, so with constant time off the block skips almost every + // multiply, and the two times differ the most. Both configurations keep the search off, the + // default, so only the constant time setting changes the time. + let constant_time = esp_hal::rsa::Config::default(); + let accelerated = constant_time.with_constant_time(false); + let exponent = U512::from_u32(65537); + let r = compute_r(&BIGNUM_3); + let mprime = compute_mprime(&BIGNUM_3); + let exponentiation_us = |rsa: &mut Rsa<'static, Blocking>| { + let mut outbuf = [0_u32; U512::LIMBS]; + let start = esp_hal::time::Instant::now(); + let mut mod_exp = RsaModularExponentiation::::new( + rsa, + exponent.as_words(), + BIGNUM_3.as_words(), + mprime, + ); + mod_exp.start_exponentiation(BIGNUM_1.as_words(), r.as_words()); + mod_exp.read_results(&mut outbuf); + start.elapsed().as_micros() + }; + + // An untimed run first, so that neither timed run pays for cache misses. + exponentiation_us(&mut ctx.rsa); + ctx.rsa.apply_config(&constant_time).unwrap(); + let constant_time_us = exponentiation_us(&mut ctx.rsa); + ctx.rsa.apply_config(&accelerated).unwrap(); + let accelerated_us = exponentiation_us(&mut ctx.rsa); + + hil_test::assert!( + accelerated_us * 8 < constant_time_us, + "constant time {} us, accelerated {} us", + constant_time_us, + accelerated_us + ); + } + #[test] async fn modular_async_exponentiation(ctx: Context<'static>) { let mut rsa = ctx.rsa.into_async(); @@ -440,4 +473,43 @@ mod work_queue_tests { hil_test::assert_eq!(EXPECTED_EXPONENTIATION_OUTPUT, outbuf); } + + #[test] + #[cfg(not(esp32))] + fn test_rsa_work_queue_is_constant_time_by_default(mut ctx: Context<'static>) { + let _rsa = ctx.rsa.start(); + + // Sparse, for the reason in `test_constant_time_off_speeds_up_exponentiation`. + let exponent = U512::from_u32(65537); + let r = compute_r(&BIGNUM_3); + let mprime = compute_mprime(&BIGNUM_3); + let exponentiation_us = |rsa: &mut RsaContext| { + let mut outbuf = [0_u32; U512::LIMBS]; + let start = esp_hal::time::Instant::now(); + rsa.modular_exponentiate::( + BIGNUM_1.as_words(), + exponent.as_words(), + BIGNUM_3.as_words(), + r.as_words(), + mprime, + &mut outbuf, + ) + .wait_blocking(); + start.elapsed().as_micros() + }; + + // An untimed run first, so that neither timed run pays for cache misses. + exponentiation_us(&mut RsaContext::new()); + let constant_time_us = exponentiation_us(&mut RsaContext::new()); + let mut accelerated = RsaContext::new(); + accelerated.enable_acceleration(); + let accelerated_us = exponentiation_us(&mut accelerated); + + hil_test::assert!( + accelerated_us * 8 < constant_time_us, + "constant time {} us, accelerated {} us", + constant_time_us, + accelerated_us + ); + } } diff --git a/hil-test/src/bin/crypto/sha.rs b/hil-test/src/bin/crypto/sha.rs index d2aee2fdabc..81dd563e65b 100644 --- a/hil-test/src/bin/crypto/sha.rs +++ b/hil-test/src/bin/crypto/sha.rs @@ -1,12 +1,18 @@ use digest::{Digest, Update}; #[cfg(rng_trng_supported)] use esp_hal::rng::TrngSource; -#[cfg(not(esp32))] +#[cfg(sha_has_sha224)] use esp_hal::sha::Sha224; -#[cfg(any(esp32, esp32s2, esp32s3))] -use esp_hal::sha::{Sha384, Sha512}; -#[cfg(any(esp32s2, esp32s3))] -use esp_hal::sha::{Sha512_224, Sha512_256}; +#[cfg(sha_has_sha384)] +use esp_hal::sha::Sha384; +#[cfg(sha_has_sha512)] +use esp_hal::sha::Sha512; +#[cfg(sha_has_sha512_224)] +use esp_hal::sha::Sha512_224; +#[cfg(sha_has_sha512_256)] +use esp_hal::sha::Sha512_256; +#[cfg(sha_has_sm3)] +use esp_hal::sha::Sm3; use esp_hal::{ clock::CpuClock, rng::Rng, @@ -103,12 +109,12 @@ fn with_random_data( // Fill source data with random data rng.read(&mut sha1_random); - #[cfg(not(esp32))] + #[cfg(sha_has_sha224)] rng.read(&mut sha224_random); rng.read(&mut sha256_random); - #[cfg(any(esp32, esp32s2, esp32s3))] + #[cfg(sha_has_sha384)] rng.read(&mut sha384_random); - #[cfg(any(esp32, esp32s2, esp32s3))] + #[cfg(sha_has_sha512)] rng.read(&mut sha512_random); for size in [1, 64, 128, 256, BUFFER_LEN] { @@ -128,15 +134,15 @@ fn with_random_data( // Calculate software result to compare against assert_sw_hash::("SHA-1", &sha1_random[..size], &sha1_output); - #[cfg(not(esp32))] + #[cfg(sha_has_sha224)] assert_sw_hash::("SHA-224", &sha224_random[..size], &sha224_output); assert_sw_hash::("SHA-256", &sha256_random[..size], &sha256_output); - #[cfg(any(esp32, esp32s2, esp32s3))] + #[cfg(sha_has_sha384)] assert_sw_hash::("SHA-384", &sha384_random[..size], &sha384_output); - #[cfg(any(esp32, esp32s2, esp32s3))] + #[cfg(sha_has_sha512)] assert_sw_hash::("SHA-512", &sha512_random[..size], &sha512_output); } } @@ -164,7 +170,33 @@ mod tests { } #[test] - #[cfg(any(esp32s2, esp32s3))] + #[cfg(sha_has_sm3)] + fn test_sm3(mut ctx: Context) { + let mut output = [0u8; 32]; + for len in [0, 3, 55, 56, 63, 64, 65, 127, 128, 129, SOURCE_DATA.len()] { + let input = &SOURCE_DATA[..len]; + hash_sha::(&mut ctx.sha, input, &mut output); + assert_sw_hash::("SM3", input, &output); + hash_digest::(&mut ctx.sha, input, &mut output); + assert_sw_hash::("SM3 digest", input, &output); + } + + let (first, second) = SOURCE_DATA.split_at(SOURCE_DATA.len() / 2); + let mut context = esp_hal::sha::Context::::new(); + { + let mut hash = ctx.sha.start::(); + Update::update(&mut hash, first); + block!(hash.save(&mut context)).unwrap(); + } + hash_sha::(&mut ctx.sha, SOURCE_DATA, &mut output); + let mut hash = ShaDigest::restore(&mut ctx.sha, &mut context); + Update::update(&mut hash, second); + block!(hash.finish(&mut output)).unwrap(); + assert_sw_hash::("SM3 restored", SOURCE_DATA, &output); + } + + #[test] + #[cfg(sha_has_sha512_224)] fn test_sha_512_224(mut ctx: Context) { let expected_output = [ 0x19, 0xf2, 0xb3, 0x88, 0x22, 0x86, 0x94, 0x38, 0xee, 0x24, 0xc1, 0xc3, 0xb0, 0xb1, @@ -180,7 +212,7 @@ mod tests { } #[test] - #[cfg(any(esp32s2, esp32s3))] + #[cfg(sha_has_sha512_256)] fn test_sha_512_256(mut ctx: Context) { let expected_output = [ 0xb7, 0x49, 0x4e, 0xe1, 0xdb, 0xcd, 0xe5, 0x47, 0x5a, 0x61, 0x25, 0xac, 0x27, 0xc2, @@ -205,7 +237,7 @@ mod tests { assert_sha::(&mut ctx.sha, &SOURCE_DATA[..i]); assert_digest::(&mut ctx.sha, &SOURCE_DATA[..i]); - #[cfg(not(esp32))] + #[cfg(sha_has_sha224)] { assert_sha::(&mut ctx.sha, &SOURCE_DATA[..i]); assert_digest::(&mut ctx.sha, &SOURCE_DATA[..i]); @@ -214,11 +246,14 @@ mod tests { assert_sha::(&mut ctx.sha, &SOURCE_DATA[..i]); assert_digest::(&mut ctx.sha, &SOURCE_DATA[..i]); - #[cfg(any(esp32, esp32s2, esp32s3))] + #[cfg(sha_has_sha384)] { assert_sha::(&mut ctx.sha, &SOURCE_DATA[..i]); assert_digest::(&mut ctx.sha, &SOURCE_DATA[..i]); + } + #[cfg(sha_has_sha512)] + { assert_sha::(&mut ctx.sha, &SOURCE_DATA[..i]); assert_digest::(&mut ctx.sha, &SOURCE_DATA[..i]); } @@ -233,19 +268,21 @@ mod tests { #[allow(unused)] with_random_data(|sha1_p, sha224_p, sha256_p, sha384_p, sha512_p| { let mut sha1_remaining = sha1_p.0; + #[cfg(sha_has_sha224)] let mut sha224_remaining = sha224_p.0; let mut sha256_remaining = sha256_p.0; - #[cfg(any(esp32, esp32s2, esp32s3))] + #[cfg(sha_has_sha384)] let mut sha384_remaining = sha384_p.0; - #[cfg(any(esp32, esp32s2, esp32s3))] + #[cfg(sha_has_sha512)] let mut sha512_remaining = sha512_p.0; let mut sha1 = esp_hal::sha::Context::::new(); + #[cfg(sha_has_sha224)] let mut sha224 = esp_hal::sha::Context::::new(); let mut sha256 = esp_hal::sha::Context::::new(); - #[cfg(any(esp32, esp32s2, esp32s3))] + #[cfg(sha_has_sha384)] let mut sha384 = esp_hal::sha::Context::::new(); - #[cfg(any(esp32, esp32s2, esp32s3))] + #[cfg(sha_has_sha512)] let mut sha512 = esp_hal::sha::Context::::new(); loop { @@ -256,6 +293,7 @@ mod tests { block!(digest.save(&mut sha1)); all_done = false; } + #[cfg(sha_has_sha224)] if !sha224_remaining.is_empty() { let mut digest = ShaDigest::restore(&mut ctx.sha, &mut sha224); sha224_remaining = block!(digest.update(sha224_remaining)).unwrap(); @@ -270,21 +308,20 @@ mod tests { all_done = false; } - #[cfg(any(esp32, esp32s2, esp32s3))] - { - if !sha384_remaining.is_empty() { - let mut digest = ShaDigest::restore(&mut ctx.sha, &mut sha384); - sha384_remaining = block!(digest.update(sha384_remaining)).unwrap(); - block!(digest.save(&mut sha384)); - all_done = false; - } - - if !sha512_remaining.is_empty() { - let mut digest = ShaDigest::restore(&mut ctx.sha, &mut sha512); - sha512_remaining = block!(digest.update(sha512_remaining)).unwrap(); - block!(digest.save(&mut sha512)); - all_done = false; - } + #[cfg(sha_has_sha384)] + if !sha384_remaining.is_empty() { + let mut digest = ShaDigest::restore(&mut ctx.sha, &mut sha384); + sha384_remaining = block!(digest.update(sha384_remaining)).unwrap(); + block!(digest.save(&mut sha384)); + all_done = false; + } + + #[cfg(sha_has_sha512)] + if !sha512_remaining.is_empty() { + let mut digest = ShaDigest::restore(&mut ctx.sha, &mut sha512); + sha512_remaining = block!(digest.update(sha512_remaining)).unwrap(); + block!(digest.save(&mut sha512)); + all_done = false; } if all_done { @@ -294,14 +331,20 @@ mod tests { let mut digest = ShaDigest::restore(&mut ctx.sha, &mut sha1); block!(digest.finish(sha1_p.1)).unwrap(); - let mut digest = ShaDigest::restore(&mut ctx.sha, &mut sha224); - block!(digest.finish(sha224_p.1)).unwrap(); + #[cfg(sha_has_sha224)] + { + let mut digest = ShaDigest::restore(&mut ctx.sha, &mut sha224); + block!(digest.finish(sha224_p.1)).unwrap(); + } let mut digest = ShaDigest::restore(&mut ctx.sha, &mut sha256); block!(digest.finish(sha256_p.1)).unwrap(); - #[cfg(any(esp32, esp32s2, esp32s3))] + #[cfg(sha_has_sha384)] { let mut digest = ShaDigest::restore(&mut ctx.sha, &mut sha384); block!(digest.finish(sha384_p.1)).unwrap(); + } + #[cfg(sha_has_sha512)] + { let mut digest = ShaDigest::restore(&mut ctx.sha, &mut sha512); block!(digest.finish(sha512_p.1)).unwrap(); } @@ -322,7 +365,7 @@ mod tests { let sha1_output = digest::FixedOutput::finalize_fixed(sha1); sha1_p.1.copy_from_slice(&sha1_output); - #[cfg(not(esp32))] + #[cfg(sha_has_sha224)] { let mut sha224 = ctx.sha.start::(); Update::update(&mut sha224, sha224_p.0); @@ -335,13 +378,16 @@ mod tests { let sha256_output = digest::FixedOutput::finalize_fixed(sha256); sha256_p.1.copy_from_slice(&sha256_output); - #[cfg(any(esp32, esp32s2, esp32s3))] + #[cfg(sha_has_sha384)] { let mut sha384 = ctx.sha.start::(); Update::update(&mut sha384, sha384_p.0); let sha384_output = digest::FixedOutput::finalize_fixed(sha384); sha384_p.1.copy_from_slice(&sha384_output); + } + #[cfg(sha_has_sha512)] + { let mut sha512 = ctx.sha.start::(); Update::update(&mut sha512, sha512_p.0); let sha512_output = digest::FixedOutput::finalize_fixed(sha512); @@ -390,6 +436,26 @@ mod work_queue_tests { } } + #[test] + #[cfg(sha_has_sm3)] + fn test_sm3_context(mut ctx: Context) { + use esp_hal::sha::{Sha256Context, Sm3Context}; + + let _sha_driver = ctx.sha.start(); + + let mut sm3 = Sm3Context::new(); + let mut sha256 = Sha256Context::new(); + for chunk in SOURCE_DATA.chunks(3) { + sm3.update(chunk).wait_blocking(); + sha256.update(chunk).wait_blocking(); + } + let mut output = [0u8; 32]; + Sha256Context::finalize(&mut sha256, &mut output).wait_blocking(); + assert_sw_hash::("SHA-256 context", SOURCE_DATA, &output); + Sm3Context::finalize(&mut sm3, &mut output).wait_blocking(); + assert_sw_hash::("SM3 context", SOURCE_DATA, &output); + } + /// Calling finalize repeatedly will first return the result of the first hashing operation, /// then return result for hashing 0 bytes. #[test] @@ -452,7 +518,7 @@ mod work_queue_tests { sha1.finalize_into_slice(sha1_p.1).unwrap().wait_blocking(); } - #[cfg(not(esp32))] + #[cfg(sha_has_sha224)] { let mut sha224 = esp_hal::sha::Sha224Context::new(); sha224.update(sha224_p.0).wait_blocking(); @@ -471,7 +537,7 @@ mod work_queue_tests { .wait_blocking(); } - #[cfg(any(esp32, esp32s2, esp32s3))] + #[cfg(sha_has_sha384)] { let mut sha384 = esp_hal::sha::Sha384Context::new(); sha384.update(sha384_p.0).wait_blocking(); @@ -481,7 +547,7 @@ mod work_queue_tests { .wait_blocking(); } - #[cfg(any(esp32, esp32s2, esp32s3))] + #[cfg(sha_has_sha512)] { let mut sha512 = esp_hal::sha::Sha512Context::new(); sha512.update(sha512_p.0).wait_blocking(); @@ -501,15 +567,15 @@ mod work_queue_tests { let mut sha1 = esp_hal::sha::Sha1Context::new(); - #[cfg(not(esp32))] + #[cfg(sha_has_sha224)] let mut sha224 = esp_hal::sha::Sha224Context::new(); let mut sha256 = esp_hal::sha::Sha256Context::new(); - #[cfg(any(esp32, esp32s2, esp32s3))] + #[cfg(sha_has_sha384)] let mut sha384 = esp_hal::sha::Sha384Context::new(); - #[cfg(any(esp32, esp32s2, esp32s3))] + #[cfg(sha_has_sha512)] let mut sha512 = esp_hal::sha::Sha512Context::new(); #[allow(unused)] @@ -519,7 +585,7 @@ mod work_queue_tests { sha1.finalize_into_slice(sha1_p.1).unwrap().wait_blocking(); } - #[cfg(not(esp32))] + #[cfg(sha_has_sha224)] { sha224.update(sha224_p.0).wait_blocking(); sha224 @@ -536,7 +602,7 @@ mod work_queue_tests { .wait_blocking(); } - #[cfg(any(esp32, esp32s2, esp32s3))] + #[cfg(sha_has_sha384)] { sha384.update(sha384_p.0).wait_blocking(); sha384 @@ -545,7 +611,7 @@ mod work_queue_tests { .wait_blocking(); } - #[cfg(any(esp32, esp32s2, esp32s3))] + #[cfg(sha_has_sha512)] { sha512.update(sha512_p.0).wait_blocking(); sha512 diff --git a/hil-test/src/bin/embassy_timers_executors.rs b/hil-test/src/bin/embassy_timers_executors.rs index ec3ff3081c2..da0d0322654 100644 --- a/hil-test/src/bin/embassy_timers_executors.rs +++ b/hil-test/src/bin/embassy_timers_executors.rs @@ -69,6 +69,11 @@ mod timers_executors { "diff: {:?}", (t2 - t1).as_millis() ); + assert!( + (t2 - t1).as_millis() < 80u64, + "diff: {:?}", + (t2 - t1).as_millis() + ); } pub async fn run_join_test() { @@ -87,13 +92,13 @@ mod timers_executors { fn set_up_embassy_with_timg0(peripherals: Peripherals) { let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); } #[cfg(not(feature = "esp32"))] fn set_up_embassy_with_systimer(peripherals: Peripherals) { let systimer = SystemTimer::new(peripherals.SYSTIMER); - esp_rtos::start(systimer.alarm0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(systimer.alarm0); } #[init] @@ -165,7 +170,7 @@ mod timers_executors { #[test] async fn test_interrupt_executor(peripherals: Peripherals) { let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let executor = mk_static!( InterruptExecutor<2>, @@ -256,7 +261,7 @@ mod interrupt_executor { use esp_hal::{interrupt::Priority, peripherals::FROM_CPU_INTR2, timer::timg::TimerGroup}; #[cfg(multi_core)] use esp_hal::{ - peripherals::{CPU_CTRL, FROM_CPU_INTR1}, + peripherals::CPU_CTRL, system::{Cpu, CpuControl, Stack}, }; use esp_rtos::embassy::{Callbacks, Executor, InterruptExecutor}; @@ -307,8 +312,6 @@ mod interrupt_executor { } struct Context { - #[cfg(multi_core)] - sw_int1: FROM_CPU_INTR1<'static>, sw_int2: FROM_CPU_INTR2<'static>, #[cfg(multi_core)] cpu_control: CPU_CTRL<'static>, @@ -319,11 +322,9 @@ mod interrupt_executor { let peripherals = esp_hal::init(esp_hal::Config::default()); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); Context { - #[cfg(multi_core)] - sw_int1: peripherals.FROM_CPU_INTR1, sw_int2: peripherals.FROM_CPU_INTR2, #[cfg(multi_core)] cpu_control: peripherals.CPU_CTRL, @@ -382,7 +383,7 @@ mod interrupt_executor { let response = &*mk_static!(Signal, Signal::new()); let signal = &*mk_static!(Signal, Signal::new()); - esp_rtos::start_second_core(ctx.cpu_control, ctx.sw_int1, app_core_stack, || { + esp_rtos::start_second_core(ctx.cpu_control, app_core_stack, || { let interrupt_executor = mk_static!(InterruptExecutor<2>, InterruptExecutor::new(ctx.sw_int2)); @@ -404,7 +405,7 @@ mod interrupt_executor { let signal = mk_static!(Signal, Signal::new()); let response = mk_static!(Signal, Signal::new()); - esp_rtos::start_second_core(ctx.cpu_control, ctx.sw_int1, app_core_stack, || { + esp_rtos::start_second_core(ctx.cpu_control, app_core_stack, || { let executor = mk_static!(Executor, Executor::new()); executor.run(|spawner| { spawner.spawn(responder_task(signal, response).unwrap()); @@ -493,16 +494,15 @@ mod interrupt_spi_dma { let peripherals = esp_hal::init(esp_hal::Config::default()); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); - - let (dma_channel1, dma_channel2) = - cfg_select! { - spi_master_dma_engine = "SPI_DMA" => (peripherals.DMA_SPI2, peripherals.DMA_SPI3), - spi_master_dma_engine = "AXI_GDMA" => { - (peripherals.DMA_AXI_CH0, peripherals.DMA_AXI_CH1) - } - _ => (peripherals.DMA_CH0, peripherals.DMA_CH1), - }; + esp_rtos::start(timg0.timer0); + + let (dma_channel1, dma_channel2) = cfg_select! { + spi_master_dma_engine = "SPI_DMA" => (peripherals.DMA_SPI2, peripherals.DMA_SPI3), + spi_master_dma_engine = "AXI_GDMA" => { + (peripherals.DMA_AXI_CH0, peripherals.DMA_AXI_CH1) + } + _ => (peripherals.DMA_CH0, peripherals.DMA_CH1), + }; let dma_rx_buf = dma_rx_buffer!(1024).unwrap(); let dma_tx_buf = dma_tx_buffer!(1024).unwrap(); @@ -544,8 +544,8 @@ mod interrupt_spi_dma { .unwrap(); let interrupt_executor = mk_static!( - InterruptExecutor<1>, - InterruptExecutor::new(peripherals.FROM_CPU_INTR1) + InterruptExecutor<2>, + InterruptExecutor::new(peripherals.FROM_CPU_INTR2) ); let spawner = interrupt_executor.start(Priority::Priority3); @@ -612,12 +612,16 @@ mod interrupt_spi_dma { let dma_rx_buf = dma_rx_buffer!(3200).unwrap(); let dma_tx_buf = dma_tx_buffer!(3200).unwrap(); - let mut spi = Spi::new( - peripherals.spi, - Config::default() + let mut spi = Spi::new(peripherals.spi, { + let config = Config::default() .with_frequency(Rate::from_khz(100)) - .with_mode(Mode::_0), - ) + .with_mode(Mode::_0); + + #[cfg(soc_clock_node_spi_function_clock_is_configurable)] + let config = config.with_clock_source(esp_hal::spi::master::ClockSource::Xtal); + + config + }) .unwrap() .with_dma(peripherals.dma_channel) .with_buffers(dma_rx_buf, dma_tx_buf) @@ -636,7 +640,7 @@ mod interrupt_spi_dma { let peripherals = esp_hal::init(esp_hal::Config::default()); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let dma_channel = cfg_select! { spi_master_dma_engine = "SPI_DMA" => peripherals.DMA_SPI2, @@ -653,23 +657,18 @@ mod interrupt_spi_dma { let app_core_stack = mk_static!(Stack<8192>, Stack::new()); - esp_rtos::start_second_core( - peripherals.CPU_CTRL, - peripherals.FROM_CPU_INTR1, - app_core_stack, - || { - use esp_hal::interrupt::Priority; - let software_interrupt = peripherals.FROM_CPU_INTR2; - let hp_executor = mk_static!( - InterruptExecutor<2>, - InterruptExecutor::new(software_interrupt) - ); - let high_pri_spawner = hp_executor.start(Priority::Priority2); - - // spi runs as high priority task - high_pri_spawner.spawn(run_spi(spi_peripherals, transfer_finished).unwrap()); - }, - ); + esp_rtos::start_second_core(peripherals.CPU_CTRL, app_core_stack, || { + use esp_hal::interrupt::Priority; + let software_interrupt = peripherals.FROM_CPU_INTR2; + let hp_executor = mk_static!( + InterruptExecutor<2>, + InterruptExecutor::new(software_interrupt) + ); + let high_pri_spawner = hp_executor.start(Priority::Priority2); + + // spi runs as high priority task + high_pri_spawner.spawn(run_spi(spi_peripherals, transfer_finished).unwrap()); + }); // Wait for a few SPI transfers to happen for _ in 0..5 { diff --git a/hil-test/src/bin/flash.rs b/hil-test/src/bin/flash.rs new file mode 100644 index 00000000000..418cdcf4954 --- /dev/null +++ b/hil-test/src/bin/flash.rs @@ -0,0 +1,621 @@ +//! Internal SPI flash driver tests. +//! +//! Assumes a certain (i.e. default) partition table layout. +//% CHIP_FILTER: flash_driver_supported +//% FEATURES: unstable +//% CARGO-CONFIG: target.'cfg(target_arch = "riscv32")'.rustflags = [ "--cfg=__test_flash" ] +//% CARGO-CONFIG: target.'cfg(target_arch = "xtensa")'.rustflags = [ "--cfg=__test_flash" ] + +#![no_std] +#![no_main] + +use core::ptr::{addr_of, read_volatile}; + +use esp_hal::{ + Blocking, + flash::{Config, Error, Flash}, +}; +use hil_test as _; + +/// Default factory-app image: `0x1_0000` plus 32 bytes of headers. +const APP_DESC_OFFSET: u32 = 0x10_020; +/// Default NVS data partition. First sector is used as scratch. +const NVS: u32 = 0x9000; + +/// Source that lives in flash (`.rodata`); writes of this must be rejected. +static FLASH_PATTERN: [u32; 4] = [0x3C3C_3C3C; 4]; + +/// Mapped DROM sector reserved for cache-invalidation. Aligned so erase cannot +/// touch neighboring `.rodata` (including the app descriptor). +#[repr(C, align(4096))] +struct Scratch([u32; 1024]); + +#[used] +static SCRATCH: Scratch = Scratch([0xA5A5_A5A5; 1024]); + +/// Flash address of `SCRATCH`. Same RODATA segment as [`hil_test::ESP_APP_DESC`]. +fn scratch_flash_offset() -> u32 { + let scratch = addr_of!(SCRATCH) as u32; + let app_desc = addr_of!(hil_test::ESP_APP_DESC) as u32; + let delta = scratch + .checked_sub(app_desc) + .expect("SCRATCH must follow ESP_APP_DESC in DROM"); + APP_DESC_OFFSET + delta +} + +fn as_bytes(words: &[u32]) -> &[u8] { + // SAFETY: inspecting the in-memory bytes of `u32` words. + unsafe { core::slice::from_raw_parts(words.as_ptr().cast(), size_of_val(words)) } +} + +#[embedded_test::tests(default_timeout = 3)] +mod tests { + use super::*; + + fn flash_from_peripherals( + peripherals: esp_hal::peripherals::Peripherals, + ) -> Flash<'static, Blocking> { + Flash::new(peripherals.FLASH, Config::default()).unwrap() + } + + fn assert_range_erased(flash: &mut Flash<'static, Blocking>, offset: u32, len: usize) { + let mut buf = [0u32; 64]; + let mut remaining = len; + let mut addr = offset; + while remaining > 0 { + let n = remaining.min(size_of_val(&buf)); + flash.read(addr, &mut buf[..n / 4]).unwrap(); + assert!(as_bytes(&buf)[..n].iter().all(|&b| b == 0xFF)); + addr += n as u32; + remaining -= n; + } + } + + fn expected_app_desc() -> &'static [u8] { + unsafe { core::slice::from_raw_parts(addr_of!(hil_test::ESP_APP_DESC) as *const u8, 256) } + } + + #[test] + fn test_can_read_app_desc() { + let peripherals = esp_hal::init(esp_hal::Config::default()); + let mut flash = flash_from_peripherals(peripherals); + + let mut words = [0u32; 64]; + flash.read(APP_DESC_OFFSET, &mut words).unwrap(); + assert_eq!(as_bytes(&words), expected_app_desc()); + } + + #[test] + fn test_chip_info() { + let peripherals = esp_hal::init(esp_hal::Config::default()); + let flash = flash_from_peripherals(peripherals); + let info = flash.chip_info(); + + // TODO: Assert decoded `capacity` against this board's known flash size. + // Checking only that decode succeeded can pass with the JEDEC byte order reversed. + assert_eq!(info.capacity, flash.capacity()); + assert_eq!(info.sector_size, Flash::SECTOR_SIZE); + assert_eq!(info.block_size, Flash::BLOCK_SIZE); + assert_eq!(info.page_size, Flash::PAGE_SIZE); + } + + #[test] + fn test_erase_write_read_nvs() { + let peripherals = esp_hal::init(esp_hal::Config::default()); + let mut flash = flash_from_peripherals(peripherals); + + let sector = flash.chip_info().sector_size; + let pattern = [0xA5A5_A5A5u32; 64]; + let mut read_back = [0u32; 64]; + + // SAFETY: NVS is not mapped firmware. + unsafe { flash.erase(NVS, NVS + sector).unwrap() }; + assert_range_erased(&mut flash, NVS, size_of_val(&pattern)); + + unsafe { flash.write(NVS, &pattern).unwrap() }; + flash.read(NVS, &mut read_back).unwrap(); + assert_eq!(pattern, read_back); + + // NOR: programming cannot turn 0-bits back to 1 without an erase. + let zeros = [0x0000_0000u32; 1]; + let ones = [0xFFFF_FFFFu32; 1]; + unsafe { flash.write(NVS, &zeros).unwrap() }; + unsafe { flash.write(NVS, &ones).unwrap() }; + let mut word = [0u32; 1]; + flash.read(NVS, &mut word).unwrap(); + assert_eq!(word, [0x0000_0000; 1]); + } + + #[test] + fn test_aligned_buffers() { + let peripherals = esp_hal::init(esp_hal::Config::default()); + let mut flash = flash_from_peripherals(peripherals); + + let sector = flash.chip_info().sector_size; + let mut pattern = [0u32; 128]; + for (i, word) in pattern.iter_mut().enumerate() { + let b0 = (4 * i) as u8; + *word = u32::from_le_bytes([ + b0, + b0.wrapping_add(1), + b0.wrapping_add(2), + b0.wrapping_add(3), + ]); + } + + // SAFETY: NVS is not mapped firmware. + unsafe { flash.erase(NVS, NVS + sector).unwrap() }; + assert_range_erased(&mut flash, NVS, size_of_val(&pattern)); + unsafe { flash.write(NVS, &pattern).unwrap() }; + + let mut read_back = [0u32; 128]; + flash.read(NVS, &mut read_back).unwrap(); + assert_eq!(pattern, read_back); + + // Remaining writes need 1-bits; erase first (NOR cannot program 0→1). + unsafe { flash.erase(NVS, NVS + sector).unwrap() }; + + let page_cross = [0xAAAA_AAAAu32; 2]; + unsafe { flash.write(NVS + 252, &page_cross).unwrap() }; + let mut page_cross_read = [0u32; 2]; + flash.read(NVS + 252, &mut page_cross_read).unwrap(); + assert_eq!(page_cross, page_cross_read); + + // Flash-resident source is rejected; the caller must stage through RAM. + assert_eq!( + unsafe { flash.write(NVS, &FLASH_PATTERN) }, + Err(Error::NotSupported) + ); + } + + #[test] + fn test_multi_sector_erase() { + let peripherals = esp_hal::init(esp_hal::Config::default()); + let mut flash = flash_from_peripherals(peripherals); + + let sector = flash.chip_info().sector_size; + // SAFETY: NVS is not mapped firmware. + unsafe { flash.erase(NVS, NVS + 2 * sector).unwrap() }; + assert_range_erased(&mut flash, NVS, sector as usize); + assert_range_erased(&mut flash, NVS + sector, 256); + } + + #[test] + fn test_out_of_bounds_and_unaligned() { + let peripherals = esp_hal::init(esp_hal::Config::default()); + let mut flash = flash_from_peripherals(peripherals); + + let cap = flash.capacity() as u32; + let sector = flash.chip_info().sector_size; + let mut buf = [0u32; 1]; + + assert_eq!(flash.read(cap, &mut buf), Err(Error::OutOfBounds)); + assert_eq!(flash.read(cap - 4, &mut [0u32; 2]), Err(Error::OutOfBounds)); + assert_eq!( + unsafe { flash.write(cap, &[0u32; 1]) }, + Err(Error::OutOfBounds) + ); + assert_eq!( + unsafe { flash.write(cap - 4, &[0u32; 2]) }, + Err(Error::OutOfBounds) + ); + assert_eq!( + unsafe { flash.erase(cap, cap + sector) }, + Err(Error::OutOfBounds) + ); + assert_eq!( + unsafe { flash.erase(NVS + sector, NVS) }, + Err(Error::OutOfBounds) + ); + + flash.read(0, &mut []).unwrap(); + flash.read(cap, &mut []).unwrap(); + // Empty slices skip alignment and only check bounds. + flash.read(1, &mut []).unwrap(); + unsafe { flash.write(1, &[]).unwrap() }; + unsafe { flash.erase(1, 1).unwrap() }; + assert_eq!(flash.read(cap + 1, &mut []), Err(Error::OutOfBounds)); + unsafe { flash.write(NVS, &[]).unwrap() }; + unsafe { flash.erase(NVS, NVS).unwrap() }; + + flash + .apply_config(&Config::default()) + .expect("apply_config is a no-op on success"); + + assert_eq!(flash.read(1, &mut buf), Err(Error::NotAligned)); + assert_eq!(unsafe { flash.write(1, &buf) }, Err(Error::NotAligned)); + assert_eq!( + unsafe { flash.erase(1, 1 + sector) }, + Err(Error::NotAligned) + ); + } + + /// ROM-read of mapped firmware still works after programming *unmapped* NVS. + /// + /// Does not test invalidation of a programmed mapped page; see + /// `test_mapped_drom_read_after_program`. + #[test] + fn test_mapped_read_after_nvs_program() { + let peripherals = esp_hal::init(esp_hal::Config::default()); + let mut flash = flash_from_peripherals(peripherals); + + let mut before = [0u32; 64]; + flash.read(APP_DESC_OFFSET, &mut before).unwrap(); + assert_eq!(as_bytes(&before), expected_app_desc()); + + let sector = flash.chip_info().sector_size; + // SAFETY: NVS is not mapped firmware. + unsafe { flash.erase(NVS, NVS + sector).unwrap() }; + let marker = [0x5A5A_5A5Au32; 4]; + unsafe { flash.write(NVS, &marker).unwrap() }; + + let mut after = [0u32; 64]; + flash.read(APP_DESC_OFFSET, &mut after).unwrap(); + assert_eq!(before, after); + assert_eq!(as_bytes(&after), expected_app_desc()); + } + + /// Program a mapped DROM sector and read it back through the cache. + /// + /// The first volatile load fills D-cache. After erase/write the driver must + /// drop that line; a second load must see the programmed word. The sector + /// stays dirty until the image is re-flashed. + #[test] + fn test_mapped_drom_read_after_program() { + let peripherals = esp_hal::init(esp_hal::Config::default()); + let mut flash = flash_from_peripherals(peripherals); + + let sector = Flash::SECTOR_SIZE; + let offset = scratch_flash_offset(); + assert!( + offset.is_multiple_of(sector), + "scratch flash offset {offset:#x} is not sector-aligned" + ); + assert!( + offset >= APP_DESC_OFFSET + sector || offset + sector <= APP_DESC_OFFSET, + "scratch sector {offset:#x} overlaps the app descriptor" + ); + + let mapped = addr_of!(SCRATCH.0[0]); + // Warm D-cache; do not use `SCRATCH.0[0]` as a value (const-folded). + let _cached = unsafe { read_volatile(mapped) }; + + let pattern = [0x5A5A_5A5Au32; 1]; + // SAFETY: `SCRATCH` is a dedicated mapped sector, not firmware. + unsafe { + flash.erase(offset, offset + sector).unwrap(); + flash.write(offset, &pattern).unwrap(); + } + + let mut via_rom = [0u32; 1]; + flash.read(offset, &mut via_rom).unwrap(); + assert_eq!(via_rom, pattern); + + let via_cache = unsafe { read_volatile(mapped) }; + assert_eq!(via_cache, pattern[0]); + } + + #[cfg(multi_core)] + #[test] + fn test_auto_park_other_core() { + use core::sync::atomic::{AtomicU32, Ordering}; + + use esp_hal::system::{CpuControl, Stack}; + use hil_test::mk_static; + + static TICKS: AtomicU32 = AtomicU32::new(0); + + let peripherals = esp_hal::init(esp_hal::Config::default()); + let mut cpu_control = CpuControl::new(peripherals.CPU_CTRL); + let stack = mk_static!(Stack<8192>, Stack::new()); + let _guard = cpu_control + .start_app_core(stack, || { + loop { + TICKS.fetch_add(1, Ordering::Relaxed); + } + }) + .unwrap(); + + while TICKS.load(Ordering::Relaxed) == 0 {} + + let mut flash = Flash::new(peripherals.FLASH, Config::default()).unwrap(); + let sector = flash.chip_info().sector_size; + let pattern = [0x5A5A_5A5Au32; 64]; + let mut read_back = [0u32; 64]; + + // SAFETY: NVS is not mapped firmware. + unsafe { flash.erase(NVS, NVS + sector).unwrap() }; + unsafe { flash.write(NVS, &pattern).unwrap() }; + flash.read(NVS, &mut read_back).unwrap(); + assert_eq!(pattern, read_back); + + let before = TICKS.load(Ordering::Relaxed); + while TICKS.load(Ordering::Relaxed) == before {} + } + + #[cfg(multi_core)] + #[test] + fn test_auto_park_other_core_in_cas_loop() { + use core::sync::atomic::{AtomicU32, Ordering}; + + use esp_hal::system::{CpuControl, Stack}; + use hil_test::mk_static; + + static COUNTER: AtomicU32 = AtomicU32::new(0); + + let peripherals = esp_hal::init(esp_hal::Config::default()); + let mut cpu_control = CpuControl::new(peripherals.CPU_CTRL); + let stack = mk_static!(Stack<8192>, Stack::new()); + let _guard = cpu_control + .start_app_core(stack, || { + loop { + let mut current = COUNTER.load(Ordering::Relaxed); + while let Err(actual) = COUNTER.compare_exchange_weak( + current, + current.wrapping_add(1), + Ordering::AcqRel, + Ordering::Relaxed, + ) { + current = actual; + } + } + }) + .unwrap(); + + while COUNTER.load(Ordering::Relaxed) == 0 {} + + let mut flash = Flash::new(peripherals.FLASH, Config::default()).unwrap(); + let mut words = [0u32; 64]; + + for _ in 0..1000 { + flash.read(APP_DESC_OFFSET, &mut words).unwrap(); + assert_eq!(as_bytes(&words), expected_app_desc()); + } + + let before = COUNTER.load(Ordering::Relaxed); + while COUNTER.load(Ordering::Relaxed) == before {} + } + + #[cfg(multi_core)] + #[test] + fn test_error_if_other_core_running() { + use core::sync::atomic::{AtomicBool, Ordering}; + + use esp_hal::{ + flash::MultiCoreStrategy, + system::{CpuControl, Stack}, + }; + use hil_test::mk_static; + + static STARTED: AtomicBool = AtomicBool::new(false); + + let peripherals = esp_hal::init(esp_hal::Config::default()); + let mut cpu_control = CpuControl::new(peripherals.CPU_CTRL); + let stack = mk_static!(Stack<8192>, Stack::new()); + let _guard = cpu_control + .start_app_core(stack, || { + STARTED.store(true, Ordering::Relaxed); + loop {} + }) + .unwrap(); + + while !STARTED.load(Ordering::Relaxed) {} + + let mut flash = Flash::new( + peripherals.FLASH, + Config::default().with_multi_core_strategy(MultiCoreStrategy::Error), + ) + .unwrap(); + + let mut buf = [0u32; 1]; + assert_eq!( + flash.read(APP_DESC_OFFSET, &mut buf), + Err(Error::OtherCoreRunning) + ); + } + + /// HIL boards have no encryption key burned, so `read_encrypted` returns + /// the raw image and must agree with a plain read. + #[test] + fn test_read_encrypted_same_as_unencrypted_wo_encryption_enabled() { + let peripherals = esp_hal::init(esp_hal::Config::default()); + let mut flash = flash_from_peripherals(peripherals); + + let mut words = [0u32; 32]; + let mut encrypted = [0u32; 32]; + for offset in (0x10_000..0x20_000).step_by(128) { + flash.read(offset, &mut words).unwrap(); + flash.read_encrypted(offset, &mut encrypted).unwrap(); + assert_eq!(words, encrypted); + } + } + + /// The read loop remaps once per MMU page. This range straddles a 64 KiB + /// boundary, which is a page boundary on every chip whose MMU page is + /// 64 KiB or smaller. + #[test] + fn test_read_encrypted_across_mmu_page() { + let peripherals = esp_hal::init(esp_hal::Config::default()); + let mut flash = flash_from_peripherals(peripherals); + + let mut words = [0u32; 64]; + let mut encrypted = [0u32; 64]; + flash.read(0x1_FF80, &mut words).unwrap(); + flash.read_encrypted(0x1_FF80, &mut encrypted).unwrap(); + assert_eq!(words, encrypted); + } + + #[test] + fn test_write_encrypted_will_encrypt() { + let peripherals = esp_hal::init(esp_hal::Config::default()); + let mut flash = flash_from_peripherals(peripherals); + + let sector = flash.chip_info().sector_size; + // SAFETY: NVS is not mapped firmware. + unsafe { flash.erase(NVS, NVS + sector).unwrap() }; + + let zeros = [0u32; 64]; + unsafe { flash.write_encrypted(NVS, &zeros).unwrap() }; + + // A plain read sees ciphertext, so the stored bytes differ from the + // plaintext that was written. + let mut words = [0u32; 64]; + flash.read(NVS, &mut words).unwrap(); + assert_ne!(words, zeros); + + unsafe { flash.erase(NVS, NVS + sector).unwrap() }; + } + + #[test] + fn test_write_encrypted_alignment_and_bounds() { + let peripherals = esp_hal::init(esp_hal::Config::default()); + let mut flash = flash_from_peripherals(peripherals); + + let cap = flash.capacity() as u32; + let buf16 = [0u32; 4]; + let mut read1 = [0u32; 1]; + + assert_eq!( + unsafe { flash.write_encrypted(NVS + 1, &buf16) }, + Err(Error::NotAligned) + ); + assert_eq!( + unsafe { flash.write_encrypted(NVS, &[0u32; 3]) }, + Err(Error::NotAligned) + ); + assert_eq!(flash.read_encrypted(1, &mut read1), Err(Error::NotAligned)); + assert_eq!( + flash.read_encrypted(cap, &mut read1), + Err(Error::OutOfBounds) + ); + assert_eq!( + unsafe { flash.write_encrypted(cap, &buf16) }, + Err(Error::OutOfBounds) + ); + + // Flash-resident source is rejected; the caller must stage through RAM. + assert_eq!( + unsafe { flash.write_encrypted(NVS, &FLASH_PATTERN) }, + Err(Error::NotSupported) + ); + + flash.read_encrypted(NVS, &mut []).unwrap(); + unsafe { flash.write_encrypted(NVS, &[]).unwrap() }; + } + + /// True when writing up to `addr` needs the ESP32 neighbor bridge. + /// + /// On ESP32 a 16- but not 32-byte aligned boundary shares an AES row with + /// the neighboring block, so the driver decrypts and re-encrypts that + /// neighbor. That only reproduces the original ciphertext once the + /// encryption eFuses are burned — without them the ROM encrypts on write + /// but `read_encrypted` cannot decrypt, so the neighbor does change. HIL + /// boards are never encrypted; `qa-test/flash_encrypted` covers the bridge. + fn needs_row_bridge(addr: u32) -> bool { + cfg!(esp32) && !addr.is_multiple_of(32) + } + + /// ROM headers copy-paste ESP32's 32-byte alignment onto every chip. + /// On later chips `esp_rom_spiflash_write_encrypted` accepts 16-byte rows + /// (and 64-byte rows when the XTS block allows). Each case below is a + /// single ROM call: a 32-byte-only ROM would return an error, or program + /// past the request. + #[cfg(not(esp32))] + #[test] + fn test_rom_write_encrypted_accepts_non_32_byte_rows() { + let peripherals = esp_hal::init(esp_hal::Config::default()); + let mut flash = flash_from_peripherals(peripherals); + + let sector = flash.chip_info().sector_size; + let row16 = [0x5A5A_5A5Au32; 4]; + + // 16 bytes at a 32-byte aligned address. + // SAFETY: NVS is not mapped firmware. + unsafe { flash.erase(NVS, NVS + sector).unwrap() }; + unsafe { flash.write_encrypted(NVS, &row16).unwrap() }; + let mut written = [0u32; 4]; + flash.read(NVS, &mut written).unwrap(); + assert_ne!(written, row16); + assert_range_erased(&mut flash, NVS + 16, 16); + + // 16 bytes at a 16- but not 32-byte aligned address. + unsafe { flash.erase(NVS, NVS + sector).unwrap() }; + unsafe { flash.write_encrypted(NVS + 16, &row16).unwrap() }; + flash.read(NVS + 16, &mut written).unwrap(); + assert_ne!(written, row16); + assert_range_erased(&mut flash, NVS, 16); + assert_range_erased(&mut flash, NVS + 32, 16); + + #[cfg(not(any(esp32c2, esp32c3)))] + { + let row64 = [0x5A5A_5A5Au32; 16]; + unsafe { flash.erase(NVS, NVS + sector).unwrap() }; + unsafe { flash.write_encrypted(NVS, &row64).unwrap() }; + let mut written64 = [0u32; 16]; + flash.read(NVS, &mut written64).unwrap(); + assert_ne!(written64, row64); + assert_range_erased(&mut flash, NVS + 64, 16); + } + + unsafe { flash.erase(NVS, NVS + sector).unwrap() }; + } + + /// 16-, 32-, and 48-byte writes (48 is 32+16) at both 32- and 16-byte + /// aligned offsets. Bytes outside the requested range must keep their + /// erased value. + #[test] + fn test_write_encrypted_does_not_touch_neighbors() { + let peripherals = esp_hal::init(esp_hal::Config::default()); + let mut flash = flash_from_peripherals(peripherals); + + let sector = flash.chip_info().sector_size; + let data = [0x5A5A_5A5Au32; 12]; + + for (offset, words) in [(0u32, 4usize), (0, 8), (0, 12), (16, 4), (16, 8), (16, 12)] { + // SAFETY: NVS is not mapped firmware. + unsafe { flash.erase(NVS, NVS + sector).unwrap() }; + unsafe { flash.write_encrypted(NVS + offset, &data[..words]).unwrap() }; + + let end = offset + (words * 4) as u32; + if offset > 0 && !needs_row_bridge(offset) { + assert_range_erased(&mut flash, NVS, offset as usize); + } + if !needs_row_bridge(end) { + assert_range_erased(&mut flash, NVS + end, 16); + } + } + + unsafe { flash.erase(NVS, NVS + sector).unwrap() }; + } + + #[test] + fn test_booted_partition_is_the_factory_app() { + use esp_bootloader_esp_idf::partitions::{self, AppPartitionSubType, PartitionType}; + + let mut flash = flash_from_peripherals(esp_hal::init(esp_hal::Config::default())); + let mut pt_mem = [0u8; partitions::PARTITION_TABLE_MAX_LEN]; + let pt = partitions::read_partition_table(&mut flash, &mut pt_mem).unwrap(); + + let booted = pt.booted_partition().unwrap().unwrap(); + assert_eq!( + booted.partition_type(), + PartitionType::App(AppPartitionSubType::Factory) + ); + assert_eq!(booted.offset(), APP_DESC_OFFSET - 0x20); + } + + #[test] + fn test_drom_entry_offset_reads_the_window() { + use esp_hal::flash::{flash_mmu_drom_entries, flash_mmu_entry_offset}; + + let _peripherals = esp_hal::init(esp_hal::Config::default()); + let drom = flash_mmu_drom_entries(); + + // The linker scripts put the app's rodata at the start of the DROM window. + assert_eq!( + flash_mmu_entry_offset(drom.start), + Some(APP_DESC_OFFSET - 0x20) + ); + assert_eq!(flash_mmu_entry_offset(drom.end), None); + } +} diff --git a/hil-test/src/bin/gpio.rs b/hil-test/src/bin/gpio.rs index c396cde6fa8..d8fb58a5ea3 100644 --- a/hil-test/src/bin/gpio.rs +++ b/hil-test/src/bin/gpio.rs @@ -58,7 +58,7 @@ struct Context { dedicated_gpio: DedicatedGpio<'static>, #[cfg(feature = "unstable")] - int1: esp_hal::peripherals::FROM_CPU_INTR1<'static>, + int1: esp_hal::peripherals::FROM_CPU_INTR2<'static>, #[cfg(all(multi_core, feature = "unstable"))] cpu_ctrl: esp_hal::peripherals::CPU_CTRL<'static>, #[cfg(all(multi_core, feature = "unstable"))] @@ -161,8 +161,8 @@ mod tests { let int1 = { // Timers are unstable let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); - peripherals.FROM_CPU_INTR1 + esp_rtos::start(timg0.timer0); + peripherals.FROM_CPU_INTR2 }; Context { @@ -374,7 +374,7 @@ mod tests { async fn gpio_interrupt_enabled_on_other_core(mut ctx: Context) { let io_set_up = &*mk_static!(Signal::, Signal::new()); - esp_rtos::start_second_core(ctx.cpu_ctrl, ctx.int1, ctx.app_core_stack, move || { + esp_rtos::start_second_core(ctx.cpu_ctrl, ctx.app_core_stack, move || { // Set the interrupt handler for GPIO. ctx.io.set_interrupt_handler(interrupt_handler); io_set_up.signal(()); @@ -535,44 +535,6 @@ mod tests { assert_eq!(test_gpio2.is_set_low(), true); } - #[test] - #[cfg(all(feature = "unstable", lp_io_driver_supported))] - fn creating_a_driver_releases_the_hold_of_a_pad(mut ctx: Context) { - let probe = Input::new( - ctx.test_gpio2.reborrow(), - InputConfig::default().with_pull(Pull::None), - ); - - // A program that held the pad while it drove a high level. - { - let mut pin = Flex::new(ctx.test_gpio1.reborrow()); - pin.apply_output_config(&OutputConfig::default()); - pin.set_output_enable(true); - pin.set_high(); - - pin.set_pad_hold(true); - assert!(pin.is_pad_held(), "the pad does not report its hold"); - - pin.set_low(); - ctx.delay.delay_millis(1); - assert_eq!( - probe.level(), - Level::High, - "the hold does not keep the level of the pad" - ); - } - - let mut pin = Flex::new(ctx.test_gpio1.reborrow()); - pin.apply_output_config(&OutputConfig::default()); - pin.set_output_enable(true); - pin.set_low(); - - assert!(!pin.is_pad_held(), "the pad still reports a hold"); - - ctx.delay.delay_millis(1); - assert_eq!(probe.level(), Level::Low, "the pad is still held"); - } - // Tests touch pin (GPIO2) as AnyPin and Output // https://github.com/esp-rs/esp-hal/issues/1943 #[test] @@ -616,7 +578,7 @@ mod tests { use esp_rtos::embassy::InterruptExecutor; use static_cell::StaticCell; - static INTERRUPT_EXECUTOR: StaticCell> = StaticCell::new(); + static INTERRUPT_EXECUTOR: StaticCell> = StaticCell::new(); let interrupt_executor = INTERRUPT_EXECUTOR.init(InterruptExecutor::new(ctx.int1)); let spawner = interrupt_executor.start(Priority::max()); @@ -690,17 +652,12 @@ mod tests { const CORE1_STACK_SIZE: usize = 8192; let app_core_stack = mk_static!(Stack, Stack::new()); - esp_rtos::start_second_core( - unsafe { CPU_CTRL::steal() }, - ctx.int1, - app_core_stack, - move || { - let executor = mk_static!(Executor, Executor::new()); - executor.run(|spawner| { - spawner.spawn(edge_counter_task(in_pin, input_pin_listening).unwrap()); - }); - }, - ); + esp_rtos::start_second_core(unsafe { CPU_CTRL::steal() }, app_core_stack, move || { + let executor = mk_static!(Executor, Executor::new()); + executor.run(|spawner| { + spawner.spawn(edge_counter_task(in_pin, input_pin_listening).unwrap()); + }); + }); // Now drive the OutputPin and assert that the other core saw exactly as many // edges as we generated here. @@ -723,36 +680,38 @@ mod tests { #[test] #[cfg(all(dedicated_gpio_driver_supported, feature = "unstable"))] fn dedicated_gpios(ctx: Context) { + fn settle() { + #[cfg(esp32s2)] + unsafe { + core::arch::asm!("nop"); + core::arch::asm!("nop"); + core::arch::asm!("nop"); + core::arch::asm!("nop"); + } + } let input = Input::new(ctx.test_gpio1, InputConfig::default().with_pull(Pull::Down)); let output = Output::new(ctx.test_gpio2, Level::Low, OutputConfig::default()); let input_dedicated = DedicatedGpioInput::new(ctx.dedicated_gpio.channel0.input, input); - let mut output_dedicated = - DedicatedGpioOutput::new(ctx.dedicated_gpio.channel0.output).with_pin(output); + let mut output_dedicated = DedicatedGpioOutput::new(ctx.dedicated_gpio.channel0.output); - // output_dedicated.set_level(Level::Low); + // There is no pin connected. We can change the output level, but it only sets some internal + // state. assert_eq!(input_dedicated.level(), Level::Low); assert_eq!(output_dedicated.output_level(), Level::Low); output_dedicated.set_level(Level::High); - #[cfg(esp32s2)] - unsafe { - core::arch::asm!("nop"); - core::arch::asm!("nop"); - core::arch::asm!("nop"); - core::arch::asm!("nop"); - } + settle(); + assert_eq!(output_dedicated.output_level(), Level::High); + assert_eq!(input_dedicated.level(), Level::Low); + + // Connect pin and observe its state changing without calling `set_level`. + let mut output_dedicated = output_dedicated.with_pin(output); + settle(); assert_eq!(input_dedicated.level(), Level::High); assert_eq!(output_dedicated.output_level(), Level::High); - // It used to only be possible for dedicated gpio to drive the pin High, not back to Low - // again on the esp32s2 and esp32s3, this makes sure that is not the case + output_dedicated.set_level(Level::Low); - #[cfg(esp32s2)] - unsafe { - core::arch::asm!("nop"); - core::arch::asm!("nop"); - core::arch::asm!("nop"); - core::arch::asm!("nop"); - } + settle(); assert_eq!(input_dedicated.level(), Level::Low); assert_eq!(output_dedicated.output_level(), Level::Low); } @@ -787,7 +746,7 @@ mod tests { // creating the driver at core1, and then use it at core // this should panic - esp_rtos::start_second_core(ctx.cpu_ctrl, ctx.int1, ctx.app_core_stack, move || { + esp_rtos::start_second_core(ctx.cpu_ctrl, ctx.app_core_stack, move || { let input = Input::new(pin1, InputConfig::default().with_pull(Pull::Down)); let driver = DedicatedGpioInput::new(ctx.dedicated_gpio.channel1.input, input); @@ -917,3 +876,112 @@ mod tests { } } } + +// LP and HP pads have separate hold implementations, so each needs a connected pair of its own. +#[cfg(all(feature = "unstable", lp_io_driver_supported))] +#[embedded_test::tests(default_timeout = 3)] +mod pad_hold { + use esp_hal::{ + delay::Delay, + gpio::{AnyPin, Flex, Input, InputConfig, Level, OutputConfig, Pin, Pull}, + }; + + struct Context { + lp_pad: AnyPin<'static>, + lp_probe: AnyPin<'static>, + #[cfg(not(esp32))] + hp_pad: AnyPin<'static>, + #[cfg(not(esp32))] + hp_probe: AnyPin<'static>, + delay: Delay, + } + + #[init] + fn init() -> Context { + let peripherals = esp_hal::init(esp_hal::Config::default()); + + let (lp_pad, lp_probe) = hil_test::lp_test_pins!(peripherals); + #[cfg(not(esp32))] + let (hp_pad, hp_probe) = hil_test::hp_test_pins!(peripherals); + + Context { + lp_pad: lp_pad.degrade(), + lp_probe: lp_probe.degrade(), + #[cfg(not(esp32))] + hp_pad: hp_pad.degrade(), + #[cfg(not(esp32))] + hp_probe: hp_probe.degrade(), + delay: Delay::new(), + } + } + + fn creating_a_driver_releases_the_hold( + mut pad: AnyPin<'static>, + probe: AnyPin<'static>, + delay: Delay, + ) { + let probe = Input::new(probe, InputConfig::default().with_pull(Pull::None)); + + // A program that held the pad while it drove a high level. + { + let mut pin = Flex::new(pad.reborrow()); + pin.apply_output_config(&OutputConfig::default()); + pin.set_output_enable(true); + pin.set_high(); + + pin.set_pad_hold(true); + assert!(pin.is_pad_held(), "the pad does not report its hold"); + + pin.set_low(); + delay.delay_millis(1); + assert_eq!( + probe.level(), + Level::High, + "the hold does not keep the level of the pad" + ); + } + + let mut pin = Flex::new(pad.reborrow()); + pin.apply_output_config(&OutputConfig::default()); + pin.set_output_enable(true); + pin.set_low(); + + assert!(!pin.is_pad_held(), "the pad still reports a hold"); + + delay.delay_millis(1); + assert_eq!(probe.level(), Level::Low, "the pad is still held"); + } + + #[test] + fn creating_a_driver_releases_the_hold_of_an_lp_pad(ctx: Context) { + creating_a_driver_releases_the_hold(ctx.lp_pad, ctx.lp_probe, ctx.delay); + } + + #[test] + #[cfg(not(esp32))] + fn creating_a_driver_releases_the_hold_of_an_hp_pad(ctx: Context) { + creating_a_driver_releases_the_hold(ctx.hp_pad, ctx.hp_probe, ctx.delay); + } +} + +#[allow(unused, reason = "Compile tests")] +#[cfg(spi_master_driver_supported)] // unimportant, one device is enough to check the API +mod compile_regression_tests { + use esp_hal::{ + Blocking, + gpio::{InputPin, OutputPin}, + spi::master::Spi, + }; + + fn pin_traits_imply_peripheral_signals() { + // The interconnect module is not stable, meaning users can't name `PeripheralInput`. + // `InputPin` must therefore imply `PeripheralInput` to allow generic code. This is done by + // a blanket implementation, which must be preserved despite the subpar documentation. + fn input_pin_generic_user_function(spi: Spi<'_, Blocking>, p: impl InputPin) { + spi.with_miso(p); + } + fn output_pin_generic_user_function(spi: Spi<'_, Blocking>, p: impl OutputPin) { + spi.with_mosi(p); + } + } +} diff --git a/hil-test/src/bin/gpio_custom_handler.rs b/hil-test/src/bin/gpio_custom_handler.rs index 1c4ef520d0d..bf3da0c8e3b 100644 --- a/hil-test/src/bin/gpio_custom_handler.rs +++ b/hil-test/src/bin/gpio_custom_handler.rs @@ -161,7 +161,7 @@ mod tests { let (gpio1, gpio2) = hil_test::common_test_pins!(peripherals); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let counter = drive_pins(gpio1, gpio2).await; @@ -178,7 +178,7 @@ mod tests { let (gpio1, gpio2) = hil_test::common_test_pins!(peripherals); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let counter = drive_pins(gpio1, gpio2).await; @@ -199,11 +199,11 @@ mod tests { let (gpio1, gpio2) = hil_test::common_test_pins!(peripherals); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let interrupt_executor = mk_static!( - InterruptExecutor<1>, - InterruptExecutor::new(peripherals.FROM_CPU_INTR1) + InterruptExecutor<2>, + InterruptExecutor::new(peripherals.FROM_CPU_INTR2) ); // Run the executor at interrupt priority 1, which is the same as the default // interrupt priority of the GPIO interrupt handler. @@ -231,7 +231,7 @@ mod tests { let (gpio1, gpio2) = hil_test::common_test_pins!(peripherals); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let counter = drive_pins(gpio1, gpio2).await; @@ -257,7 +257,7 @@ mod tests { HANDLER_MODE.store(HandlerMode::WakeSpecificPin as u8, Ordering::Relaxed); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let counter = drive_pins(gpio1, gpio2).await; @@ -283,7 +283,7 @@ mod tests { let (gpio1, gpio2) = hil_test::common_test_pins!(peripherals); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); static IO_SET_UP: ConstStaticCell> = ConstStaticCell::new(Signal::::new()); @@ -293,7 +293,6 @@ mod tests { let mut io = Io::new(peripherals.IO_MUX); esp_rtos::start_second_core( peripherals.CPU_CTRL, - peripherals.FROM_CPU_INTR1, mk_static!(Stack<4096>, Stack::new()), move || { // Set the interrupt handler for GPIO. diff --git a/hil-test/src/bin/i2c.rs b/hil-test/src/bin/i2c.rs index afd97ba4f5e..4abd79974cc 100644 --- a/hil-test/src/bin/i2c.rs +++ b/hil-test/src/bin/i2c.rs @@ -21,7 +21,7 @@ use esp_hal::{ SoftwareTimeout, }, interrupt::Priority, - peripherals::FROM_CPU_INTR1, + peripherals::FROM_CPU_INTR2, time, timer::timg::TimerGroup, }; @@ -29,7 +29,7 @@ use esp_rtos::embassy::InterruptExecutor; use hil_test::mk_static; struct Context { - interrupt: FROM_CPU_INTR1<'static>, + interrupt: FROM_CPU_INTR2<'static>, i2c: I2c<'static, Blocking>, } @@ -75,7 +75,7 @@ mod tests { let peripherals = esp_hal::init(esp_hal::Config::default()); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let (sda, scl) = hil_test::i2c_pins!(peripherals); // Test that the pin can be explicitly configured using Flex: @@ -98,7 +98,7 @@ mod tests { Context { i2c, - interrupt: peripherals.FROM_CPU_INTR1, + interrupt: peripherals.FROM_CPU_INTR2, } } @@ -352,7 +352,7 @@ mod tests { let mut i2c = ctx.i2c.into_async(); let interrupt_executor = - mk_static!(InterruptExecutor<1>, InterruptExecutor::new(ctx.interrupt)); + mk_static!(InterruptExecutor<2>, InterruptExecutor::new(ctx.interrupt)); let spawner = interrupt_executor.start(Priority::Priority3); diff --git a/hil-test/src/bin/i2s.rs b/hil-test/src/bin/i2s.rs index e9b003cc961..9436d7ee164 100644 --- a/hil-test/src/bin/i2s.rs +++ b/hil-test/src/bin/i2s.rs @@ -51,6 +51,8 @@ macro_rules! i2s_instance_resources { #[embedded_test::tests(default_timeout = 3, executor = hil_test::Executor::new())] mod tests { + #[cfg(not(i2s_version = "1"))] + use esp_hal::i2s::master::Alignment; use esp_hal::{ Async, delay::Delay, @@ -698,6 +700,125 @@ mod tests { } } + #[cfg(all(soc_has_i2s0, not(i2s_version = "1")))] + async fn run_test_i2s0_loopback_data_formats( + tx_data_format: DataFormat, + rx_data_format: DataFormat, + tx_alignment: Alignment, + rx_alignment: Alignment, + mut expected: &[u8], + ) { + use core::cmp::min; + + use esp_hal::i2s::master::{Endianness, TdmUnitConfig}; + + let (i2s, dma_channel, dout): (AnyI2s, AnyI2sDmaChannel, AnyPin) = + i2s_instance_resources!(I2S0); + let spawner = unsafe { embassy_executor::Spawner::for_current_executor().await }; + + let rx_buffer = dma_rx_stream_buffer!(BUFFER_SIZE, 128); + let tx_buffer = dma_tx_stream_buffer!(BUFFER_SIZE, 128); + + let i2s = I2s::new( + i2s, + dma_channel, + TdmConfig::default() + .with_signal_loopback(true) + .with_tx_config( + TdmUnitConfig::new_tdm_philips() + .with_sample_rate(Rate::from_hz(16000)) + .with_data_format(tx_data_format) + // By using big-endian we maintain the byte ordering between the + // representation in memory and in the i2s stream (the naming is very + // confusing here). This simplifies the loopback test. + .with_endianness(Endianness::BigEndian) + // Ensures that all the data goes out to i2s stream unchanged + .with_channels(Channels::STEREO) + .with_alignment(tx_alignment), + ) + .with_rx_config( + TdmUnitConfig::new_tdm_philips() + .with_sample_rate(Rate::from_hz(16000)) + .with_data_format(rx_data_format) + // By using big-endian we maintain the byte ordering between the + // representation in memory and in the i2s stream (the naming is very + // confusing here). This simplifies the loopback test. + .with_endianness(Endianness::BigEndian) + // Ensures that all the data from the i2s stream comes back in + .with_channels(Channels::STEREO) + .with_alignment(rx_alignment), + ), + ) + .unwrap() + .into_async(); + + let (din, dout) = unsafe { dout.split() }; + + let i2s_tx = i2s + .i2s_tx + .with_bclk(NoPin) + .with_ws(NoPin) + .with_dout(dout) + .build(); + + let i2s_rx = i2s + .i2s_rx + .with_bclk(NoPin) + .with_ws(NoPin) + .with_din(din) + .build(); + + let mut rx_transfer = i2s_rx.read(rx_buffer).ok().unwrap(); + spawner.spawn(writer(tx_buffer, i2s_tx).unwrap()); + + let mut buffer = [0u8; 8]; + while !expected.is_empty() { + rx_transfer.wait_for_available_async().await.unwrap(); + let len = min(buffer.len(), expected.len()); + let n = rx_transfer.pop(&mut buffer[..len]); + assert_eq!(&buffer[..n], &expected[..n]); + expected = &expected[n..]; + } + } + + // For the tests where we change the tx data format we want to keep rx on Data8Channel8 so + // that we capture all the data + #[cfg(all(soc_has_i2s0, not(i2s_version = "1")))] + async fn run_test_data_formats_tx( + data_format: DataFormat, + alignment: Alignment, + expected: &[u8], + ) { + use esp_hal::i2s::master::Alignment; + + run_test_i2s0_loopback_data_formats( + data_format, + DataFormat::Data8Channel8, + alignment, + Alignment::Left, + expected, + ) + .await; + } + + // For the tests where we change the rx data format we want to keep tx on Data32Channel32 so + // that we know we're sending all the data + #[cfg(all(soc_has_i2s0, not(i2s_version = "1")))] + async fn run_test_data_formats_rx( + data_format: DataFormat, + alignment: Alignment, + expected: &[u8], + ) { + run_test_i2s0_loopback_data_formats( + DataFormat::Data32Channel32, + data_format, + Alignment::Left, + alignment, + expected, + ) + .await; + } + #[test] #[cfg(soc_has_i2s0)] async fn test_i2s_loopback_async_i2s0() { @@ -872,20 +993,293 @@ mod tests { let (i2s, dma_channel, _) = i2s_instance_resources!(I2S0); run_test_i2s_rx_half_sample_bits_regression(i2s, dma_channel); } + + #[test] + #[cfg(all(soc_has_i2s0, not(i2s_version = "1")))] + async fn test_rx_32() { + run_test_data_formats_rx( + DataFormat::Data32Channel32, + Alignment::Left, + &[1, 6, 11, 16, 21, 26, 31, 36], + ) + .await; + } + + #[test] + #[cfg(all(soc_has_i2s0, not(i2s_version = "1")))] + async fn test_rx_32_24_left() { + run_test_data_formats_rx( + DataFormat::Data32Channel24, + Alignment::Left, + &[1, 6, 11, 21, 26, 31, 41, 46], + ) + .await; + } + + #[test] + #[cfg(all(soc_has_i2s0, not(i2s_version = "1")))] + async fn test_rx_32_16_left() { + run_test_data_formats_rx( + DataFormat::Data32Channel16, + Alignment::Left, + &[1, 6, 21, 26, 41, 46, 61, 66], + ) + .await; + } + + #[test] + #[cfg(all(soc_has_i2s0, not(i2s_version = "1")))] + async fn test_rx_32_16_right() { + run_test_data_formats_rx( + DataFormat::Data32Channel16, + Alignment::Right, + &[11, 16, 31, 36, 51, 56, 71, 76], + ) + .await; + } + + #[test] + #[cfg(all(soc_has_i2s0, not(i2s_version = "1")))] + async fn test_rx_32_8_left() { + run_test_data_formats_rx( + DataFormat::Data32Channel8, + Alignment::Left, + &[1, 21, 41, 61, 81, 101, 8, 28], + ) + .await; + } + + #[test] + #[cfg(all(soc_has_i2s0, not(i2s_version = "1")))] + async fn test_rx_16() { + run_test_data_formats_rx( + DataFormat::Data16Channel16, + Alignment::Left, + &[1, 6, 11, 16, 21, 26, 31, 36], + ) + .await; + } + + #[test] + #[cfg(all(soc_has_i2s0, not(i2s_version = "1")))] + async fn test_rx_16_8_left() { + run_test_data_formats_rx( + DataFormat::Data16Channel8, + Alignment::Left, + &[1, 11, 21, 31, 41, 51, 61, 71], + ) + .await; + } + + #[test] + #[cfg(all(soc_has_i2s0, not(i2s_version = "1")))] + async fn test_rx_8() { + run_test_data_formats_rx( + DataFormat::Data8Channel8, + Alignment::Left, + &[1, 6, 11, 16, 21, 26, 31, 36], + ) + .await; + } + + #[test] + #[cfg(all(soc_has_i2s0, not(i2s_version = "1")))] + async fn test_tx_32_24_left() { + run_test_data_formats_tx( + DataFormat::Data32Channel24, + Alignment::Left, + &[1, 6, 11, 0, 16, 21, 26, 0], + ) + .await; + } + + #[test] + #[cfg(all(soc_has_i2s0, not(i2s_version = "1")))] + async fn test_tx_32_16_left() { + run_test_data_formats_tx( + DataFormat::Data32Channel16, + Alignment::Left, + &[1, 6, 0, 0, 11, 16, 0, 0], + ) + .await; + } + + #[test] + #[cfg(all(soc_has_i2s0, not(i2s_version = "1")))] + async fn test_tx_32_16_right() { + use esp_hal::i2s::master::Alignment; + + run_test_data_formats_tx( + DataFormat::Data32Channel16, + Alignment::Right, + &[0, 0, 1, 6, 0, 0, 11, 16], + ) + .await; + } + + #[test] + #[cfg(all(soc_has_i2s0, not(i2s_version = "1")))] + async fn test_tx_32_8_left() { + run_test_data_formats_tx( + DataFormat::Data32Channel8, + Alignment::Left, + &[1, 0, 0, 0, 6, 0, 0, 0], + ) + .await; + } + + #[test] + #[cfg(all(soc_has_i2s0, not(i2s_version = "1")))] + async fn test_tx_16() { + run_test_data_formats_tx( + DataFormat::Data16Channel16, + Alignment::Left, + &[1, 6, 11, 16, 21, 26, 31, 36], + ) + .await; + } + + #[test] + #[cfg(all(soc_has_i2s0, not(i2s_version = "1")))] + async fn test_tx_16_8_left() { + run_test_data_formats_tx( + DataFormat::Data16Channel8, + Alignment::Left, + &[1, 0, 6, 0, 11, 0, 16, 0], + ) + .await; + } + + #[test] + #[cfg(all(soc_has_i2s0, not(i2s_version = "1")))] + async fn test_tx_8() { + run_test_data_formats_tx( + DataFormat::Data8Channel8, + Alignment::Left, + &[1, 6, 11, 16, 21, 26, 31, 36], + ) + .await; + } } #[cfg(esp32)] #[embedded_test::tests(default_timeout = 3, executor = hil_test::Executor::new())] mod i2s_parallel_tests { + use core::cell::RefCell; + + use critical_section::Mutex as CsMutex; use esp_hal::{ + Blocking, dma::I2sDmaChannel, gpio::NoPin, i2s::{ AnyI2s, - parallel::{I2sParallel, TxSixteenBits}, + parallel::{I2sParallel, I2sParallelInterrupt, I2sParallelTransfer, TxSixteenBits}, }, + interrupt::{InterruptHandler, Priority}, time::Rate, }; + use portable_atomic::{AtomicUsize, Ordering}; + + static ISR_COUNT: AtomicUsize = AtomicUsize::new(0); + + type BlockingTransfer = I2sParallelTransfer<'static, esp_hal::dma::DmaTxBuf, Blocking>; + + // The ongoing transfer, so the ISR can query and clear interrupt flags + // through it (the driver itself is consumed by `send`). + static TRANSFER: CsMutex>> = CsMutex::new(RefCell::new(None)); + + extern "C" fn i2s_parallel_isr() { + critical_section::with(|cs| { + if let Some(xfer) = TRANSFER.borrow_ref(cs).as_ref() { + let active = xfer.interrupts(); + xfer.clear_interrupts(active); + } + }); + ISR_COUNT.fetch_add(1, Ordering::Relaxed); + } + + fn poll_until(mut condition: impl FnMut() -> bool, message: &str) { + let delay = esp_hal::delay::Delay::new(); + for _ in 0..1000 { + if condition() { + return; + } + delay.delay_millis(1); + } + panic!("{}", message); + } + + fn run_i2s_parallel_interrupt(i2s: AnyI2s<'static>, dma_channel: I2sDmaChannel<'static>) { + ISR_COUNT.store(0, Ordering::Relaxed); + critical_section::with(|cs| TRANSFER.replace(cs, None)); + + let pins = TxSixteenBits::new( + NoPin, NoPin, NoPin, NoPin, NoPin, NoPin, NoPin, NoPin, NoPin, NoPin, NoPin, NoPin, + NoPin, NoPin, NoPin, NoPin, + ); + let mut i2s = I2sParallel::new(i2s, dma_channel, Rate::from_mhz(20), pins, NoPin); + i2s.set_interrupt_handler(InterruptHandler::new(i2s_parallel_isr, Priority::Priority1)); + + let mut tx_buf = esp_hal::dma_tx_buffer!(4096).unwrap(); + tx_buf.fill(&[0x55; 512]); + + // Publish the transfer so the ISR can use it, then listen. + // The transfer may complete before we listen; the flags still assert, + // so the ISR still fires. + let xfer = i2s + .send(tx_buf) + .map_err(|_| "failed to send buffer") + .unwrap(); + critical_section::with(|cs| TRANSFER.replace(cs, Some(xfer))); + critical_section::with(|cs| { + if let Some(xfer) = TRANSFER.borrow_ref(cs).as_ref() { + xfer.listen(I2sParallelInterrupt::TotalEof | I2sParallelInterrupt::Done); + } + }); + + // Wait for the transfer to complete and the ISR to fire. + poll_until( + || { + critical_section::with(|cs| { + TRANSFER + .borrow_ref(cs) + .as_ref() + .is_some_and(|xfer| xfer.is_done()) + }) && ISR_COUNT.load(Ordering::Relaxed) > 0 + }, + "transfer did not complete or ISR did not fire", + ); + assert!( + ISR_COUNT.load(Ordering::Relaxed) > 0, + "ISR should have fired at least once" + ); + + let xfer = critical_section::with(|cs| TRANSFER.take(cs)).unwrap(); + let (_i2s, _tx_buf) = xfer.wait(); + } + + #[test] + #[cfg(soc_has_i2s0)] + fn i2s_parallel_interrupt_i2s0() { + let peripherals = esp_hal::init( + esp_hal::Config::default().with_cpu_clock(esp_hal::clock::CpuClock::max()), + ); + let i2s = peripherals.I2S0.into(); + let dma_channel: I2sDmaChannel<'static> = peripherals.DMA_I2S0.into(); + run_i2s_parallel_interrupt(i2s, dma_channel); + } + + #[test] + #[cfg(soc_has_i2s1)] + fn i2s_parallel_interrupt_i2s1() { + let peripherals = esp_hal::init( + esp_hal::Config::default().with_cpu_clock(esp_hal::clock::CpuClock::max()), + ); + let i2s = peripherals.I2S1.into(); + let dma_channel: I2sDmaChannel<'static> = peripherals.DMA_I2S1.into(); + run_i2s_parallel_interrupt(i2s, dma_channel); + } async fn run_driver_does_not_hang_when_async( i2s: AnyI2s<'static>, @@ -996,7 +1390,8 @@ mod pdm_tx_tests { let tx_cfg = if info.pcm2pdm { PdmTxConfig::new_codec_default(Rate::from_hz(16_000), PdmSlotMode::Mono) } else { - PdmTxConfig::new_raw_default(Rate::from_hz(2_048_000), PdmSlotMode::Mono) + // 1.024 MHz: raw MCLK is sample_rate * 16; 2.048 MHz exceeds S31's 40 MHz XTAL. + PdmTxConfig::new_raw_default(Rate::from_hz(1_024_000), PdmSlotMode::Mono) }; assert!(tx_cfg.validate(info).is_ok()); } @@ -1011,7 +1406,7 @@ mod pdm_tx_tests { let tx_cfg = if info.pcm2pdm { PdmTxConfig::new_codec_default(Rate::from_hz(16_000), PdmSlotMode::Mono) } else { - PdmTxConfig::new_raw_default(Rate::from_hz(2_048_000), PdmSlotMode::Mono) + PdmTxConfig::new_raw_default(Rate::from_hz(1_024_000), PdmSlotMode::Mono) }; let pdm_cfg = PdmConfig::tx_only(tx_cfg); @@ -1095,7 +1490,8 @@ mod pdm_rx_tests { let rx_cfg = if info.pdm2pcm { PdmRxConfig::new_pcm_default(Rate::from_hz(16_000), PdmSlotMode::Mono) } else { - PdmRxConfig::new_raw_default(Rate::from_hz(2_048_000), PdmSlotMode::Mono) + // 1.024 MHz: raw MCLK is sample_rate * 16; 2.048 MHz exceeds S31's 40 MHz XTAL. + PdmRxConfig::new_raw_default(Rate::from_hz(1_024_000), PdmSlotMode::Mono) }; assert!(rx_cfg.validate(info).is_ok()); } @@ -1110,7 +1506,7 @@ mod pdm_rx_tests { let rx_cfg = if info.pdm2pcm { PdmRxConfig::new_pcm_default(Rate::from_hz(16_000), PdmSlotMode::Mono) } else { - PdmRxConfig::new_raw_default(Rate::from_hz(2_048_000), PdmSlotMode::Mono) + PdmRxConfig::new_raw_default(Rate::from_hz(1_024_000), PdmSlotMode::Mono) }; let pdm_cfg = PdmConfig::rx_only(rx_cfg); @@ -1175,7 +1571,7 @@ mod pdm_rx_tests { struct EdgeCounter<'a> { #[cfg(pcnt_driver_supported)] - unit: esp_hal::pcnt::unit::Unit<'a, 0>, + unit: esp_hal::pcnt::unit::Unit<'a>, phantom: core::marker::PhantomData<&'a ()>, } @@ -1183,8 +1579,7 @@ struct EdgeCounter<'a> { #[cfg(pcnt_driver_supported)] impl<'a> EdgeCounter<'a> { fn new<'i>(input: impl esp_hal::gpio::interconnect::PeripheralInput<'i>) -> Self { - let pcnt = esp_hal::pcnt::Pcnt::new(unsafe { esp_hal::peripherals::PCNT::steal() }); - let unit = pcnt.unit0; + let unit = esp_hal::pcnt::Unit::new(unsafe { esp_hal::peripherals::PCNT0_UNIT0::steal() }); unit.channel0.set_edge_signal(input); unit.channel0.set_input_mode( esp_hal::pcnt::channel::EdgeMode::Hold, diff --git a/hil-test/src/bin/ieee802154.rs b/hil-test/src/bin/ieee802154.rs new file mode 100644 index 00000000000..6863f80acb1 --- /dev/null +++ b/hil-test/src/bin/ieee802154.rs @@ -0,0 +1,40 @@ +//! IEEE 802.15.4 driver tests. + +//% CHIP_FILTER: ieee802154_driver_supported && rng_trng_supported +//% FEATURES: unstable esp-alloc esp-radio/ieee802154 esp-radio/unstable + +#![no_std] +#![no_main] + +use hil_test as _; + +extern crate alloc; + +#[embedded_test::tests(default_timeout = 3)] +mod tests { + use esp_hal::{peripherals::Peripherals, rng::Trng}; + use esp_radio::ieee802154::Ieee802154; + + #[init] + fn init() -> Peripherals { + esp_alloc::heap_allocator!(size: 24 * 1024); + esp_hal::init(esp_hal::Config::default()) + } + + #[test] + fn trng_is_available_while_radio_is_enabled(p: Peripherals) { + assert!(Trng::try_new().is_err()); + + let radio = Ieee802154::new(p.IEEE802154); + let trng = Trng::try_new().unwrap(); + + let mut values = [0u8; 16]; + trng.read(&mut values); + assert!(values.windows(2).any(|w| w[0] != w[1])); + + core::mem::drop(trng); + core::mem::drop(radio); + + assert!(Trng::try_new().is_err()); + } +} diff --git a/hil-test/src/bin/interrupt.rs b/hil-test/src/bin/interrupt.rs index 83478af732e..b9a1ab00198 100644 --- a/hil-test/src/bin/interrupt.rs +++ b/hil-test/src/bin/interrupt.rs @@ -21,7 +21,7 @@ use esp_hal::{ }; use hil_test as _; -static SWINT0: Mutex>>> = Mutex::new(RefCell::new(None)); +static SWINT0: Mutex>>> = Mutex::new(RefCell::new(None)); #[unsafe(no_mangle)] static mut LAST_PERF: u32 = 0; @@ -79,7 +79,7 @@ mod tests { _ => &peripherals.SYSTEM, }; - let sw0_trigger_addr = cpu_intr.register_block().cpu_intr_from_cpu(0) as *const _ as u32; + let sw0_trigger_addr = cpu_intr.register_block().cpu_intr_from_cpu(2) as *const _ as u32; unsafe { SW_TRIGGER_ADDR = sw0_trigger_addr as *mut u32; } @@ -87,13 +87,13 @@ mod tests { critical_section::with(|cs| { SWINT0 .borrow_ref_mut(cs) - .replace(SoftwareInterrupt::new(peripherals.FROM_CPU_INTR0)) + .replace(SoftwareInterrupt::new(peripherals.FROM_CPU_INTR2)) }); interrupt::enable_direct( - Interrupt::FROM_CPU_INTR0, + Interrupt::FROM_CPU_INTR2, Priority::Priority3, - interrupt::DirectBindableCpuInterrupt::Interrupt0, + interrupt::DirectBindableCpuInterrupt::Interrupt1, interrupt_handler, ); @@ -121,7 +121,7 @@ mod tests { " li {bit}, 1 # Flip flag (bit 0) csrrwi x0, 0x7e1, 1 # enable timer - sw {bit}, 0({addr}) # trigger FROM_CPU_INTR0 + sw {bit}, 0({addr}) # trigger FROM_CPU_INTR2 ", options(nostack), addr = in(reg) ctx.sw0_trigger_addr, diff --git a/hil-test/src/bin/lcd_cam.rs b/hil-test/src/bin/lcd_cam.rs index bd3ab8858f1..ba97098fc19 100644 --- a/hil-test/src/bin/lcd_cam.rs +++ b/hil-test/src/bin/lcd_cam.rs @@ -1,385 +1,451 @@ //! lcd_cam_i8080 and camera tests +//! +//! Camera/DPI loopback uses GPIO `split()` (no jumpers). +//! ESP32-S31 avoids USB Serial/JTAG (GPIO13/14), Ethernet RGMII (GPIO8-19), +//! and the CI GPIO2-GPIO3 tie. //% CHIP_FILTER: camera_driver_supported -//% FEATURES: unstable +//% FEATURES: unstable defmt #![no_std] #![no_main] +#[cfg(pcnt_driver_supported)] +use esp_hal::pcnt::{ + Unit, + channel::{CtrlMode, EdgeMode}, +}; use esp_hal::{ Async, - Blocking, - dma::{DmaChannel, DmaRxBuf, DmaTxBuf}, + dma::{DmaChannel, DmaLoopBuf, DmaRxBuf, DmaTxBuf}, + dma_loop_buffer, dma_rx_buffer, dma_tx_buffer, gpio::Level, lcd_cam::{ - BitOrder, LcdCam, cam::{self, Camera, VhdeMode}, lcd::{ ClockMode, Phase, Polarity, - dpi::{self, Dpi, Format, FrameTiming}, + dpi::{self, Dpi, DpiInterrupt, Format, FrameTiming}, i8080::{Command, Config, I8080}, }, }, - pcnt::{ - Pcnt, - channel::{CtrlMode, EdgeMode}, - }, - peripherals::{DMA_CH0, Peripherals}, + peripherals::Peripherals, time::Rate, }; use hil_test as _; const DATA_SIZE: usize = 1024 * 10; -#[allow(non_snake_case)] -struct Pins { - pub GPIO8: esp_hal::peripherals::GPIO8<'static>, - pub GPIO11: esp_hal::peripherals::GPIO11<'static>, - pub GPIO12: esp_hal::peripherals::GPIO12<'static>, - pub GPIO16: esp_hal::peripherals::GPIO16<'static>, - pub GPIO17: esp_hal::peripherals::GPIO17<'static>, -} - -struct AsyncContext<'d> { - lcd_cam: LcdCam<'d, Async>, - dma: DMA_CH0<'d>, - dma_buf: DmaTxBuf, +fn dpi_test_config() -> dpi::Config { + dpi::Config::default() + .with_clock_mode(ClockMode { + polarity: Polarity::IdleHigh, + phase: Phase::ShiftLow, + }) + .with_frequency(Rate::from_khz(500)) + .with_format(Format { + enable_2byte_mode: false, + ..Default::default() + }) + .with_timing(FrameTiming { + horizontal_total_width: 65, + hsync_width: 5, + horizontal_blank_front_porch: 10, + horizontal_active_width: 50, + vertical_total_height: 65, + vsync_width: 5, + vertical_blank_front_porch: 10, + vertical_active_height: 50, + hsync_position: 0, + }) + .with_vsync_idle_level(Level::High) + .with_hsync_idle_level(Level::High) + .with_de_idle_level(Level::Low) + .with_disable_black_region(false) } -struct BlockingContext<'d> { - lcd_cam: LcdCam<'d, Blocking>, - pcnt: Pcnt<'d>, - pins: Pins, - dma: DMA_CH0<'d>, - dma_buf: DmaTxBuf, -} +cfg_select! { + lcd_cam_dma_engine = "AHB_GDMA" => { + use esp_hal::peripherals::DMA_CH0 as DmaChannelInstance; + } -struct CameraContext { - peripherals: Peripherals, - dma_tx_buf: DmaTxBuf, - dma_rx_buf: DmaRxBuf, + lcd_cam_dma_engine = "AXI_GDMA" => { + use esp_hal::peripherals::DMA_AXI_CH0 as DmaChannelInstance; + } } // lcd_cam_i8080 tests +#[embedded_test::tests(default_timeout = 3, executor = hil_test::Executor::new())] mod async_tests { use super::*; - #[embedded_test::tests(default_timeout = 3, executor = hil_test::Executor::new())] - mod tests { - use super::*; - - #[init] - async fn init() -> AsyncContext<'static> { - let peripherals = esp_hal::init(esp_hal::Config::default()); - let lcd_cam = LcdCam::new(peripherals.LCD_CAM).into_async(); - let dma_buf = dma_tx_buffer!(DATA_SIZE).unwrap(); + struct Context<'d> { + lcd_cam: LcdCam<'d, Async>, + dma: DmaChannelInstance<'d>, + dma_buf: DmaTxBuf, + } - AsyncContext { - lcd_cam, - dma: peripherals.DMA_CH0, - dma_buf, - } + #[init] + async fn init() -> Context<'static> { + let peripherals = esp_hal::init(esp_hal::Config::default()); + let lcd_cam = LcdCam::new(peripherals.LCD_CAM).into_async(); + let dma_buf = dma_tx_buffer!(DATA_SIZE).unwrap(); + let dma_channel = cfg_select! { + lcd_cam_dma_engine = "AHB_GDMA" => peripherals.DMA_CH0, + lcd_cam_dma_engine = "AXI_GDMA" => peripherals.DMA_AXI_CH0, + }; + + Context { + lcd_cam, + dma: dma_channel, + dma_buf, } + } - #[test] - async fn test_i8080_8bit(ctx: AsyncContext<'static>) { - let i8080 = I8080::new( - ctx.lcd_cam.lcd, - ctx.dma, - Config::default().with_frequency(Rate::from_mhz(20)), - ) - .unwrap(); - - core::mem::drop(ctx.lcd_cam.cam); - let mut transfer = i8080.send(Command::::None, 0, ctx.dma_buf).unwrap(); - - transfer.wait_for_done().await; - transfer.wait_for_done().await; - transfer.wait().0.unwrap(); - } + #[test] + async fn test_i8080_8bit(ctx: Context<'static>) { + let i8080 = I8080::new( + ctx.lcd_cam.lcd, + ctx.dma, + Config::default().with_frequency(Rate::from_mhz(20)), + ) + .unwrap(); + + core::mem::drop(ctx.lcd_cam.cam); + let mut transfer = i8080.send(Command::::None, 0, ctx.dma_buf).unwrap(); + + transfer.wait_for_done().await; + transfer.wait_for_done().await; + transfer.wait().0.unwrap(); } } // lcd_cam_i8080 tests +#[cfg(pcnt_driver_supported)] +#[embedded_test::tests(default_timeout = 3)] mod blocking_tests { - use super::*; + use esp_hal::{Blocking, gpio::AnyPin, lcd_cam::BitOrder}; - #[embedded_test::tests(default_timeout = 3)] - mod tests { - use super::*; - - #[init] - fn init() -> BlockingContext<'static> { - let peripherals = esp_hal::init(esp_hal::Config::default()); - let lcd_cam = LcdCam::new(peripherals.LCD_CAM); - let pcnt = Pcnt::new(peripherals.PCNT); - let dma_buf = dma_tx_buffer!(DATA_SIZE).unwrap(); - - BlockingContext { - lcd_cam, - dma: peripherals.DMA_CH0, - pcnt, - pins: Pins { - GPIO8: peripherals.GPIO8, - GPIO11: peripherals.GPIO11, - GPIO12: peripherals.GPIO12, - GPIO16: peripherals.GPIO16, - GPIO17: peripherals.GPIO17, - }, - dma_buf, - } - } + use super::*; - #[test] - fn test_i8080_8bit(ctx: BlockingContext<'static>) { - let i8080 = I8080::new( - ctx.lcd_cam.lcd, - ctx.dma, - Config::default().with_frequency(Rate::from_mhz(20)), - ) - .unwrap(); + struct Context<'d> { + lcd_cam: LcdCam<'d, Blocking>, + units: [Unit<'d>; 4], + pins: [AnyPin<'d>; 5], + dma: DmaChannelInstance<'d>, + dma_buf: DmaTxBuf, + } - let xfer = i8080.send(Command::::None, 0, ctx.dma_buf).unwrap(); - xfer.wait().0.unwrap(); + #[init] + fn init() -> Context<'static> { + let peripherals = esp_hal::init(esp_hal::Config::default()); + let lcd_cam = LcdCam::new(peripherals.LCD_CAM); + let dma_buf = dma_tx_buffer!(DATA_SIZE).unwrap(); + let dma_channel = cfg_select! { + lcd_cam_dma_engine = "AHB_GDMA" => peripherals.DMA_CH0, + lcd_cam_dma_engine = "AXI_GDMA" => peripherals.DMA_AXI_CH0, + }; + + Context { + lcd_cam, + dma: dma_channel, + units: [ + Unit::new(peripherals.PCNT0_UNIT0), + Unit::new(peripherals.PCNT0_UNIT1), + Unit::new(peripherals.PCNT0_UNIT2), + Unit::new(peripherals.PCNT0_UNIT3), + ], + pins: [ + peripherals.GPIO8.into(), + peripherals.GPIO11.into(), + peripherals.GPIO12.into(), + peripherals.GPIO16.into(), + peripherals.GPIO17.into(), + ], + dma_buf, } + } - #[test] - fn test_i8080_8bit_is_seen_by_pcnt(ctx: BlockingContext<'static>) { - let (unit_ctrl, cs_signal) = unsafe { ctx.pins.GPIO8.split() }; - let (unit0_input, unit0_signal) = unsafe { ctx.pins.GPIO11.split() }; - let (unit1_input, unit1_signal) = unsafe { ctx.pins.GPIO12.split() }; - let (unit2_input, unit2_signal) = unsafe { ctx.pins.GPIO16.split() }; - let (unit3_input, unit3_signal) = unsafe { ctx.pins.GPIO17.split() }; - - let pcnt = ctx.pcnt; - pcnt.unit0 - .channel0 - .set_ctrl_mode(CtrlMode::Keep, CtrlMode::Disable); - pcnt.unit1 - .channel0 - .set_ctrl_mode(CtrlMode::Keep, CtrlMode::Disable); - pcnt.unit2 - .channel0 - .set_ctrl_mode(CtrlMode::Keep, CtrlMode::Disable); - pcnt.unit3 - .channel0 - .set_ctrl_mode(CtrlMode::Keep, CtrlMode::Disable); - - pcnt.unit0 - .channel0 - .set_input_mode(EdgeMode::Hold, EdgeMode::Increment); - pcnt.unit1 - .channel0 - .set_input_mode(EdgeMode::Hold, EdgeMode::Increment); - pcnt.unit2 - .channel0 - .set_input_mode(EdgeMode::Hold, EdgeMode::Increment); - pcnt.unit3 - .channel0 - .set_input_mode(EdgeMode::Hold, EdgeMode::Increment); - - let mut i8080 = I8080::new( - ctx.lcd_cam.lcd, - ctx.dma, - Config::default().with_frequency(Rate::from_mhz(20)), - ) - .unwrap() - .with_cs(cs_signal) - .with_data0(unit0_signal) - .with_data1(unit1_signal) - .with_data2(unit2_signal) - .with_data3(unit3_signal); - - core::mem::drop(ctx.lcd_cam.cam); - i8080.set_bit_order(BitOrder::Inverted); - - pcnt.unit0.channel0.set_edge_signal(unit0_input); - pcnt.unit1.channel0.set_edge_signal(unit1_input); - pcnt.unit2.channel0.set_edge_signal(unit2_input); - pcnt.unit3.channel0.set_edge_signal(unit3_input); - - pcnt.unit0.channel0.set_ctrl_signal(unit_ctrl.clone()); - pcnt.unit1.channel0.set_ctrl_signal(unit_ctrl.clone()); - pcnt.unit2.channel0.set_ctrl_signal(unit_ctrl.clone()); - pcnt.unit3.channel0.set_ctrl_signal(unit_ctrl.clone()); - - pcnt.unit0.resume(); - pcnt.unit1.resume(); - pcnt.unit2.resume(); - pcnt.unit3.resume(); - - let data_to_send = [ - 0b0000_0000, - 0b1010_0000, - 0b0110_0000, - 0b1110_0000, - 0b0000_0000, - 0b1000_0000, - 0b0100_0000, - 0b1010_0000, - 0b0101_0000, - 0b1000_0000, - ]; - - let mut dma_buf = ctx.dma_buf; - dma_buf.as_mut_slice().fill(0); - dma_buf.as_mut_slice()[..data_to_send.len()].copy_from_slice(&data_to_send); - - let xfer = i8080.send(Command::::None, 0, dma_buf).unwrap(); - xfer.wait().0.unwrap(); - - let actual = [ - pcnt.unit0.value(), - pcnt.unit1.value(), - pcnt.unit2.value(), - pcnt.unit3.value(), - ]; - assert_eq!([5, 3, 2, 1], actual); - } + #[test] + fn test_i8080_8bit(ctx: Context<'static>) { + let i8080 = I8080::new( + ctx.lcd_cam.lcd, + ctx.dma, + Config::default().with_frequency(Rate::from_mhz(20)), + ) + .unwrap(); + + let xfer = i8080.send(Command::::None, 0, ctx.dma_buf).unwrap(); + xfer.wait().0.unwrap(); + } - #[test] - fn test_i8080_16bit_is_seen_by_pcnt(ctx: BlockingContext<'static>) { - let (unit_ctrl, cs_signal) = unsafe { ctx.pins.GPIO8.split() }; - let (unit0_input, unit0_signal) = unsafe { ctx.pins.GPIO11.split() }; - let (unit1_input, unit1_signal) = unsafe { ctx.pins.GPIO12.split() }; - let (unit2_input, unit2_signal) = unsafe { ctx.pins.GPIO16.split() }; - let (unit3_input, unit3_signal) = unsafe { ctx.pins.GPIO17.split() }; - - let pcnt = ctx.pcnt; - pcnt.unit0 - .channel0 - .set_ctrl_mode(CtrlMode::Keep, CtrlMode::Disable); - pcnt.unit1 - .channel0 - .set_ctrl_mode(CtrlMode::Keep, CtrlMode::Disable); - pcnt.unit2 - .channel0 - .set_ctrl_mode(CtrlMode::Keep, CtrlMode::Disable); - pcnt.unit3 - .channel0 - .set_ctrl_mode(CtrlMode::Keep, CtrlMode::Disable); - - pcnt.unit0 - .channel0 - .set_input_mode(EdgeMode::Hold, EdgeMode::Increment); - pcnt.unit1 - .channel0 - .set_input_mode(EdgeMode::Hold, EdgeMode::Increment); - pcnt.unit2 - .channel0 - .set_input_mode(EdgeMode::Hold, EdgeMode::Increment); - pcnt.unit3 - .channel0 - .set_input_mode(EdgeMode::Hold, EdgeMode::Increment); - - let mut i8080 = I8080::new( - ctx.lcd_cam.lcd, - ctx.dma, - Config::default().with_frequency(Rate::from_mhz(20)), - ) - .unwrap() - .with_cs(cs_signal) - .with_data3(unit0_signal) - .with_data7(unit1_signal) - .with_data11(unit2_signal) - .with_data15(unit3_signal); - - i8080.set_bit_order(BitOrder::Inverted); - - pcnt.unit0.channel0.set_edge_signal(unit0_input); - pcnt.unit1.channel0.set_edge_signal(unit1_input); - pcnt.unit2.channel0.set_edge_signal(unit2_input); - pcnt.unit3.channel0.set_edge_signal(unit3_input); - - pcnt.unit0.channel0.set_ctrl_signal(unit_ctrl.clone()); - pcnt.unit1.channel0.set_ctrl_signal(unit_ctrl.clone()); - pcnt.unit2.channel0.set_ctrl_signal(unit_ctrl.clone()); - pcnt.unit3.channel0.set_ctrl_signal(unit_ctrl.clone()); - - pcnt.unit0.resume(); - pcnt.unit1.resume(); - pcnt.unit2.resume(); - pcnt.unit3.resume(); - - let data_to_send = [ - 0b0000_0000_0000_0000u16, - 0b0001_0000_0001_0000, - 0b0000_0001_0001_0000, - 0b0001_0001_0001_0000, - 0b0000_0000_0000_0000, - 0b0001_0000_0000_0000, - 0b0000_0001_0000_0000, - 0b0001_0000_0001_0000, - 0b0000_0001_0000_0001, - 0b0001_0000_0000_0000, - ]; - - let mut dma_buf = ctx.dma_buf; - dma_buf - .as_mut_slice() - .iter_mut() - .zip(data_to_send.iter().flat_map(|&d| d.to_ne_bytes())) - .for_each(|(d, s)| *d = s); - - let xfer = i8080.send(Command::::None, 0, dma_buf).unwrap(); - xfer.wait().0.unwrap(); - - let actual = [ - pcnt.unit0.value(), - pcnt.unit1.value(), - pcnt.unit2.value(), - pcnt.unit3.value(), - ]; - assert_eq!([5, 3, 2, 1], actual); - } + #[test] + fn test_i8080_8bit_is_seen_by_pcnt(ctx: Context<'static>) { + let [ctrl, u0, u1, u2, u3] = ctx.pins; + let (unit_ctrl, cs_signal) = unsafe { ctrl.split() }; + let (unit0_input, unit0_signal) = unsafe { u0.split() }; + let (unit1_input, unit1_signal) = unsafe { u1.split() }; + let (unit2_input, unit2_signal) = unsafe { u2.split() }; + let (unit3_input, unit3_signal) = unsafe { u3.split() }; + + let [unit0, unit1, unit2, unit3] = ctx.units; + unit0 + .channel0 + .set_ctrl_mode(CtrlMode::Keep, CtrlMode::Disable); + unit1 + .channel0 + .set_ctrl_mode(CtrlMode::Keep, CtrlMode::Disable); + unit2 + .channel0 + .set_ctrl_mode(CtrlMode::Keep, CtrlMode::Disable); + unit3 + .channel0 + .set_ctrl_mode(CtrlMode::Keep, CtrlMode::Disable); + + unit0 + .channel0 + .set_input_mode(EdgeMode::Hold, EdgeMode::Increment); + unit1 + .channel0 + .set_input_mode(EdgeMode::Hold, EdgeMode::Increment); + unit2 + .channel0 + .set_input_mode(EdgeMode::Hold, EdgeMode::Increment); + unit3 + .channel0 + .set_input_mode(EdgeMode::Hold, EdgeMode::Increment); + + let mut i8080 = I8080::new( + ctx.lcd_cam.lcd, + ctx.dma, + Config::default().with_frequency(Rate::from_mhz(20)), + ) + .unwrap() + .with_cs(cs_signal) + .with_data0(unit0_signal) + .with_data1(unit1_signal) + .with_data2(unit2_signal) + .with_data3(unit3_signal); + + core::mem::drop(ctx.lcd_cam.cam); + i8080.set_bit_order(BitOrder::Inverted); + + unit0.channel0.set_edge_signal(unit0_input); + unit1.channel0.set_edge_signal(unit1_input); + unit2.channel0.set_edge_signal(unit2_input); + unit3.channel0.set_edge_signal(unit3_input); + + unit0.channel0.set_ctrl_signal(unit_ctrl.clone()); + unit1.channel0.set_ctrl_signal(unit_ctrl.clone()); + unit2.channel0.set_ctrl_signal(unit_ctrl.clone()); + unit3.channel0.set_ctrl_signal(unit_ctrl.clone()); + + unit0.resume(); + unit1.resume(); + unit2.resume(); + unit3.resume(); + + let data_to_send = [ + 0b0000_0000, + 0b1010_0000, + 0b0110_0000, + 0b1110_0000, + 0b0000_0000, + 0b1000_0000, + 0b0100_0000, + 0b1010_0000, + 0b0101_0000, + 0b1000_0000, + ]; + + let mut dma_buf = ctx.dma_buf; + dma_buf.as_mut_slice().fill(0); + dma_buf.as_mut_slice()[..data_to_send.len()].copy_from_slice(&data_to_send); + + let xfer = i8080.send(Command::::None, 0, dma_buf).unwrap(); + xfer.wait().0.unwrap(); + + let actual = [unit0.value(), unit1.value(), unit2.value(), unit3.value()]; + assert_eq!([5, 3, 2, 1], actual); + } + + #[test] + fn test_i8080_16bit_is_seen_by_pcnt(ctx: Context<'static>) { + let [ctrl, u0, u1, u2, u3] = ctx.pins; + let (unit_ctrl, cs_signal) = unsafe { ctrl.split() }; + let (unit0_input, unit0_signal) = unsafe { u0.split() }; + let (unit1_input, unit1_signal) = unsafe { u1.split() }; + let (unit2_input, unit2_signal) = unsafe { u2.split() }; + let (unit3_input, unit3_signal) = unsafe { u3.split() }; + + let [unit0, unit1, unit2, unit3] = ctx.units; + unit0 + .channel0 + .set_ctrl_mode(CtrlMode::Keep, CtrlMode::Disable); + unit1 + .channel0 + .set_ctrl_mode(CtrlMode::Keep, CtrlMode::Disable); + unit2 + .channel0 + .set_ctrl_mode(CtrlMode::Keep, CtrlMode::Disable); + unit3 + .channel0 + .set_ctrl_mode(CtrlMode::Keep, CtrlMode::Disable); + + unit0 + .channel0 + .set_input_mode(EdgeMode::Hold, EdgeMode::Increment); + unit1 + .channel0 + .set_input_mode(EdgeMode::Hold, EdgeMode::Increment); + unit2 + .channel0 + .set_input_mode(EdgeMode::Hold, EdgeMode::Increment); + unit3 + .channel0 + .set_input_mode(EdgeMode::Hold, EdgeMode::Increment); + + let mut i8080 = I8080::new( + ctx.lcd_cam.lcd, + ctx.dma, + Config::default().with_frequency(Rate::from_mhz(20)), + ) + .unwrap() + .with_cs(cs_signal) + .with_data3(unit0_signal) + .with_data7(unit1_signal) + .with_data11(unit2_signal) + .with_data15(unit3_signal); + + i8080.set_bit_order(BitOrder::Inverted); + + unit0.channel0.set_edge_signal(unit0_input); + unit1.channel0.set_edge_signal(unit1_input); + unit2.channel0.set_edge_signal(unit2_input); + unit3.channel0.set_edge_signal(unit3_input); + + unit0.channel0.set_ctrl_signal(unit_ctrl.clone()); + unit1.channel0.set_ctrl_signal(unit_ctrl.clone()); + unit2.channel0.set_ctrl_signal(unit_ctrl.clone()); + unit3.channel0.set_ctrl_signal(unit_ctrl.clone()); + + unit0.resume(); + unit1.resume(); + unit2.resume(); + unit3.resume(); + + let data_to_send = [ + 0b0000_0000_0000_0000u16, + 0b0001_0000_0001_0000, + 0b0000_0001_0001_0000, + 0b0001_0001_0001_0000, + 0b0000_0000_0000_0000, + 0b0001_0000_0000_0000, + 0b0000_0001_0000_0000, + 0b0001_0000_0001_0000, + 0b0000_0001_0000_0001, + 0b0001_0000_0000_0000, + ]; + + let mut dma_buf = ctx.dma_buf; + dma_buf + .as_mut_slice() + .iter_mut() + .zip(data_to_send.iter().flat_map(|&d| d.to_ne_bytes())) + .for_each(|(d, s)| *d = s); + + let xfer = i8080.send(Command::::None, 0, dma_buf).unwrap(); + xfer.wait().0.unwrap(); + + let actual = [unit0.value(), unit1.value(), unit2.value(), unit3.value()]; + assert_eq!([5, 3, 2, 1], actual); } } // LCD_CAM Camera and DPI tests +#[embedded_test::tests(default_timeout = 3, executor = hil_test::Executor::new())] mod camera_tests { + use core::task::Poll; + + use embassy_futures::{join::join, poll_once}; + use esp_hal::{dma::DmaError, gpio::interconnect::InputSignal as GpioInputSignal}; + use super::*; - #[embedded_test::tests] - mod tests { - use super::*; + const FRAME_BYTES: usize = 50 * 50; - #[init] - fn init() -> CameraContext { - let peripherals = esp_hal::init(esp_hal::Config::default()); - let dma_rx_buf = dma_rx_buffer!(2500).unwrap(); - let dma_tx_buf = dma_tx_buffer!(2500).unwrap(); + struct Context { + peripherals: Peripherals, + dma_tx_buf: DmaTxBuf, + dma_rx_buf: DmaRxBuf, + } - CameraContext { - peripherals, - dma_tx_buf, - dma_rx_buf, - } + #[init] + fn init() -> Context { + let peripherals = esp_hal::init(esp_hal::Config::default()); + let dma_rx_buf = dma_rx_buffer!(3 * FRAME_BYTES).unwrap(); + let dma_tx_buf = dma_tx_buffer!(FRAME_BYTES).unwrap(); + + Context { + peripherals, + dma_tx_buf, + dma_rx_buf, } + } - #[test] - fn test_camera_can_receive_from_rgb(ctx: CameraContext) { - let peripherals = ctx.peripherals; - let lcd_cam = LcdCam::new(peripherals.LCD_CAM); - let (rx_channel, tx_channel) = peripherals.DMA_CH2.split(); - - let ( - (vsync_in, vsync_out), - (hsync_in, hsync_out), - (de_in, de_out), - (pclk_in, pclk_out), - (d0_in, d0_out), - (d1_in, d1_out), - (d2_in, d2_out), - (d3_in, d3_out), - (d4_in, d4_out), - (d5_in, d5_out), - (d6_in, d6_out), - (d7_in, d7_out), - ) = unsafe { + #[test] + fn test_camera_configuration(ctx: Context) { + let peripherals = ctx.peripherals; + let lcd_cam = LcdCam::new(peripherals.LCD_CAM); + let dma_channel = cfg_select! { + lcd_cam_dma_engine = "AHB_GDMA" => peripherals.DMA_CH0, + lcd_cam_dma_engine = "AXI_GDMA" => peripherals.DMA_AXI_CH0, + }; + let _camera = Camera::new( + lcd_cam.cam, + dma_channel, + cam::Config::default().with_eof_mode(cam::EofMode::VsyncSignal), + ) + .unwrap(); + let regs = esp_hal::peripherals::LCD_CAM::regs(); + hil_test::assert!(regs.cam_ctrl().read().cam_vs_eof_en().bit_is_set()); + } + + fn loopback( + ctx: Context, + ) -> ( + Camera<'static>, + Dpi<'static, esp_hal::Blocking>, + DmaTxBuf, + DmaRxBuf, + GpioInputSignal<'static>, + ) { + let peripherals = ctx.peripherals; + let lcd_cam = LcdCam::new(peripherals.LCD_CAM); + let dma_channel = cfg_select! { + lcd_cam_dma_engine = "AHB_GDMA" => peripherals.DMA_CH0, + lcd_cam_dma_engine = "AXI_GDMA" => peripherals.DMA_AXI_CH0, + }; + let (rx_channel, tx_channel) = dma_channel.split(); + + let ( + (vsync_in, vsync_out), + (hsync_in, hsync_out), + (de_in, de_out), + (pclk_in, pclk_out), + (d0_in, d0_out), + (d1_in, d1_out), + (d2_in, d2_out), + (d3_in, d3_out), + (d4_in, d4_out), + (d5_in, d5_out), + (d6_in, d6_out), + (d7_in, d7_out), + ) = cfg_select! { + esp32s3 => unsafe { ( peripherals.GPIO6.split(), peripherals.GPIO7.split(), @@ -394,84 +460,331 @@ mod camera_tests { peripherals.GPIO17.split(), peripherals.GPIO16.split(), ) - }; - - let config = dpi::Config::default() - .with_clock_mode(ClockMode { - polarity: Polarity::IdleHigh, - phase: Phase::ShiftLow, - }) - .with_frequency(Rate::from_khz(500)) - .with_format(Format { - enable_2byte_mode: false, - ..Default::default() - }) - .with_timing(FrameTiming { - horizontal_total_width: 65, - hsync_width: 5, - horizontal_blank_front_porch: 10, - horizontal_active_width: 50, - vertical_total_height: 65, - vsync_width: 5, - vertical_blank_front_porch: 10, - vertical_active_height: 50, - hsync_position: 0, - }) - .with_vsync_idle_level(Level::High) - .with_hsync_idle_level(Level::High) - .with_de_idle_level(Level::Low) - .with_disable_black_region(false); - - let dpi = Dpi::new(lcd_cam.lcd, tx_channel, config) - .unwrap() - .with_vsync(vsync_out) - .with_hsync(hsync_out) - .with_de(de_out) - .with_pclk(pclk_out) - .with_data0(d0_out) - .with_data1(d1_out) - .with_data2(d2_out) - .with_data3(d3_out) - .with_data4(d4_out) - .with_data5(d5_out) - .with_data6(d6_out) - .with_data7(d7_out); - - let camera = Camera::new( - lcd_cam.cam, - rx_channel, - cam::Config::default() - .with_frequency(Rate::from_mhz(1)) - .with_vh_de_mode(VhdeMode::VsyncHsync), - ) + }, + esp32s31 => unsafe { + ( + peripherals.GPIO20.split(), + peripherals.GPIO21.split(), + peripherals.GPIO22.split(), + peripherals.GPIO23.split(), + peripherals.GPIO24.split(), + peripherals.GPIO25.split(), + peripherals.GPIO35.split(), + peripherals.GPIO42.split(), + peripherals.GPIO43.split(), + peripherals.GPIO46.split(), + peripherals.GPIO47.split(), + peripherals.GPIO48.split(), + ) + }, + }; + + let dpi = Dpi::new(lcd_cam.lcd, tx_channel, dpi_test_config()) .unwrap() - .with_vsync(vsync_in) - .with_hsync(hsync_in) - .with_h_enable(de_in) - .with_pixel_clock(pclk_in) - .with_data0(d0_in) - .with_data1(d1_in) - .with_data2(d2_in) - .with_data3(d3_in) - .with_data4(d4_in) - .with_data5(d5_in) - .with_data6(d6_in) - .with_data7(d7_in); - - let mut dma_tx_buf = ctx.dma_tx_buf; - let mut dma_rx_buf = ctx.dma_rx_buf; - - for (i, b) in dma_tx_buf.as_mut_slice().iter_mut().enumerate() { - *b = (i % 256) as u8; + .with_vsync(vsync_out) + .with_hsync(hsync_out) + .with_de(de_out) + .with_pclk(pclk_out) + .with_data0(d0_out) + .with_data1(d1_out) + .with_data2(d2_out) + .with_data3(d3_out) + .with_data4(d4_out) + .with_data5(d5_out) + .with_data6(d6_out) + .with_data7(d7_out); + + let camera = Camera::new( + lcd_cam.cam, + rx_channel, + cam::Config::default() + .with_frequency(Rate::from_mhz(2)) + .with_vh_de_mode(VhdeMode::VsyncHsync), + ) + .unwrap() + .with_vsync(vsync_in) + .with_hsync(hsync_in) + .with_h_enable(de_in) + .with_pixel_clock(pclk_in.clone()) + .with_data0(d0_in) + .with_data1(d1_in) + .with_data2(d2_in) + .with_data3(d3_in) + .with_data4(d4_in) + .with_data5(d5_in) + .with_data6(d6_in) + .with_data7(d7_in); + + let mut dma_tx_buf = ctx.dma_tx_buf; + let mut dma_rx_buf = ctx.dma_rx_buf; + dma_tx_buf.set_length(FRAME_BYTES); + dma_rx_buf.set_length(FRAME_BYTES); + + for (i, b) in dma_tx_buf.as_mut_slice().iter_mut().enumerate() { + *b = (i % FRAME_BYTES % 256) as u8; + } + + (camera, dpi, dma_tx_buf, dma_rx_buf, pclk_in) + } + + fn pulse_camera_vsync(pclk: &GpioInputSignal<'static>) { + use esp_hal::gpio::{InputSignal, interconnect::PeripheralSignal}; + + let delay = esp_hal::delay::Delay::new(); + // Keep PCLK running during manual VSYNC pulses. + for vsync in [Level::Low, Level::High] { + vsync.connect_input_to_peripheral(InputSignal::CAM_V_SYNC); + for _ in 0..10 { + Level::Low.connect_input_to_peripheral(InputSignal::CAM_PCLK); + delay.delay_micros(1); + Level::High.connect_input_to_peripheral(InputSignal::CAM_PCLK); + delay.delay_micros(1); + } + } + InputSignal::CAM_PCLK.connect_to(pclk); + } + + fn send_frame( + dpi: Dpi<'static, esp_hal::Blocking>, + sent: DmaTxBuf, + pclk: &GpioInputSignal<'static>, + ) -> (Dpi<'static, esp_hal::Blocking>, DmaTxBuf) { + let output = dpi.send(false, sent).map_err(|e| e.0).unwrap(); + let (result, dpi, sent) = output.wait(); + hil_test::assert_eq!(result, Ok(())); + // Pulse VSYNC after pixel input has stopped. + pulse_camera_vsync(pclk); + (dpi, sent) + } + + #[test] + fn test_camera_can_receive_from_rgb(ctx: Context) { + let (camera, dpi, dma_tx_buf, dma_rx_buf, _) = loopback(ctx); + let camera_transfer = camera.receive(dma_rx_buf).map_err(|e| e.0).unwrap(); + let dpi_transfer = dpi.send(true, dma_tx_buf).map_err(|e| e.0).unwrap(); + let (result, _, dma_rx_buf) = camera_transfer.wait(); + let (_, dma_tx_buf) = dpi_transfer.stop(); + + hil_test::assert_eq!(result, Ok(())); + hil_test::assert_eq!(dma_rx_buf.number_of_received_bytes(), FRAME_BYTES); + hil_test::assert_eq!( + &dma_tx_buf.as_slice()[..FRAME_BYTES], + &dma_rx_buf.as_slice()[..FRAME_BYTES] + ); + } + + #[test] + async fn test_camera_dma_eof(ctx: Context) { + let (camera, mut dpi, mut sent, mut received, pclk) = loopback(ctx); + let mut camera = camera + .with_vsync(Level::High) + .into_async() + .into_blocking() + .into_async(); + for eof_mode in [ + cam::EofMode::VsyncSignal, + cam::EofMode::ByteLen((FRAME_BYTES - 1) as u16), + ] { + camera + .apply_config( + &cam::Config::default() + .with_frequency(Rate::from_mhz(2)) + .with_vh_de_mode(VhdeMode::VsyncHsync) + .with_eof_mode(eof_mode), + ) + .unwrap(); + for (rx_bytes, minimum_received) in [ + (FRAME_BYTES, FRAME_BYTES), + (3 * FRAME_BYTES, 2 * FRAME_BYTES), + ] { + received.set_length(rx_bytes); + let mut transfer = camera.receive(received).map_err(|e| e.0).unwrap(); + pulse_camera_vsync(&pclk); + for _ in 0..minimum_received / FRAME_BYTES { + hil_test::assert!(poll_once(transfer.wait_for_dma_eof()).is_pending()); + + let (eof_result, next_output) = join(transfer.wait_for_dma_eof(), async { + send_frame(dpi, sent, &pclk) + }) + .await; + hil_test::assert_eq!(eof_result, Ok(())); + (dpi, sent) = next_output; + } + (camera, received) = transfer.stop(); + + hil_test::assert_eq!(received.number_of_received_bytes(), minimum_received); + hil_test::assert!( + received.received_data().flatten().eq(sent + .as_slice() + .iter() + .cycle() + .take(minimum_received)) + ); } + } + } + + #[test] + async fn test_camera_dma_eof_pending(ctx: Context) { + let (camera, mut dpi, mut sent, mut received, pclk) = loopback(ctx); + let mut camera = camera.with_vsync(Level::High).into_async(); + received.set_length(received.capacity()); + for poll_before_eof in [false, true] { + let mut transfer = camera.receive(received).map_err(|e| e.0).unwrap(); + pulse_camera_vsync(&pclk); + { + let mut wait = core::pin::pin!(transfer.wait_for_dma_eof()); + if poll_before_eof { + hil_test::assert!(poll_once(wait.as_mut()).is_pending()); + } + (dpi, sent) = send_frame(dpi, sent, &pclk); + // Cancel the wait after EOF, before observing its result. + } + hil_test::assert!(matches!( + poll_once(transfer.wait_for_dma_eof()), + Poll::Ready(Ok(())) + )); + (camera, received) = transfer.stop(); + + hil_test::assert!(received.number_of_received_bytes() >= sent.len()); + hil_test::assert_eq!( + &received.as_slice()[..sent.len()], + &sent.as_slice()[..sent.len()] + ); + } + } - let camera_transfer = camera.receive(dma_rx_buf).map_err(|e| e.0).unwrap(); - let dpi_transfer = dpi.send(true, dma_tx_buf).map_err(|e| e.0).unwrap(); + #[test] + async fn test_camera_dma_eof_overflow(ctx: Context) { + let (camera, mut dpi, mut sent, mut received, pclk) = loopback(ctx); + let mut camera = camera.with_vsync(Level::High).into_async(); + for (rx_bytes, expected) in [ + (1024, Err(DmaError::DescriptorError)), + (2 * FRAME_BYTES, Ok(())), + ] { + received.set_length(rx_bytes); + let mut transfer = camera.receive(received).map_err(|e| e.0).unwrap(); + pulse_camera_vsync(&pclk); + (dpi, sent) = send_frame(dpi, sent, &pclk); + + hil_test::assert_eq!( + transfer.wait_for_dma_eof().await, + expected, + "First EOF, RX length {}", + rx_bytes + ); + if expected.is_err() { + hil_test::assert!(matches!( + poll_once(transfer.wait_for_dma_eof()), + Poll::Ready(result) if result == expected + )); + let (result, next_camera, next_received) = transfer.wait(); + hil_test::assert_eq!(result, expected); + (camera, received) = (next_camera, next_received); + } else { + (camera, received) = transfer.stop(); + hil_test::assert_eq!(received.number_of_received_bytes(), FRAME_BYTES); + hil_test::assert_eq!(&received.as_slice()[..FRAME_BYTES], sent.as_slice()); + } + } + } + + #[test] + fn test_dpi_vsync_blocking(ctx: Context) { + let peripherals = ctx.peripherals; + let dma = cfg_select! { + lcd_cam_dma_engine = "AHB_GDMA" => peripherals.DMA_CH0, + lcd_cam_dma_engine = "AXI_GDMA" => peripherals.DMA_AXI_CH0, + }; + let lcd_cam = LcdCam::new(peripherals.LCD_CAM); + let dpi = Dpi::new(lcd_cam.lcd, dma, dpi_test_config()).unwrap(); + drop(lcd_cam.cam); + let mut transfer = dpi + .send(true, dma_loop_buffer!(2500)) + .map_err(|e| e.0) + .unwrap(); - (_, _, dma_rx_buf) = camera_transfer.wait(); - (_, dma_tx_buf) = dpi_transfer.stop(); + transfer.clear_interrupts(DpiInterrupt::Vsync); + transfer.wait_for_vsync(); + hil_test::assert!(transfer.interrupts().is_empty()); + transfer.wait_for_vsync(); + hil_test::assert!(transfer.interrupts().is_empty()); - assert_eq!(dma_tx_buf.as_slice(), dma_rx_buf.as_slice()); + while !transfer.interrupts().contains(DpiInterrupt::Vsync) { + core::hint::spin_loop(); } + let (dpi, buffer) = transfer.stop(); + let transfer = dpi.send(true, buffer).map_err(|e| e.0).unwrap(); + hil_test::assert!(transfer.interrupts().is_empty()); + + let _ = transfer.stop(); + } +} + +#[embedded_test::tests(default_timeout = 3, executor = hil_test::Executor::new())] +mod dpi_async_tests { + use core::{future::Future, task::Poll}; + + use super::*; + + struct Context<'d> { + lcd_cam: LcdCam<'d, Async>, + dma: DmaChannelInstance<'d>, + dma_buf: DmaLoopBuf, + } + + #[init] + async fn init() -> Context<'static> { + let peripherals = esp_hal::init(esp_hal::Config::default()); + let dma = cfg_select! { + lcd_cam_dma_engine = "AHB_GDMA" => peripherals.DMA_CH0, + lcd_cam_dma_engine = "AXI_GDMA" => peripherals.DMA_AXI_CH0, + }; + + Context { + lcd_cam: LcdCam::new(peripherals.LCD_CAM).into_async(), + dma, + dma_buf: dma_loop_buffer!(2500), + } + } + + #[test] + async fn test_dpi_vsync(ctx: Context<'static>) { + let dpi = Dpi::new(ctx.lcd_cam.lcd, ctx.dma, dpi_test_config()).unwrap(); + drop(ctx.lcd_cam.cam); + let mut transfer = dpi.send(true, ctx.dma_buf).map_err(|e| e.0).unwrap(); + + while !transfer.interrupts().contains(DpiInterrupt::Vsync) { + core::hint::spin_loop(); + } + transfer.clear_interrupts(DpiInterrupt::Vsync); + { + let mut wait = core::pin::pin!(transfer.wait_for_vsync()); + let first_poll = core::future::poll_fn(|cx| Poll::Ready(wait.as_mut().poll(cx))).await; + hil_test::assert!(first_poll.is_pending()); + } + transfer.wait_for_vsync().await; + hil_test::assert!(transfer.interrupts().is_empty()); + transfer.wait_for_vsync().await; + hil_test::assert!(transfer.interrupts().is_empty()); + + while !transfer.interrupts().contains(DpiInterrupt::Vsync) { + core::hint::spin_loop(); + } + { + let mut wait = core::pin::pin!(transfer.wait_for_vsync()); + let first_poll = core::future::poll_fn(|cx| Poll::Ready(wait.as_mut().poll(cx))).await; + hil_test::assert!(first_poll.is_ready()); + } + hil_test::assert!(transfer.interrupts().is_empty()); + + while !transfer.interrupts().contains(DpiInterrupt::Vsync) { + core::hint::spin_loop(); + } + let (dpi, buffer) = transfer.stop(); + let transfer = dpi.send(true, buffer).map_err(|e| e.0).unwrap(); + hil_test::assert!(transfer.interrupts().is_empty()); + + let _ = transfer.stop(); } } diff --git a/hil-test/src/bin/misc_drivers.rs b/hil-test/src/bin/misc_drivers.rs index ff4a9030aaf..1d1e5bcfcb3 100644 --- a/hil-test/src/bin/misc_drivers.rs +++ b/hil-test/src/bin/misc_drivers.rs @@ -1,9 +1,12 @@ //! Interrupt Tests //! "Disabled" for now - see https://github.com/esp-rs/esp-hal/pull/1635#issuecomment-2137405251 +//! MCPWM Tests //! PCNT Tests //! RNG Tests +//! SDMMC Tests //! System Timer Tests //! TWAI Tests +//! Debug Assist Tests //% CHIP_FILTER: gpio_driver_supported //% FEATURES: unstable embassy @@ -18,11 +21,24 @@ mod pcnt { use esp_hal::{ delay::Delay, gpio::{AnyPin, Input, InputConfig, Level, Output, OutputConfig, Pin, Pull}, - pcnt::{Pcnt, channel::EdgeMode}, + handler, + pcnt::{Unit, channel::EdgeMode}, + time::{Duration, Instant}, }; + use portable_atomic::{AtomicUsize, Ordering}; + + static HANDLER_CALLS: AtomicUsize = AtomicUsize::new(0); + + #[handler] + fn count_calls() { + HANDLER_CALLS.fetch_add(1, Ordering::Relaxed); + } struct Context<'d> { - pcnt: Pcnt<'d>, + unit0: Unit<'d>, + unit1: Unit<'d>, + unit2: Unit<'d>, + unit3: Unit<'d>, input: AnyPin<'d>, output: AnyPin<'d>, delay: Delay, @@ -37,7 +53,10 @@ mod pcnt { let dout = dout.degrade(); Context { - pcnt: Pcnt::new(peripherals.PCNT), + unit0: Unit::new(peripherals.PCNT0_UNIT0), + unit1: Unit::new(peripherals.PCNT0_UNIT1), + unit2: Unit::new(peripherals.PCNT0_UNIT2), + unit3: Unit::new(peripherals.PCNT0_UNIT3), input: din, output: dout, delay: Delay::new(), @@ -46,7 +65,7 @@ mod pcnt { #[test] fn test_increment_on_pos_edge(ctx: Context<'static>) { - let unit = ctx.pcnt.unit0; + let unit = ctx.unit0; // Setup channel 0 to increment the count when input changes LOW -> HIGH unit.channel0.set_edge_signal(Input::new( @@ -85,7 +104,7 @@ mod pcnt { #[test] fn test_increment_on_neg_edge(ctx: Context<'static>) { - let unit = ctx.pcnt.unit1; + let unit = ctx.unit1; // Setup channel 0 to increment the count when input changes HIGH -> LOW unit.channel0.set_edge_signal(Input::new( @@ -124,7 +143,7 @@ mod pcnt { #[test] fn test_increment_past_high_limit(ctx: Context<'static>) { - let unit = ctx.pcnt.unit3; + let unit = ctx.unit3; unit.set_high_limit(Some(3)).unwrap(); @@ -184,7 +203,7 @@ mod pcnt { #[test] fn test_increment_past_thresholds(ctx: Context<'static>) { - let unit = ctx.pcnt.unit0; + let unit = ctx.unit0; unit.set_threshold0(Some(2)); unit.set_threshold1(Some(4)); @@ -252,7 +271,7 @@ mod pcnt { #[test] fn test_decrement_past_low_limit(ctx: Context<'static>) { - let unit = ctx.pcnt.unit0; + let unit = ctx.unit0; unit.set_low_limit(Some(-3)).unwrap(); // For some reason this is needed for the above limit to apply. @@ -314,7 +333,7 @@ mod pcnt { #[test] fn test_unit_count_range(ctx: Context<'static>) { - let unit = ctx.pcnt.unit2; + let unit = ctx.unit2; // Setup channel 1 to increment the count when gpio2 does LOW -> HIGH unit.channel1.set_edge_signal(Input::new( @@ -354,6 +373,139 @@ mod pcnt { ctx.delay.delay_micros(1); } } + + #[test] + fn test_unit_counts_after_previous_unit_dropped(ctx: Context<'static>) { + let input = Input::new(ctx.input, InputConfig::default().with_pull(Pull::Down)); + let mut output = Output::new(ctx.output, Level::Low, OutputConfig::default()); + + let unit = ctx.unit0; + unit.channel0.set_edge_signal(input.peripheral_input()); + unit.channel0 + .set_input_mode(EdgeMode::Hold, EdgeMode::Increment); + + output.set_high(); + ctx.delay.delay_micros(1); + assert_eq!(1, unit.value()); + + core::mem::drop(unit); + output.set_low(); + ctx.delay.delay_micros(1); + + // A unit built from a fresh singleton must count without an explicit resume, + // the same as after a cold boot. + let unit = Unit::new(unsafe { esp_hal::peripherals::PCNT0_UNIT0::steal() }); + unit.channel0.set_edge_signal(input.peripheral_input()); + unit.channel0 + .set_input_mode(EdgeMode::Hold, EdgeMode::Increment); + + assert_eq!(0, unit.value()); + + output.set_high(); + ctx.delay.delay_micros(1); + + assert_eq!(1, unit.value()); + } + + #[test] + fn test_listening_unit_without_handler_does_not_stall_the_cpu(ctx: Context<'static>) { + let input = Input::new(ctx.input, InputConfig::default().with_pull(Pull::Down)); + let mut output = Output::new(ctx.output, Level::Low, OutputConfig::default()); + + let mut unit0 = ctx.unit0; + unit0.set_interrupt_handler(count_calls); + + let unit1 = ctx.unit1; + unit1.channel0.set_edge_signal(input.peripheral_input()); + unit1 + .channel0 + .set_input_mode(EdgeMode::Hold, EdgeMode::Increment); + unit1.set_high_limit(Some(1)).unwrap(); + unit1.clear(); + unit1.listen(); + + output.set_high(); + + let deadline = Instant::now() + Duration::from_millis(50); + while Instant::now() < deadline {} + + assert_eq!(0, HANDLER_CALLS.load(Ordering::Relaxed)); + assert!(unit0.value() == 0); + } +} + +#[cfg(all(mcpwm_driver_supported, pcnt_driver_supported))] +#[embedded_test::tests(default_timeout = 3)] +mod mcpwm { + use esp_hal::{ + delay::Delay, + gpio::{AnyPin, Input, InputConfig, Pin, Pull}, + mcpwm::{McPwm, PeripheralClockConfig, operator::PwmPinConfig, timer::PwmWorkingMode}, + pcnt::{Unit, channel::EdgeMode}, + peripherals::MCPWM0, + time::Rate, + }; + + struct Context<'d> { + mcpwm: MCPWM0<'d>, + unit: Unit<'d>, + input: AnyPin<'d>, + output: AnyPin<'d>, + delay: Delay, + } + + #[init] + fn init() -> Context<'static> { + let peripherals = esp_hal::init(esp_hal::Config::default()); + + let (din, dout) = hil_test::common_test_pins!(peripherals); + + Context { + mcpwm: peripherals.MCPWM0, + unit: Unit::new(peripherals.PCNT0_UNIT0), + input: din.degrade(), + output: dout.degrade(), + delay: Delay::new(), + } + } + + #[test] + fn output_frequency_follows_peripheral_clock_prescaler(ctx: Context<'static>) { + // Divide the source clock by 8. On chips that divide the group clock in the PCR, the + // divider resets to 5, so this tells "prescaler applied" from "reset value left in place". + let clock_cfg = PeripheralClockConfig::with_prescaler(7); + + let mut mcpwm = McPwm::new(ctx.mcpwm, clock_cfg); + mcpwm.operator0.set_timer(&mcpwm.timer0); + let mut pwm_pin = mcpwm + .operator0 + .with_pin_a(ctx.output, PwmPinConfig::UP_ACTIVE_HIGH); + pwm_pin.set_timestamp(50); + + // 10 kHz is an exact divisor of the peripheral clock on every chip with MCPWM. + let timer_clock_cfg = clock_cfg + .timer_clock_with_frequency(99, PwmWorkingMode::Increase, Rate::from_khz(10)) + .unwrap(); + + let unit = ctx.unit; + unit.channel0.set_edge_signal(Input::new( + ctx.input, + InputConfig::default().with_pull(Pull::Down), + )); + unit.channel0 + .set_input_mode(EdgeMode::Hold, EdgeMode::Increment); + + mcpwm.timer0.start(timer_clock_cfg); + + // 10 ms at 10 kHz is 100 rising edges. + unit.clear(); + unit.resume(); + ctx.delay.delay_millis(10); + unit.pause(); + + let edges = unit.value(); + hil_test::assert!((98..=102).contains(&edges), "counted {} edges", edges); + } } #[cfg(systimer_driver_supported)] @@ -585,6 +737,81 @@ mod twai { assert_eq!(frame.data(), &[1, 2, 3]) } + #[test] + // The receive FIFO holds 64 bytes, four 8-byte standard frames; later + // frames overrun it. A blocking receiver must see the overrun once + // and then an empty FIFO, not the same overrun entry for ever. + fn test_blocking_receive_releases_overrun(mut ctx: Context) { + let frame = EspTwaiFrame::new_self_reception(StandardId::ZERO, b"12345678").unwrap(); + + const SENT: usize = 10; + for _ in 0..SENT { + block!(ctx.twai.transmit(&frame)).unwrap(); + } + + let mut frames = 0; + let mut overruns = 0; + loop { + match ctx.twai.receive() { + Ok(received) => { + assert_eq!(received.data(), b"12345678"); + frames += 1; + } + Err(nb::Error::Other(twai::EspTwaiError::EmbeddedHAL(ErrorKind::Overrun))) => { + overruns += 1; + } + Err(nb::Error::WouldBlock) => break, + Err(nb::Error::Other(err)) => panic!("{:?}", err), + } + assert!(frames + overruns <= SENT, "the same overrun reported again"); + } + + assert!(frames > 0, "no frame received"); + assert!(overruns > 0, "no overrun reported"); + assert!(frames < SENT, "the FIFO did not overrun"); + } + + #[test] + // A stopped driver takes a new bitrate and operating mode, and starts + // again with them. + fn test_reconfigure_stopped_driver(ctx: Context) { + let frame = EspTwaiFrame::new_self_reception(StandardId::ZERO, &[1, 2, 3]).unwrap(); + + // Normal mode: nobody acknowledges on the loopback pin, so the + // frame is retried until the peripheral turns error passive and + // the driver gives up on it. In self-test mode it would have been + // sent. + let mut config = ctx.twai.stop(); + config.set_operating_mode(TwaiMode::Normal); + config.set_baud_rate(twai::BaudRate::B500K); + let mut twai = config.start(); + + block!(twai.transmit(&frame)).unwrap(); + assert_eq!( + block!(twai.transmit(&frame)), + Err(twai::EspTwaiError::TransmissionAborted) + ); + assert!(twai.transmit_error_count() >= 128); + assert!( + twai.receive().is_err(), + "an unacknowledged frame was received" + ); + + // Back to self-test mode at another bitrate: the frame loops back + let mut config = twai.stop(); + config.set_operating_mode(TwaiMode::SelfTest); + config.set_baud_rate(twai::BaudRate::B250K); + let mut twai = config.start(); + + let (rx, tx) = twai.split_mut(); + block!(tx.transmit(&frame)).unwrap(); + let received = block!(rx.receive()).unwrap(); + assert_eq!(received.data(), &[1, 2, 3]); + + // The borrowed halves are gone: the driver can be stopped again + let _config = twai.stop(); + } + fn no_init() {} #[test(init = no_init)] @@ -642,7 +869,7 @@ mod twai { let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let twai = config.into_async().start(); @@ -703,6 +930,38 @@ mod twai { receive_frames(&mut ctx, NUM_SENT_FRAMES + NUM_ASYNC_SENT_FRAMES).await; } + #[test] + async fn test_overruns_are_counted(mut ctx: Context) { + let frame = + EspTwaiFrame::new_self_reception(StandardId::new(0).unwrap(), b"12345678").unwrap(); + + // Nothing drains the receive FIFO while the interrupt is off, so + // it overruns + interrupt::disable(Cpu::ProCpu, TWAI0); + const SENT: usize = 10; + for _ in 0..SENT { + block!(ctx.twai.transmit(&frame)).unwrap(); + } + interrupt::enable(TWAI0, Priority3); + + // Let the handler run, then take everything it queued + transmit_frames(&mut ctx, &frame, 1).await; + let mut overruns = 0; + for _ in 0..SENT + 1 { + match ctx.twai.receive_async().await { + Ok(_) => {} + Err(esp_hal::twai::EspTwaiError::EmbeddedHAL(ErrorKind::Overrun)) => { + overruns += 1 + } + Err(err) => panic!("{:#?}", err), + } + } + + assert!(overruns > 0, "the FIFO did not overrun"); + assert_eq!(ctx.twai.error_counts().overrun, overruns); + assert_eq!(ctx.twai.error_counts().bit, 0); + } + fn no_init() {} #[test(init = no_init)] @@ -711,7 +970,7 @@ mod twai { let peripherals = esp_hal::init(esp_hal::Config::default()); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); // The bus is permanently recessive, so every transmission attempt // fails immediately (a transmitted dominant bit reads back @@ -734,6 +993,12 @@ mod twai { twai.transmit_async(&frame).await, Err(twai::EspTwaiError::TransmissionAborted) ); + + // Every attempt read its first dominant bit back recessive: bit + // errors, one per attempt until the controller went error passive + let counts = twai.error_counts(); + assert!(counts.bit > 0, "{:?}", counts); + assert_eq!(counts.acknowledge, 0, "{:?}", counts); } } } @@ -767,3 +1032,250 @@ mod lp_timekeeping { ); } } + +#[cfg(assist_debug_has_region_monitor)] +#[embedded_test::tests(default_timeout = 3)] +mod assist_debug { + #[cfg(all(multi_core, soc_has_cpu_ctrl))] + use core::hint::spin_loop; + use core::ptr::addr_of; + + #[cfg(all(multi_core, soc_has_cpu_ctrl))] + use esp_hal::system::{CpuControl, Stack}; + use esp_hal::{assist_debug::DebugAssist, peripherals::Peripherals}; + use hil_test::mk_static; + + #[esp_hal::ram] + fn monitored_write(address: u32) { + unsafe { (address as *mut u32).write_volatile(0x1234_5678) }; + } + + fn assert_pc_in_ram(pc: u32) { + unsafe extern "C" { + static _rwtext_start: u8; + static _rwtext_end: u8; + } + + let code = addr_of!(_rwtext_start) as u32..addr_of!(_rwtext_end) as u32; + assert!( + code.contains(&pc), + "captured PC {pc:#x} is outside RAM code" + ); + } + + #[init] + fn init() -> Peripherals { + esp_hal::init(esp_hal::Config::default()) + } + + #[test] + fn region_monitor_pc(p: Peripherals) { + let address = mk_static!(u32, 0) as *mut u32 as u32; + let mut da = DebugAssist::new(p.ASSIST_DEBUG); + da.enable_region0_monitor(address, address + size_of::() as u32, false, true); + + monitored_write(address); + assert!(da.is_region0_monitor_interrupt_set()); + let pc = da.region_monitor_pc(); + da.disable_region0_monitor(); + da.clear_region0_monitor_interrupt(); + + assert_pc_in_ram(pc); + } + + #[cfg(all(multi_core, soc_has_cpu_ctrl))] + #[test] + fn core1_region_monitor_pc(p: Peripherals) { + let address = mk_static!(u32, 0) as *mut u32 as u32; + let mut da = DebugAssist::new(p.ASSIST_DEBUG); + da.enable_core1_region0_monitor(address, address + size_of::() as u32, false, true); + + let mut cpu_control = CpuControl::new(p.CPU_CTRL); + let stack = mk_static!(Stack<8192>, Stack::new()); + let _guard = cpu_control + .start_app_core(stack, move || { + monitored_write(address); + loop { + spin_loop(); + } + }) + .unwrap(); + + while !da.is_core1_region0_monitor_interrupt_set() { + spin_loop(); + } + let pc = da.core1_region_monitor_pc(); + da.disable_core1_region0_monitor(); + da.clear_core1_region0_monitor_interrupt(); + + assert_pc_in_ram(pc); + } +} + +#[cfg(esp32p4)] +#[embedded_test::tests(default_timeout = 10, executor = hil_test::Executor::new())] +mod sdmmc { + use block_device_adapters::BufStream; + use embassy_time::Delay; + use embedded_fatfs::{FileSystem, FsOptions, ReadWriteSeek}; + use embedded_io_async::{Read, Seek, SeekFrom, Write}; + use embedded_partitions::mbr::Scheme; + use esp_hal::{ + Async, + sdmmc::{Config, DelayPhase, SdHostController, Slot, SlotConfig}, + timer::timg::TimerGroup, + }; + use hil_test::mk_static; + use sdio::{BlockDevice, sd::Card}; + + type SdCard = BlockDevice, Delay, 512>; + + const CARD_HZ: u32 = 40_000_000; + + // The test writes the file only when it is missing, to limit wear on the card. + const TEST_FILE: &str = "ESPHIL.TXT"; + + // Spans several 512-byte blocks, so reads use the multi-block path. + const FILE_LEN: usize = 2048; + + // The prime modulus keeps the pattern from lining up with block boundaries. + const fn pattern_byte(i: usize) -> u8 { + (i % 251) as u8 + } + + fn expected() -> [u8; FILE_LEN] { + core::array::from_fn(pattern_byte) + } + + #[derive(Clone, Copy)] + enum ReadMethod { + ReadToEnd, + ReadExact, + Chunked, + Seek, + } + + #[init] + async fn init() -> SdCard { + let peripherals = esp_hal::init(esp_hal::Config::default()); + + let timg0 = TimerGroup::new(peripherals.TIMG0); + esp_rtos::start(timg0.timer0); + + let controller = mk_static!( + SdHostController<'static>, + SdHostController::new(peripherals.SDHOST, Config::default()).unwrap() + ); + let slot = controller + .slot::<0>(SlotConfig::default().with_input_delay_phase(DelayPhase::_0)) + .unwrap() + .with_clk(peripherals.GPIO43) + .with_cmd(peripherals.GPIO44) + .with_data0(peripherals.GPIO39) + .with_data1(peripherals.GPIO40) + .with_data2(peripherals.GPIO41) + .with_data3(peripherals.GPIO42) + .into_async(); + + BlockDevice::new_sd_card(slot, CARD_HZ, Delay) + .await + .unwrap() + } + + async fn run_on_volume(card: &mut SdCard, method: ReadMethod) { + let stream = BufStream::<_, 512>::new(card); + match Scheme::open(stream).await.unwrap() { + Scheme::Mbr(mut mbr) => { + let idx = mbr + .iter_used() + .find(|(_, p)| p.is_fat()) + .map(|(i, _)| i) + .expect("no FAT partition found"); + check_file(mbr.open_partition(idx).await.unwrap(), method).await; + } + Scheme::Superfloppy(io) => check_file(io, method).await, + Scheme::Unknown(_) => panic!("unrecognised volume layout"), + } + } + + async fn check_file(io: IO, method: ReadMethod) { + let expected = expected(); + let fs = FileSystem::new(io, FsOptions::new()).await.unwrap(); + { + let root = fs.root_dir(); + + match root.open_file(TEST_FILE).await { + Ok(_) => {} + Err(embedded_fatfs::Error::NotFound) => { + let mut file = root.create_file(TEST_FILE).await.unwrap(); + file.write_all(&expected).await.unwrap(); + file.flush().await.unwrap(); + } + Err(e) => panic!("open_file failed: {:?}", e), + } + + let mut file = root.open_file(TEST_FILE).await.unwrap(); + let mut buf = [0u8; FILE_LEN + 1]; + match method { + ReadMethod::ReadToEnd => { + let mut len = 0; + loop { + match file.read(&mut buf[len..]).await.unwrap() { + 0 => break, + n => len += n, + } + } + assert_eq!(len, FILE_LEN); + assert_eq!(&buf[..len], &expected[..]); + } + ReadMethod::ReadExact => { + file.read_exact(&mut buf[..FILE_LEN]).await.unwrap(); + assert_eq!(&buf[..FILE_LEN], &expected[..]); + assert_eq!(file.read(&mut buf).await.unwrap(), 0); + } + ReadMethod::Chunked => { + // 100 bytes does not divide the block size, so chunks cross block boundaries. + for (i, chunk) in buf[..FILE_LEN].chunks_mut(100).enumerate() { + file.read_exact(chunk).await.unwrap(); + let start = i * 100; + assert_eq!(chunk, &expected[start..start + chunk.len()]); + } + } + ReadMethod::Seek => { + file.seek(SeekFrom::Start(700)).await.unwrap(); + file.read_exact(&mut buf[..1000]).await.unwrap(); + assert_eq!(&buf[..1000], &expected[700..1700]); + + file.seek(SeekFrom::End(-10)).await.unwrap(); + file.read_exact(&mut buf[..10]).await.unwrap(); + assert_eq!(&buf[..10], &expected[FILE_LEN - 10..]); + + file.seek(SeekFrom::Start(0)).await.unwrap(); + file.read_exact(&mut buf[..10]).await.unwrap(); + assert_eq!(&buf[..10], &expected[..10]); + } + } + } + fs.unmount().await.unwrap(); + } + + #[test] + async fn read_to_end(mut card: SdCard) { + run_on_volume(&mut card, ReadMethod::ReadToEnd).await; + } + + #[test] + async fn read_exact(mut card: SdCard) { + run_on_volume(&mut card, ReadMethod::ReadExact).await; + } + + #[test] + async fn read_in_chunks(mut card: SdCard) { + run_on_volume(&mut card, ReadMethod::Chunked).await; + } + + #[test] + async fn seek_and_read(mut card: SdCard) { + run_on_volume(&mut card, ReadMethod::Seek).await; + } +} diff --git a/hil-test/src/bin/misc_non_drivers/clock_monitor.rs b/hil-test/src/bin/misc_non_drivers/clock_monitor.rs index 6c823f6914a..acf329163f3 100644 --- a/hil-test/src/bin/misc_non_drivers/clock_monitor.rs +++ b/hil-test/src/bin/misc_non_drivers/clock_monitor.rs @@ -8,7 +8,7 @@ mod tests { let target_frequency = if cfg!(esp32c2) { 26 - } else if cfg!(esp32h2) { + } else if cfg!(any(esp32h2, esp32h4)) { 32 } else if cfg!(esp32c5) { 48 diff --git a/hil-test/src/bin/misc_non_drivers/critical_section.rs b/hil-test/src/bin/misc_non_drivers/critical_section.rs index 44e449be5f3..3b674a4fe5b 100644 --- a/hil-test/src/bin/misc_non_drivers/critical_section.rs +++ b/hil-test/src/bin/misc_non_drivers/critical_section.rs @@ -3,7 +3,7 @@ mod tests { use esp_hal::{ clock::CpuClock, interrupt::{InterruptHandler, Priority, software::SoftwareInterrupt}, - peripherals::{FROM_CPU_INTR0, FROM_CPU_INTR1, Peripherals}, + peripherals::{FROM_CPU_INTR2, FROM_CPU_INTR3, Peripherals}, sync::RawPriorityLimitedMutex, }; use esp_sync::NonReentrantMutex; @@ -13,12 +13,12 @@ mod tests { static LOCK: RawPriorityLimitedMutex = RawPriorityLimitedMutex::new(Priority::Priority1); extern "C" fn access() { - SoftwareInterrupt::new(unsafe { FROM_CPU_INTR1::steal() }).reset(); + SoftwareInterrupt::new(unsafe { FROM_CPU_INTR3::steal() }).reset(); LOCK.lock(|| {}); embedded_test::export::check_outcome(()); } - let mut prio_2_interrupt = SoftwareInterrupt::new(p.FROM_CPU_INTR1); + let mut prio_2_interrupt = SoftwareInterrupt::new(p.FROM_CPU_INTR3); prio_2_interrupt.set_interrupt_handler(InterruptHandler::new(access, priority)); @@ -30,11 +30,11 @@ mod tests { static COUNTER: AtomicU32 = AtomicU32::new(0); extern "C" fn increment() { - SoftwareInterrupt::new(unsafe { FROM_CPU_INTR0::steal() }).reset(); + SoftwareInterrupt::new(unsafe { FROM_CPU_INTR2::steal() }).reset(); COUNTER.fetch_add(1, Ordering::AcqRel); } - let mut interrupt = SoftwareInterrupt::new(p.FROM_CPU_INTR0); + let mut interrupt = SoftwareInterrupt::new(p.FROM_CPU_INTR2); interrupt.set_interrupt_handler(InterruptHandler::new(increment, Priority::Priority1)); const ITERATIONS: u32 = 100; @@ -99,20 +99,20 @@ mod tests { extern "C" fn increment() { match INT { - 0 => SoftwareInterrupt::new(unsafe { FROM_CPU_INTR0::steal() }).reset(), - 1 => SoftwareInterrupt::new(unsafe { FROM_CPU_INTR1::steal() }).reset(), + 2 => SoftwareInterrupt::new(unsafe { FROM_CPU_INTR2::steal() }).reset(), + 3 => SoftwareInterrupt::new(unsafe { FROM_CPU_INTR3::steal() }).reset(), _ => unreachable!(), } COUNTER.fetch_add(1, Ordering::AcqRel); } - let mut prio_1_interrupt = SoftwareInterrupt::new(peripherals.FROM_CPU_INTR0); - let mut prio_2_interrupt = SoftwareInterrupt::new(peripherals.FROM_CPU_INTR1); + let mut prio_1_interrupt = SoftwareInterrupt::new(peripherals.FROM_CPU_INTR2); + let mut prio_2_interrupt = SoftwareInterrupt::new(peripherals.FROM_CPU_INTR3); prio_1_interrupt - .set_interrupt_handler(InterruptHandler::new(increment::<0>, Priority::Priority1)); + .set_interrupt_handler(InterruptHandler::new(increment::<2>, Priority::Priority1)); prio_2_interrupt - .set_interrupt_handler(InterruptHandler::new(increment::<1>, Priority::Priority2)); + .set_interrupt_handler(InterruptHandler::new(increment::<3>, Priority::Priority2)); let lock = RawPriorityLimitedMutex::new(Priority::Priority1); @@ -152,15 +152,15 @@ mod tests { extern "C" fn increment() { match INT { - 0 => SoftwareInterrupt::new(unsafe { FROM_CPU_INTR0::steal() }).reset(), - 1 => SoftwareInterrupt::new(unsafe { FROM_CPU_INTR1::steal() }).reset(), + 2 => SoftwareInterrupt::new(unsafe { FROM_CPU_INTR2::steal() }).reset(), + 3 => SoftwareInterrupt::new(unsafe { FROM_CPU_INTR3::steal() }).reset(), _ => unreachable!(), } COUNTER.fetch_add(1, Ordering::AcqRel); } - let mut interrupt = SoftwareInterrupt::new(peripherals.FROM_CPU_INTR0); - interrupt.set_interrupt_handler(InterruptHandler::new(increment::<0>, Priority::Priority1)); + let mut interrupt = SoftwareInterrupt::new(peripherals.FROM_CPU_INTR2); + interrupt.set_interrupt_handler(InterruptHandler::new(increment::<2>, Priority::Priority1)); let lock = RawPriorityLimitedMutex::new(Priority::max()); diff --git a/hil-test/src/bin/misc_non_drivers/dma_buffers.rs b/hil-test/src/bin/misc_non_drivers/dma_buffers.rs index b6da07423c5..3ef67e961a2 100644 --- a/hil-test/src/bin/misc_non_drivers/dma_buffers.rs +++ b/hil-test/src/bin/misc_non_drivers/dma_buffers.rs @@ -477,4 +477,27 @@ mod tests { core::assert!(matches!(descriptors[3].owner(), Owner::Cpu)); }); } + + #[test] + fn test_dma_tx_stream_buf_reuse_starts_with_empty_prefill() { + with_tx_stream_buffer(|mut buf| { + core::assert_eq!(buf.push(&[1u8; BUFFER_SIZE]), BUFFER_SIZE); + buf.prepare(); + + let view = buf.into_view(); + let mut buf = ::from_view(view); + + // Pushing into a buffer returned by a transfer starts from an empty pre-fill. + core::assert_eq!(buf.push(&[2u8; CHUNK_SIZE * 2]), CHUNK_SIZE * 2); + buf.prepare(); + + let (descriptors, buffer) = buf.split(); + core::assert!(buffer[..CHUNK_SIZE * 2].iter().all(|&b| b == 2)); + core::assert!(matches!(descriptors[0].owner(), Owner::Dma)); + core::assert!(matches!(descriptors[1].owner(), Owner::Dma)); + // Only the newly pushed bytes are handed to the DMA, not stale data. + core::assert!(matches!(descriptors[2].owner(), Owner::Cpu)); + core::assert!(matches!(descriptors[3].owner(), Owner::Cpu)); + }); + } } diff --git a/hil-test/src/bin/misc_non_drivers/init.rs b/hil-test/src/bin/misc_non_drivers/init.rs index f5b3b48d477..0c7c6731e8e 100644 --- a/hil-test/src/bin/misc_non_drivers/init.rs +++ b/hil-test/src/bin/misc_non_drivers/init.rs @@ -9,7 +9,7 @@ mod tests { #[cfg(timergroup_driver_supported)] use esp_hal::{ clock::CpuClock, - timer::timg::{MwdtStage, TimerGroup}, + timer::timg::{MwdtStage, MwdtStageAction, TimerGroup}, }; #[test] @@ -131,4 +131,67 @@ mod tests { let delay = Delay::new(); delay.delay(Duration::from_millis(1000)); } + + #[test] + #[cfg(timergroup_timg0)] + fn test_timg0_wdt_timeout_is_applied() { + let p = esp_hal::init(Config::default()); + + let timg0 = TimerGroup::new(p.TIMG0); + let mut wdt0 = timg0.wdt; + + wdt0.set_timeout(MwdtStage::Stage0, Duration::from_secs(2)); + wdt0.enable(); + + let delay = Delay::new(); + + // Outliving the default hold proves the requested timeout is applied. + delay.delay(Duration::from_millis(1_500)); + + // Disable the watchdog, to prevent accidentally resetting the MCU while the host is setting + // up the next test. + wdt0.disable(); + } + + #[test] + #[cfg(timergroup_timg0)] + fn test_timg0_wdt_stage_action_is_applied() { + let p = esp_hal::init(Config::default()); + + let timg0 = TimerGroup::new(p.TIMG0); + let mut wdt0 = timg0.wdt; + + wdt0.set_timeout(MwdtStage::Stage0, Duration::from_secs(1)); + wdt0.enable(); + wdt0.set_stage_action(MwdtStage::Stage0, MwdtStageAction::Off); + + let delay = Delay::new(); + + // Stage 0 is off - outliving the hold proves the stage action is applied. + delay.delay(Duration::from_millis(1_500)); + + // Disable the watchdog, to prevent accidentally resetting the MCU while the host is setting + // up the next test. + wdt0.disable(); + } + + #[test] + #[cfg(timergroup_timg0)] + fn test_timg0_wdt_disable_is_applied() { + let p = esp_hal::init(Config::default()); + + let timg0 = TimerGroup::new(p.TIMG0); + let mut wdt0 = timg0.wdt; + + wdt0.set_timeout(MwdtStage::Stage0, Duration::from_secs(1)); + wdt0.enable(); + + let delay = Delay::new(); + delay.delay(Duration::from_millis(50)); + + wdt0.disable(); + + // Outliving the hold after disabling (and not feeding) proves disable is applied. + delay.delay(Duration::from_millis(1_500)); + } } diff --git a/hil-test/src/bin/misc_non_drivers/interrupt_nesting.rs b/hil-test/src/bin/misc_non_drivers/interrupt_nesting.rs index d73b61cdf9d..5ab74543937 100644 --- a/hil-test/src/bin/misc_non_drivers/interrupt_nesting.rs +++ b/hil-test/src/bin/misc_non_drivers/interrupt_nesting.rs @@ -4,7 +4,7 @@ mod tests { use esp_hal::{ handler, interrupt::{Priority, software::SoftwareInterrupt}, - peripherals::{FROM_CPU_INTR0, FROM_CPU_INTR1, FROM_CPU_INTR2, Peripherals}, + peripherals::{FROM_CPU_INTR2, FROM_CPU_INTR3, Peripherals}, }; use portable_atomic::{AtomicU32, Ordering}; @@ -20,37 +20,21 @@ mod tests { #[handler(priority = Priority::min())] fn handler_low_prio() { info!("Low runs"); - SoftwareInterrupt::new(unsafe { FROM_CPU_INTR0::steal() }).reset(); - - // Fire the checker interrupt. It must run after this one and the higher prio one are - // done. - SoftwareInterrupt::new(unsafe { FROM_CPU_INTR2::steal() }).raise(); + SoftwareInterrupt::new(unsafe { FROM_CPU_INTR2::steal() }).reset(); // Trigger high priority interrupt before incrementing counter - SoftwareInterrupt::new(unsafe { FROM_CPU_INTR1::steal() }).raise(); - // Se that high priority interrupted us + SoftwareInterrupt::new(unsafe { FROM_CPU_INTR3::steal() }).raise(); + // See that high priority interrupted us hil_test::assert_eq!(COUNTER.load(Ordering::Relaxed), 1); COUNTER.fetch_add(1, Ordering::Relaxed); info!("Low returns"); } - #[handler(priority = Priority::min())] - fn handler_low_prio_checker() { - info!("Checker runs"); - SoftwareInterrupt::new(unsafe { FROM_CPU_INTR2::steal() }).reset(); - - // Se that we didn't interrupt anything - hil_test::assert_eq!(COUNTER.load(Ordering::Relaxed), 2); - - COUNTER.fetch_add(1, Ordering::Relaxed); - info!("Checker returns"); - } - #[handler(priority = Priority::max())] fn handler_high_prio() { info!("High runs"); - SoftwareInterrupt::new(unsafe { FROM_CPU_INTR1::steal() }).reset(); + SoftwareInterrupt::new(unsafe { FROM_CPU_INTR3::steal() }).reset(); // See if we interrupted the low priority handler as we should assert_eq!(COUNTER.load(Ordering::Relaxed), 0); @@ -58,15 +42,13 @@ mod tests { info!("High returns"); } - let mut interrupt0 = SoftwareInterrupt::new(p.FROM_CPU_INTR0); - let mut interrupt1 = SoftwareInterrupt::new(p.FROM_CPU_INTR1); - let mut interrupt2 = SoftwareInterrupt::new(p.FROM_CPU_INTR2); + let mut interrupt_low = SoftwareInterrupt::new(p.FROM_CPU_INTR2); + let mut interrupt_high = SoftwareInterrupt::new(p.FROM_CPU_INTR3); - interrupt0.set_interrupt_handler(handler_low_prio); - interrupt1.set_interrupt_handler(handler_high_prio); - interrupt2.set_interrupt_handler(handler_low_prio_checker); + interrupt_low.set_interrupt_handler(handler_low_prio); + interrupt_high.set_interrupt_handler(handler_high_prio); - interrupt0.raise(); - hil_test::assert_eq!(COUNTER.load(Ordering::Relaxed), 3); + interrupt_low.raise(); + hil_test::assert_eq!(COUNTER.load(Ordering::Relaxed), 2); } } diff --git a/hil-test/src/bin/parl_io.rs b/hil-test/src/bin/parl_io.rs index b57b97c36f2..2d09b86a375 100644 --- a/hil-test/src/bin/parl_io.rs +++ b/hil-test/src/bin/parl_io.rs @@ -10,8 +10,6 @@ use hil_test as _; #[embedded_test::tests(default_timeout = 3)] mod tests { - #[cfg(esp32c6)] - use esp_hal::parl_io::{RxEightBits, TxEightBits}; use esp_hal::{ dma_rx_buffer, dma_tx_buffer, @@ -23,12 +21,15 @@ mod tests { ParlIo, RxClkInPin, RxConfig, + RxEightBits, RxFourBits, RxOneBit, + RxPinConfigIncludingValidPin, RxPinConfigWithValidPin, RxTwoBits, SampleEdge, TxConfig, + TxEightBits, TxFourBits, TxOneBit, TxPinConfigWithValidPin, @@ -38,6 +39,21 @@ mod tests { time::Rate, }; + cfg_select! { + esp32c5 => { + use esp_hal::gpio::NoPin; + } + esp32c6 => { + use esp_hal::{ + gpio::NoPin, + parl_io::{RxSixteenBits, TxPinConfigIncludingValidPin, TxSixteenBits}, + }; + } + esp32h2 => { + use esp_hal::parl_io::TxPinConfigIncludingValidPin; + } + } + struct Context { parl_io: PARL_IO<'static>, dma_channel: DMA_CH0<'static>, @@ -46,13 +62,7 @@ mod tests { data_pins: [AnyPin<'static>; 8], } - const MAX_CLK_RATE: Rate = Rate::from_mhz(if cfg!(esp32c5) { - // FIXME: Tests become flakey at higher speeds, no matter the sampling edge. - // Maybe an effect of the GPIO matrix injecting delay to the valid signal? - 10 - } else { - 40 - }); + const MAX_CLK_RATE: Rate = Rate::from_mhz(40); #[init] fn init() -> Context { @@ -64,15 +74,15 @@ mod tests { let (valid_pin, clock_pin, data_pins) = cfg_select! { esp32c5 => { - // 27 is RGB, 9 and 10 are connected, 13 and 14 is USB + // 27 is RGB, 13 and 14 is USB, 4 is tied to 5, 9 is tied to 10 (only 9 is driven) ( peripherals.GPIO0.degrade(), peripherals.GPIO1.degrade(), [ peripherals.GPIO2.degrade(), peripherals.GPIO3.degrade(), - peripherals.GPIO4.degrade(), - peripherals.GPIO5.degrade(), + peripherals.GPIO23.degrade(), + peripherals.GPIO24.degrade(), peripherals.GPIO6.degrade(), peripherals.GPIO7.degrade(), peripherals.GPIO8.degrade(), @@ -81,7 +91,7 @@ mod tests { ) } esp32c6 => { - // 8 is RGB, 2 and 3 are connected, 12 and 13 is USB + // 8 is RGB, 12 and 13 is USB, 2 is tied to 3 (only 2 is driven) ( peripherals.GPIO0.degrade(), peripherals.GPIO1.degrade(), @@ -98,7 +108,8 @@ mod tests { ) } esp32h2 => { - // 8 is RGB, 2 and 3 are connected, 26 and 27 is USB + // 8 is RGB, 26 and 27 is USB, 12 and 22 are I2C, 2 is tied to 3, 10 is tied to 11. + // 23 is UART0 RX. The 8-bit test does not drive the last pin. ( peripherals.GPIO0.degrade(), peripherals.GPIO1.degrade(), @@ -108,8 +119,8 @@ mod tests { peripherals.GPIO5.degrade(), peripherals.GPIO8.degrade(), peripherals.GPIO9.degrade(), - peripherals.GPIO10.degrade(), - peripherals.GPIO11.degrade(), + peripherals.GPIO13.degrade(), + peripherals.GPIO25.degrade(), peripherals.GPIO23.degrade(), ], ) @@ -143,7 +154,9 @@ mod tests { let rx_pins = RxPinConfigWithValidPin::new(rx_pins, valid_rx, EnableMode::HighLevel); let clock_out_pin = ClkOutPin::new(clock_tx); - let clock_in_pin = RxClkInPin::new(clock_rx, SampleEdge::Normal); + // Sample on the opposite edge of TX. Loopback through the GPIO matrix delays + // clock and data and same-edge sampling can violate hold time. + let clock_in_pin = RxClkInPin::new(clock_rx, SampleEdge::Invert); let pio = ParlIo::new(ctx.parl_io, ctx.dma_channel).unwrap(); @@ -205,7 +218,7 @@ mod tests { let rx_pins = RxPinConfigWithValidPin::new(rx_pins, valid_rx, EnableMode::HighLevel); let clock_out_pin = ClkOutPin::new(clock_tx); - let clock_in_pin = RxClkInPin::new(clock_rx, SampleEdge::Normal); + let clock_in_pin = RxClkInPin::new(clock_rx, SampleEdge::Invert); let pio = ParlIo::new(ctx.parl_io, ctx.dma_channel).unwrap(); @@ -273,7 +286,7 @@ mod tests { let rx_pins = RxPinConfigWithValidPin::new(rx_pins, valid_rx, EnableMode::HighLevel); let clock_out_pin = ClkOutPin::new(clock_tx); - let clock_in_pin = RxClkInPin::new(clock_rx, SampleEdge::Normal); + let clock_in_pin = RxClkInPin::new(clock_rx, SampleEdge::Invert); let pio = ParlIo::new(ctx.parl_io, ctx.dma_channel).unwrap(); @@ -317,10 +330,7 @@ mod tests { assert_eq!(dma_rx_buf.as_slice(), dma_tx_buf.as_slice()); } - // This test is disabled on the H2 because in 8-bit mode, there's no external - // enable pin to indicate when data is valid. The C6 has the same issue in - // 16-bit mode. The test would have to be written differently for it to work - // reliably. See https://github.com/esp-rs/esp-hal/pull/3339. + // On 8-line chips, `RxEightBits` uses data line 7 for the valid signal. #[cfg(esp32c6)] #[test] fn test_parl_io_rx_can_read_tx_in_8_bit_mode(ctx: Context) { @@ -349,7 +359,7 @@ mod tests { let rx_pins = RxPinConfigWithValidPin::new(rx_pins, valid_rx, EnableMode::HighLevel); let clock_out_pin = ClkOutPin::new(clock_tx); - let clock_in_pin = RxClkInPin::new(clock_rx, SampleEdge::Normal); + let clock_in_pin = RxClkInPin::new(clock_rx, SampleEdge::Invert); let pio = ParlIo::new(ctx.parl_io, ctx.dma_channel).unwrap(); @@ -392,17 +402,179 @@ mod tests { assert_eq!(dma_rx_buf.as_slice(), dma_tx_buf.as_slice()); } + + #[cfg(any(esp32c5, esp32h2))] + #[test] + fn test_parl_io_rx_can_read_tx_in_8_bit_mode_with_included_valid_pin(ctx: Context) { + const BUFFER_SIZE: usize = 64; + + let mut dma_rx_buf = dma_rx_buffer!(BUFFER_SIZE).unwrap(); + let mut dma_tx_buf = dma_tx_buffer!(BUFFER_SIZE).unwrap(); + + let (clock_rx, clock_tx) = unsafe { ctx.clock_pin.split() }; + let (valid_rx, valid_tx) = unsafe { ctx.valid_pin.split() }; + let [ + (d0_rx, d0_tx), + (d1_rx, d1_tx), + (d2_rx, d2_tx), + (d3_rx, d3_tx), + (d4_rx, d4_tx), + (d5_rx, d5_tx), + (d6_rx, d6_tx), + _, + ] = ctx.data_pins.map(|pin| unsafe { pin.split() }); + + let tx_pins = cfg_select! { + esp32c5 => TxPinConfigWithValidPin::new( + TxEightBits::new(d0_tx, d1_tx, d2_tx, d3_tx, d4_tx, d5_tx, d6_tx, NoPin), + valid_tx, + ), + _ => TxPinConfigIncludingValidPin::new(TxEightBits::new( + d0_tx, d1_tx, d2_tx, d3_tx, d4_tx, d5_tx, d6_tx, valid_tx, + )), + }; + let rx_pins = RxEightBits::new(d0_rx, d1_rx, d2_rx, d3_rx, d4_rx, d5_rx, d6_rx, valid_rx); + let rx_pins = RxPinConfigIncludingValidPin::new(rx_pins, EnableMode::HighLevel); + + let clock_out_pin = ClkOutPin::new(clock_tx); + let clock_in_pin = RxClkInPin::new(clock_rx, SampleEdge::Invert); + + let pio = ParlIo::new(ctx.parl_io, ctx.dma_channel).unwrap(); + + let pio_tx = pio + .tx + .with_config( + tx_pins, + clock_out_pin, + TxConfig::default() + .with_frequency(MAX_CLK_RATE) + .with_sample_edge(SampleEdge::Normal) + .with_bit_order(BitPackOrder::Lsb), + ) + .unwrap(); + let pio_rx = pio + .rx + .with_config( + rx_pins, + clock_in_pin, + RxConfig::default() + .with_frequency(MAX_CLK_RATE) + .with_bit_order(BitPackOrder::Lsb), + ) + .unwrap(); + + for (i, b) in dma_tx_buf.as_mut_slice().iter_mut().enumerate() { + *b = i as u8; + } + + let rx_transfer = pio_rx + .read(Some(dma_rx_buf.len()), dma_rx_buf) + .map_err(|e| e.0) + .unwrap(); + let tx_transfer = pio_tx + .write(dma_tx_buf.len(), dma_tx_buf) + .map_err(|e| e.0) + .unwrap(); + (_, _, dma_tx_buf) = tx_transfer.wait(); + (_, _, dma_rx_buf) = rx_transfer.wait(); + + // Data line 7 carries the valid signal. RX reads the valid level as data bit 7. + for (rx, tx) in dma_rx_buf.as_slice().iter().zip(dma_tx_buf.as_slice()) { + assert_eq!(*rx, tx & 0x7F | 0x80); + } + } + + #[cfg(esp32c6)] + #[test] + fn test_parl_io_rx_can_read_tx_in_16_bit_mode_with_included_valid_pin(ctx: Context) { + const BUFFER_SIZE: usize = 128; + + let mut dma_rx_buf = dma_rx_buffer!(BUFFER_SIZE).unwrap(); + let mut dma_tx_buf = dma_tx_buffer!(BUFFER_SIZE).unwrap(); + + let (clock_rx, clock_tx) = unsafe { ctx.clock_pin.split() }; + let (valid_rx, valid_tx) = unsafe { ctx.valid_pin.split() }; + let [ + (d0_rx, d0_tx), + (d1_rx, d1_tx), + (d2_rx, d2_tx), + (d3_rx, d3_tx), + (d4_rx, d4_tx), + (d5_rx, d5_tx), + (d6_rx, d6_tx), + (d7_rx, d7_tx), + ] = ctx.data_pins.map(|pin| unsafe { pin.split() }); + + let tx_pins = TxSixteenBits::new( + d0_tx, d1_tx, d2_tx, d3_tx, d4_tx, d5_tx, d6_tx, d7_tx, NoPin, NoPin, NoPin, NoPin, + NoPin, NoPin, NoPin, valid_tx, + ); + let rx_pins = RxSixteenBits::new( + d0_rx, d1_rx, d2_rx, d3_rx, d4_rx, d5_rx, d6_rx, d7_rx, NoPin, NoPin, NoPin, NoPin, + NoPin, NoPin, NoPin, valid_rx, + ); + + let tx_pins = TxPinConfigIncludingValidPin::new(tx_pins); + let rx_pins = RxPinConfigIncludingValidPin::new(rx_pins, EnableMode::HighLevel); + + let clock_out_pin = ClkOutPin::new(clock_tx); + let clock_in_pin = RxClkInPin::new(clock_rx, SampleEdge::Invert); + + let pio = ParlIo::new(ctx.parl_io, ctx.dma_channel).unwrap(); + + // RX times out with 16 lines at `MAX_CLK_RATE`. + // With `BitPackOrder::Lsb`, RX swaps each pair of 16-bit samples. + let pio_tx = pio + .tx + .with_config( + tx_pins, + clock_out_pin, + TxConfig::default() + .with_frequency(MAX_CLK_RATE / 2) + .with_sample_edge(SampleEdge::Normal) + .with_bit_order(BitPackOrder::Msb), + ) + .unwrap(); + let pio_rx = pio + .rx + .with_config( + rx_pins, + clock_in_pin, + RxConfig::default() + .with_frequency(MAX_CLK_RATE / 2) + .with_bit_order(BitPackOrder::Msb), + ) + .unwrap(); + + for (i, b) in dma_tx_buf.as_mut_slice().iter_mut().enumerate() { + *b = i as u8; + } + + let rx_transfer = pio_rx + .read(Some(dma_rx_buf.len()), dma_rx_buf) + .map_err(|e| e.0) + .unwrap(); + let tx_transfer = pio_tx + .write(dma_tx_buf.len(), dma_tx_buf) + .map_err(|e| e.0) + .unwrap(); + (_, _, dma_tx_buf) = tx_transfer.wait(); + (_, _, dma_rx_buf) = rx_transfer.wait(); + + // Data lines 8 to 14 read low. Data line 15 carries the valid signal. + // RX reads the valid level as data bit 15. + let rx = dma_rx_buf.as_slice().chunks_exact(2); + let tx = dma_tx_buf.as_slice().chunks_exact(2); + for (rx, tx) in rx.zip(tx) { + assert_eq!(rx[0], tx[0]); + assert_eq!(rx[1], 0x80); + } + } } #[embedded_test::tests(default_timeout = 3)] mod tx { use defmt::info; - #[cfg(any(esp32c6, esp32h2))] - use esp_hal::parl_io::TxPinConfigIncludingValidPin; - #[cfg(any(esp32c5, esp32c6))] - use esp_hal::parl_io::TxPinConfigWithValidPin; - #[cfg(esp32c6)] - use esp_hal::parl_io::TxSixteenBits; use esp_hal::{ dma::DmaTxBuf, dma_tx_buffer, @@ -412,7 +584,6 @@ mod tx { }, parl_io::{BitPackOrder, ClkOutPin, ParlIo, SampleEdge, TxConfig, TxEightBits}, pcnt::{ - Pcnt, channel::{CtrlMode, EdgeMode}, unit::Unit, }, @@ -420,6 +591,22 @@ mod tx { time::Rate, }; + cfg_select! { + esp32c5 => { + use esp_hal::parl_io::TxPinConfigWithValidPin; + } + esp32c6 => { + use esp_hal::parl_io::{ + TxPinConfigIncludingValidPin, + TxPinConfigWithValidPin, + TxSixteenBits, + }; + } + esp32h2 => { + use esp_hal::parl_io::TxPinConfigIncludingValidPin; + } + } + struct Context { parl_io: PARL_IO<'static>, dma_channel: DMA_CH0<'static>, @@ -427,7 +614,7 @@ mod tx { valid: OutputSignal<'static>, clock_loopback: InputSignal<'static>, valid_loopback: InputSignal<'static>, - pcnt_unit: Unit<'static, 0>, + pcnt_unit: Unit<'static>, } #[init] fn init() -> Context { @@ -437,8 +624,7 @@ mod tx { let valid = hil_test::unconnected_pin!(peripherals); let (clock_loopback, clock) = unsafe { clock.split() }; let (valid_loopback, valid) = unsafe { valid.split() }; - let pcnt = Pcnt::new(peripherals.PCNT); - let pcnt_unit = pcnt.unit0; + let pcnt_unit = Unit::new(peripherals.PCNT0_UNIT0); let dma_channel = peripherals.DMA_CH0; let parl_io = peripherals.PARL_IO; @@ -505,29 +691,72 @@ mod tx { } } + #[test] + fn test_parl_io_tx_clock_frequency(ctx: Context) { + use esp_hal::{ + parl_io::{TxOneBit, TxPinConfigWithValidPin}, + time::{Duration, Instant}, + }; + + // 64000 clock cycles, 4 ms at 16 MHz. + let dma_tx_buf: DmaTxBuf = dma_tx_buffer!(8000).unwrap(); + let pins = TxPinConfigWithValidPin::new(TxOneBit::new(NoPin), ctx.valid); + + let pio = ParlIo::new(ctx.parl_io, ctx.dma_channel).unwrap(); + + // 16 MHz divides the PARL_IO source clock of all chips. + let pio = pio + .tx + .with_config( + pins, + ClkOutPin::new(ctx.clock), + TxConfig::default().with_frequency(Rate::from_mhz(16)), + ) + .unwrap(); + + let clock_unit = ctx.pcnt_unit; + clock_unit.channel0.set_edge_signal(ctx.clock_loopback); + clock_unit + .channel0 + .set_input_mode(EdgeMode::Increment, EdgeMode::Hold); + clock_unit + .channel0 + .set_ctrl_mode(CtrlMode::Keep, CtrlMode::Keep); + + let xfer = pio + .write(dma_tx_buf.len(), dma_tx_buf) + .map_err(|e| e.0) + .unwrap(); + + // Count the clock edges in a window after the start of the transfer. + let start = Instant::now(); + while start.elapsed() < Duration::from_micros(200) {} + clock_unit.clear(); + let start = Instant::now(); + while start.elapsed() < Duration::from_micros(1000) {} + let edges = clock_unit.value() as u64; + let elapsed = start.elapsed().as_micros(); + _ = xfer.wait(); + + let khz = edges * 1000 / elapsed; + info!("clock frequency: {} kHz", khz); + assert!((15840..=16160).contains(&khz), "clock is {} kHz", khz); + } + #[test] fn test_parl_io_tx_8bit_valid_clock_count(ctx: Context) { const BUFFER_SIZE: usize = 64; let mut dma_tx_buf: DmaTxBuf = dma_tx_buffer!(BUFFER_SIZE).unwrap(); - let pins = TxEightBits::new( - NoPin, - NoPin, - NoPin, - NoPin, - NoPin, - NoPin, - NoPin, - #[cfg(esp32h2)] - ctx.valid, - #[cfg(any(esp32c5, esp32c6))] - NoPin, - ); - - #[cfg(esp32h2)] - let pins = TxPinConfigIncludingValidPin::new(pins); - #[cfg(any(esp32c5, esp32c6))] - let pins = TxPinConfigWithValidPin::new(pins, ctx.valid); + let pins = cfg_select! { + esp32h2 => TxPinConfigIncludingValidPin::new(TxEightBits::new( + NoPin, NoPin, NoPin, NoPin, NoPin, NoPin, NoPin, ctx.valid, + )), + _ => TxPinConfigWithValidPin::new( + TxEightBits::new(NoPin, NoPin, NoPin, NoPin, NoPin, NoPin, NoPin, NoPin), + ctx.valid, + ), + }; let clock_pin = ClkOutPin::new(ctx.clock); @@ -571,12 +800,6 @@ mod tx { #[embedded_test::tests(default_timeout = 3, executor = hil_test::Executor::new())] mod async_tx { use defmt::info; - #[cfg(any(esp32c6, esp32h2))] - use esp_hal::parl_io::TxPinConfigIncludingValidPin; - #[cfg(any(esp32c5, esp32c6))] - use esp_hal::parl_io::TxPinConfigWithValidPin; - #[cfg(esp32c6)] - use esp_hal::parl_io::TxSixteenBits; use esp_hal::{ dma::DmaTxBuf, dma_tx_buffer, @@ -586,7 +809,6 @@ mod async_tx { }, parl_io::{BitPackOrder, ClkOutPin, ParlIo, SampleEdge, TxConfig, TxEightBits}, pcnt::{ - Pcnt, channel::{CtrlMode, EdgeMode}, unit::Unit, }, @@ -594,6 +816,22 @@ mod async_tx { time::Rate, }; + cfg_select! { + esp32c5 => { + use esp_hal::parl_io::TxPinConfigWithValidPin; + } + esp32c6 => { + use esp_hal::parl_io::{ + TxPinConfigIncludingValidPin, + TxPinConfigWithValidPin, + TxSixteenBits, + }; + } + esp32h2 => { + use esp_hal::parl_io::TxPinConfigIncludingValidPin; + } + } + struct Context { parl_io: PARL_IO<'static>, dma_channel: DMA_CH0<'static>, @@ -601,7 +839,7 @@ mod async_tx { valid: OutputSignal<'static>, clock_loopback: InputSignal<'static>, valid_loopback: InputSignal<'static>, - pcnt_unit: Unit<'static, 0>, + pcnt_unit: Unit<'static>, } #[init] async fn init() -> Context { @@ -611,8 +849,7 @@ mod async_tx { let valid = hil_test::unconnected_pin!(peripherals); let (clock_loopback, clock) = unsafe { clock.split() }; let (valid_loopback, valid) = unsafe { valid.split() }; - let pcnt = Pcnt::new(peripherals.PCNT); - let pcnt_unit = pcnt.unit0; + let pcnt_unit = Unit::new(peripherals.PCNT0_UNIT0); let dma_channel = peripherals.DMA_CH0; let parl_io = peripherals.PARL_IO; @@ -657,7 +894,7 @@ mod async_tx { ) .unwrap(); - // use a PCNT unit to count the negitive clock edges only when valid is high + // use a PCNT unit to count the negative clock edges only when valid is high let clock_unit = ctx.pcnt_unit; clock_unit.channel0.set_edge_signal(ctx.clock_loopback); clock_unit.channel0.set_ctrl_signal(ctx.valid_loopback); @@ -687,24 +924,15 @@ mod async_tx { let mut dma_tx_buf: DmaTxBuf = dma_tx_buffer!(BUFFER_SIZE).unwrap(); - let pins = TxEightBits::new( - NoPin, - NoPin, - NoPin, - NoPin, - NoPin, - NoPin, - NoPin, - #[cfg(esp32h2)] - ctx.valid, - #[cfg(any(esp32c5, esp32c6))] - NoPin, - ); - - #[cfg(esp32h2)] - let pins = TxPinConfigIncludingValidPin::new(pins); - #[cfg(any(esp32c5, esp32c6))] - let pins = TxPinConfigWithValidPin::new(pins, ctx.valid); + let pins = cfg_select! { + esp32h2 => TxPinConfigIncludingValidPin::new(TxEightBits::new( + NoPin, NoPin, NoPin, NoPin, NoPin, NoPin, NoPin, ctx.valid, + )), + _ => TxPinConfigWithValidPin::new( + TxEightBits::new(NoPin, NoPin, NoPin, NoPin, NoPin, NoPin, NoPin, NoPin), + ctx.valid, + ), + }; let clock_pin = ClkOutPin::new(ctx.clock); @@ -724,7 +952,7 @@ mod async_tx { ) .unwrap(); - // use a PCNT unit to count the negitive clock edges only when + // use a PCNT unit to count the negative clock edges only when // valid is high let clock_unit = ctx.pcnt_unit; clock_unit.channel0.set_edge_signal(ctx.clock_loopback); diff --git a/hil-test/src/bin/radio_basic.rs b/hil-test/src/bin/radio_basic.rs index 66b4d877983..5c0ced57af1 100644 --- a/hil-test/src/bin/radio_basic.rs +++ b/hil-test/src/bin/radio_basic.rs @@ -1,8 +1,8 @@ //% CHIP_FILTER(no_wifi): bt_driver_supported && !wifi_driver_supported //% CHIP_FILTER(no_ble): wifi_driver_supported && !bt_driver_supported //% CHIP_FILTER(no_radio): !wifi_driver_supported && !bt_driver_supported -//% CHIP_FILTER(has_wifi_ble): wifi_driver_supported && bt_driver_supported //% CHIP_FILTER(stable_wifi): wifi_driver_supported +//% CHIP_FILTER(has_wifi_ble): wifi_driver_supported && bt_driver_supported //% FEATURES: unstable esp-alloc embassy //% FEATURES(no_radio): rtos-radio-driver @@ -30,6 +30,12 @@ fn init_heap() { esp32h2 => { esp_alloc::heap_allocator!(size: 72 * 1024); } + // The reclaimed region (dram2_seg) is only 56 KiB on the H4. + esp32h4 => { + use esp_hal::ram; + esp_alloc::heap_allocator!(#[ram(reclaimed)] size: 56 * 1024); + esp_alloc::heap_allocator!(size: 56 * 1024); + } _ => { use esp_hal::ram; esp_alloc::heap_allocator!(#[ram(reclaimed)] size: 64 * 1024); @@ -44,6 +50,7 @@ static mut APP_CORE_STACK: Stack<8192> = Stack::new(); #[path = "radio_basic/esp_rtos.rs"] mod esp_rtos; +#[cfg(soc_has_wifi)] #[path = "radio_basic/init_tests.rs"] #[cfg(feature = "esp-radio")] mod init_tests; @@ -58,6 +65,11 @@ mod ble_controller; #[cfg(feature = "esp-radio")] mod wifi_controller; +#[cfg(any(esp32c5, esp32c6, esp32c61, esp32h2))] +#[path = "radio_basic/adc.rs"] +#[cfg(feature = "esp-radio-unstable")] +mod adc; + #[cfg(soc_has_wifi)] #[path = "radio_basic/esp_now_config.rs"] #[cfg(feature = "esp-radio-unstable")] diff --git a/hil-test/src/bin/radio_basic/adc.rs b/hil-test/src/bin/radio_basic/adc.rs new file mode 100644 index 00000000000..07a4aa5be27 --- /dev/null +++ b/hil-test/src/bin/radio_basic/adc.rs @@ -0,0 +1,80 @@ +//! Checks that one-shot ADC conversions are unaffected by a running radio. +//! +//! Radio initialization hands SAR power to the PHY's power detector, which powers the SAR down +//! between its own measurements. Without the ADC driver overriding that, a grounded pad reads close +//! to full scale. + +#[embedded_test::tests(default_timeout = 10, executor = hil_test::Executor::new())] +mod tests { + use esp_hal::{ + analog::adc::{Adc, AdcConfig, Attenuation}, + clock::CpuClock, + gpio::{Level, Output, OutputConfig}, + peripherals::Peripherals, + timer::timg::TimerGroup, + }; + + // The grounded pad reads a few codes; the failure reads close to full scale. + const TOLERANCE: u16 = 0x100; + + #[init] + fn init() -> Peripherals { + crate::init_heap(); + + let config = esp_hal::Config::default().with_cpu_clock(CpuClock::max()); + esp_hal::init(config) + } + + #[test] + async fn adc_reads_unaffected_by_radio(p: Peripherals) { + let timg0: TimerGroup<'_, _> = TimerGroup::new(p.TIMG0); + esp_rtos::start(timg0.timer0); + + // The ADC pads of the `adc` test, driven by the other pad of their pair. + cfg_select! { + any(esp32c5, esp32c6) => { + let (adc_pin, driver) = hil_test::lp_test_pins!(p); + } + esp32c61 => { + let (driver, adc_pin) = hil_test::lp_test_pins!(p); + } + esp32h2 => { + let (adc_pin, driver) = hil_test::hp_test_pins!(p); + } + } + + let _driver = Output::new(driver, Level::Low, OutputConfig::default()); + + let mut config = AdcConfig::new(); + let mut pin = config.enable_pin(adc_pin, Attenuation::_11dB); + let mut adc = Adc::new(p.ADC1, config).unwrap(); + let mut read = || nb::block!(adc.read_oneshot(&mut pin)).unwrap(); + + let before = read(); + hil_test::assert!(before < TOLERANCE, "grounded pad read {}", before); + + { + let _radio = cfg_select! { + soc_has_wifi => esp_radio::wifi::WifiController::new(p.WIFI, Default::default()), + _ => esp_radio::ble::controller::BleConnector::new(p.BT, Default::default()), + } + .unwrap(); + + let with_radio = read(); + hil_test::assert!( + with_radio.abs_diff(before) < TOLERANCE, + "read {} with the radio running, {} before", + with_radio, + before + ); + } + + let after = read(); + hil_test::assert!( + after.abs_diff(before) < TOLERANCE, + "read {} after the radio stopped, {} before", + after, + before + ); + } +} diff --git a/hil-test/src/bin/radio_basic/ble_controller.rs b/hil-test/src/bin/radio_basic/ble_controller.rs index b5da1f905ff..1667a09fbdd 100644 --- a/hil-test/src/bin/radio_basic/ble_controller.rs +++ b/hil-test/src/bin/radio_basic/ble_controller.rs @@ -31,7 +31,7 @@ mod tests { let mut p = esp_hal::init(esp_hal::Config::default()); let timg0: TimerGroup<'_, _> = TimerGroup::new(p.TIMG0); - esp_rtos::start(timg0.timer0, p.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); { let _connector = BleConnector::new(p.BT.reborrow(), Default::default()).unwrap(); @@ -57,7 +57,7 @@ mod tests { #[test] fn test_controller_comms(p: Peripherals) { let timg0: TimerGroup<'_, _> = TimerGroup::new(p.TIMG0); - esp_rtos::start(timg0.timer0, p.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let mut connector = BleConnector::new(p.BT, Default::default()).unwrap(); @@ -106,7 +106,7 @@ mod tests { #[test] fn test_dropping_controller_during_reset(p: Peripherals) { let timg0: TimerGroup<'_, _> = TimerGroup::new(p.TIMG0); - esp_rtos::start(timg0.timer0, p.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let mut connector = BleConnector::new(p.BT, Default::default()).unwrap(); @@ -134,14 +134,14 @@ mod tests { #[test] async fn test_trouble_starts_advertising(p: Peripherals) { let timg0: TimerGroup<'_, _> = TimerGroup::new(p.TIMG0); - esp_rtos::start(timg0.timer0, p.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let connector = BleConnector::new(p.BT, Default::default()).unwrap(); let controller: ExternalController<_, 1> = ExternalController::new(connector); let address: Address = Address::random([0xff, 0x8f, 0x1a, 0x05, 0xe4, 0xff]); - let mut resources: HostResources<_, DefaultPacketPool, 1, 1> = HostResources::new(); + let mut resources: HostResources = HostResources::new(); let stack = trouble_host::new(controller, &mut resources) .set_random_address(address) .build(); diff --git a/hil-test/src/bin/radio_basic/esp_now_config.rs b/hil-test/src/bin/radio_basic/esp_now_config.rs index c3eb0a2d7b7..5ef05ae8525 100644 --- a/hil-test/src/bin/radio_basic/esp_now_config.rs +++ b/hil-test/src/bin/radio_basic/esp_now_config.rs @@ -2,7 +2,7 @@ mod tests { use esp_hal::{clock::CpuClock, peripherals::Peripherals, timer::timg::TimerGroup}; use esp_radio::{ - esp_now::{Error, EspNowError, EspNowWifiInterface, PeerInfo}, + esp_now::{BROADCAST_ADDRESS, Error, EspNowError, EspNowWifiInterface, PeerInfo}, wifi::{ControllerConfig, WifiController}, }; @@ -30,7 +30,7 @@ mod tests { #[test] fn espnow_max_encrypt_num_is_honored(p: Peripherals) { let timg0 = TimerGroup::new(p.TIMG0); - esp_rtos::start(timg0.timer0, p.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let controller = WifiController::new( p.WIFI, @@ -58,7 +58,7 @@ mod tests { #[test] fn espnow_max_encrypt_num_raises_the_limit(p: Peripherals) { let timg0 = TimerGroup::new(p.TIMG0); - esp_rtos::start(timg0.timer0, p.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let controller = WifiController::new( p.WIFI, @@ -76,10 +76,32 @@ mod tests { assert_eq!(esp_now.peer_count().unwrap().encrypted_count, 4); } + #[test] + fn esp_now_survives_controller_drop(p: Peripherals) { + let timg0 = TimerGroup::new(p.TIMG0); + esp_rtos::start(timg0.timer0); + + let mut wifi = p.WIFI; + let controller = WifiController::new(wifi.reborrow(), Default::default()).unwrap(); + let mut esp_now = controller.esp_now(); + drop(controller); + + esp_now.set_channel(1).unwrap(); + esp_now + .send(&BROADCAST_ADDRESS, b"hello") + .unwrap() + .wait() + .unwrap(); + + drop(esp_now); + + let _controller = WifiController::new(wifi, Default::default()).unwrap(); + } + #[test] fn sta_disconnected_pm_can_be_configured(p: Peripherals) { let timg0 = TimerGroup::new(p.TIMG0); - esp_rtos::start(timg0.timer0, p.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let mut wifi = p.WIFI; for enabled in [true, false] { diff --git a/hil-test/src/bin/radio_basic/esp_rtos.rs b/hil-test/src/bin/radio_basic/esp_rtos.rs index 4d590113b57..db7410b5793 100644 --- a/hil-test/src/bin/radio_basic/esp_rtos.rs +++ b/hil-test/src/bin/radio_basic/esp_rtos.rs @@ -7,27 +7,26 @@ mod tests { use esp_hal::{ clock::CpuClock, interrupt::{Priority, software::SoftwareInterrupt}, - peripherals::{FROM_CPU_INTR0, FROM_CPU_INTR2, TIMG0}, + peripherals::{FROM_CPU_INTR2, TIMG0}, time::{Duration, Instant}, timer::timg::TimerGroup, }; #[cfg(multi_core)] - use esp_hal::{ - peripherals::{CPU_CTRL, FROM_CPU_INTR1}, - system::Cpu, - }; + use esp_hal::{peripherals::CPU_CTRL, system::Cpu}; use esp_radio_rtos_driver::{ self as preempt, queue::QueueHandle, semaphore::{SemaphoreHandle, SemaphoreKind}, }; - use esp_rtos::{CurrentThreadHandle, embassy::InterruptExecutor}; + use esp_rtos::{ + CurrentThreadHandle, + embassy::InterruptExecutor, + thread::{Stack as ThreadStack, ThreadSpawner}, + }; use portable_atomic::{AtomicBool, AtomicPtr, AtomicUsize, Ordering}; - use static_cell::StaticCell; + use static_cell::{ConstStaticCell, StaticCell}; struct Context { - #[cfg(multi_core)] - sw_int1: FROM_CPU_INTR1<'static>, sw_int2: FROM_CPU_INTR2<'static>, #[cfg(multi_core)] cpu_cntl: CPU_CTRL<'static>, @@ -36,9 +35,8 @@ mod tests { #[allow(unused)] // compile test fn baremetal_preempt_can_be_initialized_with_any_timer( timer: esp_hal::timer::AnyTimer<'static>, - int: FROM_CPU_INTR0<'static>, ) { - esp_rtos::start(timer, int); + esp_rtos::start(timer); } #[init] @@ -49,11 +47,9 @@ mod tests { let p = esp_hal::init(config); let timg0 = TimerGroup::new(p.TIMG0); - esp_rtos::start(timg0.timer0, p.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); Context { - #[cfg(multi_core)] - sw_int1: p.FROM_CPU_INTR1, sw_int2: p.FROM_CPU_INTR2, #[cfg(multi_core)] cpu_cntl: p.CPU_CTRL, @@ -66,9 +62,9 @@ mod tests { #[should_panic] fn panics_in_interrupt_context() { #[embassy_executor::task] - async fn try_init(timer: TIMG0<'static>, sw_int0: FROM_CPU_INTR0<'static>) { + async fn try_init(timer: TIMG0<'static>) { let timg0 = TimerGroup::new(timer); - esp_rtos::start(timg0.timer0, sw_int0); + esp_rtos::start(timg0.timer0); } crate::init_heap(); @@ -76,13 +72,13 @@ mod tests { let config = esp_hal::Config::default().with_cpu_clock(CpuClock::max()); let p = esp_hal::init(config); - static EXECUTOR_CORE_0: StaticCell> = StaticCell::new(); - let executor_core0 = InterruptExecutor::new(p.FROM_CPU_INTR1); + static EXECUTOR_CORE_0: StaticCell> = StaticCell::new(); + let executor_core0 = InterruptExecutor::new(p.FROM_CPU_INTR2); let executor_core0 = EXECUTOR_CORE_0.init(executor_core0); let spawner = executor_core0.start(Priority::Priority1); - spawner.spawn(try_init(p.TIMG0, p.FROM_CPU_INTR0).unwrap()); + spawner.spawn(try_init(p.TIMG0).unwrap()); } #[test] @@ -94,6 +90,110 @@ mod tests { hil_test::assert!(now.elapsed() >= Duration::from_millis(10)); } + #[test] + fn thread_runs_a_function_and_returns_its_value() { + fn worker() -> u32 { + 42 + } + + let handle = ThreadSpawner::new(4096).with_name("worker").spawn(worker); + + hil_test::assert_eq!(handle.name(), Some("worker")); + + let (value, _spawner) = handle.join(); + hil_test::assert_eq!(value, 42); + } + + #[test] + fn thread_returns_a_value_that_is_not_copy() { + let captured = Box::new(3_u32); + + let handle = ThreadSpawner::new(4096).spawn(move || { + let mut items = alloc::vec::Vec::new(); + items.push(*captured); + items.push(*captured); + items + }); + + let (value, _spawner) = handle.join(); + hil_test::assert_eq!(value.len(), 2); + hil_test::assert_eq!(value[0], 3); + hil_test::assert_eq!(value[1], 3); + } + + #[test] + fn a_static_stack_can_be_reused_after_a_join() { + static STACK: ConstStaticCell> = ConstStaticCell::new(ThreadStack::new()); + + let spawner = ThreadSpawner::from_static(STACK.take()).with_priority(2); + + let (first, spawner) = spawner.spawn(|| 1_u32).join(); + let (second, _spawner) = spawner.spawn(|| 2_u32).join(); + + hil_test::assert_eq!(first, 1); + hil_test::assert_eq!(second, 2); + } + + #[test] + fn a_detached_thread_keeps_running() { + static FINISHED: AtomicBool = AtomicBool::new(false); + + ThreadSpawner::new(4096) + .spawn(|| { + CurrentThreadHandle::get().delay(Duration::from_millis(10)); + FINISHED.store(true, Ordering::SeqCst); + }) + .detach(); + + while !FINISHED.load(Ordering::SeqCst) { + CurrentThreadHandle::get().delay(Duration::from_millis(1)); + } + } + + #[test] + fn a_detached_thread_drops_its_return_value() { + static DROPPED: AtomicBool = AtomicBool::new(false); + + struct Observed; + impl Drop for Observed { + fn drop(&mut self) { + DROPPED.store(true, Ordering::SeqCst); + } + } + + ThreadSpawner::new(4096).spawn(|| Observed).detach(); + + while !DROPPED.load(Ordering::SeqCst) { + CurrentThreadHandle::get().delay(Duration::from_millis(1)); + } + } + + #[test] + #[cfg(multi_core)] + fn a_thread_can_be_pinned_to_the_second_core(ctx: Context) { + esp_rtos::start_second_core( + unsafe { ctx.cpu_cntl.clone_unchecked() }, + #[allow(static_mut_refs)] + unsafe { + &mut crate::APP_CORE_STACK + }, + || {}, + ); + + let (cpu, _spawner) = ThreadSpawner::new(4096) + .with_pinned_to(Cpu::AppCpu) + .with_priority(2) + .spawn(Cpu::current) + .join(); + + hil_test::assert!(cpu == Cpu::AppCpu); + + unsafe { + // Park the second core, we don't need it anymore + esp_hal::system::CpuControl::new(ctx.cpu_cntl).park_core(Cpu::AppCpu); + } + } + #[test] #[timeout(2)] fn time_slicing() { @@ -461,7 +561,6 @@ mod tests { esp_rtos::start_second_core( unsafe { ctx.cpu_cntl.clone_unchecked() }, - ctx.sw_int1, #[allow(static_mut_refs)] unsafe { &mut crate::APP_CORE_STACK @@ -537,7 +636,6 @@ mod tests { esp_rtos::start_second_core( unsafe { ctx.cpu_cntl.clone_unchecked() }, - ctx.sw_int1, #[allow(static_mut_refs)] unsafe { &mut crate::APP_CORE_STACK @@ -588,6 +686,112 @@ mod tests { } } + /// State that the victim and the waker of `woken_task_runs_on_one_core` share. + #[cfg(multi_core)] + struct WakeTest { + victim: SemaphoreHandle, + waker: SemaphoreHandle, + victim_blocks_on_core_0: AtomicBool, + victim_running: AtomicBool, + rounds: AtomicUsize, + } + + /// Wakes the waker, then blocks. `context` points to a `WakeTest`. + #[cfg(multi_core)] + extern "C" fn wake_test_victim(context: *mut c_void) { + let test = unsafe { &*(context as *const WakeTest) }; + loop { + test.waker.give(); + test.victim_blocks_on_core_0 + .store(Cpu::current() == Cpu::ProCpu, Ordering::Relaxed); + test.victim.take(None); + + hil_test::assert!( + !test.victim_running.swap(true, Ordering::Relaxed), + "Two cores run the same task" + ); + // Must be longer than the busy interrupt, so that two copies of the task overlap here. + let start = Instant::now(); + while start.elapsed() < Duration::from_micros(200) {} + test.victim_running.store(false, Ordering::Relaxed); + + test.rounds.fetch_add(1, Ordering::Relaxed); + } + } + + /// Delays core 0 while the victim blocks, wakes the victim, then blocks. + /// + /// `context` points to a `WakeTest`. + #[cfg(multi_core)] + extern "C" fn wake_test_waker(context: *mut c_void) { + let test = unsafe { &*(context as *const WakeTest) }; + loop { + test.waker.take(None); + + let start = Instant::now(); + while !test.victim_blocks_on_core_0.swap(false, Ordering::Relaxed) + && start.elapsed() < Duration::from_millis(10) + {} + SoftwareInterrupt::<'static, 2>::new(unsafe { FROM_CPU_INTR2::steal() }).raise(); + test.victim.give(); + } + } + + #[test] + #[timeout(10)] + #[cfg(multi_core)] + fn woken_task_runs_on_one_core(ctx: Context) { + // The victim blocks on core 0. The waker on core 1 delays the switch on core 0. + // The waker then wakes the victim and blocks. + // Core 1 selects a task while core 0 still runs the victim. + #[esp_hal::handler(priority = Priority::Priority3)] + fn keep_core_busy() { + SoftwareInterrupt::<'static, 2>::new(unsafe { FROM_CPU_INTR2::steal() }).reset(); + let start = Instant::now(); + while start.elapsed() < Duration::from_micros(100) {} + } + + esp_rtos::start_second_core( + unsafe { ctx.cpu_cntl.clone_unchecked() }, + #[allow(static_mut_refs)] + unsafe { + &mut crate::APP_CORE_STACK + }, + || {}, + ); + + // The main task must preempt the victim to check the result. + CurrentThreadHandle::get().set_priority(5); + + let mut sw_int2 = SoftwareInterrupt::new(ctx.sw_int2); + sw_int2.set_interrupt_handler(keep_core_busy); + + let test: &'static WakeTest = Box::leak(Box::new(WakeTest { + victim: SemaphoreHandle::new(SemaphoreKind::Counting { initial: 0, max: 1 }), + waker: SemaphoreHandle::new(SemaphoreKind::Counting { initial: 0, max: 1 }), + victim_blocks_on_core_0: AtomicBool::new(false), + victim_running: AtomicBool::new(false), + rounds: AtomicUsize::new(0), + })); + let context = (test as *const WakeTest).cast::().cast_mut(); + unsafe { + preempt::task_create("waker", wake_test_waker, context, 2, Some(1), 4096); + preempt::task_create("victim", wake_test_victim, context, 1, None, 4096); + } + + CurrentThreadHandle::get().delay(Duration::from_secs(3)); + + hil_test::assert!( + test.rounds.load(Ordering::Relaxed) > 0, + "The victim never woke up" + ); + + unsafe { + // Park the second core, we don't need it anymore + esp_hal::system::CpuControl::new(ctx.cpu_cntl).park_core(Cpu::AppCpu); + } + } + #[test] #[cfg(multi_core)] async fn embassy_cross_core(ctx: Context) { @@ -603,7 +807,6 @@ mod tests { esp_rtos::start_second_core( unsafe { ctx.cpu_cntl.clone_unchecked() }, - ctx.sw_int1, #[allow(static_mut_refs)] unsafe { &mut crate::APP_CORE_STACK @@ -651,7 +854,6 @@ mod tests { esp_rtos::start_second_core( unsafe { ctx.cpu_cntl.clone_unchecked() }, - ctx.sw_int1, #[allow(static_mut_refs)] unsafe { &mut crate::APP_CORE_STACK @@ -698,7 +900,7 @@ mod tests { static SIGNAL: Signal = Signal::new(); - let _gaurd = esp_hal::system::CpuControl::new(ctx.cpu_cntl) + let _guard = esp_hal::system::CpuControl::new(ctx.cpu_cntl) .start_app_core( #[allow(static_mut_refs)] unsafe { @@ -878,7 +1080,7 @@ mod second_core_only { use esp_hal::{ clock::CpuClock, - peripherals::{CPU_CTRL, FROM_CPU_INTR1}, + peripherals::CPU_CTRL, system::Cpu, time::Duration, timer::timg::{Timer, TimerGroup}, @@ -889,7 +1091,6 @@ mod second_core_only { struct Context { cpu_control: CPU_CTRL<'static>, - sw_int1: FROM_CPU_INTR1<'static>, timer: Timer<'static>, } @@ -904,7 +1105,6 @@ mod second_core_only { Context { cpu_control: p.CPU_CTRL, - sw_int1: p.FROM_CPU_INTR1, timer: timg0.timer0, } } @@ -912,7 +1112,6 @@ mod second_core_only { fn start_on_second_core(ctx: Context, func: impl FnOnce() + Send + 'static) { esp_rtos::start_on_second_core_only( ctx.cpu_control, - ctx.sw_int1, ctx.timer, #[allow(static_mut_refs)] unsafe { diff --git a/hil-test/src/bin/radio_basic/fpu.rs b/hil-test/src/bin/radio_basic/fpu.rs index bcc6722d482..f0c401f42f5 100644 --- a/hil-test/src/bin/radio_basic/fpu.rs +++ b/hil-test/src/bin/radio_basic/fpu.rs @@ -68,11 +68,10 @@ mod tests { static DONE: AtomicBool = AtomicBool::new(false); let timg0 = TimerGroup::new(p.TIMG0); - esp_rtos::start(timg0.timer0, p.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); esp_rtos::start_second_core::<8192>( p.CPU_CTRL, - p.FROM_CPU_INTR1, #[allow(static_mut_refs)] unsafe { &mut crate::APP_CORE_STACK diff --git a/hil-test/src/bin/radio_basic/init_tests.rs b/hil-test/src/bin/radio_basic/init_tests.rs index a6ef0c00add..b23b7945d77 100644 --- a/hil-test/src/bin/radio_basic/init_tests.rs +++ b/hil-test/src/bin/radio_basic/init_tests.rs @@ -47,6 +47,7 @@ mod init_tests { #[test] #[should_panic] + #[timeout(6)] #[cfg(soc_has_wifi)] fn test_init_fails_without_scheduler(p: Peripherals) { // esp-rtos must be initialized before esp-radio. @@ -55,10 +56,11 @@ mod init_tests { #[test] #[should_panic] + #[timeout(6)] #[cfg(soc_has_wifi)] fn test_init_fails_cs(p: Peripherals) { let timg0 = TimerGroup::new(p.TIMG0); - esp_rtos::start(timg0.timer0, p.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let _ = critical_section::with(|_| { esp_radio::wifi::WifiController::new(p.WIFI, Default::default()) @@ -67,26 +69,28 @@ mod init_tests { #[test] #[should_panic] + #[timeout(6)] #[cfg(soc_has_wifi)] fn test_init_fails_interrupt_free(p: Peripherals) { let timg0 = TimerGroup::new(p.TIMG0); - esp_rtos::start(timg0.timer0, p.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let _ = interrupt_free(|| esp_radio::wifi::WifiController::new(p.WIFI, Default::default())); } #[test] #[should_panic] + #[timeout(6)] #[cfg(soc_has_wifi)] async fn test_init_fails_in_interrupt_executor_task(p: Peripherals) { - static EXECUTOR_CORE_0: StaticCell> = StaticCell::new(); - let executor_core0 = InterruptExecutor::new(p.FROM_CPU_INTR1); + static EXECUTOR_CORE_0: StaticCell> = StaticCell::new(); + let executor_core0 = InterruptExecutor::new(p.FROM_CPU_INTR2); let executor_core0 = EXECUTOR_CORE_0.init(executor_core0); let spawner = executor_core0.start(Priority::Priority1); let timg0 = TimerGroup::new(p.TIMG0); - esp_rtos::start(timg0.timer0, p.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let signal = mk_static!(Signal>, Signal::new()); @@ -99,7 +103,7 @@ mod init_tests { #[cfg(soc_has_wifi)] fn test_wifi_can_be_initialized(mut p: Peripherals) { let timg0 = TimerGroup::new(p.TIMG0); - esp_rtos::start(timg0.timer0, p.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); // Initialize, then de-initialize wifi let wifi = @@ -116,7 +120,7 @@ mod init_tests { #[cfg(all(bt_driver_supported, feature = "esp-radio-unstable"))] fn test_init_and_drop(mut p: Peripherals) { let timg0: TimerGroup<'_, _> = TimerGroup::new(p.TIMG0); - esp_rtos::start(timg0.timer0, p.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); // Initialize BLE and WiFi then drop BLE let connector = BleConnector::new(p.BT.reborrow(), Default::default()).unwrap(); @@ -135,7 +139,7 @@ mod init_tests { #[cfg(all(bt_driver_supported, feature = "esp-radio-unstable"))] fn test_create_ble_wifi_drop_ble_wifi_create_wifi_ble(mut p: Peripherals) { let timg0: TimerGroup<'_, _> = TimerGroup::new(p.TIMG0); - esp_rtos::start(timg0.timer0, p.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); // Initialize WiFi and BLE then drop BLE and WiFi let wifi = diff --git a/hil-test/src/bin/radio_basic/wifi_controller.rs b/hil-test/src/bin/radio_basic/wifi_controller.rs index 9324fda72d9..bb1bf66b9d8 100644 --- a/hil-test/src/bin/radio_basic/wifi_controller.rs +++ b/hil-test/src/bin/radio_basic/wifi_controller.rs @@ -17,7 +17,7 @@ mod tests { #[test] async fn wifi_starts_with_trng_enabled(p: Peripherals) { let timg0: TimerGroup<'_, _> = TimerGroup::new(p.TIMG0); - esp_rtos::start(timg0.timer0, p.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let _source = esp_hal::rng::TrngSource::new(p.RNG, p.ADC1); @@ -30,7 +30,7 @@ mod tests { #[timeout(15)] async fn test_scan_doesnt_leak(p: Peripherals) { let timg0: TimerGroup<'_, _> = TimerGroup::new(p.TIMG0); - esp_rtos::start(timg0.timer0, p.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let mut controller = esp_radio::wifi::WifiController::new(p.WIFI, Default::default()).unwrap(); diff --git a/hil-test/src/bin/rmt.rs b/hil-test/src/bin/rmt.rs index fe66f2fac38..38236ad1d5a 100644 --- a/hil-test/src/bin/rmt.rs +++ b/hil-test/src/bin/rmt.rs @@ -59,7 +59,7 @@ use hil_test::{assert, assert_eq}; // RMT channel clock = 500kHz cfg_select! { - esp32h2 => { + any(esp32h2, esp32h4) => { const FREQ: Rate = Rate::from_mhz(32); const DIV: u8 = 64; } @@ -88,6 +88,8 @@ struct LoopbackConfig { length1_base: u16, length1_step: u16, length2: u16, + sclk_div: u16, // 1 - 256 + ch_div: u8, } impl Default for LoopbackConfig { @@ -105,14 +107,20 @@ impl Default for LoopbackConfig { length1_base: 100, length1_step: 10, length2: 50, + sclk_div: 1, + ch_div: DIV, } } } impl LoopbackConfig { + fn sclk_freq(&self) -> Rate { + FREQ / self.sclk_div as u32 + } + fn tx_config(&self) -> TxChannelConfig { TxChannelConfig::default() - .with_clk_divider(DIV) + .with_clk_divider(self.ch_div) .with_idle_output(self.idle_output) .with_idle_output_level(Level::Low) .with_memsize(self.tx_memsize) @@ -120,7 +128,7 @@ impl LoopbackConfig { fn rx_config(&self) -> RxChannelConfig { RxChannelConfig::default() - .with_clk_divider(DIV) + .with_clk_divider(self.ch_div) .with_idle_threshold(self.idle_threshold) .with_memsize(self.rx_memsize) } @@ -133,17 +141,21 @@ impl LoopbackConfig { // buffer in loopback tests with buffer wrapping. If we did, that might hide bugs. // FIXME: Make a method on LoopbackConfig? fn generate_tx_data(conf: &LoopbackConfig) -> Vec { + const WRAP_COUNT: u16 = 23; + let mut tx_data: Vec<_> = (0..) .take(conf.tx_len) .map(|i| { - PulseCode::new( + PulseCode::try_new( Level::High, - conf.length1_base + conf.length1_step * (i % 23), + conf.length1_base + conf.length1_step * (i % WRAP_COUNT), Level::Low, conf.length2, ) + .expect("pulse code length out of range") }) .collect(); + let mut i_max = WRAP_COUNT.min(conf.tx_len as u16); let mut pos = conf.tx_len - 1; match conf.end_marker { @@ -151,19 +163,25 @@ fn generate_tx_data(conf: &LoopbackConfig) -> Vec { EndMarkerConfig::Field1 => { tx_data[pos] = PulseCode::end_marker(); pos -= 1; + i_max -= 1; } EndMarkerConfig::Field2 => { tx_data[pos] = tx_data[pos].with_length2(0).unwrap(); pos -= 1; + i_max -= 1; } } if conf.write_stop_code { - tx_data[pos] = PulseCode::new( + i_max -= 1; + assert!(conf.length1_base + i_max * conf.length1_step + conf.length2 < conf.idle_threshold); + + tx_data[pos] = PulseCode::try_new( Level::High, 2 * conf.idle_threshold, Level::Low, conf.length2, - ); + ) + .expect("idle_threshold out of range"); } tx_data @@ -289,10 +307,13 @@ fn check_data_eq( struct BitbangTransmitter { pin: Flex<'static>, + cycles_per_us: u32, } impl BitbangTransmitter { - fn new(pin: impl Pin + 'static) -> Self { + const SCALE: u32 = 1024; + + fn new(pin: impl Pin + 'static, conf: &LoopbackConfig) -> Self { let mut pin = Flex::new(pin); pin.set_input_enable(true); pin.set_output_enable(true); @@ -301,7 +322,10 @@ impl BitbangTransmitter { pin.set_low(); - Self { pin } + Self { + pin, + cycles_per_us: conf.ch_div as u32 * 1000 * Self::SCALE / conf.sclk_freq().as_khz(), + } } fn rx_pin(&mut self) -> impl PeripheralInput<'static> { @@ -309,8 +333,6 @@ impl BitbangTransmitter { } fn transmit(&mut self, tx_data: &[PulseCode]) { - let cycles_per_us = DIV as u32 / FREQ.as_mhz(); - let delay = Delay::new(); for code in tx_data { @@ -318,22 +340,23 @@ impl BitbangTransmitter { break; } self.pin.set_level(code.level1()); - delay.delay_micros(code.length1() as u32 * cycles_per_us); + delay.delay_micros(code.length1() as u32 * self.cycles_per_us / Self::SCALE); if code.length2() == 0 { break; } self.pin.set_level(code.level2()); - delay.delay_micros(code.length2() as u32 * cycles_per_us); + delay.delay_micros(code.length2() as u32 * self.cycles_per_us / Self::SCALE); } } } -fn do_rmt_loopback_inner( +// Returns the channels for reuse if the transactions completed. +fn do_rmt_loopback_inner<'ch>( conf: &LoopbackConfig, - tx_channel: Channel, - rx_channel: Channel, -) { + tx_channel: Channel<'ch, Blocking, Tx>, + rx_channel: Channel<'ch, Blocking, Rx>, +) -> Option<(Channel<'ch, Blocking, Tx>, Channel<'ch, Blocking, Rx>)> { let tx_data = generate_tx_data(conf); let mut rcv_data = vec![PulseCode::default(); conf.tx_len]; @@ -358,6 +381,8 @@ fn do_rmt_loopback_inner( // The test should fail here when the delay above is increased, e.g. to 100ms. assert!(!rx_done); assert!(!tx_done); + + None } else { let run = move || match rx_transaction { Ok(mut rx_transaction) => { @@ -370,17 +395,19 @@ fn do_rmt_loopback_inner( } } - tx_transaction.wait().unwrap(); + let tx_channel = tx_transaction.wait().unwrap(); match rx_transaction.wait() { - Ok((rx_count, _channel)) => Ok(rx_count), - Err((err, _channel)) => Err(err), + Ok((rx_count, rx_channel)) => (Ok(rx_count), Some((tx_channel, rx_channel))), + Err((err, rx_channel)) => (Err(err), Some((tx_channel, rx_channel))), } } - Err((e, _)) => Err(e), + Err((e, _)) => (Err(e), None), }; - let rx_res = run(); + let (rx_res, channels) = run(); check_data_eq(conf, &tx_data, &rcv_data, rx_res); + + channels } } @@ -435,6 +462,36 @@ async fn do_rmt_loopback_async(ctx: &mut Context, conf: &LoopbackConfig) { do_rmt_loopback_async_inner(&conf, &mut tx_channel, &mut rx_channel).await } +// SCLK dividers to test; ESP32 and ESP32-S2 don't have an SCLK divider. +const SCLK_DIVIDERS: &[u16] = if cfg!(any(esp32, esp32s2)) { + &[1] +} else { + &[1, 16, 256] +}; + +const CHANNEL_DIVIDERS: &[u8] = &[1, 16, 255]; + +fn divider_loopback_config(sclk_div: u16, ch_div: u8) -> LoopbackConfig { + let div = sclk_div as u32 * ch_div as u32; + // the stop code is sent with length 2 * idle_threshold = 40 * step, cf. generate_tx_data + let step = (32767 / (41 * div)).max(5) as u16; + + #[cfg(feature = "defmt")] + defmt::info!("sclk_div: {}, ch_div: {}, step: {}", sclk_div, ch_div, step); + + LoopbackConfig { + idle_output: true, + sclk_div, + ch_div, + tx_len: 5, + length1_base: 10 * step, + length1_step: step, + length2: 2 * step, + idle_threshold: 20 * step, + ..Default::default() + } +} + macro_rules! pins { ($ctx:expr) => { Flex::new($ctx.pin.reborrow()).split() @@ -491,7 +548,7 @@ impl Context { &mut self, conf: &LoopbackConfig, ) -> (Channel<'_, Blocking, Tx>, Channel<'_, Blocking, Rx>) { - let rmt = Rmt::new(self.rmt.reborrow(), FREQ).unwrap(); + let rmt = Rmt::new(self.rmt.reborrow(), conf.sclk_freq()).unwrap(); let (rx, tx) = pins!(self); Self::setup_impl(rmt, rx, tx, conf) } @@ -500,7 +557,9 @@ impl Context { &mut self, conf: &LoopbackConfig, ) -> (Channel<'_, Async, Tx>, Channel<'_, Async, Rx>) { - let rmt = Rmt::new(self.rmt.reborrow(), FREQ).unwrap().into_async(); + let rmt = Rmt::new(self.rmt.reborrow(), conf.sclk_freq()) + .unwrap() + .into_async(); let (rx, tx) = pins!(self); Self::setup_impl(rmt, rx, tx, conf) } @@ -521,7 +580,7 @@ mod tests { let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let (pin, _pin2) = hil_test::common_test_pins!(peripherals); @@ -649,7 +708,7 @@ mod tests { } // Test that errors on invalid data are returned as expected (in particular, checks that the - // methods don't hang executing a never-ending/never-started tranmission). + // methods don't hang executing a never-ending/never-started transmission). #[test] fn rmt_tx_errors_blocking(mut ctx: Context) { let conf = LoopbackConfig { @@ -847,7 +906,7 @@ mod tests { let conf = LoopbackConfig::default(); let (rx_pin, tx_pin) = pins!($ctx); - let mut rmt = Rmt::new($ctx.rmt.reborrow(), FREQ).unwrap(); + let mut rmt = Rmt::new($ctx.rmt.reborrow(), conf.sclk_freq()).unwrap(); let tx_channel = rmt .$tx_channel @@ -939,9 +998,9 @@ mod tests { ..Default::default() }; - let rmt = Rmt::new(ctx.rmt, FREQ).unwrap(); + let rmt = Rmt::new(ctx.rmt, conf.sclk_freq()).unwrap(); - let mut bitbang_tx = BitbangTransmitter::new(ctx.pin); + let mut bitbang_tx = BitbangTransmitter::new(ctx.pin, &conf); let (_, rx_channel) = Context::setup_impl(rmt, bitbang_tx.rx_pin(), NoPin, &conf); let tx_data = generate_tx_data(&conf); @@ -1010,7 +1069,7 @@ mod tests { // Test that dropping & recreating Rmt works for _ in 0..3 { - let mut rmt = Rmt::new(ctx.rmt.reborrow(), FREQ).unwrap(); + let mut rmt = Rmt::new(ctx.rmt.reborrow(), conf.sclk_freq()).unwrap(); // Test that dropping & recreating ChannelCreator works for _ in 0..3 { @@ -1074,7 +1133,9 @@ mod tests { // Test that dropping & recreating Rmt works for _ in 0..3 { - let mut rmt = Rmt::new(ctx.rmt.reborrow(), FREQ).unwrap().into_async(); + let mut rmt = Rmt::new(ctx.rmt.reborrow(), conf.sclk_freq()) + .unwrap() + .into_async(); // Test that dropping & recreating ChannelCreator works for _ in 0..3 { @@ -1191,6 +1252,64 @@ mod tests { rmt_loopback_continuous_tx_impl(ctx, true); } + // Regression test for continuous tx with a slow SCLK, where the loop count interrupt often + // never fired, see esp-rs/esp-hal#3930. + #[cfg(all(rmt_has_tx_loop_count, not(esp32s2)))] + #[test] + #[timeout(3)] + fn rmt_continuous_tx_slow_sclk(mut ctx: Context) { + use esp_hal::time::Instant; + + const LOOPS: u16 = 10; + const CODE_LENGTH: u16 = 289; + + let sclk = FREQ / 256; + let expected_us = (LOOPS as u64 * 2 * CODE_LENGTH as u64 * 1_000_000) / sclk.as_hz() as u64; + + let tx_data = [ + PulseCode::new(Level::High, CODE_LENGTH, Level::Low, CODE_LENGTH), + PulseCode::end_marker(), + ]; + let config = TxChannelConfig::default() + .with_clk_divider(1) + .with_idle_output(true) + .with_idle_output_level(Level::Low); + + let mut rmt = Rmt::new(ctx.rmt.reborrow(), sclk).unwrap(); + + // Reconfigure the channel for every transaction, as in the original report. + for _ in 0..10 { + let tx_channel = rmt + .channel0 + .reborrow() + .configure_tx(&config) + .unwrap() + .with_pin(ctx.pin.reborrow()); + + #[cfg(rmt_has_tx_loop_auto_stop)] + let loopmode = LoopMode::Finite(LOOPS); + #[cfg(not(rmt_has_tx_loop_auto_stop))] + let loopmode = LoopMode::InfiniteWithInterrupt(LOOPS); + + let start = Instant::now(); + let tx_transaction = tx_channel + .transmit_continuously(&tx_data, loopmode) + .unwrap(); + + while !tx_transaction.is_loopcount_interrupt_set() {} + let elapsed_us = start.elapsed().as_micros(); + + tx_transaction.stop_next().unwrap(); + + assert!( + elapsed_us * 10 >= expected_us * 9 && elapsed_us * 10 <= expected_us * 11, + "unexpected tx duration: {} us (expected {} us)", + elapsed_us, + expected_us + ); + } + } + // Test that using loopcount 0 doesn't hang, but returns success immediately. #[cfg(rmt_has_tx_loop_auto_stop)] #[test] @@ -1285,4 +1404,37 @@ mod tests { ) .await; } + + // Repeated transactions on the same channels are required to trigger some of the issues with + // slow SCLK. + #[test] + #[timeout(10)] + fn rmt_dividers(mut ctx: Context) { + for &sclk_div in SCLK_DIVIDERS { + for &ch_div in CHANNEL_DIVIDERS { + let conf = divider_loopback_config(sclk_div, ch_div); + + let (mut tx_channel, mut rx_channel) = ctx.setup_loopback(&conf); + for _ in 0..3 { + (tx_channel, rx_channel) = + do_rmt_loopback_inner(&conf, tx_channel, rx_channel).unwrap(); + } + } + } + } + + #[test] + #[timeout(10)] + async fn rmt_dividers_async(mut ctx: Context) { + for &sclk_div in SCLK_DIVIDERS { + for &ch_div in CHANNEL_DIVIDERS { + let conf = divider_loopback_config(sclk_div, ch_div); + + let (mut tx_channel, mut rx_channel) = ctx.setup_loopback_async(&conf); + for _ in 0..3 { + do_rmt_loopback_async_inner(&conf, &mut tx_channel, &mut rx_channel).await; + } + } + } + } } diff --git a/hil-test/src/bin/sdm.rs b/hil-test/src/bin/sdm.rs index 498bf8ea472..4dfd112bd32 100644 --- a/hil-test/src/bin/sdm.rs +++ b/hil-test/src/bin/sdm.rs @@ -13,7 +13,7 @@ use esp_hal::{ Blocking, delay::Delay, - gpio::{AnyPin, Level, Output, OutputConfig, interconnect::PeripheralInput}, + gpio::{AnyPin, Level, interconnect::PeripheralInput}, peripherals::{RMT, SDM_CH0}, rmt::{CHANNEL_RAM_SIZE, Channel, PulseCode, Rmt, Rx, RxChannelConfig, RxChannelCreator}, sdm::{Channel as SdmChannel, ChannelConfig}, @@ -22,7 +22,7 @@ use esp_hal::{ use hil_test as _; // Configure a 1 MHz RMT clock on every supported chip. -const RMT_DIVIDER: u8 = if cfg!(esp32h2) { 32 } else { 80 }; +const RMT_DIVIDER: u8 = if cfg!(any(esp32h2, esp32h4)) { 32 } else { 80 }; const RMT_FREQUENCY: Rate = Rate::from_mhz(RMT_DIVIDER as u32); const SDM_FREQUENCY: Rate = Rate::from_khz(500); @@ -168,11 +168,14 @@ fn high_ratio_per_mille(data: &[PulseCode], count: usize) -> u32 { let mut low = 0_u32; let mut remaining = SAMPLE_TIME_US; - for code in data.iter().take(count) { - if code.length1() != 0 { - let length = u32::from(code.length1()).min(remaining); + 'pulses: for code in data.iter().take(count) { + for (level, length) in [ + (code.level1(), code.length1()), + (code.level2(), code.length2()), + ] { + let length = u32::from(length).min(remaining); - if code.level1() == Level::High { + if level == Level::High { high += length; } else { low += length; @@ -180,22 +183,7 @@ fn high_ratio_per_mille(data: &[PulseCode], count: usize) -> u32 { remaining -= length; if remaining == 0 { - break; - } - } - - if code.length2() != 0 { - let length = u32::from(code.length2()).min(remaining); - - if code.level2() == Level::High { - high += length; - } else { - low += length; - } - - remaining -= length; - if remaining == 0 { - break; + break 'pulses; } } } @@ -213,7 +201,7 @@ fn measure_high_ratio(ctx: &mut Context, duty: u8) -> Measurement { .with_frequency(SDM_FREQUENCY) .unwrap() .with_duty(duty); - let channel = SdmChannel::new(ctx.sdm_ch0.reborrow(), ctx.sdm_pin.reborrow(), config); + let mut channel = SdmChannel::new(ctx.sdm_ch0.reborrow(), ctx.sdm_pin.reborrow(), config); Delay::new().delay_micros(SDM_WARM_UP_US); @@ -224,11 +212,8 @@ fn measure_high_ratio(ctx: &mut Context, duty: u8) -> Measurement { Delay::new().delay_micros(SAMPLE_TIME_US); - drop(channel); - let mut output = Output::new(ctx.sdm_pin.reborrow(), Level::Low, OutputConfig::default()); - output.set_low(); // send idle signal so that RMT will stop recording pulses - + channel.set_duty(0); let (count, _rx_channel) = rx_transaction.wait().unwrap(); Measurement::new(&rx_data, count) diff --git a/hil-test/src/bin/spi.rs b/hil-test/src/bin/spi.rs index f7f6b4915f2..7df78e2a9bf 100644 --- a/hil-test/src/bin/spi.rs +++ b/hil-test/src/bin/spi.rs @@ -13,9 +13,11 @@ use embedded_hal::spi::SpiBus; use embedded_hal_async::spi::SpiBus as SpiBusAsync; use esp_hal::{ Blocking, - gpio::Input, - spi::master::{Config, Spi}, - time::Rate, + spi::{ + Mode, + master::{Config, Spi}, + }, + time::{Duration, Instant, Rate}, }; use hil_test as _; @@ -25,8 +27,6 @@ cfg_select! { use allocator_api2::vec::Vec; #[cfg(all(spi_master_supports_dma, pcnt_driver_supported))] use esp_hal::Async; - #[cfg(pcnt_driver_supported)] - use esp_hal::pcnt::{Pcnt, channel::EdgeMode, unit::Unit}; #[cfg(spi_master_supports_dma)] use esp_hal::{ dma::{DmaDescriptor, DmaRxBuf, DmaTxBuf, aligned::DmaAlignedMut}, @@ -36,6 +36,11 @@ cfg_select! { gpio::{Level, NoPin}, spi::master::SpiDma, }; + #[cfg(pcnt_driver_supported)] + use esp_hal::{ + gpio::Input, + pcnt::{channel::EdgeMode, unit::Unit}, + }; use esp_hal::{ peripherals::SPI2, spi::master::{Address, Command, DataMode}, @@ -44,6 +49,20 @@ cfg_select! { _ => {} } +#[cfg(soc_clock_node_spi_function_clock_is_configurable)] +use esp_hal::spi::master::ClockSource; + +fn half_duplex_config() -> Config { + let config = Config::default() + .with_frequency(Rate::from_khz(100)) + .with_mode(Mode::_0); + + #[cfg(soc_clock_node_spi_function_clock_is_configurable)] + let config = config.with_clock_source(ClockSource::Xtal); + + config +} + #[cfg(all(spi_master_supports_dma, feature = "unstable"))] type DmaChannel<'a> = cfg_select! { spi_master_dma_engine = "SPI_DMA" => { @@ -73,12 +92,13 @@ struct Context { #[cfg(all(spi_master_supports_dma, feature = "unstable"))] tx_descriptors: &'static mut [DmaDescriptor], + #[cfg(all(pcnt_driver_supported, feature = "unstable"))] miso_input: Input<'static>, #[cfg(all(pcnt_driver_supported, feature = "unstable"))] sclk_input: Input<'static>, #[cfg(all(pcnt_driver_supported, feature = "unstable"))] - pcnt_unit: Unit<'static, 0>, + pcnt_unit: Unit<'static>, } #[cfg(all(pcnt_driver_supported, feature = "unstable"))] @@ -310,15 +330,14 @@ mod tests { let sclk = hil_test::unconnected_pin!(peripherals); // A bit ugly but the peripheral interconnect APIs aren't yet stable. - let miso_input = unsafe { miso.clone_unchecked() }; - #[cfg(all(pcnt_driver_supported, feature = "unstable"))] - let sclk_input = unsafe { sclk.clone_unchecked() }; - - // Will be used later to detect edges directly or through PCNT. - let miso_input = Input::new(miso_input, Default::default()); - + // Will be used later to detect edges through PCNT. #[cfg(all(pcnt_driver_supported, feature = "unstable"))] - let sclk_input = Input::new(sclk_input, Default::default()); + let (miso_input, sclk_input) = unsafe { + ( + Input::new(miso.clone_unchecked(), Default::default()), + Input::new(sclk.clone_unchecked(), Default::default()), + ) + }; #[cfg(all(spi_master_supports_dma, feature = "unstable"))] let dma_channel = cfg_select! { @@ -356,6 +375,7 @@ mod tests { spi, rx_buffer, tx_buffer, + #[cfg(pcnt_driver_supported)] miso_input, #[cfg(pcnt_driver_supported)] sclk_input, @@ -366,17 +386,30 @@ mod tests { #[cfg(spi_master_supports_dma)] tx_descriptors, #[cfg(pcnt_driver_supported)] - pcnt_unit: Pcnt::new(peripherals.PCNT).unit0, + pcnt_unit: Unit::new(peripherals.PCNT0_UNIT0), }, _ => Context { spi, rx_buffer, tx_buffer, - miso_input, }, } } + #[test] + fn max_output_frequency_is_attainable_by_default(mut ctx: Context) { + let max_mhz = cfg_select! { + any(esp32, esp32c2) => 40, + any(esp32h2, esp32h4) => 48, // and H21 + any( + esp32c3, esp32c5, esp32c6, esp32c61, esp32p4, esp32s2, esp32s3, esp32s31 + ) => 80, + }; + ctx.spi + .apply_config(&Config::default().with_frequency(Rate::from_mhz(max_mhz))) + .unwrap(); + } + #[test] fn test_symmetric_transfer(mut ctx: Context) { let write = [0xde, 0xad, 0xbe, 0xef]; @@ -512,8 +545,13 @@ mod tests { let mut spi = ctx.spi.into_async(); // Slow down SCLK so that transferring the buffer takes a while. - spi.apply_config(&Config::default().with_frequency(Rate::from_khz(80))) - .expect("Apply config failed"); + spi.apply_config(&{ + let config = Config::default().with_frequency(Rate::from_khz(80)); + #[cfg(soc_clock_node_spi_function_clock_is_configurable)] + let config = config.with_clock_source(ClockSource::Xtal); + config + }) + .expect("Apply config failed"); SpiBus::write(&mut spi, &write[..]).expect("Sync write failed"); SpiBusAsync::write(&mut spi, &write[..]) @@ -759,7 +797,7 @@ mod tests { // Test logic fn test_write( spi: &mut SpiDma<'_, Blocking>, - miso_pulse_counter: &Unit<'_, 0>, + miso_pulse_counter: &Unit<'_>, tx_buf: &mut [u8], rx_buf: &mut [u8], ) { @@ -876,7 +914,7 @@ mod tests { async fn test_write( spi: &mut SpiDma<'_, Async>, - miso_pulse_counter: &Unit<'_, 0>, + miso_pulse_counter: &Unit<'_>, tx_buf: &mut [u8], rx_buf: &mut [u8], ) { @@ -919,7 +957,7 @@ mod tests { async fn test_transfer( spi: &mut SpiDma<'_, Async>, - miso_pulse_counter: &Unit<'_, 0>, + miso_pulse_counter: &Unit<'_>, tx_buf: &mut [u8], rx_buf: &mut [u8], ) { @@ -991,47 +1029,86 @@ mod tests { assert_eq!(&[0xff, 0xff, 0xff, 0xff], dma_rx_buf.as_slice()); } - #[test] - async fn cancel_stops_basic_async_spi_transfer(mut ctx: Context) { - // Slow down. We don't rely on the transfer speed much, just that it's slow - // enough that we can detect pulses if cancelling the future leaves the - // transfer running. + async fn check_cancel_stops_basic_async_spi( + mut ctx: Context, + op: impl AsyncFnOnce(&mut Spi<'static, esp_hal::Async>, &mut [u8], &mut [u8]), + ) { + use embassy_futures::select::{Either, select}; + + // At 100 kHz, a 64-byte FIFO chunk takes ~5.12 ms. Cancelling after 500 µs + // leaves ~4.6 ms of that chunk if cancelling does not abort it. ctx.spi - .apply_config(&Config::default().with_frequency(Rate::from_khz(800))) + .apply_config(&{ + let config = Config::default().with_frequency(Rate::from_khz(100)); + #[cfg(soc_clock_node_spi_function_clock_is_configurable)] + let config = config.with_clock_source(ClockSource::Xtal); + config + }) .unwrap(); let mut spi = ctx.spi.into_async(); - for i in 0..ctx.tx_buffer.len() { - ctx.tx_buffer[i] = (i % 256) as u8; - } - - let transfer = spi.transfer_in_place_async(ctx.tx_buffer); - - // Wait for a bit before cancelling let cancel = async { - for _ in 0..100 { + let start = Instant::now(); + while start.elapsed() < Duration::from_micros(500) { embassy_futures::yield_now().await; } }; + let result = select(op(&mut spi, ctx.rx_buffer, ctx.tx_buffer), cancel).await; + assert!( + matches!(result, Either::Second(_)), + "Operation was not cancelled" + ); - embassy_futures::select::select(transfer, cancel).await; + // A transfer waits for the peripheral to become idle before it starts. If a + // chunk was left over, its rest (~4.6 ms) is clocked out before this transfer's + // own ~320 µs. That is true whether the chunk kept running, or was frozen + // because releasing the clock guard turned off the SPI function clock. + let write = [0xde, 0xad, 0xbe, 0xef]; + let mut read = [0x00; 4]; + let start = Instant::now(); + SpiBusAsync::transfer(&mut spi, &mut read, &write) + .await + .expect("Transfer after cancel failed"); + let elapsed = start.elapsed(); + assert_eq!(write, read); + assert!( + elapsed < Duration::from_millis(2), + "Transfer after cancel took too long ({:?}), leftover chunk was not aborted", + elapsed + ); + } - // Listen for a while to see if the SPI peripheral correctly stopped. - let detect_edge = ctx.miso_input.wait_for_any_edge(); - let wait = async { - for _ in 0..10000 { - embassy_futures::yield_now().await; - } - }; + #[test] + async fn cancel_stops_basic_async_spi_transfer_in_place(ctx: Context) { + check_cancel_stops_basic_async_spi(ctx, async |spi, _rx, tx| { + SpiBusAsync::transfer_in_place(spi, tx).await.unwrap(); + }) + .await; + } - let result = embassy_futures::select::select(detect_edge, wait).await; + #[test] + async fn cancel_stops_basic_async_spi_transfer(ctx: Context) { + check_cancel_stops_basic_async_spi(ctx, async |spi, rx, tx| { + SpiBusAsync::transfer(spi, rx, tx).await.unwrap(); + }) + .await; + } - // Assert that we timed out - we should not have detected any edges - assert!( - matches!(result, embassy_futures::select::Either::Second(_)), - "Detected edge after cancellation" - ); + #[test] + async fn cancel_stops_basic_async_spi_write(ctx: Context) { + check_cancel_stops_basic_async_spi(ctx, async |spi, _rx, tx| { + SpiBusAsync::write(spi, tx).await.unwrap(); + }) + .await; + } + + #[test] + async fn cancel_stops_basic_async_spi_read(ctx: Context) { + check_cancel_stops_basic_async_spi(ctx, async |spi, rx, _tx| { + SpiBusAsync::read(spi, rx).await.unwrap(); + }) + .await; } #[test] @@ -1041,7 +1118,12 @@ mod tests { // This means that without working cancellation, the test case should // fail. ctx.spi - .apply_config(&Config::default().with_frequency(Rate::from_khz(80))) + .apply_config(&{ + let config = Config::default().with_frequency(Rate::from_khz(80)); + #[cfg(soc_clock_node_spi_function_clock_is_configurable)] + let config = config.with_clock_source(ClockSource::Xtal); + config + }) .unwrap(); // Set up a large buffer that would trigger a timeout @@ -1073,7 +1155,12 @@ mod tests { // Slow down. At 80kHz, the transfer is supposed to take a bit over 3 seconds. ctx.spi - .apply_config(&Config::default().with_frequency(Rate::from_khz(80))) + .apply_config(&{ + let config = Config::default().with_frequency(Rate::from_khz(80)); + #[cfg(soc_clock_node_spi_function_clock_is_configurable)] + let config = config.with_clock_source(ClockSource::Xtal); + config + }) .unwrap(); // Set up a large buffer that would trigger a timeout @@ -1176,7 +1263,12 @@ mod tests { let sclk_counter = set_up_pcnt!(ctx, sclk_input); ctx.spi - .apply_config(&Config::default().with_frequency(Rate::from_khz(80))) + .apply_config(&{ + let config = Config::default().with_frequency(Rate::from_khz(80)); + #[cfg(soc_clock_node_spi_function_clock_is_configurable)] + let config = config.with_clock_source(ClockSource::Xtal); + config + }) .unwrap(); // 320 clock cycles @@ -1261,7 +1353,12 @@ mod tests { let sclk_counter = set_up_pcnt!(ctx, sclk_input); ctx.spi - .apply_config(&Config::default().with_frequency(Rate::from_khz(80))) + .apply_config(&{ + let config = Config::default().with_frequency(Rate::from_khz(80)); + #[cfg(soc_clock_node_spi_function_clock_is_configurable)] + let config = config.with_clock_source(ClockSource::Xtal); + config + }) .unwrap(); // 32 clock cycles @@ -1374,7 +1471,7 @@ mod tests { check_typical_values(&mut ctx, SpiFunctionClockConfig::Xtal); #[cfg(esp32c2)] check_typical_values(&mut ctx, SpiFunctionClockConfig::Pll40m); - #[cfg(esp32h2)] + #[cfg(any(esp32h2, esp32h4))] check_typical_values(&mut ctx, SpiFunctionClockConfig::PllF48m); #[cfg(esp32c3)] check_typical_values(&mut ctx, SpiFunctionClockConfig::Pll80m); @@ -1384,6 +1481,10 @@ mod tests { check_typical_values(&mut ctx, SpiFunctionClockConfig::PllF120m); #[cfg(any(esp32c5, esp32c61))] check_typical_values(&mut ctx, SpiFunctionClockConfig::PllF160m); + #[cfg(esp32p4)] + check_typical_values(&mut ctx, SpiFunctionClockConfig::Spll); + #[cfg(esp32s31)] + check_typical_values(&mut ctx, SpiFunctionClockConfig::Bbpll); } } @@ -1391,13 +1492,8 @@ mod tests { #[embedded_test::tests(default_timeout = 10)] mod psram_dma { use esp_hal::{ - Blocking, dma::ExternalBurstConfig, - spi::{ - Mode, - master::{Config, Spi, SpiDma}, - }, - time::Rate, + spi::master::{Spi, SpiDma}, }; use hil_test as _; @@ -1423,17 +1519,12 @@ mod psram_dma { spi_master_dma_engine = "AXI_GDMA" => peripherals.DMA_AXI_CH0, }; - let spi = Spi::new( - peripherals.SPI2, - Config::default() - .with_frequency(Rate::from_khz(100)) - .with_mode(Mode::_0), - ) - .unwrap() - .with_sck(sclk) - .with_miso(miso) - .with_mosi(mosi) - .with_dma(dma_channel); + let spi = Spi::new(peripherals.SPI2, half_duplex_config()) + .unwrap() + .with_sck(sclk) + .with_miso(miso) + .with_mosi(mosi) + .with_dma(dma_channel); Context { spi } } @@ -1465,19 +1556,15 @@ mod half_duplex_write_psram { dma::ExternalBurstConfig, dma_rx_buffer, gpio::{Flex, interconnect::InputSignal}, - pcnt::{Pcnt, channel::EdgeMode, unit::Unit}, - spi::{ - Mode, - master::{Address, Command, Config, DataMode, Spi, SpiDma}, - }, - time::Rate, + pcnt::{channel::EdgeMode, unit::Unit}, + spi::master::{Address, Command, DataMode, Spi, SpiDma}, }; use super::*; struct Context { spi: SpiDma<'static, Blocking>, - pcnt_unit: Unit<'static, 0>, + pcnt_unit: Unit<'static>, pcnt_source: InputSignal<'static>, } @@ -1491,8 +1578,6 @@ mod half_duplex_write_psram { let sclk = peripherals.GPIO0; let (mosi, _) = hil_test::common_test_pins!(peripherals); - let pcnt = Pcnt::new(peripherals.PCNT); - let dma_channel = cfg_select! { spi_master_dma_engine = "SPI_DMA" => peripherals.DMA_SPI2, spi_master_dma_engine = "AHB_GDMA" => peripherals.DMA_CH0, @@ -1504,20 +1589,15 @@ mod half_duplex_write_psram { mosi.set_output_enable(true); let mosi_loopback = mosi.peripheral_input(); - let spi = Spi::new( - peripherals.SPI2, - Config::default() - .with_frequency(Rate::from_khz(100)) - .with_mode(Mode::_0), - ) - .unwrap() - .with_sck(sclk) - .with_sio0(mosi) - .with_dma(dma_channel); + let spi = Spi::new(peripherals.SPI2, half_duplex_config()) + .unwrap() + .with_sck(sclk) + .with_sio0(mosi) + .with_dma(dma_channel); Context { spi, - pcnt_unit: pcnt.unit0, + pcnt_unit: Unit::new(peripherals.PCNT0_UNIT0), pcnt_source: mosi_loopback, } } @@ -1609,17 +1689,14 @@ mod half_duplex_write_psram { #[embedded_test::tests(default_timeout = 3, executor = hil_test::Executor::new())] mod read { + #[cfg(spi_master_supports_dma)] + use esp_hal::{dma_rx_buffer, dma_tx_buffer}; use esp_hal::{ - Blocking, gpio::{Level, Output, OutputConfig}, - spi::{ - Mode, - master::{Address, Command, Config, DataMode, Spi}, - }, - time::Rate, + spi::master::{Address, Command, DataMode, Spi}, }; - #[cfg(spi_master_supports_dma)] - use esp_hal::{dma_rx_buffer, dma_tx_buffer}; + + use super::*; #[cfg(spi_master_supports_dma)] type DmaChannel<'a> = cfg_select! { @@ -1657,15 +1734,10 @@ mod read { spi_master_dma_engine = "AXI_GDMA" => peripherals.DMA_AXI_CH0, }; - let spi = Spi::new( - peripherals.SPI2, - Config::default() - .with_frequency(Rate::from_khz(100)) - .with_mode(Mode::_0), - ) - .unwrap() - .with_sck(sclk) - .with_miso(miso); + let spi = Spi::new(peripherals.SPI2, half_duplex_config()) + .unwrap() + .with_sck(sclk) + .with_miso(miso); Context { spi, @@ -1831,6 +1903,57 @@ mod read { assert_eq!(buffer.as_slice(), &[0xFF; DMA_BUFFER_SIZE]); } + /// A DMA transfer must not leave the descriptor link armed. + /// + /// PDMA chips (ESP32, ESP32-S2) have no DMA enable bit in `dma_conf`: the + /// peripheral reads from the descriptors instead of the FIFO for as long as + /// a link is armed, so `disable_dma` has to clear them. Without that, the + /// CPU-driven transfer that follows a DMA transfer is routed into the + /// previous transfer's descriptors: the received data lands in the DMA + /// buffer and the CPU reads back the bytes it just wrote into the FIFO. + /// + /// Note that a plain loopback cannot catch this. There the CPU transfer + /// reads back what it wrote whether or not the link is stale, which is why + /// this drives MISO to a level of its own and flips it between the two + /// transfers. A transfer that is really sampling the pin follows the flip; + /// one that is reading a stale FIFO cannot, and echoes `CPU_TX` instead. + #[test] + #[cfg(spi_master_supports_dma)] + fn cpu_transfer_works_after_dma_transfer(mut ctx: Context) { + const CPU_LEN: usize = 4; + const DMA_LEN: usize = 64; + /// Distinct from both mirror levels, so a stale FIFO cannot look like a + /// correctly sampled pin. + const CPU_TX: [u8; CPU_LEN] = [0xde, 0xad, 0xbe, 0xef]; + + // Transfers shorter than this are driven by the CPU. + ctx.spi + .apply_config(&half_duplex_config().with_min_async_transfer_size(CPU_LEN + 1)) + .unwrap(); + + let mut spi = ctx.spi.with_dma(ctx.dma_channel).with_buffers( + dma_rx_buffer!(DMA_LEN).unwrap(), + dma_tx_buffer!(DMA_LEN).unwrap(), + ); + + for (dma_level, cpu_level) in [(Level::Low, Level::High), (Level::High, Level::Low)] { + let dma_expected = if dma_level == Level::High { 0xFF } else { 0x00 }; + let cpu_expected = if cpu_level == Level::High { 0xFF } else { 0x00 }; + + // Long enough to go through DMA, which arms the link. + ctx.miso_mirror.set_level(dma_level); + let mut dma_rx = [0xAA; DMA_LEN]; + spi.transfer(&mut dma_rx, &[0x00; DMA_LEN]).unwrap(); + assert_eq!(dma_rx.as_slice(), &[dma_expected; DMA_LEN]); + + // Below the threshold, so this one goes through the FIFO. + ctx.miso_mirror.set_level(cpu_level); + let mut cpu_rx = [0xAA; CPU_LEN]; + spi.transfer(&mut cpu_rx, &CPU_TX).unwrap(); + assert_eq!(cpu_rx.as_slice(), &[cpu_expected; CPU_LEN]); + } + } + #[test] #[cfg(spi_master_supports_dma)] fn data_mode_combinations_are_not_rejected(ctx: Context) { @@ -1886,18 +2009,15 @@ mod read { #[cfg(pcnt_driver_supported)] #[embedded_test::tests(default_timeout = 3, executor = hil_test::Executor::new())] mod write { + #[cfg(spi_master_supports_dma)] + use esp_hal::{dma_rx_buffer, dma_tx_buffer}; use esp_hal::{ - Blocking, gpio::{Flex, interconnect::InputSignal}, - pcnt::{Pcnt, channel::EdgeMode, unit::Unit}, - spi::{ - Mode, - master::{Address, Command, Config, DataMode, Spi}, - }, - time::Rate, + pcnt::{channel::EdgeMode, unit::Unit}, + spi::master::{Address, Command, DataMode, Spi}, }; - #[cfg(spi_master_supports_dma)] - use esp_hal::{dma_rx_buffer, dma_tx_buffer}; + + use super::*; #[cfg(spi_master_supports_dma)] type DmaChannel<'a> = cfg_select! { @@ -1914,9 +2034,9 @@ mod write { struct Context { spi: Spi<'static, Blocking>, - pcnt_unit: Unit<'static, 0>, + pcnt_unit: Unit<'static>, pcnt_source: InputSignal<'static>, - cs_unit: Unit<'static, 1>, + cs_unit: Unit<'static>, cs_source: InputSignal<'static>, #[cfg(spi_master_supports_dma)] @@ -1930,8 +2050,6 @@ mod write { let (mosi, _) = hil_test::common_test_pins!(peripherals); let (sclk, cs) = hil_test::i2c_pins!(peripherals); - let pcnt = Pcnt::new(peripherals.PCNT); - #[cfg(spi_master_supports_dma)] let dma_channel = cfg_select! { spi_master_dma_engine = "SPI_DMA" => peripherals.DMA_SPI2, @@ -1949,22 +2067,17 @@ mod write { cs.set_output_enable(true); let cs_loopback = cs.peripheral_input(); - let spi = Spi::new( - peripherals.SPI2, - Config::default() - .with_frequency(Rate::from_khz(100)) - .with_mode(Mode::_0), - ) - .unwrap() - .with_sck(sclk) - .with_sio0(mosi) - .with_cs(cs); + let spi = Spi::new(peripherals.SPI2, half_duplex_config()) + .unwrap() + .with_sck(sclk) + .with_sio0(mosi) + .with_cs(cs); Context { spi, - pcnt_unit: pcnt.unit0, + pcnt_unit: Unit::new(peripherals.PCNT0_UNIT0), pcnt_source: mosi_loopback, - cs_unit: pcnt.unit1, + cs_unit: Unit::new(peripherals.PCNT0_UNIT1), cs_source: cs_loopback, #[cfg(spi_master_supports_dma)] dma_channel, @@ -2162,13 +2275,14 @@ mod write { #[cfg(any(feature = "unstable", spi_slave_driver_supported))] #[cfg(spi_slave_supports_dma)] mod spi_slave { + #[cfg(spi_slave_supports_dma)] + use esp_hal::{dma_rx_buffer, dma_tx_buffer}; use esp_hal::{ - Blocking, gpio::{Flex, Input, InputConfig, Level, OutputConfig, Pull}, spi::{Mode, slave::Spi}, }; - #[cfg(spi_slave_supports_dma)] - use esp_hal::{dma_rx_buffer, dma_tx_buffer}; + + use super::*; #[cfg(spi_slave_supports_dma)] type DmaChannel<'a> = cfg_select! { @@ -2341,22 +2455,19 @@ mod qspi_dma { #[cfg(pcnt_driver_supported)] use esp_hal::{ Async, - pcnt::{Pcnt, channel::EdgeMode, unit::Unit}, - peripherals::PCNT, + pcnt::{channel::EdgeMode, unit::Unit}, + peripherals::{PCNT0_UNIT0, PCNT0_UNIT1}, }; use esp_hal::{ - Blocking, dma::{DmaRxBuf, DmaTxBuf}, dma_rx_buffer, dma_tx_buffer, gpio::{AnyPin, Input, InputConfig, Level, Output, OutputConfig, Pull}, - spi::{ - Mode, - master::{Address, Command, Config, DataMode, Spi, SpiDma}, - }, - time::Rate, + spi::master::{Address, Command, Config, DataMode, Spi, SpiDma}, }; + use super::*; + type DmaChannel0<'a> = cfg_select! { spi_master_dma_engine = "SPI_DMA" => { esp_hal::peripherals::DMA_SPI2<'a> @@ -2384,7 +2495,9 @@ mod qspi_dma { struct Context { spi: Spi<'static, Blocking>, #[cfg(pcnt_driver_supported)] - pcnt: PCNT<'static>, + pcnt_u0: PCNT0_UNIT0<'static>, + #[cfg(pcnt_driver_supported)] + pcnt_u1: PCNT0_UNIT1<'static>, dma_channel: DmaChannel0<'static>, gpios: [AnyPin<'static>; 3], } @@ -2490,8 +2603,8 @@ mod qspi_dma { #[cfg(pcnt_driver_supported)] fn execute_write( - unit0: Unit<'_, 0>, - unit1: Unit<'_, 1>, + unit0: Unit<'_>, + unit1: Unit<'_>, mut spi: SpiUnderTest<'_>, write: u8, data_on_multiple_pins: bool, @@ -2538,8 +2651,8 @@ mod qspi_dma { #[cfg(pcnt_driver_supported)] async fn execute_write_async( - unit0: Unit<'_, 0>, - unit1: Unit<'_, 1>, + unit0: Unit<'_>, + unit1: Unit<'_>, mut spi: SpiDma<'_, esp_hal::Async>, write: u8, data_on_multiple_pins: bool, @@ -2605,8 +2718,8 @@ mod qspi_dma { #[cfg(pcnt_driver_supported)] fn execute_write_with_cpu( - unit0: Unit<'_, 0>, - unit1: Unit<'_, 1>, + unit0: Unit<'_>, + unit1: Unit<'_>, mut spi: Spi<'_, Blocking>, write: u8, data_on_multiple_pins: bool, @@ -2650,8 +2763,8 @@ mod qspi_dma { #[cfg(pcnt_driver_supported)] async fn execute_write_with_cpu_async( - unit0: Unit<'_, 0>, - unit1: Unit<'_, 1>, + unit0: Unit<'_>, + unit1: Unit<'_>, mut spi: Spi<'_, Async>, write: u8, data_on_multiple_pins: bool, @@ -2707,18 +2820,14 @@ mod qspi_dma { spi_master_dma_engine = "AXI_GDMA" => peripherals.DMA_AXI_CH0, }; - let spi = Spi::new( - peripherals.SPI2, - Config::default() - .with_frequency(Rate::from_khz(100)) - .with_mode(Mode::_0), - ) - .unwrap(); + let spi = Spi::new(peripherals.SPI2, half_duplex_config()).unwrap(); Context { spi, #[cfg(pcnt_driver_supported)] - pcnt: peripherals.PCNT, + pcnt_u0: peripherals.PCNT0_UNIT0, + #[cfg(pcnt_driver_supported)] + pcnt_u1: peripherals.PCNT0_UNIT1, dma_channel, gpios: [pin.into(), pin_mirror.into(), unconnected_pin.into()], } @@ -2877,9 +2986,8 @@ mod qspi_dma { #[cfg(pcnt_driver_supported)] fn test_spi_writes_correctly_to_pin_0(ctx: Context) { let [_, _, mosi] = ctx.gpios; - let pcnt = Pcnt::new(ctx.pcnt); - let unit0 = pcnt.unit0; - let unit1 = pcnt.unit1; + let unit0 = Unit::new(ctx.pcnt_u0); + let unit1 = Unit::new(ctx.pcnt_u1); let mut mosi = Flex::new(mosi); mosi.set_input_enable(true); @@ -2901,9 +3009,8 @@ mod qspi_dma { const BUFFER_SIZE: usize = 4; let [_, _, mosi] = ctx.gpios; - let pcnt = Pcnt::new(ctx.pcnt); - let unit0 = pcnt.unit0; - let unit1 = pcnt.unit1; + let unit0 = Unit::new(ctx.pcnt_u0); + let unit1 = Unit::new(ctx.pcnt_u1); let mut mosi = Flex::new(mosi); mosi.set_input_enable(true); @@ -2934,7 +3041,8 @@ mod qspi_dma { test_spi_writes_correctly_to_pin_x( ctx.spi, ctx.dma_channel, - ctx.pcnt, + ctx.pcnt_u0, + ctx.pcnt_u1, gpio, mosi, |spi, sio_n| spi.with_sio1(sio_n), @@ -2949,7 +3057,8 @@ mod qspi_dma { test_spi_writes_correctly_to_pin_x( ctx.spi, ctx.dma_channel, - ctx.pcnt, + ctx.pcnt_u0, + ctx.pcnt_u1, gpio, mosi, |spi, sio_n| spi.with_sio2(sio_n), @@ -2964,7 +3073,8 @@ mod qspi_dma { test_spi_writes_correctly_to_pin_x( ctx.spi, ctx.dma_channel, - ctx.pcnt, + ctx.pcnt_u0, + ctx.pcnt_u1, gpio, mosi, |spi, sio_n| spi.with_sio3(sio_n), @@ -2976,15 +3086,15 @@ mod qspi_dma { fn test_spi_writes_correctly_to_pin_x( spi: Spi<'_, Blocking>, dma_channel: DmaChannel0<'_>, - pcnt: PCNT<'_>, + pcnt_u0: PCNT0_UNIT0<'_>, + pcnt_u1: PCNT0_UNIT1<'_>, gpio: AnyPin<'_>, mosi: AnyPin<'_>, set_pin: impl for<'a> FnOnce(Spi<'a, Blocking>, Flex<'a>) -> Spi<'a, Blocking>, write: u8, ) { - let pcnt = Pcnt::new(pcnt); - let unit0 = pcnt.unit0; - let unit1 = pcnt.unit1; + let unit0 = Unit::new(pcnt_u0); + let unit1 = Unit::new(pcnt_u1); let mut mosi = Flex::new(mosi); mosi.set_input_enable(true); @@ -3014,9 +3124,8 @@ mod qspi_dma { #[cfg(pcnt_driver_supported)] fn test_spi_writes_correctly_to_pin_0_with_cpu(ctx: Context) { let [_, _, mosi] = ctx.gpios; - let pcnt = Pcnt::new(ctx.pcnt); - let unit0 = pcnt.unit0; - let unit1 = pcnt.unit1; + let unit0 = Unit::new(ctx.pcnt_u0); + let unit1 = Unit::new(ctx.pcnt_u1); let mut mosi = Flex::new(mosi); mosi.set_input_enable(true); @@ -3036,9 +3145,8 @@ mod qspi_dma { #[cfg(pcnt_driver_supported)] async fn test_spi_writes_correctly_to_pin_0_with_cpu_async(ctx: Context) { let [_, _, mosi] = ctx.gpios; - let pcnt = Pcnt::new(ctx.pcnt); - let unit0 = pcnt.unit0; - let unit1 = pcnt.unit1; + let unit0 = Unit::new(ctx.pcnt_u0); + let unit1 = Unit::new(ctx.pcnt_u1); let mut mosi = Flex::new(mosi); mosi.set_input_enable(true); @@ -3060,7 +3168,8 @@ mod qspi_dma { let [gpio, _, mosi] = ctx.gpios; test_spi_writes_correctly_to_pin_x_with_cpu( ctx.spi, - ctx.pcnt, + ctx.pcnt_u0, + ctx.pcnt_u1, gpio, mosi, |spi, sio_n| spi.with_sio1(sio_n), @@ -3074,7 +3183,8 @@ mod qspi_dma { let [gpio, _, mosi] = ctx.gpios; test_spi_writes_correctly_to_pin_x_with_cpu( ctx.spi, - ctx.pcnt, + ctx.pcnt_u0, + ctx.pcnt_u1, gpio, mosi, |spi, sio_n| spi.with_sio2(sio_n), @@ -3088,7 +3198,8 @@ mod qspi_dma { let [gpio, _, mosi] = ctx.gpios; test_spi_writes_correctly_to_pin_x_with_cpu( ctx.spi, - ctx.pcnt, + ctx.pcnt_u0, + ctx.pcnt_u1, gpio, mosi, |spi, sio_n| spi.with_sio3(sio_n), @@ -3099,15 +3210,15 @@ mod qspi_dma { #[cfg(pcnt_driver_supported)] fn test_spi_writes_correctly_to_pin_x_with_cpu( spi: Spi<'_, Blocking>, - pcnt: PCNT<'_>, + pcnt_u0: PCNT0_UNIT0<'_>, + pcnt_u1: PCNT0_UNIT1<'_>, gpio: AnyPin<'_>, mosi: AnyPin<'_>, set_pin: impl for<'a> FnOnce(Spi<'a, Blocking>, Flex<'a>) -> Spi<'a, Blocking>, write: u8, ) { - let pcnt = Pcnt::new(pcnt); - let unit0 = pcnt.unit0; - let unit1 = pcnt.unit1; + let unit0 = Unit::new(pcnt_u0); + let unit1 = Unit::new(pcnt_u1); let mut mosi = Flex::new(mosi); mosi.set_input_enable(true); diff --git a/hil-test/src/bin/storage.rs b/hil-test/src/bin/storage.rs deleted file mode 100644 index ed9a8f4a8ab..00000000000 --- a/hil-test/src/bin/storage.rs +++ /dev/null @@ -1,92 +0,0 @@ -//! esp-storage tests -//! -//! Assumes a certain (i.e. default) partition table layout. -//% CHIP_FILTER: soc_has_flash -//% FEATURES: unstable esp-storage -//% CARGO-CONFIG: target.'cfg(target_arch = "riscv32")'.rustflags = [ "--cfg=__test_esp_storage" ] -//% CARGO-CONFIG: target.'cfg(target_arch = "xtensa")'.rustflags = [ "--cfg=__test_esp_storage" ] - -#![no_std] -#![no_main] - -use esp_bootloader_esp_idf::EspAppDesc; -use esp_storage::FlashStorage; -use hil_test as _; - -#[embedded_test::tests(default_timeout = 3)] -mod tests { - use super::*; - - fn flash_from_peripherals( - peripherals: esp_hal::peripherals::Peripherals, - ) -> FlashStorage<'static> { - let flash = FlashStorage::new(peripherals.FLASH); - #[cfg(multi_core)] - let flash = flash.multicore_auto_park(); - flash - } - - // Test we place the app descriptor at the right position in the image and we - // can read it - #[test] - fn test_can_read_app_desc() { - let peripherals = esp_hal::init(esp_hal::Config::default()); - - let mut bytes = [0u8; 256]; - - let mut flash = flash_from_peripherals(peripherals); - - // esp-idf 2nd stage bootloader would expect the app-descriptor at the start of - // DROM it also expects DROM segment to the the first page of the - // app-image and we need to account for the image header - so we end up - // with flash-address 0x10_000 + 0x20 - flash.read(0x10_020, &mut bytes).unwrap(); - - assert_eq!(&bytes, unsafe { - core::mem::transmute::<&EspAppDesc, &[u8; 256]>(&hil_test::ESP_APP_DESC) - }); - } - - #[test] - fn test_read_encrypted_same_as_unencrypted_wo_encryption_enabled() { - let peripherals = esp_hal::init(esp_hal::Config::default()); - - let mut bytes1 = [0u8; 256]; - let mut bytes2 = [0u8; 256]; - - let mut flash = flash_from_peripherals(peripherals); - - for offset in (0x10_000..0x20_000).step_by(128) { - flash.read(offset, &mut bytes1).unwrap(); - flash.read_encrypted(offset, &mut bytes2).unwrap(); - - // if encryption is not enabled we should read the same plain text - assert_eq!(&bytes1, &bytes2); - } - } - - #[test] - fn test_write_encrypted_will_encrypt() { - let peripherals = esp_hal::init(esp_hal::Config::default()); - - let mut bytes1 = [0u8; 256]; - let mut bytes2 = [0u8; 256]; - - let mut flash = flash_from_peripherals(peripherals); - - flash.write_encrypted(0x9000, &[0x0u8; 256]).unwrap(); - - flash.read(0x9000, &mut bytes1).unwrap(); - flash.read_encrypted(0x9000, &mut bytes2).unwrap(); - - // if encryption is not enabled we should read the same bytes in both cases - assert_eq!(&bytes1, &bytes2); - - // but encrypted write should do "something" to the data even w/o encryption actually - // enabled - assert_ne!(&bytes1, &[0x0u8; 256]); - - // overwrite NVS so the next time the test runs it actually needs to overwrite the data - flash.write(0x9000, &[0xffu8; 256]).unwrap(); - } -} diff --git a/hil-test/src/bin/uart.rs b/hil-test/src/bin/uart.rs index 28f82f611bc..0eb4e508430 100644 --- a/hil-test/src/bin/uart.rs +++ b/hil-test/src/bin/uart.rs @@ -29,11 +29,10 @@ mod tests { #[init] fn init() -> Context { - let config = - cfg_select! { - esp32s31 => esp_hal::Config::default(), - _ => esp_hal::Config::default().with_cpu_clock(esp_hal::clock::CpuClock::max()), - }; + let config = cfg_select! { + esp32s31 => esp_hal::Config::default(), + _ => esp_hal::Config::default().with_cpu_clock(esp_hal::clock::CpuClock::max()), + }; let peripherals = esp_hal::init(config); let (rx, tx) = hil_test::common_test_pins!(peripherals); @@ -161,13 +160,12 @@ mod tests { // working as expected. We will also using different clock sources // while we're at it. - let fastest_clock_source = - cfg_select! { - esp32c2 => ClockSource::PllF40m, - any(esp32c5, esp32c6, esp32c61, esp32p4, esp32s31) => ClockSource::PllF80m, - esp32h2 => ClockSource::PllF48m, - _ => ClockSource::Apb, - }; + let fastest_clock_source = cfg_select! { + esp32c2 => ClockSource::PllF40m, + any(esp32c5, esp32c6, esp32c61, esp32p4, esp32s31) => ClockSource::PllF80m, + any(esp32h2, esp32h4) => ClockSource::PllF48m, + _ => ClockSource::Apb, + }; let configs = [ #[cfg(not(soc_has_clock_node_ref_tick))] @@ -245,36 +243,12 @@ mod tests { } #[test] - fn test_break_detection(ctx: Context) { + fn test_break_detection_interleaved(ctx: Context) { let mut tx = ctx.uart0.split().1.with_tx(ctx.tx); let mut rx = ctx.uart1.split().0.with_rx(ctx.rx); - tx.send_break(100); - assert!(rx.wait_for_break_with_timeout(Duration::from_secs(1))); - } - - #[test] - fn test_break_detection_no_break(ctx: Context) { - let mut rx = ctx.uart1.split().0.with_rx(ctx.rx); - + // Initially, there is no break assert!(!rx.wait_for_break_with_timeout(Duration::from_millis(100))); - } - - #[test] - fn test_break_detection_multiple(ctx: Context) { - let mut tx = ctx.uart0.split().1.with_tx(ctx.tx); - let mut rx = ctx.uart1.split().0.with_rx(ctx.rx); - - for _ in 0..3 { - tx.send_break(100); - assert!(rx.wait_for_break_with_timeout(Duration::from_secs(1))); - } - } - - #[test] - fn test_break_detection_interleaved(ctx: Context) { - let mut tx = ctx.uart0.split().1.with_tx(ctx.tx); - let mut rx = ctx.uart1.split().0.with_rx(ctx.rx); // Test 1: Send break, expect detection tx.send_break(100); @@ -287,10 +261,7 @@ mod tests { tx.send_break(100); assert!(rx.wait_for_break_with_timeout(Duration::from_secs(1))); - // Test 4: Don't send break, expect timeout again - assert!(!rx.wait_for_break_with_timeout(Duration::from_millis(100))); - - // Test 5: Final break detection, expect detection + // Test 4: Repeat sending break, expect detection tx.send_break(100); assert!(rx.wait_for_break_with_timeout(Duration::from_secs(1))); } @@ -407,7 +378,7 @@ mod async_tests { Async, Blocking, interrupt::Priority, - peripherals::FROM_CPU_INTR1, + peripherals::FROM_CPU_INTR2, timer::timg::TimerGroup, uart::{self, Uart, UartRx}, }; @@ -415,7 +386,7 @@ mod async_tests { use hil_test::mk_static; struct Context { - interrupt: FROM_CPU_INTR1<'static>, + interrupt: FROM_CPU_INTR2<'static>, uart: Uart<'static, Async>, } @@ -453,10 +424,10 @@ mod async_tests { .into_async(); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); Context { - interrupt: peripherals.FROM_CPU_INTR1, + interrupt: peripherals.FROM_CPU_INTR2, uart, } } @@ -485,7 +456,7 @@ mod async_tests { let (rx, mut tx) = ctx.uart.into_blocking().split(); let interrupt_executor = - mk_static!(InterruptExecutor<1>, InterruptExecutor::new(ctx.interrupt)); + mk_static!(InterruptExecutor<2>, InterruptExecutor::new(ctx.interrupt)); let signal = &*mk_static!(Signal, Signal::new()); @@ -569,7 +540,7 @@ mod async_tx_rx { let (rx, tx) = hil_test::common_test_pins!(peripherals); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let tx = UartTx::new(peripherals.UART0, uart::Config::default()) .unwrap() @@ -903,7 +874,7 @@ mod async_tx_rx_split { let (rx, tx) = hil_test::common_test_pins!(peripherals); let timg0 = TimerGroup::new(peripherals.TIMG0); - esp_rtos::start(timg0.timer0, peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let (rx, tx) = Uart::new(peripherals.UART0, uart::Config::default()) .unwrap() @@ -1003,7 +974,7 @@ mod uhci { #[test] fn test_send_receive(ctx: Context) { let timg0 = TimerGroup::new(ctx.peripherals.TIMG0); - esp_rtos::start(timg0.timer0, ctx.peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let (rx, tx) = hil_test::common_test_pins!(ctx.peripherals); let uart = Uart::new(ctx.peripherals.UART0, uart::Config::default()) @@ -1060,7 +1031,7 @@ mod uhci { #[test] fn test_long_strings(ctx: Context) { let timg0 = TimerGroup::new(ctx.peripherals.TIMG0); - esp_rtos::start(timg0.timer0, ctx.peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let (rx, tx) = hil_test::common_test_pins!(ctx.peripherals); let uart = Uart::new(ctx.peripherals.UART0, uart::Config::default()) @@ -1117,7 +1088,7 @@ mod uhci { #[test] async fn test_send_receive_async(ctx: Context) { let timg0 = TimerGroup::new(ctx.peripherals.TIMG0); - esp_rtos::start(timg0.timer0, ctx.peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let (rx, tx) = hil_test::common_test_pins!(ctx.peripherals); let uart = Uart::new(ctx.peripherals.UART0, uart::Config::default()) @@ -1176,7 +1147,7 @@ mod uhci { #[test] async fn test_long_strings_async(ctx: Context) { let timg0 = TimerGroup::new(ctx.peripherals.TIMG0); - esp_rtos::start(timg0.timer0, ctx.peripherals.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let (rx, tx) = hil_test::common_test_pins!(ctx.peripherals); let uart = Uart::new(ctx.peripherals.UART0, uart::Config::default()) @@ -1324,7 +1295,7 @@ mod new_tests { ); let timg0 = TimerGroup::new(p.TIMG0); - esp_rtos::start(timg0.timer0, p.FROM_CPU_INTR0); + esp_rtos::start(timg0.timer0); let (rx, tx) = hil_test::common_test_pins!(p); @@ -1370,6 +1341,77 @@ mod new_tests { } } + #[test] + #[timeout(10)] + fn applying_config_does_not_cause_a_pulse(mut ctx: Context) { + fn inner( + tx_instance: usize, + rx: AnyUart<'_>, + rx_pin: AnyPin<'_>, + tx: AnyUart<'_>, + tx_pin: AnyPin<'_>, + ) { + info!("Testing UART{}", tx_instance); + + let config = uart::Config::default(); + let mut rx = Uart::new(rx, config).unwrap().with_rx(rx_pin); + let mut uart = Uart::new(tx, config).unwrap().with_tx(tx_pin); + + // Applying the configuration must keep the TX line at the idle level. A low + // pulse on it would look like a glitch to the receiver. + for i in 0..20 { + uart.apply_config(&config).unwrap(); + + uart.write(b"a").unwrap(); + uart.flush().unwrap(); + + let mut buf = [0u8; 1]; + let read = rx.read(&mut buf).unwrap(); + + assert_eq!( + &buf[..read], + b"a", + "UART{}: failed in iteration #{}", + tx_instance, + i + ); + } + + let (_, mut tx) = uart.split(); + + for i in 0..20 { + tx.apply_config(&config).unwrap(); + + tx.write(b"a").unwrap(); + tx.flush().unwrap(); + + let mut buf = [0u8; 1]; + let read = rx.read(&mut buf).unwrap(); + + assert_eq!( + &buf[..read], + b"a", + "UART{}: failed in iteration #{} (transmitter only)", + tx_instance, + i + ); + } + + info!("UART{} test passed", tx_instance); + } + + // Run the test for each UART instance + for_each_uart_pair(|tx_num, rx_num| { + inner( + tx_num, + unsafe { ctx.uart[rx_num].clone_unchecked() }, + ctx.rx.reborrow(), + unsafe { ctx.uart[tx_num].clone_unchecked() }, + ctx.tx.reborrow(), + ); + }); + } + #[test] #[timeout(10)] fn creating_uart_clears_fifo(mut ctx: Context) { @@ -1408,9 +1450,7 @@ mod new_tests { } // Run the test for each UART instance - // https://github.com/esp-rs/esp-hal/issues/6138 - let uart_count = if cfg!(esp32) { 2 } else { UART_COUNT }; - for (tx_num, rx_num) in (0..uart_count).map(|i| (i, (i + 1) % uart_count)) { + for_each_uart_pair(|tx_num, rx_num| { inner( tx_num, unsafe { ctx.uart[rx_num].clone_unchecked() }, @@ -1418,6 +1458,14 @@ mod new_tests { unsafe { ctx.uart[tx_num].clone_unchecked() }, ctx.tx.reborrow(), ); + }); + } + + fn for_each_uart_pair(mut f: impl FnMut(usize, usize)) { + // https://github.com/esp-rs/esp-hal/issues/6138 + let uart_count = if cfg!(esp32) { 2 } else { UART_COUNT }; + for (tx_num, rx_num) in (0..uart_count).map(|i| (i, (i + 1) % uart_count)) { + f(tx_num, rx_num); } } diff --git a/hil-test/src/lib.rs b/hil-test/src/lib.rs index 6547fde39b0..9c99e609674 100644 --- a/hil-test/src/lib.rs +++ b/hil-test/src/lib.rs @@ -83,6 +83,7 @@ macro_rules! i2c_pins { any(esp32c6, esp32c61) => ($peripherals.GPIO6, $peripherals.GPIO7), esp32s31 => ($peripherals.GPIO7, $peripherals.GPIO6), esp32h2 => ($peripherals.GPIO12, $peripherals.GPIO22), + esp32h4 => ($peripherals.GPIO26, $peripherals.GPIO27), esp32c2 => ($peripherals.GPIO18, $peripherals.GPIO9), any(esp32c5, esp32p4) => ($peripherals.GPIO2, $peripherals.GPIO3), // esp32c3 @@ -98,12 +99,49 @@ macro_rules! common_test_pins { any(esp32s2, esp32s3, esp32c5) => ($peripherals.GPIO9, $peripherals.GPIO10), esp32 => ($peripherals.GPIO2, $peripherals.GPIO4), esp32p4 => ($peripherals.GPIO5, $peripherals.GPIO6), - // esp32c6, esp32c61, esp32h2, esp32c2, esp32c3, esp32s31 + // esp32c6, esp32c61, esp32h2, esp32h4, esp32c2, esp32c3, esp32s31 _ => ($peripherals.GPIO2, $peripherals.GPIO3), } }}; } +// A pair of connected LP pads. +#[macro_export] +macro_rules! lp_test_pins { + ($peripherals:expr) => {{ + cfg_select! { + esp32c5 => ($peripherals.GPIO4, $peripherals.GPIO5), + esp32h2 => ($peripherals.GPIO10, $peripherals.GPIO11), + // The pair of every other board is the one of `common_test_pins!`. + _ => $crate::common_test_pins!($peripherals), + } + }}; +} + +// A pair of connected HP pads. +// +// On the C2 the second pin is an LP pad, because the board has no second free HP pad. It only +// observes the first one, so the pad under test is still HP. +// +// The ESP32 is missing, the devkit we use has no free HP pad at all. +#[macro_export] +macro_rules! hp_test_pins { + ($peripherals:expr) => {{ + cfg_select! { + esp32c2 => ($peripherals.GPIO10, $peripherals.GPIO0), + esp32c3 => ($peripherals.GPIO6, $peripherals.GPIO7), + any(esp32c6, esp32c61) => ($peripherals.GPIO22, $peripherals.GPIO23), + esp32h4 => ($peripherals.GPIO19, $peripherals.GPIO20), + esp32p4 => ($peripherals.GPIO46, $peripherals.GPIO53), + esp32s2 => ($peripherals.GPIO37, $peripherals.GPIO38), + esp32s3 => ($peripherals.GPIO40, $peripherals.GPIO41), + esp32s31 => ($peripherals.GPIO8, $peripherals.GPIO44), + // The HP pair of the C5 and of the H2 is the one of `common_test_pins!`. + any(esp32c5, esp32h2) => $crate::common_test_pins!($peripherals), + } + }}; +} + // A GPIO that's not connected to anything. We use the BOOT pin for this, but // beware: it has a pullup. #[macro_export] @@ -115,6 +153,9 @@ macro_rules! unconnected_pin { esp32c5 => $peripherals.GPIO28, esp32p4 => $peripherals.GPIO35, esp32s31 => $peripherals.GPIO61, + // H4 has no BOOT GPIO pin, the boot mode is selected by the dedicated STRAP_MODE_0 + // pin, which is not a GPIO. + esp32h4 => $peripherals.GPIO34, // esp32c3, esp32c6, esp32c61, esp32h2 _ => $peripherals.GPIO9, } @@ -169,3 +210,84 @@ mod executor { pub use esp_rtos::embassy::Executor; #[cfg(not(feature = "embassy"))] pub use executor::Executor; + +/// Disables every watchdog timer with raw register writes. +/// +/// This prevents the firmware reset loop if no debugger is attached. The function must not depend +/// on esp-hal drivers, because a driver that is broken or half-initialized must not stop the tests +/// from running. +#[embedded_test::setup] +fn disable_watchdogs_before_semihosting() { + cfg_select! { + soc_has_lp_wdt => { + use esp_hal::peripherals::LP_WDT; + } + _ => { + use esp_hal::peripherals::LPWR as LP_WDT; + } + } + + // RWDT + let lp_wdt = LP_WDT::regs(); + cfg_select! { + esp32p4 => { + lp_wdt.wprotect().write(|w| unsafe { w.bits(0x50D8_3AA1) }); + lp_wdt.config0().write(|w| unsafe { w.bits(0) }); + lp_wdt.wprotect().write(|w| unsafe { w.bits(0) }); + } + _ => { + lp_wdt + .wdtwprotect() + .write(|w| unsafe { w.bits(0x50D8_3AA1) }); + lp_wdt.wdtconfig0().write(|w| unsafe { w.bits(0) }); + lp_wdt.wdtwprotect().write(|w| unsafe { w.bits(0) }); + } + } + + // SWD + #[cfg(soc_has_swd_watchdog)] + { + const SWD_WKEY: u32 = cfg_select! { + any(esp32c2, esp32c3, esp32s2, esp32s3) => 0x8F1D_312A, + _ => 0x50D8_3AA1, + }; + + lp_wdt + .swd_wprotect() + .write(|w| unsafe { w.swd_wkey().bits(SWD_WKEY) }); + cfg_select! { + esp32p4 => lp_wdt + .swd_config() + .write(|w| w.swd_auto_feed_en().set_bit()), + _ => lp_wdt.swd_conf().write(|w| w.swd_auto_feed_en().set_bit()), + }; + lp_wdt + .swd_wprotect() + .write(|w| unsafe { w.swd_wkey().bits(0) }); + } + + // MWDT + #[cfg(timergroup_timg0)] + { + let timg0 = esp_hal::peripherals::TIMG0::regs(); + timg0 + .wdtwprotect() + .write(|w| unsafe { w.wdt_wkey().bits(0x50D8_3AA1) }); + timg0.wdtconfig0().modify(|_, w| w.wdt_en().clear_bit()); + timg0 + .wdtwprotect() + .write(|w| unsafe { w.wdt_wkey().bits(0) }); + } + + #[cfg(timergroup_timg1)] + { + let timg1 = esp_hal::peripherals::TIMG1::regs(); + timg1 + .wdtwprotect() + .write(|w| unsafe { w.wdt_wkey().bits(0x50D8_3AA1) }); + timg1.wdtconfig0().modify(|_, w| w.wdt_en().clear_bit()); + timg1 + .wdtwprotect() + .write(|w| unsafe { w.wdt_wkey().bits(0) }); + } +} diff --git a/qa-test/src/bin/lcd_dpi.rs b/qa-test/src/bin/lcd_dpi.rs deleted file mode 100644 index ecb6fdbb292..00000000000 --- a/qa-test/src/bin/lcd_dpi.rs +++ /dev/null @@ -1,389 +0,0 @@ -//! Drives the 16-bit parallel RGB display on ESP32-S3-LCD-EV-Board v1.5 -//! -//! This example fills the screen with every color. -//! -//! The following wiring is assumed: -//! - LCD_VSYNC => GPIO3 -//! - LCD_HSYNC => GPIO46 -//! - LCD_DE => GPIO17 -//! - LCD_PCLK => GPIO9 -//! - LCD_DATA0 => GPIO10 -//! - LCD_DATA1 => GPIO11 -//! - LCD_DATA2 => GPIO12 -//! - LCD_DATA3 => GPIO13 -//! - LCD_DATA4 => GPIO14 -//! - LCD_DATA5 => GPIO21 -//! - LCD_DATA6 => GPIO8 -//! - LCD_DATA7 => GPIO18 -//! - LCD_DATA8 => GPIO45 -//! - LCD_DATA9 => GPIO38 -//! - LCD_DATA10 => GPIO39 -//! - LCD_DATA11 => GPIO40 -//! - LCD_DATA12 => GPIO41 -//! - LCD_DATA13 => GPIO42 -//! - LCD_DATA14 => GPIO2 -//! - LCD_DATA15 => GPIO1 - -//% CHIP_FILTER: rgb_display_driver_supported && !esp32 - -#![no_std] -#![no_main] - -use core::iter::{empty, once}; - -use esp_backtrace as _; -use esp_hal::{ - Blocking, - delay::Delay, - dma_loop_buffer, - gpio::{Level, Output, OutputConfig}, - i2c::{self, master::I2c}, - lcd_cam::{ - LcdCam, - lcd::{ - ClockMode, - Phase, - Polarity, - dpi::{Config, Dpi, Format, FrameTiming}, - }, - }, - main, - peripherals::Peripherals, - time::Rate, -}; -use esp_println::println; - -esp_bootloader_esp_idf::esp_app_desc!(); - -#[main] -fn main() -> ! { - esp_println::logger::init_logger_from_env(); - - let peripherals: Peripherals = esp_hal::init(esp_hal::Config::default()); - - let i2c = I2c::new( - peripherals.I2C0, - i2c::master::Config::default().with_frequency(Rate::from_khz(400)), - ) - .unwrap() - .with_sda(peripherals.GPIO47) - .with_scl(peripherals.GPIO48); - - let tx_channel = peripherals.DMA_CH2; - let lcd_cam = LcdCam::new(peripherals.LCD_CAM); - - let mut expander = Tca9554::new(i2c); - expander.write_output_reg(0b1111_0011).unwrap(); - expander.write_direction_reg(0b1111_0001).unwrap(); - - let delay = Delay::new(); - - println!("Initialising"); - - let mut write_byte = |b: u8, is_cmd: bool| { - const SCS_BIT: u8 = 0b0000_0010; - const SCL_BIT: u8 = 0b0000_0100; - const SDA_BIT: u8 = 0b0000_1000; - - let mut output = 0b1111_0001 & !SCS_BIT; - expander.write_output_reg(output).unwrap(); - - for bit in once(!is_cmd).chain((0..8).map(|i| (b >> i) & 0b1 != 0).rev()) { - let prev = output; - if bit { - output |= SDA_BIT; - } else { - output &= !SDA_BIT; - } - if prev != output { - expander.write_output_reg(output).unwrap(); - } - - output &= !SCL_BIT; - expander.write_output_reg(output).unwrap(); - - output |= SCL_BIT; - expander.write_output_reg(output).unwrap(); - } - - output &= !SCL_BIT; - expander.write_output_reg(output).unwrap(); - - output &= !SDA_BIT; - expander.write_output_reg(output).unwrap(); - - output |= SCS_BIT; - expander.write_output_reg(output).unwrap(); - }; - - let mut vsync_pin = peripherals.GPIO3; - - let vsync_must_be_high_during_setup = - Output::new(vsync_pin.reborrow(), Level::High, OutputConfig::default()); - for &init in INIT_CMDS.iter() { - match init { - InitCmd::Cmd(cmd, args) => { - write_byte(cmd, true); - for &arg in args { - write_byte(arg, false); - } - } - InitCmd::Delay(ms) => { - delay.delay_millis(ms as _); - } - } - } - drop(vsync_must_be_high_during_setup); - - let mut dma_buf = dma_loop_buffer!(2 * 16); - - let config = Config::default() - .with_clock_mode(ClockMode { - polarity: Polarity::IdleLow, - phase: Phase::ShiftLow, - }) - .with_frequency(Rate::from_mhz(16)) - .with_format(Format { - enable_2byte_mode: true, - ..Default::default() - }) - .with_timing(FrameTiming { - horizontal_active_width: 480, - horizontal_total_width: 520, - horizontal_blank_front_porch: 10, - - vertical_active_height: 480, - vertical_total_height: 510, - vertical_blank_front_porch: 10, - - hsync_width: 10, - vsync_width: 10, - - hsync_position: 0, - }) - .with_vsync_idle_level(Level::High) - .with_hsync_idle_level(Level::High) - .with_de_idle_level(Level::Low) - .with_disable_black_region(false); - - let mut dpi = Dpi::new(lcd_cam.lcd, tx_channel, config) - .unwrap() - .with_vsync(vsync_pin) - .with_hsync(peripherals.GPIO46) - .with_de(peripherals.GPIO17) - .with_pclk(peripherals.GPIO9) - // Blue - .with_data0(peripherals.GPIO10) - .with_data1(peripherals.GPIO11) - .with_data2(peripherals.GPIO12) - .with_data3(peripherals.GPIO13) - .with_data4(peripherals.GPIO14) - // Green - .with_data5(peripherals.GPIO21) - .with_data6(peripherals.GPIO8) - .with_data7(peripherals.GPIO18) - .with_data8(peripherals.GPIO45) - .with_data9(peripherals.GPIO38) - .with_data10(peripherals.GPIO39) - // Red - .with_data11(peripherals.GPIO40) - .with_data12(peripherals.GPIO41) - .with_data13(peripherals.GPIO42) - .with_data14(peripherals.GPIO2) - .with_data15(peripherals.GPIO1); - - const MAX_RED: u16 = (1 << 5) - 1; - const MAX_GREEN: u16 = (1 << 6) - 1; - const MAX_BLUE: u16 = (1 << 5) - 1; - - fn rgb(r: u16, g: u16, b: u16) -> u16 { - (r << 11) | (g << 5) | (b << 0) - } - - let mut colors = empty() - // Start with red and gradually add green - .chain((0..=MAX_GREEN).map(|g| rgb(MAX_RED, g, 0))) - // Then remove the red - .chain((0..=MAX_RED).rev().map(|r| rgb(r, MAX_GREEN, 0))) - // Then add blue - .chain((0..=MAX_BLUE).map(|b| rgb(0, MAX_GREEN, b))) - // Then remove green - .chain((0..=MAX_GREEN).rev().map(|g| rgb(0, g, MAX_BLUE))) - // Then add red - .chain((0..=MAX_RED).map(|r| rgb(r, 0, MAX_BLUE))) - // Then remove blue - .chain((0..=MAX_BLUE).rev().map(|b| rgb(MAX_RED, 0, b))) - // Once we get we have red, and we can start again. - .cycle(); - - println!("Rendering"); - loop { - let transfer = dpi.send(false, dma_buf).map_err(|e| e.0).unwrap(); - (_, dpi, dma_buf) = transfer.wait(); - - if let Some(color) = colors.next() { - for chunk in dma_buf.chunks_mut(2) { - chunk.copy_from_slice(&color.to_le_bytes()); - } - } - } -} - -struct Tca9554 { - i2c: I2c<'static, Blocking>, - address: u8, -} - -impl Tca9554 { - pub fn new(i2c: I2c<'static, Blocking>) -> Self { - Self { i2c, address: 0x20 } - } - - pub fn write_direction_reg(&mut self, value: u8) -> Result<(), i2c::master::Error> { - self.i2c.write(self.address, &[0x03, value]) - } - - pub fn write_output_reg(&mut self, value: u8) -> Result<(), i2c::master::Error> { - self.i2c.write(self.address, &[0x01, value]) - } -} - -#[derive(Copy, Clone)] -enum InitCmd { - Cmd(u8, &'static [u8]), - Delay(u8), -} - -const INIT_CMDS: &[InitCmd] = &[ - InitCmd::Cmd(0xf0, &[0x55, 0xaa, 0x52, 0x08, 0x00]), - InitCmd::Cmd(0xf6, &[0x5a, 0x87]), - InitCmd::Cmd(0xc1, &[0x3f]), - InitCmd::Cmd(0xc2, &[0x0e]), - InitCmd::Cmd(0xc6, &[0xf8]), - InitCmd::Cmd(0xc9, &[0x10]), - InitCmd::Cmd(0xcd, &[0x25]), - InitCmd::Cmd(0xf8, &[0x8a]), - InitCmd::Cmd(0xac, &[0x45]), - InitCmd::Cmd(0xa0, &[0xdd]), - InitCmd::Cmd(0xa7, &[0x47]), - InitCmd::Cmd(0xfa, &[0x00, 0x00, 0x00, 0x04]), - InitCmd::Cmd(0x86, &[0x99, 0xa3, 0xa3, 0x51]), - InitCmd::Cmd(0xa3, &[0xee]), - InitCmd::Cmd(0xfd, &[0x3c, 0x3]), - InitCmd::Cmd(0x71, &[0x48]), - InitCmd::Cmd(0x72, &[0x48]), - InitCmd::Cmd(0x73, &[0x00, 0x44]), - InitCmd::Cmd(0x97, &[0xee]), - InitCmd::Cmd(0x83, &[0x93]), - InitCmd::Cmd(0x9a, &[0x72]), - InitCmd::Cmd(0x9b, &[0x5a]), - InitCmd::Cmd(0x82, &[0x2c, 0x2c]), - InitCmd::Cmd(0xB1, &[0x10]), - InitCmd::Cmd( - 0x6d, - &[ - 0x00, 0x1f, 0x19, 0x1a, 0x10, 0x0e, 0x0c, 0x0a, 0x02, 0x07, 0x1e, 0x1e, 0x1e, 0x1e, - 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x1e, 0x08, 0x01, 0x09, 0x0b, 0x0d, 0x0f, - 0x1a, 0x19, 0x1f, 0x00, - ], - ), - InitCmd::Cmd( - 0x64, - &[ - 0x38, 0x05, 0x01, 0xdb, 0x03, 0x03, 0x38, 0x04, 0x01, 0xdc, 0x03, 0x03, 0x7a, 0x7a, - 0x7a, 0x7a, - ], - ), - InitCmd::Cmd( - 0x65, - &[ - 0x38, 0x03, 0x01, 0xdd, 0x03, 0x03, 0x38, 0x02, 0x01, 0xde, 0x03, 0x03, 0x7a, 0x7a, - 0x7a, 0x7a, - ], - ), - InitCmd::Cmd( - 0x66, - &[ - 0x38, 0x01, 0x01, 0xdf, 0x03, 0x03, 0x38, 0x00, 0x01, 0xe0, 0x03, 0x03, 0x7a, 0x7a, - 0x7a, 0x7a, - ], - ), - InitCmd::Cmd( - 0x67, - &[ - 0x30, 0x01, 0x01, 0xe1, 0x03, 0x03, 0x30, 0x02, 0x01, 0xe2, 0x03, 0x03, 0x7a, 0x7a, - 0x7a, 0x7a, - ], - ), - InitCmd::Cmd( - 0x68, - &[ - 0x00, 0x08, 0x15, 0x08, 0x15, 0x7a, 0x7a, 0x08, 0x15, 0x08, 0x15, 0x7a, 0x7a, - ], - ), - InitCmd::Cmd(0x60, &[0x38, 0x08, 0x7a, 0x7a, 0x38, 0x09, 0x7a, 0x7a]), - InitCmd::Cmd(0x63, &[0x31, 0xe4, 0x7a, 0x7a, 0x31, 0xe5, 0x7a, 0x7a]), - InitCmd::Cmd(0x69, &[0x04, 0x22, 0x14, 0x22, 0x14, 0x22, 0x08]), - InitCmd::Cmd(0x6b, &[0x07]), - InitCmd::Cmd(0x7a, &[0x08, 0x13]), - InitCmd::Cmd(0x7b, &[0x08, 0x13]), - InitCmd::Cmd( - 0xd1, - &[ - 0x00, 0x00, 0x00, 0x04, 0x00, 0x12, 0x00, 0x18, 0x00, 0x21, 0x00, 0x2a, 0x00, 0x35, - 0x00, 0x47, 0x00, 0x56, 0x00, 0x90, 0x00, 0xe5, 0x01, 0x68, 0x01, 0xd5, 0x01, 0xd7, - 0x02, 0x36, 0x02, 0xa6, 0x02, 0xee, 0x03, 0x48, 0x03, 0xa0, 0x03, 0xba, 0x03, 0xc5, - 0x03, 0xd0, 0x03, 0xe0, 0x03, 0xea, 0x03, 0xfa, 0x03, 0xff, - ], - ), - InitCmd::Cmd( - 0xd2, - &[ - 0x00, 0x00, 0x00, 0x04, 0x00, 0x12, 0x00, 0x18, 0x00, 0x21, 0x00, 0x2a, 0x00, 0x35, - 0x00, 0x47, 0x00, 0x56, 0x00, 0x90, 0x00, 0xe5, 0x01, 0x68, 0x01, 0xd5, 0x01, 0xd7, - 0x02, 0x36, 0x02, 0xa6, 0x02, 0xee, 0x03, 0x48, 0x03, 0xa0, 0x03, 0xba, 0x03, 0xc5, - 0x03, 0xd0, 0x03, 0xe0, 0x03, 0xea, 0x03, 0xfa, 0x03, 0xff, - ], - ), - InitCmd::Cmd( - 0xd3, - &[ - 0x00, 0x00, 0x00, 0x04, 0x00, 0x12, 0x00, 0x18, 0x00, 0x21, 0x00, 0x2a, 0x00, 0x35, - 0x00, 0x47, 0x00, 0x56, 0x00, 0x90, 0x00, 0xe5, 0x01, 0x68, 0x01, 0xd5, 0x01, 0xd7, - 0x02, 0x36, 0x02, 0xa6, 0x02, 0xee, 0x03, 0x48, 0x03, 0xa0, 0x03, 0xba, 0x03, 0xc5, - 0x03, 0xd0, 0x03, 0xe0, 0x03, 0xea, 0x03, 0xfa, 0x03, 0xff, - ], - ), - InitCmd::Cmd( - 0xd4, - &[ - 0x00, 0x00, 0x00, 0x04, 0x00, 0x12, 0x00, 0x18, 0x00, 0x21, 0x00, 0x2a, 0x00, 0x35, - 0x00, 0x47, 0x00, 0x56, 0x00, 0x90, 0x00, 0xe5, 0x01, 0x68, 0x01, 0xd5, 0x01, 0xd7, - 0x02, 0x36, 0x02, 0xa6, 0x02, 0xee, 0x03, 0x48, 0x03, 0xa0, 0x03, 0xba, 0x03, 0xc5, - 0x03, 0xd0, 0x03, 0xe0, 0x03, 0xea, 0x03, 0xfa, 0x03, 0xff, - ], - ), - InitCmd::Cmd( - 0xd5, - &[ - 0x00, 0x00, 0x00, 0x04, 0x00, 0x12, 0x00, 0x18, 0x00, 0x21, 0x00, 0x2a, 0x00, 0x35, - 0x00, 0x47, 0x00, 0x56, 0x00, 0x90, 0x00, 0xe5, 0x01, 0x68, 0x01, 0xd5, 0x01, 0xd7, - 0x02, 0x36, 0x02, 0xa6, 0x02, 0xee, 0x03, 0x48, 0x03, 0xa0, 0x03, 0xba, 0x03, 0xc5, - 0x03, 0xd0, 0x03, 0xe0, 0x03, 0xea, 0x03, 0xfa, 0x03, 0xff, - ], - ), - InitCmd::Cmd( - 0xd6, - &[ - 0x00, 0x00, 0x00, 0x04, 0x00, 0x12, 0x00, 0x18, 0x00, 0x21, 0x00, 0x2a, 0x00, 0x35, - 0x00, 0x47, 0x00, 0x56, 0x00, 0x90, 0x00, 0xe5, 0x01, 0x68, 0x01, 0xd5, 0x01, 0xd7, - 0x02, 0x36, 0x02, 0xa6, 0x02, 0xee, 0x03, 0x48, 0x03, 0xa0, 0x03, 0xba, 0x03, 0xc5, - 0x03, 0xd0, 0x03, 0xe0, 0x03, 0xea, 0x03, 0xfa, 0x03, 0xff, - ], - ), - InitCmd::Cmd(0x3A, &[0x66]), - InitCmd::Cmd(0x11, &[]), - InitCmd::Delay(120), - InitCmd::Cmd(0x29, &[]), - InitCmd::Delay(20), -]; diff --git a/qa-test/src/bin/psram.rs b/qa-test/src/bin/psram.rs deleted file mode 100644 index 57f6e13aa92..00000000000 --- a/qa-test/src/bin/psram.rs +++ /dev/null @@ -1,51 +0,0 @@ -//! This shows how to use PSRAM as heap-memory via esp-alloc -//! -//! You need a supported target with at least 2 MB of PSRAM memory. - -//% CHIP_FILTER: psram_driver_supported -//% FEATURES: esp-alloc/internal-heap-stats - -#![no_std] -#![no_main] - -extern crate alloc; - -use alloc::{string::String, vec::Vec}; - -use esp_alloc as _; -use esp_backtrace as _; -use esp_hal::main; -use esp_println::println; - -esp_bootloader_esp_idf::esp_app_desc!(); - -#[cfg(is_not_release)] -compile_error!("PSRAM example must be built in release mode!"); - -#[main] -fn main() -> ! { - esp_println::logger::init_logger_from_env(); - let peripherals = esp_hal::init(esp_hal::Config::default()); - - esp_alloc::psram_allocator!(peripherals.PSRAM, esp_hal::psram); - - println!("Going to access PSRAM"); - let mut large_vec = Vec::::with_capacity(500 * 1024 / 4); - - for i in 0..(500 * 1024 / 4) { - large_vec.push((i & 0xff) as u32); - } - - println!("vec size = {} bytes", large_vec.len() * 4); - println!("vec address = {:p}", large_vec.as_ptr()); - println!("vec[..100] = {:?}", &large_vec[..100]); - - let string = String::from("A string allocated in PSRAM"); - println!("'{}' allocated at {:p}", &string, string.as_ptr()); - - println!("{}", esp_alloc::HEAP.stats()); - - println!("done"); - - loop {} -} diff --git a/resources/index.html.somni b/resources/index.html.somni index e4dbe8f177e..6f4d00845ac 100644 --- a/resources/index.html.somni +++ b/resources/index.html.somni @@ -124,6 +124,7 @@ +

Package Documentation

diff --git a/resources/latest_redirect.html.somni b/resources/latest_redirect.html.somni index ea8e228ae26..7e44f7d5f5d 100644 --- a/resources/latest_redirect.html.somni +++ b/resources/latest_redirect.html.somni @@ -6,10 +6,16 @@ - + diff --git a/resources/package_index.html.somni b/resources/package_index.html.somni index 23a6b5a850b..56314af6b87 100644 --- a/resources/package_index.html.somni +++ b/resources/package_index.html.somni @@ -20,8 +20,7 @@ margin: 0; padding: 40px 20px; display: flex; - height: 100vh; - width: 100vw; + min-height: 100vh; justify-content: center; box-sizing: border-box; } @@ -40,7 +39,8 @@ } .content { - width: 900px; + width: min(1160px, 100%); + margin: auto 0; } h2 { @@ -81,10 +81,275 @@ width: 120px; } - @media screen and (min-height: 650px) { - body { - align-items: center; - } + .peri-matrix { + margin-top: 2.5rem; + background-color: #2b2b2b; + border: 1px solid #454444; + border-radius: 8px; + overflow: hidden; + } + + .peri-matrix-summary { + display: flex; + align-items: baseline; + gap: 12px; + padding: 14px 18px; + cursor: pointer; + user-select: none; + background-color: #303030; + list-style: none; + } + + .peri-matrix-summary::-webkit-details-marker { + display: none; + } + + .peri-matrix-summary::before { + content: "▸"; + color: #d6991d; + font-size: 1.1em; + transition: transform 0.15s ease; + } + + .peri-matrix[open] > .peri-matrix-summary::before { + transform: rotate(90deg); + } + + .peri-matrix-summary:hover { + background-color: #383838; + } + + .peri-matrix-title { + color: #d6991d; + font-size: 1.15em; + font-weight: 500; + } + + .peri-matrix-subtitle { + color: #a8a8a8; + font-size: 0.88em; + } + + .peri-matrix-body { + padding: 16px 18px 20px; + border-top: 1px solid #454444; + } + + .peri-controls { + display: flex; + flex-wrap: wrap; + justify-content: space-between; + align-items: center; + gap: 12px; + padding: 10px 14px; + background-color: #353535; + border: 1px solid #454444; + border-radius: 6px; + font-size: 0.85em; + } + + .peri-legends { + display: flex; + flex-direction: column; + gap: 6px; + } + + .peri-legend-group { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 14px; + } + + .peri-legend-heading { + color: #c0c0c0; + font-weight: 500; + min-width: 95px; + } + + .peri-legend-item { + display: inline-flex; + align-items: center; + gap: 4px; + color: #e0e0e0; + } + + .peri-empty-swatch { + display: inline-flex; + align-items: center; + justify-content: center; + width: 18px; + height: 16px; + border: 1px solid #4a4a4a; + border-radius: 3px; + background: repeating-linear-gradient( + -45deg, + #252525, + #252525 3px, + #2d2d2d 3px, + #2d2d2d 6px + ); + color: #6a6a6a; + font-size: 0.75em; + line-height: 1; + } + + .peri-actions { + display: flex; + gap: 8px; + } + + .peri-btn { + background-color: #2b2b2b; + color: #d6991d; + border: 1px solid #555; + border-radius: 4px; + padding: 5px 10px; + font-family: inherit; + font-size: 0.95em; + cursor: pointer; + } + + .peri-btn:hover { + background-color: #3f3f3f; + border-color: #d6991d; + } + + .peri-note { + margin: 8px 2px 12px; + font-size: 0.8em; + color: #a8a8a8; + } + + .peri-group { + margin-top: 10px; + border: 1px solid #454444; + border-radius: 6px; + background-color: #333333; + overflow: hidden; + } + + .peri-group-summary { + display: flex; + justify-content: space-between; + align-items: center; + padding: 10px 14px; + cursor: pointer; + user-select: none; + font-weight: 500; + background-color: #383838; + } + + .peri-group-summary:hover { + background-color: #404040; + } + + .peri-group-count { + font-size: 0.8em; + font-weight: 400; + color: #bdbdbd; + background-color: #2b2b2b; + padding: 2px 8px; + border-radius: 10px; + } + + .peri-table-wrap { + overflow-x: auto; + border-top: 1px solid #454444; + } + + .peri-table { + width: 100%; + border-collapse: collapse; + font-size: 0.84rem; + } + + .peri-table th { + background-color: #292929; + color: #dcdcdc; + font-weight: 500; + white-space: nowrap; + padding: 8px 6px; + border-bottom: 1px solid #454444; + text-align: center; + } + + .peri-table td { + padding: 6px; + text-align: center; + border-top: 1px solid #3d3d3d; + white-space: nowrap; + } + + .peri-table th.driver-col, + .peri-table td.driver-col { + text-align: left; + padding-left: 14px; + padding-right: 12px; + min-width: 170px; + } + + .peri-table th.api-col, + .peri-table td.api-col { + border-right: 2px solid #454444; + width: 44px; + } + + .peri-table tbody tr:hover td { + background-color: #3c3c3c; + } + + .peri-table td.na-cell { + background: repeating-linear-gradient( + -45deg, + #252525, + #252525 4px, + #2c2c2c 4px, + #2c2c2c 8px + ); + color: #5e5e5e; + user-select: none; + } + + .peri-table tbody tr:hover td.na-cell { + background: repeating-linear-gradient( + -45deg, + #2b2b2b, + #2b2b2b 4px, + #333333 4px, + #333333 8px + ); + color: #777; + } + + .not-impl { + color: #888; + } + + .peri-table a.issue-link { + text-decoration: none; + border-bottom: 1px dashed #d6991d; + padding-bottom: 1px; + } + + .peri-table a.issue-link:hover { + border-bottom-style: solid; + } + + .peri-table td span[title="Supported"], + .peri-table td a[title^="Supported"], + .peri-table td span[title="Stable"], + .peri-table td a[title^="Stable"], + .peri-icon-tick { + display: inline-block; + filter: invert(1) sepia(1) saturate(4) hue-rotate(75deg) brightness(1.05); + } + + .peri-table td span[title="Partial support"], + .peri-table td a[title^="Partial support"], + .peri-icon-tools { + display: inline-block; + filter: invert(1) sepia(0.6) saturate(3) hue-rotate(5deg) brightness(1.05); } @@ -108,6 +373,65 @@ {{ meta.version }} {% endfor %} +{% if peripheral_support != "" %} +
+ + Peripheral Support Matrix + Per-chip feature completeness and API stability + +
+
+
+
+ API Stability: + ✔️ Stable + 🚧 Unstable + ⚠️ Planned overhaul + — Not supported +
+
+ Chip Support: + ✔️ Supported + ⚒️ Partial support + ❌ Not supported + — Not available +
+
+
+ + +
+
+

Underlined icons open the peripheral's tracking issue on GitHub.

+{{ peripheral_support }} +
+
+ +{% endif %} diff --git a/xtask-mcp-macros/src/lib.rs b/xtask-mcp-macros/src/lib.rs index 7ccd119d3b0..9c594b950cd 100644 --- a/xtask-mcp-macros/src/lib.rs +++ b/xtask-mcp-macros/src/lib.rs @@ -121,6 +121,20 @@ enum TypeClass { Other, // enums, String, PathBuf, etc. — treated as required string } +fn generic_arg0(ty: &Type) -> Option<&Type> { + let Type::Path(tp) = ty else { + return None; + }; + let args = &tp.path.segments.last()?.arguments; + let syn::PathArguments::AngleBracketed(ab) = args else { + return None; + }; + match ab.args.first()? { + syn::GenericArgument::Type(inner) => Some(inner), + _ => None, + } +} + fn classify_type(ty: &Type) -> TypeClass { let Type::Path(tp) = ty else { return TypeClass::Other; @@ -135,7 +149,13 @@ fn classify_type(ty: &Type) -> TypeClass { match segs[0].ident.to_string().as_str() { "bool" => TypeClass::Bool, "usize" | "u32" | "u64" | "i64" | "i32" => TypeClass::Integer, - "Option" => TypeClass::Option, + "Option" => { + if generic_arg0(ty).is_some_and(|inner| classify_type(inner) == TypeClass::Vec) { + TypeClass::Vec + } else { + TypeClass::Option + } + } "Vec" => TypeClass::Vec, _ => TypeClass::Other, } @@ -349,20 +369,30 @@ fn gen_cli_push(fd: &FieldDesc) -> TokenStream2 { /// /// # Usage /// +/// One CLI verb: +/// /// ```ignore /// #[cfg_attr(feature = "mcp", xtask_mcp_macros::mcp_tool( /// description = "Short description visible in tool listing", /// command = "subcommand-name" /// ))] -/// #[derive(Debug, Args)] -/// struct MyArgs { ... } +/// ``` +/// +/// Several verbs that share the same Args struct: +/// +/// ```ignore +/// #[cfg_attr(feature = "mcp", xtask_mcp_macros::mcp_tool( +/// verbs( +/// build = "Build an example or test", +/// run = "Flash and run an example or tests", +/// ) +/// ))] /// ``` /// /// The macro generates: /// 1. A `MyArgsMcpInput` struct (`Deserialize` + `JsonSchema`) -/// 2. A helper function `my_args_mcp_to_cli_args` that converts the input to a `Vec` of CLI -/// arguments. -/// 3. An `inventory::submit!` block that registers the tool. +/// 2. A helper that converts the input to CLI arguments, prefixed with the verb +/// 3. An `inventory::submit!` block per verb #[proc_macro_attribute] pub fn mcp_tool(attrs: TokenStream, input: TokenStream) -> TokenStream { let item = parse_macro_input!(input as ItemStruct); @@ -377,8 +407,8 @@ pub fn mcp_tool(attrs: TokenStream, input: TokenStream) -> TokenStream { } struct McpToolAttrs { - description: String, - command: String, + /// `(command, description)` pairs. One pair for a single-verb tool. + verbs: Vec<(String, String)>, } fn parse_mcp_tool_attrs(attrs: TokenStream2) -> syn::Result { @@ -387,51 +417,77 @@ fn parse_mcp_tool_attrs(attrs: TokenStream2) -> syn::Result { let mut description = None; let mut command = None; + let mut verbs = Vec::new(); for item in &items { - let Meta::NameValue(nv) = item else { - continue; - }; - if nv.path.is_ident("description") { - description = expr_lit_str(&nv.value); - } else if nv.path.is_ident("command") { - command = expr_lit_str(&nv.value); + match item { + Meta::NameValue(nv) if nv.path.is_ident("description") => { + description = expr_lit_str(&nv.value); + } + Meta::NameValue(nv) if nv.path.is_ident("command") => { + command = expr_lit_str(&nv.value); + } + Meta::List(list) if list.path.is_ident("verbs") => { + let inner = + Punctuated::::parse_terminated.parse2(list.tokens.clone())?; + for meta in inner { + let Meta::NameValue(nv) = meta else { + return Err(syn::Error::new_spanned( + meta, + "verbs(...) entries must be `name = \"description\"`", + )); + }; + let Some(ident) = nv.path.get_ident() else { + return Err(syn::Error::new_spanned( + &nv.path, + "verb name must be an ident", + )); + }; + let Some(desc) = expr_lit_str(&nv.value) else { + return Err(syn::Error::new_spanned( + &nv.value, + "description must be a string", + )); + }; + verbs.push((ident.to_string(), desc)); + } + } + _ => {} } } + if !verbs.is_empty() { + if command.is_some() || description.is_some() { + return Err(syn::Error::new( + proc_macro2::Span::call_site(), + "mcp_tool: use either `command`/`description` or `verbs(...)`, not both", + )); + } + return Ok(McpToolAttrs { verbs }); + } + let description = description.ok_or_else(|| { syn::Error::new( proc_macro2::Span::call_site(), - "mcp_tool requires `description = \"...\"`", + "mcp_tool requires `description = \"...\"` or `verbs(...)`", ) })?; let command = command.ok_or_else(|| { syn::Error::new( proc_macro2::Span::call_site(), - "mcp_tool requires `command = \"...\"`", + "mcp_tool requires `command = \"...\"` or `verbs(...)`", ) })?; Ok(McpToolAttrs { - description, - command, + verbs: vec![(command, description)], }) } fn expand_mcp_tool(attrs: McpToolAttrs, item: &ItemStruct) -> syn::Result { let struct_name = &item.ident; let input_type_name = format_ident!("{}McpInput", struct_name); - - // Derive the tool name from the command string: spaces/hyphens → underscores. - let tool_name = attrs.command.replace([' ', '-'], "_"); - - // Split the command string into individual CLI tokens. - let command_parts: Vec = attrs - .command - .split_whitespace() - .map(str::to_string) - .collect(); - let command_parts_lit = command_parts.iter().map(|p| quote! { #p.to_string(), }); + let struct_snake = to_snake(struct_name.to_string()); let syn::Fields::Named(fields) = &item.fields else { return Err(syn::Error::new_spanned( @@ -451,49 +507,54 @@ fn expand_mcp_tool(attrs: McpToolAttrs, item: &ItemStruct) -> syn::Result ::anyhow::Result { + let input: #input_type_name = ::serde_json::from_value(json)?; + let cli_args = #to_cli_fn(#command, &input); + crate::commands::mcp::run_xtask_subprocess(&cli_args) + } + + ::inventory::submit!(crate::McpToolRegistration { + name: #tool_name, + description: #description, + input_schema_fn: #schema_fn, + execute_fn: #exec_fn, + }); + } + }); let generated = quote! { - // 1. MCP input type #[derive(::serde::Deserialize, ::schemars::JsonSchema)] pub struct #input_type_name { #(#mcp_fields)* } - // 2. CLI conversion function - fn #to_cli_fn(input: &#input_type_name) -> Vec { - let mut args: Vec = vec![#(#command_parts_lit)*]; + fn #to_cli_fn(command: &str, input: &#input_type_name) -> Vec { + let mut args: Vec = command + .split_whitespace() + .map(str::to_string) + .collect(); #(#cli_pushes)* args } - // 3. Schema function (plain fn pointer, not closure) fn #schema_fn() -> ::serde_json::Value { let schema = ::schemars::schema_for!(#input_type_name); ::serde_json::to_value(&schema) .expect("schemars Schema serialization cannot fail") } - // 4. Inventory registration - ::inventory::submit!(crate::McpToolRegistration { - name: #tool_name, - description: #description, - input_schema_fn: #schema_fn, - execute_fn: |json| { - let input: #input_type_name = ::serde_json::from_value(json)?; - let cli_args = #to_cli_fn(&input); - crate::commands::mcp::run_xtask_subprocess(&cli_args) - }, - }); + #(#registrations)* }; - // Emit: original struct unchanged, then the generated code. - let original = quote! { #item }; Ok(quote! { - #original + #item #generated }) } diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index 1d5b956b736..e693772be8c 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -29,7 +29,7 @@ somni-template = { version = "0.3.2" } strum = { version = "0.27.1", features = ["derive"] } toml_edit = { version = "0.25", features = ["serde"] } walkdir = "2.5.0" -zip = "6.0.0" +zip = { version = "9.0.3", optional = true } # Only required when building documentation for deployment: reqwest = { version = "0.12.12", features = [ @@ -39,7 +39,11 @@ reqwest = { version = "0.12.12", features = [ ], optional = true } # This pulls a gazillion crates - don't include it by default -cargo-semver-checks = { version = "0.46.0", optional = true } +cargo-semver-checks = { version = "0.51.0", optional = true } +public-api = { version = "0.52.2", optional = true, default-features = false } + +# Reads the crates.io index +tame-index = { version = "0.25", features = ["sparse"], optional = true } flate2 = { version = "1.1.1", optional = true } temp-file = { version = "0.1.9", optional = true } @@ -55,13 +59,16 @@ xtask-mcp-macros = { path = "../xtask-mcp-macros", optional = true } pretty_assertions = "1.2.0" tempfile = "3" +[build-dependencies] +toml_edit = "0.25" + [features] deploy-docs = ["dep:reqwest", "dep:kuchikiki"] preview-docs = ["dep:opener", "dep:rocket"] -semver-checks = [ "dep:cargo-semver-checks", "dep:flate2", "dep:temp-file", "dep:regex" ] -release = ["semver-checks", "dep:opener", "dep:regex"] -report = ["dep:regex"] -rel-check = ["dep:regex"] +semver-checks = [ "dep:cargo-semver-checks", "dep:flate2", "dep:temp-file", "dep:regex", "dep:zip" ] +release = ["semver-checks", "dep:opener", "dep:regex", "dep:tame-index", "dep:public-api"] +# The registry check reads the real release `Plan`, so it needs the release feature. +rel-check = ["release"] mcp = ["dep:inventory", "dep:rmcp", "dep:schemars", "dep:tokio", "dep:xtask-mcp-macros"] # schemars is being used in `xtask_mcp_macros` and it's incorrectly detected as unused. diff --git a/xtask/README.md b/xtask/README.md index 99746b02f9a..f4f9b1bb4fc 100644 --- a/xtask/README.md +++ b/xtask/README.md @@ -8,60 +8,124 @@ Automation using [cargo-xtask](https://github.com/matklad/cargo-xtask). Usage: esp-devtool Commands: - build Build-related subcommands - run Run-related subcommands + build Build examples or HIL tests + run Run an example or qa binary + check Check crates, or try-build examples and tests + test Run HIL tests + doc Build rustdoc for the specified packages and chips + doc-tests Run rustdoc tests for the specified chip + elfs Run prebuilt ELFs with probe-rs release Release-related subcommands ci Perform (parts of) the checks done in CI - fmt-packages Format all packages in the workspace with rustfmt + fmt Format all packages in the workspace with rustfmt clean Run cargo clean - check-packages Check all packages in the workspace with cargo check - lint-packages Lint all packages in the workspace with clippy - semver-check Semver Checks - check-changelog Check the changelog for packages - check-pr-changelog Validate the changelog format of a PR description - host-tests Run host-tests in the workspace with `cargo test` - check-global-symbols Check global symbols in the compiled `.rlib` of the specified packages for the specified chips - generate-report Generate reports from CI data - rel-check Tasks for checking compile tests with a local registry - mcp Start the MCP server (stdio transport, for use with Claude Code) - help Print this message or the help of the given subcommand(s) + lint Lint all packages in the workspace with clippy + ... +``` + +`build` / `run` / `check` / `test` take free-form tokens (chip, crate, example, test, or a package +alias like `examples` / `qa` / `tests`) in any order. There is no `--chip` flag: write `esp32c6`, +or `c6` for short. +A crate name is only a token `check` acts on, the other three want firmware: examples or HIL tests. +`--package` exists for callers that want to be explicit and accepts the same names and aliases the +tokens do, so `build qa all esp32c6` and `build all --package qa-test esp32c6` are the same command. + +`lint`, `ci`, `doc`, `doc-tests` and `check-global-symbols` take the chip the same way, +as a bare name, shortened or not. The one exception is `semver-check`, which takes `--chips`, it has a subcommand of +its own, and clap cannot tell a trailing chip name from it. -Options: - -h, --help Print help +`lint` and `doc` read crates from their tokens too, so `doc esp-hal esp-radio +esp32 esp32c6` documents both crates for both chips. Naming no crate means every crate, naming no +chip means every chip. + +```text +cargo xtask build --help ``` -You can get help for subcommands, too! +```text +Usage: esp-devtool build [OPTIONS] [TOKENS]... +``` + +### Selecting examples ```text -cargo xtask build examples --help - Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.11s - Running `[...]/target/debug/xtask build examples --help` +cargo xtask build uart esp32c6 +cargo xtask build examples all esp32c6 +cargo xtask build qa all esp32c6 +cargo xtask run hello_world +``` + +`examples` / `qa` / `tests` are package aliases, so `build examples uart` still selects the examples +crate. Omitting the name is not a shortcut for `all`. The command asks which example to act on, so a +caller with no terminal — a script, a CI job, an agent — gets an error naming this argument instead +of a build. The chip name behaves the same way when it is missing. + +A name may be a binary name, a relative path (`ota/update`), or a fragment that fits one of them: +`build sdmmc` finds `sdmmc_sd_async`. `-` and `_` are interchangeable, so `run sleep_timer` finds +`sleep-timer`. A name that fits several binaries, or none, opens a selector over every binary the +command can act on, with the name already typed into its filter. Without a terminal, several fits +are an error listing them. + +`run`, `test` and `check` infer the chip from a connected device when it is not named. `run` and +`test` use the tool they are about to drive it with, `espflash` and `probe-rs`. `check` drives +nothing, so it takes whichever of the two finds a device, and only looks from a terminal — scripts +and CI jobs keep checking every chip. `build` never looks at hardware at all. + +When an example fails, `run` offers a retry. A retry looks for the board again, on every port rather +than the one it flashed, so a devkit swapped in meanwhile is picked up wherever it turns up. A +different chip starts the command over for it. -Build all examples for the specified chip +`check` with no example or test name and nothing connected checks every published crate on every +chip. To build every HIL test for a chip, write `all` or omit the test name: `build tests esp32c6`. -Usage: esp-devtool build examples [OPTIONS] +### Compiling a crate -[...] +`build` only builds firmware, so a crate goes to `check`: `check esp-hal esp32c6` compiles the crate +for that chip, once per feature case from its `check-configs`. Naming no chip does that for every +chip it supports. + +`cargo check` skips codegen and linking, so it will not hand you an artifact. Reach for cargo itself +when you need one, the crates sit outside the root workspace: + +```text +cd esp-hal +cargo build --release --target riscv32imac-unknown-none-elf --no-default-features \ + --features esp32c6,unstable,rt ``` -### Selecting examples +## `cargo xtask` vs `esp-devtool` -`build examples` and `run example` take the example name as their first argument, and `all` in that -position means every example of the package: +The binary is named **`esp-devtool`**. `cargo xtask` is just a cargo alias that builds and +runs it from this repo. + +Same CLI, two ways to invoke it: + +| How | When to use | +|---|---| +| `cargo xtask ` | Default while working in this repo. Cargo rebuilds the tool when its sources change. | +| `esp-devtool ` | Daily use after a one-time install. Skips the rebuild of the tool itself. | + +Install from the repository root: ```text -cargo xtask build examples uart --chip esp32c6 -cargo xtask build examples all --chip esp32c6 -cargo xtask build examples all --chip esp32c6 --package qa-test +cargo install-xtask ``` -Omitting the name is not a shortcut for `all`. The command asks which example to act on, so a caller -with no terminal — a script, a CI job, an agent — gets an error naming this argument instead of a -build. `--chip` behaves the same way. +That is an alias for `cargo install --path ./xtask --all-features`. The binary lands in +`~/.cargo/bin/esp-devtool` (must be on `PATH`, which rustup usually already provides). -> Tip: To avoid rebuilding the xtask, you can install it using `cargo install-xtask` from the repo root once, then call `esp-devtool `. -> -> You will need to reinstall from time to time, for example when a new driver is added to `esp-metadata`. +Reinstall after pulling changes that touch `xtask/` or `esp-metadata/` (new chips, new +drivers, CLI changes). Until you reinstall, `esp-devtool` is the old binary. + +```text +esp-devtool fmt +esp-devtool fmt --check +cargo xtask fmt # same command, rebuilt from source +cargo xfmt # cargo alias for `xtask fmt` +``` + +`fmt-packages` and `format-packages` remain aliases of `fmt`. `lint-packages` remains an alias of +`lint`. ## Releasing crates @@ -87,20 +151,24 @@ single backport package, and forces Patch bumps. No `--allow-non-main` needed. package where `Package::has_host_tests` finds a `#[test]` function under `src/**/*.rs`. -**Detection is not enough.** Each package with host tests also needs a match arm -in `run_host_tests` (`xtask/src/lib.rs`). Without it, xtask fails with -`Instructions for host testing were not provided for: ''` even though -the tests compile with `cargo test -p `. +Manifest consistency tests (for example `cargo test chip_coverage`) live in the +`xtask` crate itself. CI covers them with `cd xtask && cargo test --features release` +in the same `host-tests` job. Run that locally the same way. + +**Detection is not enough.** Each package with host tests also needs `host-test-configs` +under `[package.metadata.espressif]` in its `Cargo.toml`. Without it, xtask fails with +`Instructions for host testing were not provided in Cargo.toml (\`host-test-configs\`) for: ''` +even though the tests compile with `cargo test -p `. When adding host tests to a package: 1. Add the tests (`#[test]` in `src/`, and/or `tests/*.rs` integration tests). -2. Add a `Package:: => { ... }` arm to `run_host_tests` with the right - `cargo test` invocation (features, `--lib`, `--tests`, Miri, etc.). Copy a +2. Add a `host-test-configs` array under `[package.metadata.espressif]` in the crate's `Cargo.toml` + with the right `cargo test` options (`features`, `cargo-args`, `test-args`, `miri`). Copy a similar package if unsure. 3. Verify with `cargo xtask host-tests `. -## Package metadata: `check-configs`, `clippy-configs`, `doc-config`, `semver-config` +## Package metadata: `check-configs`, `clippy-configs`, `doc-config`, `semver-config`, `host-test-configs` Published crates can list CI check, clippy, documentation, and semver cases under `[package.metadata.espressif]` in their `Cargo.toml`. Each case is one inline table; `features` @@ -147,7 +215,7 @@ semver-config = { `check-configs` and `clippy-configs` are arrays of cases. `doc-config` and `semver-config` are single inline tables. -`cargo xtask check-packages` reads `check-configs`; `cargo xtask lint-packages` reads +`cargo xtask check` reads `check-configs`; `cargo xtask lint` reads `clippy-configs`; documentation builds read `doc-config`; semver checks read `semver-config`. If `check-configs` is absent, a single default case with no features and no env overrides is used. `CI`, `DEFMT_LOG`, and `ESP_LOG` (check only) are always set by xtask and override duplicate keys from metadata. Documentation @@ -155,6 +223,12 @@ builds and doc-tests always set `RUSTDOCFLAGS` (and `ESP_HAL_DOCTEST` for doc-te duplicate keys from `doc-config`. Semver checks always set `RUSTDOCFLAGS` and override duplicate keys from `semver-config`. +Other optional keys under `[package.metadata.espressif]`: + +- `host-test-configs` — array of host `cargo test` cases (`features`, `cargo-args`, `test-args`, `miri`); see [Host tests](#host-tests) above. +- `host-features` — array of cargo features enabled when building or checking a host-buildable package on the host target. +- `aliases` — array of short CLI aliases accepted for the package in `cargo xtask` commands (for example `["test", "tests"]` on `hil-test` or `["qa"]` on `qa-test`). + ## Test/example metadata use Each test and example can specify metadata. This metadata is read, interpreted and used by the @@ -243,6 +317,13 @@ you can use the `crate-name/feature-name` format. This key is additive. The unnamed list is added to named lists, and multiple lists with the same name are merged. +`FEATURES-IF(expr)` adds those features on every existing configuration, only for chips +matching `expr` (the same syntax as `CHIP_FILTER`), and never creates a binary: + +``` +//% FEATURES-IF(esp32s3): psram +``` + ### `//% ENV` Environmental variables to be set, when building the test or example. This is @@ -258,6 +339,16 @@ One environment variable is specified in a single line. The name and value are s This key is additive. The unnamed list is added to named lists, and multiple lists with the same name are merged. +`ENV(name)` creates that configuration if it does not exist. `ENV-IF(expr)` sets one +variable on every existing configuration, only for chips matching `expr` (the same syntax +as `CHIP_FILTER`), and never creates a binary. Other env vars are left as they are. If that +variable was already set, this line replaces it for those chips: + +``` +//% ENV-IF(esp32s3): ESP_HAL_CONFIG_DATA_CACHE_SIZE=32KB +//% ENV-IF(psram_driver_supported && !soc_has_flash): ESP_ALLOC_CONFIG_HEAP_ALGORITHM=LLFF +``` + ### `//% CARGO-CONFIG` The value of this key will be passed as a `--config` argument to `cargo`. Any amount @@ -292,9 +383,9 @@ option, while the other will select `multiple-integrated`. You can specify a test or example by file, or by configuration. If the parameters match multiple files, they will be built or executed in succession. -For example, running `cargo xtask run tests esp32 embassy_test` will run both +For example, running `cargo xtask test esp32 embassy_test` will run both `embassy_test_single_integrated` and `embassy_test_multiple_integrated`, but you can also -run `cargo xtask run tests esp32 embassy_test_multiple_integrated` to select only one. +run `cargo xtask test esp32 embassy_test_multiple_integrated` to select only one. In this example, running the `cargo xtask build tests esp32 embassy_test` command creates an `embassy_test_single_integrated` and an `embassy_test_multiple_integrated` binary. diff --git a/xtask/build.rs b/xtask/build.rs new file mode 100644 index 00000000000..35caf2bcf2c --- /dev/null +++ b/xtask/build.rs @@ -0,0 +1,254 @@ +use std::{ + env, + fmt::Write as _, + fs, + path::{Path, PathBuf}, +}; + +struct DiscoveredPackage { + name: String, + variant: String, + directory: String, + aliases: Vec, + contains_standalone_projects: bool, +} + +fn main() { + let manifest_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); + let workspace = manifest_dir + .parent() + .expect("xtask must live inside workspace root"); + let root_manifest = workspace.join("Cargo.toml"); + println!("cargo::rerun-if-changed={}", root_manifest.display()); + + let packages = discover_packages(workspace, &root_manifest); + let code = generate_packages_rs(&packages); + + let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap()); + fs::write(out_dir.join("packages.rs"), code).expect("Failed to write generated packages.rs"); +} + +fn discover_packages(workspace: &Path, root_manifest: &Path) -> Vec { + let content = fs::read_to_string(root_manifest) + .unwrap_or_else(|e| panic!("Failed to read {}: {e}", root_manifest.display())); + let doc = content + .parse::() + .unwrap_or_else(|e| panic!("Failed to parse {}: {e}", root_manifest.display())); + + // Root `[workspace].exclude` lists all crates and project folders in the repo. + let excludes = doc + .get("workspace") + .and_then(|w| w.get("exclude")) + .and_then(|e| e.as_array()) + .expect("Root Cargo.toml must have [workspace].exclude"); + + let mut discovered = Vec::new(); + for entry in excludes { + let Some(rel_dir) = entry.as_str() else { + continue; + }; + // Skip helper tools that are not xtask packages. + if rel_dir.starts_with("extras/") || rel_dir == "init-local-registry" { + continue; + } + let path = workspace.join(rel_dir); + if !path.is_dir() { + continue; + } + // A Cargo.toml marks a single crate, otherwise the folder holds standalone projects. + let manifest_path = path.join("Cargo.toml"); + if manifest_path.exists() { + println!("cargo::rerun-if-changed={}", manifest_path.display()); + let (name, aliases) = read_package_metadata(&manifest_path) + .unwrap_or_else(|| (rel_dir.to_string(), Vec::new())); + discovered.push(make_discovered_package( + name, + rel_dir.to_string(), + aliases, + false, + )); + } else { + println!("cargo::rerun-if-changed={}", path.display()); + let aliases = rel_dir + .strip_suffix('s') + .map(ToOwned::to_owned) + .into_iter() + .collect(); + discovered.push(make_discovered_package( + rel_dir.to_string(), + rel_dir.to_string(), + aliases, + true, + )); + if let Ok(entries) = fs::read_dir(&path) { + let mut subdirs: Vec = entries.flatten().map(|e| e.path()).collect(); + subdirs.sort(); + for sub_path in subdirs { + let sub_manifest = sub_path.join("Cargo.toml"); + if sub_path.is_dir() + && sub_manifest.exists() + && let Some((pkg_name, aliases)) = read_package_metadata(&sub_manifest) + { + let sub_rel = sub_path + .strip_prefix(workspace) + .unwrap() + .to_string_lossy() + .replace('\\', "/"); + // Also register multi-binary crates like `examples/qa` (`qa-test`). + if sub_path.join("src").join("bin").is_dir() { + println!("cargo::rerun-if-changed={}", sub_manifest.display()); + discovered + .push(make_discovered_package(pkg_name, sub_rel, aliases, false)); + } + } + } + } + } + } + + discovered +} + +fn read_package_metadata(manifest_path: &Path) -> Option<(String, Vec)> { + let content = fs::read_to_string(manifest_path) + .unwrap_or_else(|e| panic!("failed to read {}: {e}", manifest_path.display())); + let doc = content + .parse::() + .unwrap_or_else(|e| panic!("failed to parse {}: {e}", manifest_path.display())); + let package = doc.get("package")?; + let name = package.get("name")?.as_str()?.to_owned(); + let aliases = package + .get("metadata") + .and_then(|m| m.get("espressif")) + .and_then(|e| e.get("aliases")) + .and_then(|a| a.as_array()) + .map(|arr| { + arr.iter() + .filter_map(|v| v.as_str().map(ToOwned::to_owned)) + .collect() + }) + .unwrap_or_default(); + Some((name, aliases)) +} + +fn make_discovered_package( + name: String, + directory: String, + aliases: Vec, + contains_standalone_projects: bool, +) -> DiscoveredPackage { + let variant = kebab_to_pascal(&name); + DiscoveredPackage { + name, + variant, + directory, + aliases, + contains_standalone_projects, + } +} + +fn kebab_to_pascal(s: &str) -> String { + s.split(['-', '_', '/']) + .map(|part| { + let mut chars = part.chars(); + match chars.next() { + Some(first) => first.to_ascii_uppercase().to_string() + chars.as_str(), + None => String::new(), + } + }) + .collect() +} + +fn generate_packages_rs(packages: &[DiscoveredPackage]) -> String { + let mut out = String::new(); + writeln!( + out, + "#[derive( + Debug, + Clone, + Copy, + PartialEq, + Eq, + PartialOrd, + Ord, + Hash, + clap::ValueEnum, + strum::Display, + strum::EnumIter, + strum::AsRefStr, + serde::Deserialize, + serde::Serialize, +)] +#[serde(rename_all = \"kebab-case\")] +#[strum(serialize_all = \"kebab-case\")] +/// Represents the packages in the `esp-hal` workspace. +pub enum Package {{" + ) + .unwrap(); + + for pkg in packages { + if !pkg.aliases.is_empty() { + let aliases = pkg + .aliases + .iter() + .map(|a| format!("alias = {a:?}")) + .collect::>() + .join(", "); + writeln!(out, " #[value({aliases})]").unwrap(); + } + writeln!(out, " {},", pkg.variant).unwrap(); + } + writeln!(out, "}}\n").unwrap(); + + writeln!(out, "impl Package {{").unwrap(); + writeln!( + out, + " /// Source directory relative to the workspace root." + ) + .unwrap(); + writeln!(out, " pub fn directory(&self) -> &str {{").unwrap(); + writeln!(out, " match self {{").unwrap(); + for pkg in packages { + if pkg.directory != pkg.name { + writeln!( + out, + " Self::{} => {:?},", + pkg.variant, pkg.directory + ) + .unwrap(); + } + } + writeln!(out, " other => other.as_ref(),").unwrap(); + writeln!(out, " }}").unwrap(); + writeln!(out, " }}\n").unwrap(); + + writeln!( + out, + " /// Is this \"package\" a directory of standalone projects rather than a single crate?" + ) + .unwrap(); + writeln!( + out, + " pub fn contains_standalone_projects(&self) -> bool {{" + ) + .unwrap(); + let standalone_variants: Vec = packages + .iter() + .filter(|p| p.contains_standalone_projects) + .map(|p| format!("Self::{}", p.variant)) + .collect(); + if standalone_variants.is_empty() { + writeln!(out, " false").unwrap(); + } else { + writeln!( + out, + " matches!(self, {})", + standalone_variants.join(" | ") + ) + .unwrap(); + } + writeln!(out, " }}").unwrap(); + writeln!(out, "}}").unwrap(); + + out +} diff --git a/xtask/src/cargo.rs b/xtask/src/cargo.rs index 1ae9be33392..2f7b103aa0f 100644 --- a/xtask/src/cargo.rs +++ b/xtask/src/cargo.rs @@ -601,7 +601,7 @@ const DEPENDENCY_KINDS: [&str; 3] = ["dependencies", "dev-dependencies", "build- impl CargoToml { /// Load and parse the Cargo.toml for the specified package in the given workspace. pub fn new(workspace: &Path, package: Package) -> Result { - let package_path = workspace.join(package.to_string()); + let package_path = workspace.join(package.directory()); let manifest_path = package_path.join("Cargo.toml"); if !manifest_path.exists() { bail!( @@ -633,6 +633,18 @@ impl CargoToml { }) } + /// Load the Cargo.toml for `package` as it existed at `git_ref`, so a frozen + /// crate's requirements come from its release tag rather than the working + /// tree that `bump_crate_version` rewrites. + pub fn at_ref(workspace: &Path, package: Package, git_ref: &str) -> Result { + let repo_relative = format!("{}/Cargo.toml", package.directory()); + let manifest = crate::git::show_file_at_ref(workspace, git_ref, &repo_relative) + .with_context(|| { + format!("Failed to read {repo_relative} at {git_ref} for package {package}") + })?; + Self::from_str(workspace, package, &manifest) + } + /// Create a `CargoToml` instance from a manifest string. pub fn from_str(workspace: &Path, package: Package, manifest: &str) -> Result { // Parse the manifest string into a mutable TOML document. @@ -662,7 +674,7 @@ impl CargoToml { /// Get the absolute path to the package directory. pub fn package_path(&self) -> PathBuf { - self.workspace.join(self.package.to_string()) + self.workspace.join(self.package.directory()) } /// Get the absolute path to the Cargo.toml file of the package. @@ -778,6 +790,52 @@ impl CargoToml { dependencies } + /// The in-repo subset of [`dependency_requirements`], each dependency + /// resolved to its [`Package`]. + pub fn repo_dependency_requirements(&mut self) -> Vec<(Package, String)> { + self.dependency_requirements() + .into_iter() + .filter_map(|(name, req)| Package::from_str(&name, true).ok().map(|pkg| (pkg, req))) + .collect() + } + + /// Every non-dev dependency as a sorted `(name, requirement)` pair, so two + /// manifests can be diffed for drift directly. Renamed deps resolve to the + /// real crate name; deps without a `version` are skipped. + pub fn dependency_requirements(&mut self) -> Vec<(String, String)> { + let mut dependencies = Vec::new(); + self.visit_dependencies(|_, dependency_kind, table| { + if dependency_kind == "dev-dependencies" { + return; + } + for (key, value) in table.iter() { + let (name, version) = match value { + Item::Value(Value::String(version)) => (key, Some(version.value().to_string())), + Item::Value(Value::InlineTable(t)) => { + let name = t.get("package").and_then(|p| p.as_str()).unwrap_or(key); + let version = t.get("version").and_then(|v| v.as_str()).map(String::from); + (name, version) + } + Item::Table(t) => { + let name = t.get("package").and_then(|p| p.as_str()).unwrap_or(key); + let version = t.get("version").and_then(|v| v.as_str()).map(String::from); + (name, version) + } + _ => (key, None), + }; + + if let Some(version) = version { + dependencies.push((name.to_string(), version)); + } + } + }); + dependencies.sort(); + dependencies.dedup(); + dependencies + } + + /// Only the release commands rewrite dependency requirements. + #[cfg_attr(not(feature = "release"), allow(dead_code))] pub(crate) fn change_version_of_dependency( &mut self, package_name: &str, @@ -839,6 +897,7 @@ impl CargoToml { } } +#[cfg_attr(not(feature = "release"), allow(dead_code))] fn format_dependency_version(previous: &str, new: &semver::Version) -> String { // we can expect the version specified in a TOML to be valid let previous = semver::VersionReq::parse(previous).unwrap(); @@ -934,6 +993,47 @@ mod tests { } } + #[test] + fn repo_dependency_requirements_excludes_dev_dependencies() { + // A dev-dependency (esp-radio -> esp-rtos in reality) must not be + // reported as a release dependency; normal and build dependencies are. + let manifest = r#" + [package] + name = "esp-radio" + version = "1.0.0" + + [dependencies] + esp-hal = { version = "1.2.0", path = "../esp-hal" } + + [build-dependencies] + esp-config = { version = "0.8.0", path = "../esp-config" } + + [dev-dependencies] + esp-rtos = { version = "0.3.0", path = "../esp-rtos" } + "#; + + let mut toml = + CargoToml::from_str(&std::path::PathBuf::new(), Package::EspRadio, manifest).unwrap(); + let deps = toml + .repo_dependency_requirements() + .into_iter() + .map(|(pkg, _)| pkg) + .collect::>(); + + assert!( + deps.contains(&Package::EspHal), + "normal dep missing: {deps:?}" + ); + assert!( + deps.contains(&Package::EspConfig), + "build dep missing: {deps:?}" + ); + assert!( + !deps.contains(&Package::EspRtos), + "dev dep should be excluded: {deps:?}" + ); + } + #[test] fn test_bump_version() { struct TestCase { diff --git a/xtask/src/changelog.rs b/xtask/src/changelog.rs index 31950782cc7..7b5b0989a70 100644 --- a/xtask/src/changelog.rs +++ b/xtask/src/changelog.rs @@ -120,6 +120,7 @@ impl Changelog { } /// Finalize the changelog for a new release. + #[cfg_attr(not(feature = "release"), allow(dead_code))] pub fn finalize( &mut self, package: Package, diff --git a/xtask/src/commands/build.rs b/xtask/src/commands/build.rs index 8bc6d385142..24c528ceb66 100644 --- a/xtask/src/commands/build.rs +++ b/xtask/src/commands/build.rs @@ -1,56 +1,36 @@ use std::path::Path; -use anyhow::Result; -use clap::{Args, Subcommand}; +use anyhow::{Result, bail}; +use clap::Args; use strum::IntoEnumIterator as _; -use super::{ExamplesArgs, TestsArgs}; use crate::{ Package, - cargo::{self, CargoAction, CargoArgsBuilder, CargoCommandBatcher}, + cargo::{CargoAction, CargoCommandBatcher}, commands::move_artifacts, firmware::Metadata, metadata::Chip, + resolve::{ResolveInput, resolve}, }; // ---------------------------------------------------------------------------- -// Subcommands - -/// Build subcommands and their arguments. -#[derive(Debug, Subcommand)] -pub enum Build { - /// Build documentation for the specified chip. - Documentation(BuildDocumentationArgs), - /// Build documentation index. - #[cfg(feature = "deploy-docs")] - DocumentationIndex(BuildDocumentationIndexArgs), - /// Build all examples for the specified chip. - Examples(ExamplesArgs), - /// Build the specified package with the given options. - Package(BuildPackageArgs), - /// Build all applicable tests or the specified test for a specified chip. - Tests(TestsArgs), -} - -// ---------------------------------------------------------------------------- -// Subcommand Arguments +// Command Arguments /// Arguments for building documentation. #[cfg_attr( feature = "mcp", xtask_mcp_macros::mcp_tool( description = "Build documentation for the specified packages and chips", - command = "build documentation" + command = "documentation" ) )] #[derive(Debug, Default, Args)] pub struct BuildDocumentationArgs { - /// Package(s) to document. - #[arg(long, value_enum, value_delimiter = ',', default_values_t = Package::iter())] + /// Chip and/or package, in any order. Omitted means every package on every chip. + pub tokens: Vec, + /// Package(s) to document. Accepts the same names the tokens do. + #[arg(long, alias = "package", value_enum, value_delimiter = ',')] pub packages: Vec, - /// Chip(s) to build documentation for. - #[arg(long, value_enum, value_delimiter = ',', default_values_t = Chip::iter())] - pub chips: Vec, /// Base URL of the deployed documentation. #[arg(long)] pub base_url: Option, @@ -74,52 +54,38 @@ pub struct BuildDocumentationIndexArgs { pub base_url: Option, } -/// Arguments for building a package. -#[cfg_attr( - feature = "mcp", - xtask_mcp_macros::mcp_tool( - description = "Build the specified package with the given options", - command = "build package" - ) -)] -#[derive(Debug, Args)] -pub struct BuildPackageArgs { - /// Package to build. - #[arg(value_enum)] - pub package: Package, - /// Target to build for. - #[arg(long)] - pub target: Option, - /// Features to build with. - #[arg(long, value_delimiter = ',')] - pub features: Vec, - /// Toolchain to build with. - #[arg(long)] - pub toolchain: Option, - /// Don't enabled the default features. - #[arg(long)] - pub no_default_features: bool, -} - // ---------------------------------------------------------------------------- // Subcommand Actions /// Build documentation for the specified packages and chips. -pub fn build_documentation(workspace: &Path, mut args: BuildDocumentationArgs) -> Result<()> { - log::debug!( - "Building documentation for packages {:?} on chips {:?}", - args.packages, - args.chips - ); +pub fn build_documentation(workspace: &Path, args: BuildDocumentationArgs) -> Result<()> { + let mut input = ResolveInput::from_tokens(args.tokens); + input.packages = args.packages; + let resolution = resolve(input); + if !resolution.names.is_empty() { + bail!("Unknown argument: {}", resolution.names.join(", ")); + } + let mut packages = if resolution.packages.is_empty() { + Package::iter().collect() + } else { + resolution.packages + }; + let mut chips = if resolution.chips.is_empty() { + Chip::iter().collect() + } else { + resolution.chips + }; + + log::debug!("Building documentation for packages {packages:?} on chips {chips:?}"); crate::documentation::build_documentation( workspace, - &mut args.packages, - &mut args.chips, + &mut packages, + &mut chips, args.base_url.clone(), args.channel, )?; - crate::documentation::build_documentation_index(workspace, &mut args.packages, args.base_url)?; + crate::documentation::build_documentation_index(workspace, &mut packages, args.base_url)?; #[cfg(feature = "preview-docs")] if args.serve { @@ -166,15 +132,16 @@ pub fn build_documentation_index( /// Build all examples for the specified package and chip. pub fn build_examples( - args: ExamplesArgs, + package: Package, + chip: Chip, + debug: bool, + toolchain: Option<&str>, + timings: bool, examples: Vec, package_path: &Path, out_path: Option<&Path>, ) -> Result<()> { - let chip = args.chip.unwrap(); - - // Determine the appropriate build target for the given package and chip: - let target = args.package.as_package().target_triple(&chip)?; + let target = package.target_triple(&chip)?; // Attempt to build each supported example, with all required features enabled: @@ -188,9 +155,9 @@ pub fn build_examples( &target, example, action.clone(), - args.debug, - args.toolchain.as_deref(), - args.timings, + debug, + toolchain, + timings, &[], )?; commands.push(command); @@ -207,57 +174,3 @@ pub fn build_examples( Ok(()) } - -/// Build the specified package with the given options. -pub fn build_package(workspace: &Path, args: BuildPackageArgs) -> Result<()> { - log::debug!( - "Building package '{}' with target '{:?}' and features {:?}", - args.package, - args.target, - args.features - ); - // Absolute path of the package's root: - let package_path = crate::windows_safe_path(&workspace.join(args.package.to_string())); - - // Build the package using the provided features and/or target, if any: - - log::info!("Building package '{}'", package_path.display()); - if !args.features.is_empty() { - log::info!(" Features: {}", args.features.join(",")); - } - if let Some(ref target) = args.target { - log::info!(" Target: {}", target); - } - - let mut builder = CargoArgsBuilder::default() - .subcommand("build") - .arg("--release"); - - if let Some(toolchain) = args.toolchain { - builder = builder.toolchain(toolchain); - } - - if let Some(target) = args.target { - // If targeting an Xtensa device, we must use the '+esp' toolchain modifier: - if target.starts_with("xtensa") { - builder = builder.toolchain("esp"); - builder = builder.arg("-Zbuild-std=core,alloc") - } - builder = builder.target(target); - } - - if !args.features.is_empty() { - builder = builder.features(&args.features); - } - - if args.no_default_features { - builder = builder.arg("--no-default-features"); - } - - let args = builder.build(); - log::debug!("{args:#?}"); - - cargo::run(&args, &package_path)?; - - Ok(()) -} diff --git a/xtask/src/commands/check.rs b/xtask/src/commands/check.rs new file mode 100644 index 00000000000..44bfe8f36f5 --- /dev/null +++ b/xtask/src/commands/check.rs @@ -0,0 +1,245 @@ +use std::{ + path::{Path, PathBuf}, + process::Command, +}; + +use anyhow::{Context, Result}; +use object::{Object, ObjectSymbol, SymbolKind, read::archive::ArchiveFile}; +use rustc_demangle::try_demangle; + +use crate::{ + Package, + cargo::{CargoArgsBuilder, CargoCommandBatcher}, + metadata::{Chip, Config}, +}; + +/// Arguments for checking packages with `cargo check`. +/// +/// Not a clap `Args`, the packages and chips come from the tokens `check` resolved. +#[derive(Debug)] +pub struct CheckPackagesArgs { + /// Package(s) to target. + pub packages: Vec, + + /// Chip(s) to check for. + pub chips: Vec, + + /// The toolchain used to run the checks. + pub toolchain: Option, +} + +/// Check published packages with `cargo check`. +pub fn check_packages(workspace: &Path, args: CheckPackagesArgs) -> Result<()> { + log::debug!("Checking packages: {:?}", args.packages); + let mut packages = args.packages; + packages.sort(); + + let mut commands = CargoCommandBatcher::new(); + + for package in packages.iter().filter(|p| p.is_published()) { + // Unfortunately each package has its own unique requirements for + // building, so we need to handle each individually (though there + // is *some* overlap) + for chip in &args.chips { + log::debug!(" for chip: {}", chip); + let device = Config::for_chip(chip); + + if let Err(e) = package.validate_package_chip(chip) { + log::warn!("{e}. Skipping"); + continue; + } + + for mut check_config in package.check_config_rules(device) { + if package.has_chip_features() { + check_config.features.push(device.name.clone()); + } + + commands.push(build_check_package_command( + workspace, + *package, + chip, + &["--no-default-features"], + &check_config, + args.toolchain.as_deref(), + )?); + } + } + } + + for c in commands.build(false) { + println!( + "Command: cargo {}", + c.command.join(" ").replace("---", "\n ---") + ); + c.run(false)?; + } + + Ok(()) +} + +fn build_check_package_command( + workspace: &Path, + package: Package, + chip: &Chip, + args: &[&str], + check_config: &crate::CheckConfig, + mut toolchain: Option<&str>, +) -> Result { + log::info!( + "Checking package: {} ({}, features: {:?}, env: {:?})", + package, + chip, + check_config.features, + check_config.env + ); + + let path = workspace.join(package.directory()); + let features = &check_config.features; + + let mut builder = CargoArgsBuilder::default() + .subcommand("check") + .manifest_path(path.join("Cargo.toml")); + + if !package.build_on_host(features) { + if chip.is_xtensa() { + // In case the user doesn't specify a toolchain, make sure we use +esp + toolchain.get_or_insert("esp"); + } + builder = builder.target(package.target_triple(chip)?); + } + + if let Some(toolchain) = toolchain { + if !package.build_on_host(features) && toolchain.starts_with("esp") { + builder = builder.config("-Zbuild-std=core,alloc"); + } + builder = builder.toolchain(toolchain); + } + + builder = builder.args(args); + + if !features.is_empty() { + builder = builder.arg(format!("--features={}", features.join(","))); + } + + for (key, value) in &check_config.env { + builder.add_env_var(key, value); + } + // TODO: these should come from the outside + builder.add_env_var("CI", "1"); + builder.add_env_var("DEFMT_LOG", "trace"); + builder.add_env_var("ESP_LOG", "trace"); + + Ok(builder) +} + +/// Build the given package for the given chip and return its `.rlib path` with `esp` toolchain. +fn build_rlib(package: &str, chip: &str, target: &str) -> Result { + let workspace = std::env::current_dir().with_context(|| "Failed to get the current dir!")?; + Command::new("cargo") + .args([ + "+esp", + "build", + "--no-default-features", + "--features", + chip, + "--target", + target, + "-Zbuild-std=core", + ]) + .current_dir(workspace.join(package)) + .status() + .context("Failed to run cargo build")?; + + let lib_name = format!("lib{}.rlib", package.replace('-', "_")); + let rlib_path = Path::new("target") + .join(target) + .join("debug") + .join(&lib_name); + + if !rlib_path.exists() { + anyhow::bail!("Expected rlib not found: {}", rlib_path.display()); + } + + Ok(rlib_path) +} + +/// Check global symbols in the compiled rlib of the specified packages for the +/// specified chips. Reports any unmangled global symbols that may pollute the +/// global namespace. +pub fn check_global_symbols(chips: &[Chip]) -> Result<()> { + let mut total_problematic = vec![]; + + let package = Package::EspHal; // Only esp-hal for now + + for chip in chips { + let target = package.target_triple(chip)?; + + let rlib_path = match build_rlib(package.as_ref(), chip.as_ref(), &target) { + Ok(path) => path, + Err(e) => { + println!( + "Failed to build/find rlib for {} on {}: {}", + package, chip, e + ); + continue; + } + }; + + log::info!("Checking global symbols for {} on {}:\n", package, chip); + + let data = std::fs::read(&rlib_path) + .with_context(|| format!("Failed to read {}!", rlib_path.display()))?; + let archive = ArchiveFile::parse(data.as_slice()) + .with_context(|| "Failed to create archive!".to_string())?; + + let mut problematic_symbols: Vec<(String, SymbolKind, usize)> = Vec::new(); + + for member in archive.members().flatten() { + let obj = object::File::parse( + member + .data(data.as_slice()) + .with_context(|| "Failed to parse archive!")?, + )?; + + for symbol in obj.symbols().filter(|s| s.is_global() && s.is_definition()) { + if let Ok(name) = symbol.name() + && try_demangle(name).is_err() + { + let section = symbol.section_index().map(|i| i.0).unwrap_or(0); + problematic_symbols.push((name.to_string(), symbol.kind(), section)); + } + } + } + + if problematic_symbols.is_empty() { + println!("All global symbols are properly mangled Rust symbols\n"); + } else { + println!( + "Found {} potentially problematic global symbols:", + problematic_symbols.len(), + ); + + for (name, kind, _) in &problematic_symbols { + println!("{:?} {}", kind, name); + } + + total_problematic.extend( + problematic_symbols + .into_iter() + .map(|(name, kind, _)| (chip, name, kind)), + ); + } + } + + if !total_problematic.is_empty() { + for (chip, name, kind) in total_problematic.iter() { + println!("{}: {} ({:?})", chip, name, kind); + } + Err(anyhow::anyhow!( + "Found {count} unmangled global symbols across all packages/chips", + count = total_problematic.len() + )) + } else { + Ok(()) + } +} diff --git a/xtask/src/commands/check_changelog.rs b/xtask/src/commands/check_changelog.rs index 811ce6acabd..9f7a6e80426 100644 --- a/xtask/src/commands/check_changelog.rs +++ b/xtask/src/commands/check_changelog.rs @@ -23,7 +23,7 @@ pub fn check_changelog(workspace: &Path, packages: &[Package], normalize: bool) } fn check_changelog_for_package(workspace: &Path, package: Package, normalize: bool) -> Result<()> { - let changelog_path = workspace.join(package.to_string()).join("CHANGELOG.md"); + let changelog_path = workspace.join(package.directory()).join("CHANGELOG.md"); if !changelog_path.exists() { // No changelog exists for this package diff --git a/xtask/src/commands/ci.rs b/xtask/src/commands/ci.rs new file mode 100644 index 00000000000..f70df3f3ba1 --- /dev/null +++ b/xtask/src/commands/ci.rs @@ -0,0 +1,398 @@ +use std::{path::Path, time::Instant}; + +use anyhow::{Context, Result, bail}; +use clap::Args; +use strum::IntoEnumIterator; + +use super::{ + build::{BuildDocumentationArgs, build_documentation}, + check::{CheckPackagesArgs, check_packages}, + examples::examples, + lint::{LintPackagesArgs, lint_packages}, + run::{DocTestArgs, run_doc_tests}, + tests::tests, +}; +use crate::{Package, cargo::CargoAction, metadata::Chip}; + +/// Arguments for the `ci` subcommand. +#[cfg_attr( + feature = "mcp", + xtask_mcp_macros::mcp_tool( + description = "Perform (parts of) the checks done in CI for a given chip", + command = "ci" + ) +)] +#[derive(Debug, Args)] +pub struct CiArgs { + /// Chip to target. + #[arg(value_enum)] + pub chip: Chip, + + /// The toolchain used to run the lints + #[arg(long)] + pub toolchain: Option, + + /// Steps to run in the CI pipeline. + #[arg(long, value_delimiter = ',')] + pub steps: Vec, + + /// Whether to skip running lints + #[arg(long)] + pub no_lint: bool, + + /// Whether to skip building documentation + #[arg(long)] + pub no_docs: bool, + + /// Whether to skip checking the crates itself + #[arg(long)] + pub no_check_crates: bool, +} + +struct Runner { + failed: Vec<&'static str>, + started_at: Instant, + skip_steps: Vec, + run_steps: Vec, + steps_executed: usize, +} + +impl Runner { + fn new(options: &CiArgs) -> Self { + Self { + failed: Vec::new(), + started_at: Instant::now(), + skip_steps: { + let mut skip = vec![]; + if options.no_lint { + skip.push(String::from("lint")); + } + if options.no_docs { + skip.push(String::from("docs")); + skip.push(String::from("doc-tests")); + } + if options.no_check_crates { + skip.push(String::from("check")); + } + skip + }, + run_steps: options.steps.clone(), + steps_executed: 0, + } + } + + fn run(&mut self, id: &str, group: &'static str, op: impl FnOnce() -> Result<()>) { + if self.skip_steps.iter().any(|s| s == id) { + log::debug!("{group} skipped by user request"); + return; + } + if !self.run_steps.is_empty() && !self.run_steps.iter().any(|s| s == id) { + log::debug!("{group} skipped by user request"); + return; + } + + self.steps_executed += 1; + + // Output grouped logs + // https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-commands#grouping-log-lines + println!("::group::{group}"); + if let Err(e) = op() { + log::error!("{group} failed: {e:?}"); + self.failed.push(group); + } else { + log::debug!("{group} succeeded"); + } + println!("::endgroup::"); + } + + fn finish(self) -> Result<()> { + fn write_summary(message: &str) { + if let Some(summary_file) = std::env::var_os("GITHUB_STEP_SUMMARY") { + std::fs::write(summary_file, message).unwrap(); + } + } + + let expected_to_run = self + .run_steps + .iter() + .filter(|s| !self.skip_steps.contains(s)) + .cloned() + .collect::>(); + if self.steps_executed == 0 && !expected_to_run.is_empty() { + bail!( + "The following steps were requested but not executed: {}. Perhaps they contain typos?", + expected_to_run.join(", ") + ); + } + + log::info!("CI checks completed in {:?}", self.started_at.elapsed()); + + if !self.failed.is_empty() { + let mut summary = String::new(); + summary.push_str("# Summary of failed CI checks\n"); + for failed_check in self.failed { + summary.push_str(&format!("* {failed_check}\n")); + } + println!("{summary}"); + write_summary(&summary); + bail!("CI checks failed"); + } + + Ok(()) + } +} + +/// Perform (parts of) the checks done in CI for a given chip. +pub fn run_ci_checks(workspace: &Path, args: CiArgs) -> Result<()> { + log::info!("Running CI checks for chip: {}", args.chip); + println!("::add-matcher::.github/rust-matchers.json"); + + let run_locally = std::env::var("CI").is_err(); + + let mut runner = Runner::new(&args); + + if !run_locally && args.steps.is_empty() { + runner.skip_steps.push(String::from("tests")); + } + + unsafe { + std::env::set_var("CI", "true"); + } + + runner.run("check", "Check crates", || { + check_packages( + workspace, + CheckPackagesArgs { + packages: Package::iter().collect(), + chips: vec![args.chip], + toolchain: args.toolchain.clone(), + }, + ) + }); + + runner.run("lint", "Lint", || { + lint_packages( + workspace, + LintPackagesArgs { + tokens: vec![args.chip.to_string()], + fix: false, + toolchain: args.toolchain.clone(), + }, + ) + }); + + runner.run("doc-tests", "Run Doc Test", || { + run_doc_tests( + workspace, + DocTestArgs { + tokens: vec![args.chip.to_string()], + packages: Package::iter().collect(), + }, + ) + }); + + runner.run("docs", "Build Docs", || { + build_documentation( + workspace, + BuildDocumentationArgs { + tokens: vec![args.chip.to_string()], + packages: vec![Package::EspHal, Package::EspRadio, Package::EspRtos], + ..Default::default() + }, + ) + }); + + // for chips with esp-lp-hal: Build all supported examples for the low-power + // core first + if args.chip.has_lp_core() { + // Build prerequisite examples (esp-lp-hal) + // `examples` copies the examples to a folder with the chip name as the last + // path element then we copy it to the place where the HP core example + // expects it + runner.run("lp-examples", "Build LP-HAL Examples", || { + // The LP examples aren't really that demanding, but they need to be at a certain place. + // Instead of trying to figure out where the results are, let's just make sure the + // target folder is set up as expected. + let original_target_dir = std::env::var("CARGO_TARGET_DIR"); + + unsafe { + std::env::set_var( + "CARGO_TARGET_DIR", + workspace.join("esp-lp-hal").join("target"), + ); + } + let result = examples( + workspace, + Package::EspLpHal, + args.chip, + Some("all"), + CargoAction::Build(None), + false, + args.toolchain.as_deref(), + false, + ); + + // Still need to rename examples to remove the fingerprint off of their names: + let dir = workspace + .join("esp-lp-hal") + .join("target") + .join(Package::EspLpHal.target_triple(&args.chip)?) + .join("release") + .join("examples"); + let examples = dir + .read_dir() + .with_context(|| format!("Failed to read examples directory: {}", dir.display()))?; + for example in examples { + let example = example.context("Failed to read example")?; + let example_path = example.path(); + if example + .file_type() + .with_context(|| { + format!( + "Failed to get file type for example: {}", + example_path.display() + ) + })? + .is_file() + && example_path.extension().is_none() + { + let example_name = example.file_name().to_string_lossy().to_string(); + let Some((without_fingerprint, fingerprint)) = example_name.rsplit_once('-') + else { + // Skip non-fingerprinted files to avoid self-copying + // artifacts (for example "blinky" -> "blinky"). + continue; + }; + // Cargo fingerprints are hexadecimal, so only rewrite files + // that actually look like fingerprinted artifacts. + if !fingerprint.chars().all(|c| c.is_ascii_hexdigit()) { + continue; + } + + let dst = dir.join(without_fingerprint); + + if dst.exists() { + std::fs::remove_file(&dst).with_context(|| { + format!( + "Failed to remove destination file {} before copying", + dst.display() + ) + })?; + } + + log::debug!("Copying {} to {}", example_path.display(), dst.display()); + + // Copy so we don't trigger a rebuild unnecessarily by deleting the original + std::fs::copy(&example_path, &dst).with_context(|| { + format!( + "Failed to copy example: {} to {}", + example_path.display(), + dst.display() + ) + })?; + // Check that the destination file matches the source file + let dst_contents = std::fs::read(&dst).with_context(|| { + format!("Failed to read destination file: {}", dst.display()) + })?; + let src_contents = std::fs::read(&example_path).with_context(|| { + format!("Failed to read source file: {}", example_path.display()) + })?; + if dst_contents != src_contents { + return Err(anyhow::anyhow!( + "Destination file {} does not match source file {}", + dst.display(), + example_path.display() + )); + } + } + } + + // Restore the original target directory + unsafe { + if let Ok(target) = original_target_dir { + std::env::set_var("CARGO_TARGET_DIR", target); + } else { + std::env::remove_var("CARGO_TARGET_DIR"); + } + } + + result + }); + + // Check documentation. Reuse the "docs" ID, as the docs build should include all applicable + // packages. + runner.run("docs", "Build LP-HAL docs", || { + build_documentation( + workspace, + BuildDocumentationArgs { + tokens: vec![args.chip.to_string()], + packages: vec![Package::EspLpHal], + ..Default::default() + }, + ) + }); + } + + runner.run("examples", "Build examples", || { + // The `ota_example` expects a file named `target/ota_image` - it doesn't + // care about the contents however + std::fs::create_dir_all("./target") + .with_context(|| "Failed to create `./target`".to_string())?; + std::fs::write("./target/ota_image", "DUMMY").with_context(|| { + "Failed to create a dummy file required by ota example!".to_string() + })?; + + examples( + workspace, + Package::Examples, + args.chip, + Some("all"), + CargoAction::Build(None), + true, + args.toolchain.as_deref(), + false, + ) + }); + + runner.run("qa-test", "Build qa-test", || { + examples( + workspace, + Package::QaTest, + args.chip, + Some("all"), + CargoAction::Build(None), + true, + args.toolchain.as_deref(), + false, + ) + }); + + // Try-build tests + runner.run("tests", "Build tests", || { + let target_path = workspace.join("target"); + + tests( + workspace, + Package::HilTest, + args.chip, + None, + CargoAction::Build(Some(target_path.join("tests"))), + 1, + None, + false, + )?; + + tests( + workspace, + Package::HilTestRadio, + args.chip, + None, + CargoAction::Build(Some(target_path.join("tests"))), + 1, + None, + false, + ) + }); + + runner.finish() +} diff --git a/xtask/src/commands/clean.rs b/xtask/src/commands/clean.rs new file mode 100644 index 00000000000..cd028cf1ec4 --- /dev/null +++ b/xtask/src/commands/clean.rs @@ -0,0 +1,54 @@ +use std::path::Path; + +use anyhow::{Context, Result}; +use clap::Args; +use strum::IntoEnumIterator; + +use crate::{Package, cargo::CargoArgsBuilder}; + +/// Arguments for the `clean` subcommand. +#[cfg_attr( + feature = "mcp", + xtask_mcp_macros::mcp_tool( + description = "Run cargo clean for the specified packages", + command = "clean" + ) +)] +#[derive(Debug, Args)] +pub struct CleanArgs { + /// Package(s) to target. + #[arg(value_enum, default_values_t = Package::iter())] + pub packages: Vec, +} + +/// Run `cargo clean` for each package directory that contains a Cargo.toml. +pub fn clean(workspace: &Path, args: CleanArgs) -> Result<()> { + let mut packages = args.packages; + packages.sort(); + + for package in packages { + let path = workspace.join(package.directory()); + for dir in walkdir::WalkDir::new(path) { + if let Ok(dir) = dir + && let path = dir.path() + && path.join("Cargo.toml").exists() + { + log::info!("Cleaning folder: {}", path.display()); + let cargo_args = CargoArgsBuilder::default() + .subcommand("clean") + .arg("--target-dir") + .arg(path.join("target").display().to_string()) + .build(); + + crate::cargo::run(&cargo_args, path).with_context(|| { + format!( + "Failed to run `cargo run` with {cargo_args:?} in {}", + path.display() + ) + })?; + } + } + } + + Ok(()) +} diff --git a/xtask/src/commands/dispatch.rs b/xtask/src/commands/dispatch.rs new file mode 100644 index 00000000000..5223da1c4d0 --- /dev/null +++ b/xtask/src/commands/dispatch.rs @@ -0,0 +1,512 @@ +//! Dispatch `build` / `run` / `check` / `test` after token resolution. + +use std::{io::IsTerminal as _, path::Path}; + +use anyhow::{Result, bail}; +use clap::Args; +use inquire::Select; +use strum::IntoEnumIterator as _; + +use super::{check::CheckPackagesArgs, examples::examples, tests::tests}; +use crate::{ + Package, + cargo::CargoAction, + firmware, + metadata::Chip, + resolve::{ResolveInput, resolve}, +}; + +/// The verb being dispatched. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Verb { + Build, + Run, + Check, + Test, +} + +/// Flags and free-form tokens shared by `build` / `run` / `check` / `test`. +#[cfg_attr( + feature = "mcp", + xtask_mcp_macros::mcp_tool(verbs( + build = "Build examples or HIL tests. Tokens: chip, example, test, or package alias (examples, tests, qa), in any order. Crates are not built, use `check` for those. Always pass the chip, building detects no device.", + run = "Flash and run an example or qa binary. Tokens: chip, example name, or package alias (examples, qa). Not for HIL tests — use `test`. Chip is inferred from a connected device when omitted.", + check = "Check crates with cargo check, or try-build examples and tests. Tokens: chip, crate, example, test, or package alias. No tokens checks all published crates on all chips. Pass the chip when naming an example or test, checking detects no device.", + test = "Run HIL tests only. Tokens: chip and/or test name. Not for examples — use `run`. Chip is inferred from probe-rs when omitted.", + )) +)] +#[derive(Debug, Args)] +pub struct DispatchArgs { + /// Package(s) to act on. + #[arg(long, alias = "packages", value_enum, value_delimiter = ',')] + pub package: Vec, + + /// Build examples in debug mode. + #[arg(long)] + pub debug: bool, + + /// Toolchain used to build. + #[arg(long)] + pub toolchain: Option, + + /// Emit crate build timings. + #[arg(long)] + pub timings: bool, + + /// Repeat HIL tests this many times. Used by `test`, ignored by `run`. + #[arg(long, default_value_t = 1)] + pub repeat: usize, + + /// HIL test selector(s). Also accepted as free-form tokens. Used by `test` / `build` / + /// `check`, `run --test` is an error. + #[arg(long, short = 't', alias = "tests", value_delimiter = ',', num_args = 1..)] + pub test: Option>, + + /// Chip, crate, example, or test names, in any order. + pub tokens: Vec, +} + +/// Resolve tokens and run the matching existing action. +pub fn dispatch( + workspace: &Path, + verb: Verb, + args: DispatchArgs, + check_libs: impl FnOnce(CheckPackagesArgs) -> Result<()>, +) -> Result<()> { + let mut input = ResolveInput::from_tokens(args.tokens.iter().cloned()); + input.packages = args.package.clone(); + + let mut resolution = resolve(input); + match verb { + Verb::Run => { + if args.test.is_some() { + bail!("HIL tests use `test`, not `run`."); + } + for package in &resolution.packages { + if !is_example_package(*package) { + bail!("`run` only flashes examples or qa, use `test` for HIL tests"); + } + } + for name in &resolution.names { + if is_test_package(source_package(workspace, name)) { + log::error!( + "`{name}` is a HIL test. You probably want to use `test` instead of `run`." + ); + std::process::exit(1); + } + } + } + Verb::Test => { + for package in &resolution.packages { + if !is_test_package(*package) { + bail!("`test` only runs HIL tests. Use `run` for examples."); + } + } + } + _ => {} + } + if let Some(tests) = &args.test { + for name in tests { + if !resolution.names.iter().any(|existing| existing == name) { + resolution.names.push(name.clone()); + } + } + } + + for name in &mut resolution.names { + *name = expand_name(workspace, verb, &resolution.packages, name)?; + } + + if resolution.packages.is_empty() { + return dispatch_defaults(workspace, verb, &resolution, &args, check_libs); + } + + let mut lib_packages = Vec::new(); + + for package in &resolution.packages { + // `esp-lp-hal` holds examples but is a crate as well, so checking it without naming an + // example checks the crate. + if verb == Verb::Check && resolution.names.is_empty() && package.is_published() { + lib_packages.push(*package); + } else if is_test_package(*package) { + dispatch_tests( + workspace, + verb, + &resolution.chips, + &resolution.names, + *package, + &args, + )?; + } else if is_example_package(*package) { + dispatch_examples( + workspace, + verb, + &resolution.chips, + &resolution.names, + *package, + &args, + )?; + } else if verb == Verb::Check { + lib_packages.push(*package); + } else { + bail!( + "Cannot {} crate '{package}'. Pass an example or test name, or use `check`.", + format!("{verb:?}").to_lowercase() + ); + } + } + + if !lib_packages.is_empty() { + check_libs(CheckPackagesArgs { + packages: lib_packages, + chips: chips_or_all(&resolution.chips)?, + toolchain: args.toolchain.clone(), + })?; + } + + Ok(()) +} + +fn dispatch_defaults( + workspace: &Path, + verb: Verb, + resolution: &crate::resolve::Resolution, + args: &DispatchArgs, + check_libs: impl FnOnce(CheckPackagesArgs) -> Result<()>, +) -> Result<()> { + match verb { + Verb::Test => dispatch_tests( + workspace, + verb, + &resolution.chips, + &resolution.names, + Package::HilTest, + args, + ), + Verb::Check if resolution.names.is_empty() => check_libs(CheckPackagesArgs { + packages: Package::iter().collect(), + chips: chips_or_all(&resolution.chips)?, + toolchain: args.toolchain.clone(), + }), + Verb::Check | Verb::Build | Verb::Run => { + if resolution.names.is_empty() { + return dispatch_examples( + workspace, + verb, + &resolution.chips, + &resolution.names, + Package::Examples, + args, + ); + } + for name in &resolution.names { + let package = source_package(workspace, name); + if is_test_package(package) { + dispatch_tests( + workspace, + verb, + &resolution.chips, + std::slice::from_ref(name), + package, + args, + )?; + } else { + dispatch_examples( + workspace, + verb, + &resolution.chips, + std::slice::from_ref(name), + package, + args, + )?; + } + } + Ok(()) + } + } +} + +/// The chips to check crates for: the ones that were named, the connected one, or all of them. +fn chips_or_all(chips: &[Chip]) -> Result> { + if !chips.is_empty() { + Ok(chips.to_vec()) + } else if let Some(chip) = connected_chip()? { + Ok(vec![chip]) + } else { + Ok(Chip::iter().collect()) + } +} + +/// The connected chip, for `check`. Only looked for in a terminal, so scripts and CI jobs keep +/// checking every chip. +fn connected_chip() -> Result> { + if !std::io::stdin().is_terminal() { + return Ok(None); + } + if let Some(chip) = crate::detect::with_probe_rs()? { + return Ok(Some(chip)); + } + crate::detect::with_espflash() +} + +fn is_example_package(package: Package) -> bool { + matches!( + package, + Package::Examples | Package::QaTest | Package::EspLpHal | Package::CompileTests + ) +} + +fn is_test_package(package: Package) -> bool { + matches!(package, Package::HilTest | Package::HilTestRadio) +} + +/// The packages that hold examples or tests. +const FIRMWARE_PACKAGES: [Package; 4] = [ + Package::Examples, + Package::QaTest, + Package::HilTest, + Package::HilTestRadio, +]; + +/// Decide which package owns `name`: a standalone example, a qa bin, or a HIL test. +/// Unknown names default to [`Package::Examples`]. +fn source_package(workspace: &Path, name: &str) -> Package { + if name.eq_ignore_ascii_case("all") { + return Package::Examples; + } + + FIRMWARE_PACKAGES + .into_iter() + .find(|package| { + firmware::load_package(workspace, *package) + .is_ok_and(|firmware| firmware.iter().any(|meta| meta.matches_name(name))) + }) + .unwrap_or(Package::Examples) +} + +/// Complete a partial name, so `sdmmc` becomes `sdmmc_sd_async`. +/// +/// `-` and `_` are interchangeable, so `sleep_timer` finds `sleep-timer`. A name that fits several +/// binaries, or none, gets a selector in a terminal, with the name typed into its filter. +fn expand_name(workspace: &Path, verb: Verb, packages: &[Package], name: &str) -> Result { + if name.eq_ignore_ascii_case("all") || name.contains("::") { + return Ok(name.to_owned()); + } + + // Look in the packages that were named, or in the ones this verb can act on. + let searched: Vec = if !packages.is_empty() { + packages.to_vec() + } else { + FIRMWARE_PACKAGES + .into_iter() + .filter(|package| match verb { + Verb::Run => is_example_package(*package), + Verb::Test => is_test_package(*package), + Verb::Build | Verb::Check => true, + }) + .collect() + }; + + let mut candidates: Vec = Vec::new(); + + for package in searched { + let Ok(firmware) = firmware::load_package(workspace, package) else { + continue; + }; + if firmware.iter().any(|meta| meta.matches_name(name)) { + return Ok(name.to_owned()); + } + // One entry per supported chip, so the same name turns up more than once. + for candidate in firmware.iter().map(|meta| meta.binary_name()) { + if !candidates.contains(&candidate) { + candidates.push(candidate); + } + } + } + + let wanted = normalize_name(name); + let fits: Vec<&String> = match candidates + .iter() + .find(|candidate| normalize_name(candidate) == wanted) + { + // `spi` names a test of its own, so it is not the `spi_slave` a fragment would find. + Some(named) => vec![named], + None => candidates + .iter() + .filter(|candidate| normalize_name(candidate).contains(&wanted)) + .collect(), + }; + + if let [fit] = fits[..] { + log::info!("'{name}' selected '{fit}'"); + return Ok(fit.clone()); + } + + if !std::io::stdin().is_terminal() { + if fits.is_empty() { + // Nothing fits, so leave the name alone and let the package have its say about it. + return Ok(name.to_owned()); + } + let fits = fits.iter().map(|fit| fit.as_str()).collect::>(); + bail!("'{name}' fits several: {}", fits.join(", ")); + } + + let nothing_fits = fits.is_empty(); + let message = if nothing_fits { + format!("Nothing is called '{name}', select one:") + } else { + format!("'{name}' fits several, select one:") + }; + candidates.sort(); + + // Not the shared `select` helper: this prompt needs its own filter and a pre-filled name. + let mut prompt = Select::new(&message, candidates).with_scorer(&|input, _, candidate, _| { + normalize_name(candidate) + .contains(&normalize_name(input)) + .then_some(0) + }); + if !nothing_fits { + prompt = prompt.with_starting_filter_input(name); + } + Ok(prompt.prompt()?) +} + +/// Names that differ only in how they separate words are the same name. +fn normalize_name(name: &str) -> String { + name.to_lowercase().replace('-', "_") +} + +fn dispatch_examples( + workspace: &Path, + verb: Verb, + chips: &[Chip], + names: &[String], + package: Package, + args: &DispatchArgs, +) -> Result<()> { + let action = match verb { + Verb::Run => CargoAction::Run, + Verb::Build | Verb::Check => CargoAction::Build(None), + Verb::Test => unreachable!("`test` does not dispatch examples, use `run` instead"), + }; + + // `cargo xtask build compile-tests` with no chip builds the whole + // metadata-driven matrix: every project for every chip its `if` selects, + // each on the chip's toolchain (Xtensa has no stable channel). xtask owns + // this so the release workflow does not enumerate a fixed chip set. + if package == Package::CompileTests && chips.is_empty() && names.is_empty() { + for chip in Chip::iter() { + let toolchain = args.toolchain.as_deref().unwrap_or(if chip.is_xtensa() { + "esp" + } else { + "stable" + }); + examples( + workspace, + package, + chip, + Some("all"), + action.clone(), + args.debug, + Some(toolchain), + args.timings, + )?; + } + return Ok(()); + } + + let names: Vec> = if names.is_empty() { + vec![None] + } else { + names.iter().cloned().map(Some).collect() + }; + + for mut chip in required_chips(verb, chips)? { + loop { + let result = names.iter().try_for_each(|name| { + examples( + workspace, + package, + chip, + name.as_deref(), + action.clone(), + args.debug, + args.toolchain.as_deref(), + args.timings, + ) + }); + // A retry that found another chip connected runs the examples for that one. + if let Err(error) = &result + && let Some(&connected) = error.downcast_ref::() + { + log::info!("Starting over for {connected}"); + chip = connected; + continue; + } + result?; + break; + } + } + Ok(()) +} + +fn dispatch_tests( + workspace: &Path, + verb: Verb, + chips: &[Chip], + names: &[String], + package: Package, + args: &DispatchArgs, +) -> Result<()> { + let action = match verb { + Verb::Build => CargoAction::Build(Some(workspace.join("target").join("tests"))), + // A check only has to compile, collecting ELFs would clobber what `build` left there. + Verb::Check => CargoAction::Build(None), + Verb::Test => CargoAction::Run, + Verb::Run => unreachable!("`run` does not dispatch HIL tests, use `test` instead"), + }; + // `tests` builds every test when given no selector, which is what `all` asks for. + let test = if names.is_empty() || names.iter().any(|name| name.eq_ignore_ascii_case("all")) { + None + } else { + Some(names.to_vec()) + }; + + for chip in required_chips(verb, chips)? { + tests( + workspace, + package, + chip, + test.as_deref(), + action.clone(), + args.repeat, + args.toolchain.as_deref(), + args.timings, + )?; + } + Ok(()) +} + +fn required_chips(verb: Verb, chips: &[Chip]) -> Result> { + if !chips.is_empty() { + return Ok(chips.to_vec()); + } + + // The verbs that drive a device detect it with the tool they are about to use. `build` never + // touches hardware, so it asks instead of poking every serial port. + let inferred = match verb { + Verb::Run => crate::detect::with_espflash()?, + Verb::Test => crate::detect::with_probe_rs()?, + Verb::Check => connected_chip()?, + Verb::Build => None, + }; + if let Some(chip) = inferred { + return Ok(vec![chip]); + } + + Ok(vec![super::select( + "Select your target chip:", + Chip::iter().collect(), + "a chip name", + )?]) +} diff --git a/xtask/src/commands/examples.rs b/xtask/src/commands/examples.rs new file mode 100644 index 00000000000..183bbc6f016 --- /dev/null +++ b/xtask/src/commands/examples.rs @@ -0,0 +1,149 @@ +use std::path::Path; + +use anyhow::{Context, Result, bail}; + +use super::{build::build_examples, run::run_examples, select}; +use crate::{Package, cargo::CargoAction, firmware::ChipCoverage, metadata::Chip}; + +const EXAMPLE_ARGUMENT_HINT: &str = + "the example name as a token, or `all` to act on every example of the package"; + +/// Execute the given action on the specified examples. +pub fn examples( + workspace: &Path, + package: Package, + chip: Chip, + example: Option<&str>, + action: CargoAction, + debug: bool, + toolchain: Option<&str>, + timings: bool, +) -> Result<()> { + log::debug!("Running examples for '{package}' on '{chip:?}'"); + + package + .validate_package_chip(&chip) + .with_context(|| format!("The package '{package}' does not support the chip '{chip:?}'"))?; + + let package_path = crate::windows_safe_path(&workspace.join(package.directory())); + + // Load all examples which support the specified chip and parse their metadata. + let examples = crate::firmware::load_package(workspace, package).with_context(|| { + format!( + "Failed to load specified examples from {}", + package_path.display() + ) + })?; + + let mut examples = examples + .into_iter() + .filter(|example| example.supports_chip(chip)) + .collect::>(); + + // Guard only CompileTests; examples/ coverage is legitimately sparse. + if package == Package::CompileTests && examples.is_empty() { + bail!( + "No compile-test project selects chip '{chip}'. Every chip must be covered by at \ + least one project under compile-tests/ (the `hal` project covers all chips)." + ); + } + + // Skip projects whose forwarded `/` feature will not resolve on a + // published dependency line that predates the chip. + if package == Package::CompileTests && matches!(action, CargoAction::Build(_)) { + let mut supported = Vec::with_capacity(examples.len()); + let mut released = false; + for ex in examples { + match crate::firmware::compile_test_project_supports_chip( + workspace, + ex.example_path(), + chip, + )? { + ChipCoverage::Builds => supported.push(ex), + ChipCoverage::Skipped { released: r } => released |= r, + } + } + examples = supported; + if examples.is_empty() { + // A chip no resolving crate ships yet is legitimately untestable; one + // this release publishes must be covered. + if released { + bail!( + "Chip '{chip}' is untested: this release publishes it, but every \ + compile-test project that selects it depends on a published line that \ + predates it. Add those crates to the release so the `hal` project's pins \ + follow them." + ); + } + log::warn!( + "Skipping compile-tests for {chip}: no crate this build resolves supports it yet" + ); + return Ok(()); + } + } + + examples.sort_by_key(|a| a.binary_name()); + + let mut filtered = vec![]; + + if let Some(example) = example { + filtered.clone_from(&examples); + if !example.eq_ignore_ascii_case("all") { + filtered.retain(|ex| ex.matches_name(example)); + + if filtered.is_empty() { + log::warn!( + "Example '{example}' not found or unsupported for the given chip. Please select one of the existing examples in the desired package." + ); + + let example_name = select( + "Select the example:", + examples + .iter() + .map(|ex| ex.lookup_name(&package_path)) + .collect(), + EXAMPLE_ARGUMENT_HINT, + )?; + + if let Some(selected) = examples.iter().find(|ex| ex.matches_name(&example_name)) { + filtered.push(selected.clone()); + } + } + } + } else { + let example_name = select( + "Select an example:", + examples + .iter() + .map(|ex| ex.lookup_name(&package_path)) + .collect(), + EXAMPLE_ARGUMENT_HINT, + )?; + + if let Some(selected) = examples.iter().find(|ex| ex.matches_name(&example_name)) { + filtered.push(selected.clone()); + } + } + + match action { + CargoAction::Build(out_path) => build_examples( + package, + chip, + debug, + toolchain, + timings, + filtered, + &package_path, + out_path.as_deref(), + ), + CargoAction::Run => run_examples( + package, + chip, + debug, + toolchain, + timings, + filtered, + &package_path, + ), + } +} diff --git a/xtask/src/commands/fmt.rs b/xtask/src/commands/fmt.rs new file mode 100644 index 00000000000..3373197324d --- /dev/null +++ b/xtask/src/commands/fmt.rs @@ -0,0 +1,48 @@ +use std::path::Path; + +use anyhow::Result; +use clap::Args; +use strum::IntoEnumIterator; + +use crate::Package; + +/// Arguments for the `fmt` subcommand. +#[cfg_attr( + feature = "mcp", + xtask_mcp_macros::mcp_tool( + description = "Format all packages in the workspace with rustfmt", + command = "fmt" + ) +)] +#[derive(Debug, Args)] +pub struct FmtPackagesArgs { + /// Run in 'check' mode; exits with 0 if formatted correctly, 1 otherwise + #[arg(long)] + pub check: bool, + + /// Package(s) to target. + #[arg(value_enum, default_values_t = Package::iter())] + pub packages: Vec, +} + +/// Format workspace packages with rustfmt. +pub fn fmt_packages(workspace: &Path, args: FmtPackagesArgs) -> Result<()> { + let mut packages = args.packages; + packages.sort(); + + for package in packages { + crate::format_package(workspace, package, args.check, None)?; + } + + // Keep formatting "helper" crates that are intentionally not in + // the Package enum. + for package_path in ["xtask", "xtask-mcp-macros"] { + log::info!("Formatting package: {}", package_path); + crate::format_package_path(workspace, &workspace.join(package_path), args.check, None)?; + } + + // format ymls in .github/ + crate::format_yml(args.check, "./.github")?; + + Ok(()) +} diff --git a/xtask/src/commands/generate_report.rs b/xtask/src/commands/generate_report.rs deleted file mode 100644 index fe7b63cf18b..00000000000 --- a/xtask/src/commands/generate_report.rs +++ /dev/null @@ -1,107 +0,0 @@ -use std::{ - fs, - fs::File, - io::Write, - path::{Path, PathBuf}, -}; - -use anyhow::{Context, Result}; -use clap::Args; -use regex::Regex; - -/// Generate a combined report from individual binary size reports. -#[derive(Debug, Args)] -pub struct ReportArgs { - /// Input file path for parsing report data. - #[arg(long)] - input: PathBuf, -} - -/// Generate a combined binary size report from individual reports in the specified directory. -pub fn generate_report(workspace: &Path, args: ReportArgs) -> Result<()> { - let input_dir = &args.input; - - let combined_path = workspace.join("report.txt"); - let mut combined = File::create(&combined_path) - .with_context(|| format!("Failed to create report file: {:?}", combined_path))?; - - writeln!(combined, "## Binary Size Report\n")?; - - // Precompile regex filters - let exclude_re = Regex::new(r"\.(debug_.*|symtab|strtab|comment)").unwrap(); - let code_fence_re = Regex::new(r"^```").unwrap(); - let leading_ws_re = Regex::new(r"^[ \t]+").unwrap(); - - // Iterate through files like ./results/result-pr-*.txt - let mut entries: Vec<_> = fs::read_dir(input_dir) - .context("Couldn't open input file for reading!")? - .filter_map(|e| e.ok()) - .filter(|e| { - e.path() - .file_name() - .and_then(|n| n.to_str()) - .map(|n| n.starts_with("result-pr-") && n.ends_with(".txt")) - .unwrap_or(false) - }) - .collect(); - - // Sort for consistent ordering - entries.sort_by_key(|e| e.path()); - - for entry in entries { - let path = entry.path(); - let soc = path - .file_stem() - .and_then(|s| s.to_str()) - .unwrap_or("unknown") - .replace("result-pr-", ""); - - let content = - fs::read_to_string(&path).with_context(|| format!("Failed to read {:?}", path))?; - - let diff = extract_block( - &content, - "EXAMPLE_DIFF< String { - let mut inside = false; - let mut lines = Vec::new(); - - for line in content.lines() { - if line.contains(start_marker) { - inside = true; - continue; - } - if line.contains(end_marker) && inside { - inside = false; - continue; - } - if inside { - if code_fence_re.is_match(line) || exclude_re.is_match(line) { - continue; - } - lines.push(leading_ws_re.replace(line, "").to_string()); - } - } - - lines.join("\n") -} diff --git a/xtask/src/commands/host_tests.rs b/xtask/src/commands/host_tests.rs new file mode 100644 index 00000000000..bf8f117ff79 --- /dev/null +++ b/xtask/src/commands/host_tests.rs @@ -0,0 +1,37 @@ +use std::path::Path; + +use anyhow::Result; +use clap::Args; +use strum::IntoEnumIterator; + +use crate::Package; + +/// Arguments for the `host-tests` subcommand. +#[cfg_attr( + feature = "mcp", + xtask_mcp_macros::mcp_tool( + description = "Run host-tests in the workspace with cargo test", + command = "host-tests" + ) +)] +#[derive(Debug, Args)] +pub struct HostTestsArgs { + /// Package(s) to target. + #[arg(value_enum, default_values_t = Package::iter())] + pub packages: Vec, +} + +/// Run host-tests for packages that declare them. +pub fn host_tests(workspace: &Path, args: HostTestsArgs) -> Result<()> { + let mut packages = args.packages; + packages.sort(); + + for package in packages { + log::debug!("Running host-tests for package: {}", package); + if package.has_host_tests(workspace) { + crate::run_host_tests(workspace, package)?; + } + } + + Ok(()) +} diff --git a/xtask/src/commands/lint.rs b/xtask/src/commands/lint.rs new file mode 100644 index 00000000000..86060dd8c2f --- /dev/null +++ b/xtask/src/commands/lint.rs @@ -0,0 +1,154 @@ +use std::path::Path; + +use anyhow::{Context, Result, bail}; +use clap::Args; +use strum::IntoEnumIterator; + +use crate::{ + Package, + cargo::{CargoArgsBuilder, CargoCommandBatcher}, + metadata::{Chip, Config}, + resolve::{ResolveInput, resolve}, +}; + +/// Arguments for the `lint` subcommand. +#[cfg_attr( + feature = "mcp", + xtask_mcp_macros::mcp_tool( + description = "Lint all packages in the workspace with clippy", + command = "lint" + ) +)] +#[derive(Debug, Args)] +pub struct LintPackagesArgs { + /// Chip and/or package, in any order. Omitted means every published crate on every chip. + pub tokens: Vec, + + /// Automatically apply fixes + #[arg(long)] + pub fix: bool, + + /// The toolchain used to run the lints + #[arg(long)] + pub toolchain: Option, +} + +/// Lint published packages with clippy. +pub fn lint_packages(workspace: &Path, args: LintPackagesArgs) -> Result<()> { + let resolution = resolve(ResolveInput::from_tokens(args.tokens)); + if !resolution.names.is_empty() { + bail!("Unknown argument: {}", resolution.names.join(", ")); + } + let mut packages = if resolution.packages.is_empty() { + Package::iter().collect() + } else { + resolution.packages + }; + let chips = if resolution.chips.is_empty() { + Chip::iter().collect() + } else { + resolution.chips + }; + + log::debug!("Linting packages: {packages:?}"); + packages.sort(); + + for package in packages.iter().filter(|p| p.is_published()) { + // Unfortunately each package has its own unique requirements for + // building, so we need to handle each individually (though there + // is *some* overlap) + for chip in &chips { + log::debug!(" for chip: {}", chip); + let device = Config::for_chip(chip); + + if let Err(e) = package.validate_package_chip(chip) { + log::warn!("{e}. Skipping"); + continue; + } + + for mut check_config in package.lint_config_rules(device) { + if package.has_chip_features() { + check_config.features.push(device.name.clone()); + } + + lint_package( + workspace, + *package, + chip, + &["--no-default-features"], + &check_config, + args.fix, + args.toolchain.as_deref(), + )?; + } + } + } + + Ok(()) +} + +fn lint_package( + workspace: &Path, + package: Package, + chip: &Chip, + args: &[&str], + check_config: &crate::CheckConfig, + fix: bool, + mut toolchain: Option<&str>, +) -> Result<()> { + log::info!( + "Linting package: {} ({}, features: {:?}, env: {:?})", + package, + chip, + check_config.features, + check_config.env + ); + + let path = workspace.join(package.directory()); + let features = &check_config.features; + + let mut builder = CargoArgsBuilder::default() + .subcommand("clippy") + .manifest_path(path.join("Cargo.toml")); + + if !package.build_on_host(features) { + if chip.is_xtensa() { + // In case the user doesn't specify a toolchain, make sure we use +esp + toolchain.get_or_insert("esp"); + } + builder = builder.target(package.target_triple(chip)?); + } + + if let Some(toolchain) = toolchain { + if !package.build_on_host(features) && toolchain.starts_with("esp") { + builder = builder.config("-Zbuild-std=core,alloc"); + } + builder = builder.toolchain(toolchain); + } + + for arg in args { + builder = builder.arg(arg.to_string()); + } + + if !features.is_empty() { + builder = builder.arg(format!("--features={}", features.join(","))); + } + + let mut builder = if fix { + builder.arg("--fix").arg("--lib").arg("--allow-dirty") + } else { + builder.arg("--").arg("-D").arg("warnings").arg("--no-deps") + }; + + for (key, value) in &check_config.env { + builder.add_env_var(key, value); + } + builder.add_env_var("CI", "1"); + builder.add_env_var("DEFMT_LOG", "trace"); + + let command = CargoCommandBatcher::build_one_for_cargo(&builder); + crate::cargo::run_with_env(&command.command, &path, command.env_vars, false) + .with_context(|| format!("Failed to run `cargo clippy` in {}", path.display()))?; + + Ok(()) +} diff --git a/xtask/src/commands/mcp.rs b/xtask/src/commands/mcp.rs index ebdc0e65b65..b57832cb8b3 100644 --- a/xtask/src/commands/mcp.rs +++ b/xtask/src/commands/mcp.rs @@ -91,19 +91,11 @@ impl ServerHandler for EspHalServer { .collect(); let packages: Vec = crate::Package::iter().map(|p| p.to_string()).collect(); - // Read the copilot-instructions file for agent onboarding context. - let copilot_instructions = std::env::current_dir() - .ok() - .map(|ws| ws.join(".github/copilot-instructions.md")) - .and_then(|path| std::fs::read_to_string(path).ok()) - .unwrap_or_default(); - let instructions = format!( "esp-hal xtask automation tools. Use these to build, lint, format, test, \ and check the esp-hal workspace.\n\n\ Valid chip values: {}\n\n\ - Valid package values: {}\n\n\ - {copilot_instructions}", + Valid package values: {}", chips.join(", "), packages.join(", "), ); diff --git a/xtask/src/commands/mod.rs b/xtask/src/commands/mod.rs index de71f92be8e..5f9bb20516d 100644 --- a/xtask/src/commands/mod.rs +++ b/xtask/src/commands/mod.rs @@ -1,308 +1,55 @@ -use std::{ - collections::HashMap, - path::{Path, PathBuf}, -}; - -use anyhow::{Context, Result, bail}; -use clap::Args; +use anyhow::{Result, bail}; use inquire::Select; -use serde::Serialize; -use strum::IntoEnumIterator; -pub use self::{build::*, check_changelog::*, check_pr_changelog::*, release::*, run::*}; -use crate::{ - Package, - cargo::{CargoAction, CargoCommandBatcher}, - firmware, - metadata::Chip, +pub use self::{ + build::*, + check::*, + check_changelog::*, + check_pr_changelog::*, + ci::*, + clean::*, + dispatch::DispatchArgs, + fmt::*, + host_tests::*, + lint::*, + release::*, + run::*, }; +use crate::{cargo::CargoAction, metadata::Chip}; + mod build; +mod check; mod check_changelog; mod check_pr_changelog; -#[cfg(feature = "report")] -pub mod generate_report; +mod ci; +mod clean; +pub mod dispatch; +mod examples; +mod fmt; #[cfg(feature = "semver-checks")] pub(crate) mod generate_rom_symbols; +mod host_tests; +mod lint; #[cfg(feature = "mcp")] pub mod mcp; #[cfg(feature = "rel-check")] pub mod relcheck; mod release; mod run; +mod tests; -// ---------------------------------------------------------------------------- -// Top level command and subcommand definitions - -/// Arguments for the `ci` subcommand. -#[cfg_attr( - feature = "mcp", - xtask_mcp_macros::mcp_tool( - description = "Perform (parts of) the checks done in CI for a given chip", - command = "ci" - ) -)] -#[derive(Debug, Args)] -pub struct CiArgs { - /// Chip to target. - #[arg(value_enum)] - pub chip: Chip, - - /// The toolchain used to run the lints - #[arg(long)] - pub toolchain: Option, - - /// Steps to run in the CI pipeline. - #[arg(long, value_delimiter = ',')] - pub steps: Vec, - - /// Whether to skip running lints - #[arg(long)] - pub no_lint: bool, - - /// Whether to skip building documentation - #[arg(long)] - pub no_docs: bool, - - /// Whether to skip checking the crates itself - #[arg(long)] - pub no_check_crates: bool, -} - -/// Arguments for the `fmt-packages` subcommand. -#[cfg_attr( - feature = "mcp", - xtask_mcp_macros::mcp_tool( - description = "Format all packages in the workspace with rustfmt", - command = "fmt-packages" - ) -)] -#[derive(Debug, Args)] -pub struct FmtPackagesArgs { - /// Run in 'check' mode; exits with 0 if formatted correctly, 1 otherwise - #[arg(long)] - pub check: bool, - - /// Package(s) to target. - #[arg(value_enum, default_values_t = Package::iter())] - pub packages: Vec, -} - -/// Arguments for the `clean` subcommand. -#[cfg_attr( - feature = "mcp", - xtask_mcp_macros::mcp_tool( - description = "Run cargo clean for the specified packages", - command = "clean" - ) -)] -#[derive(Debug, Args)] -pub struct CleanArgs { - /// Package(s) to target. - #[arg(value_enum, default_values_t = Package::iter())] - pub packages: Vec, -} - -/// Arguments for the `host-tests` subcommand. -#[cfg_attr( - feature = "mcp", - xtask_mcp_macros::mcp_tool( - description = "Run host-tests in the workspace with cargo test", - command = "host-tests" - ) -)] -#[derive(Debug, Args)] -pub struct HostTestsArgs { - /// Package(s) to target. - #[arg(value_enum, default_values_t = Package::iter())] - pub packages: Vec, -} - -/// Arguments for the `check-packages` subcommand. -#[cfg_attr( - feature = "mcp", - xtask_mcp_macros::mcp_tool( - description = "Check all packages in the workspace with cargo check", - command = "check-packages" - ) -)] -#[derive(Debug, Args)] -pub struct CheckPackagesArgs { - /// Package(s) to target. - #[arg(value_enum, default_values_t = Package::iter())] - pub packages: Vec, - - /// Check for a specific chip - #[arg(long, value_enum, value_delimiter = ',', default_values_t = Chip::iter())] - pub chips: Vec, - - /// The toolchain used to run the checks - #[arg(long)] - pub toolchain: Option, -} - -/// Arguments for the `lint-packages` subcommand. -#[cfg_attr( - feature = "mcp", - xtask_mcp_macros::mcp_tool( - description = "Lint all packages in the workspace with clippy", - command = "lint-packages" - ) -)] -#[derive(Debug, Args)] -pub struct LintPackagesArgs { - /// Package(s) to target. - #[arg(value_enum, default_values_t = Package::iter())] - pub packages: Vec, - - /// Lint for a specific chip - #[arg(long, value_enum, value_delimiter = ',', default_values_t = Chip::iter())] - pub chips: Vec, - - /// Automatically apply fixes - #[arg(long)] - pub fix: bool, - - /// The toolchain used to run the lints - #[arg(long)] - pub toolchain: Option, -} - -// ---------------------------------------------------------------------------- -// Subcommand Arguments - -/// Arguments common to commands which act on examples. -#[cfg_attr( - feature = "mcp", - xtask_mcp_macros::mcp_tool( - description = "Run examples for the specified chip and package", - command = "run example" - ) -)] -#[derive(Debug, Args)] -pub struct ExamplesArgs { - /// Example to act on ("all" will execute every example). Omitting it asks, which needs a - /// terminal. - pub example: Option, - /// Chip to target. - #[arg(value_enum, long)] - pub chip: Option, - /// Package whose examples we wish to act on. - #[arg(value_enum, long, default_value_t = ExamplesPackage::Examples)] - pub package: ExamplesPackage, - /// Build examples in debug mode only - #[arg(long)] - pub debug: bool, - - /// The toolchain used to build the examples - #[arg(long)] - pub toolchain: Option, - - /// Emit crate build timings - #[arg(long)] - pub timings: bool, -} - -/// The different packages which contain examples, and which the `examples` subcommand can act on. -#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)] -pub enum ExamplesPackage { - Examples, - QaTest, - EspLpHal, - CompileTests, -} - -impl From for Package { - fn from(ep: ExamplesPackage) -> Self { - match ep { - ExamplesPackage::Examples => Package::Examples, - ExamplesPackage::QaTest => Package::QaTest, - ExamplesPackage::EspLpHal => Package::EspLpHal, - ExamplesPackage::CompileTests => Package::CompileTests, - } - } -} - -impl ExamplesPackage { - /// Get the underlying Package - pub fn as_package(self) -> Package { - Package::from(self) - } - - fn single_project_examples(&self) -> bool { - matches!( - self, - ExamplesPackage::Examples | ExamplesPackage::CompileTests - ) - } -} - -/// Arguments common to commands which act on doctests. -#[cfg_attr( - feature = "mcp", - xtask_mcp_macros::mcp_tool( - description = "Run doc tests for the specified chip and packages", - command = "run doc-tests" - ) -)] -#[derive(Debug, Args)] -pub struct DocTestArgs { - /// Package(s) where we wish to run doc tests. - #[arg(long, value_enum, value_delimiter = ',', default_values_t = Package::iter())] - pub packages: Vec, - /// Chip to target. - #[arg(value_enum)] - pub chip: Chip, -} - -/// Arguments common to commands which act on tests. -#[cfg_attr( - feature = "mcp", - xtask_mcp_macros::mcp_tool( - description = "Build or run HIL tests for the specified chip", - command = "run tests" - ) -)] -#[derive(Debug, Args)] -pub struct TestsArgs { - /// Chip to target. - #[arg(value_enum)] - pub chip: Chip, - - /// Repeat the tests for a specific number of times. - #[arg(long, default_value_t = 1)] - pub repeat: usize, - /// Optional test to act on (all tests used if omitted). - /// - /// Multiple tests may be selected via a comma-separated list, e.g. `--test rmt,i2c,uart`. - /// The `test_suite::test_name` syntax allows selecting a specific test (and may be combined - /// with commas). - #[arg(long, short = 't', alias = "tests", value_delimiter = ',', num_args = 1..)] - pub test: Option>, - - /// The toolchain used to build the tests - #[arg(long)] - pub toolchain: Option, - - /// Emit crate build timings - #[arg(long)] - pub timings: bool, - - /// "hil-test" or "hil-test-radio" - #[arg(default_value = "hil-test")] - pub package: String, -} - -// ---------------------------------------------------------------------------- -// Subcommand Actions - -const EXAMPLE_ARGUMENT_HINT: &str = - "the example name as the first argument, or `all` to act on every example of the package"; +pub use examples::examples; +pub use tests::tests; /// Asks the caller to pick one of `options`. /// /// A prompt needs someone to answer it, and a caller that is not a person — a script, a CI job, an /// agent — would wait for input that never arrives. Say what to pass instead, and stop. -fn select(message: &str, options: Vec, hint: &str) -> Result { +pub(crate) fn select( + message: &str, + options: Vec, + hint: &str, +) -> Result { use std::io::IsTerminal; if !std::io::stdin().is_terminal() { bail!("\"{message}\" needs a terminal to answer it. Pass {hint}."); @@ -311,555 +58,7 @@ fn select(message: &str, options: Vec, hint: &str) -> R Ok(Select::new(message, options).prompt()?) } -/// Execute the given action on the specified examples. -pub fn examples(workspace: &Path, mut args: ExamplesArgs, action: CargoAction) -> Result<()> { - log::debug!( - "Running examples for '{}' on '{:?}'", - args.package.as_package(), - args.chip - ); - if args.chip.is_none() { - let chip_variants = Chip::iter().collect::>(); - - let chip = select("Select your target chip:", chip_variants, "`--chip `")?; - - args.chip = Some(chip); - } - - let chip = args.chip.unwrap(); - - // Ensure that the package/chip combination provided are valid: - args.package - .as_package() - .validate_package_chip(&chip) - .with_context(|| { - format!( - "The package '{0}' does not support the chip '{chip:?}'", - args.package.as_package() - ) - })?; - - // Absolute path of the package's root: - let package_path = - crate::windows_safe_path(&workspace.join(args.package.as_package().to_string())); - - // Load all examples which support the specified chip and parse their metadata. - // - // Directories might contain a number of individual projects, and don't not rely on - // metadata comments in the source files. As such, it needs to load its metadata differently - // than other packages. - let examples = if args.package.single_project_examples() { - crate::firmware::load_cargo_toml(&package_path).with_context(|| { - format!( - "Failed to load specified examples from {}", - package_path.display() - ) - })? - } else { - let example_path = match args.package.as_package() { - Package::QaTest => package_path.join("src").join("bin"), - _ => package_path.join("examples"), - }; - - crate::firmware::load(&example_path)? - }; - - let mut examples = examples - .into_iter() - .filter(|example| example.supports_chip(chip)) - .collect::>(); - - // At this point, chip can never be `None`, so we can safely unwrap it. - let chip = args.chip.unwrap(); - - // Filter the examples down to only the binaries supported by the given chip - examples.retain(|ex| ex.supports_chip(chip)); - - // Sort all examples by name: - examples.sort_by_key(|a| a.binary_name()); - - let mut filtered = vec![]; - - if let Some(example) = args.example.as_deref() { - filtered.clone_from(&examples); - if !example.eq_ignore_ascii_case("all") { - // Only keep the example the user wants - filtered.retain(|ex| ex.matches_name(example)); - - if filtered.is_empty() { - log::warn!( - "Example '{example}' not found or unsupported for the given chip. Please select one of the existing examples in the desired package." - ); - - let example_name = select( - "Select the example:", - examples.iter().map(|ex| ex.binary_name()).collect(), - EXAMPLE_ARGUMENT_HINT, - )?; - - if let Some(selected) = examples.iter().find(|ex| ex.binary_name() == example_name) - { - filtered.push(selected.clone()); - } - } - } - } else { - let example_name = select( - "Select an example:", - examples.iter().map(|ex| ex.binary_name()).collect(), - EXAMPLE_ARGUMENT_HINT, - )?; - - if let Some(selected) = examples.iter().find(|ex| ex.binary_name() == example_name) { - filtered.push(selected.clone()); - } - } - - // Execute the specified action: - match action { - CargoAction::Build(out_path) => { - build_examples(args, filtered, &package_path, out_path.as_deref()) - } - CargoAction::Run => run_examples(args, filtered, &package_path), - } -} - -/// Execute the given action on the specified HIL tests. -pub fn tests(workspace: &Path, args: TestsArgs, action: CargoAction) -> Result<()> { - // Absolute path of the 'hil-test' package's root: - let package_name = args.package.as_str(); - - let package_path = match package_name { - "hil-test" => crate::windows_safe_path(&workspace.join("hil-test")), - "hil-test-radio" => crate::windows_safe_path(&workspace.join("hil-test-radio")), - other => bail!( - "Unknown package: {}. Use 'hil-test' or 'hil-test-radio'", - other - ), - }; - - // Determine the appropriate build target for the given package and chip: - let target = Package::HilTest.target_triple(&args.chip)?; - - // Load all test metadata first so we can differentiate between: - // - unknown test selectors (typos) - // - valid tests that are unsupported for the selected chip. - let bins_root = package_path.join("src").join("bin"); - let mut all_tests = crate::firmware::load(&bins_root)?; - if package_name == "hil-test-radio" { - let tests_root = bins_root.join("tests"); - if tests_root.exists() { - all_tests.extend(crate::firmware::load(&tests_root)?); - } - let support_root = bins_root.join("support"); - if support_root.exists() { - all_tests.extend(crate::firmware::load(&support_root)?); - } - } - all_tests.sort_by_key(|a| a.binary_name()); - let tests_for_chip = all_tests - .iter() - .filter(|example| example.supports_chip(args.chip)) - .collect::>(); - - // Radio tests reuse the normal HIL flow; the only difference is a pre-step - // that builds and flashes the support firmware on a secondary probe. - let is_radio_package = package_name == "hil-test-radio"; - if let CargoAction::Build(Some(out_dir)) = &action { - // Make sure the tmp directory has no garbage for us. - let tmp_dir = out_dir.join("tmp"); - _ = std::fs::remove_dir_all(&tmp_dir); - std::fs::create_dir_all(&tmp_dir).unwrap(); - } - - let mut commands = CargoCommandBatcher::new(); - let mut artifact_meta = HashMap::::new(); - // Execute the specified action: - // If user sets some specific test(s) - if let Some(test_arg) = args.test.as_deref() { - let trimmed: Vec<&str> = test_arg.iter().map(|s| s.trim()).collect(); - - // Reject `--test ""` / `--test " "` - if trimmed.iter().all(|s| s.is_empty()) { - bail!("Empty test selector is not allowed."); - } - - let mut unknown_selected: Vec = Vec::new(); - let mut unsupported_for_chip: Vec = Vec::new(); - - for selected in trimmed.into_iter().filter(|s| !s.is_empty()) { - let (test_arg, filter) = match selected.split_once("::") { - Some((test, filter)) => (Some(test), Some(filter)), - None => (Some(selected), None), - }; - - let run_test_extra_args = if is_radio_package && action == CargoAction::Run { - &[] - } else { - (action == CargoAction::Run) - .then(|| filter.as_ref().map(std::slice::from_ref)) - .flatten() - .unwrap_or(&[]) - }; - - let matched: Vec<_> = all_tests.iter().filter(|t| t.matches(test_arg)).collect(); - - if matched.is_empty() { - if is_radio_package - && let Some(radio_meta) = - resolve_radio_module_alias(&all_tests, args.chip, selected) - { - let command = crate::generate_build_command( - &package_path, - args.chip, - &target, - &radio_meta, - action.clone(), - false, - args.toolchain.as_deref(), - args.timings, - &[], - )?; - artifact_meta.insert(command.artifact_name.clone(), radio_meta); - commands.push(command); - continue; - } - unknown_selected.push(selected.to_string()); - } else { - let matched_for_chip: Vec<_> = matched - .into_iter() - .filter(|t| t.supports_chip(args.chip)) - .collect(); - - if matched_for_chip.is_empty() { - unsupported_for_chip.push(selected.to_string()); - continue; - } - - for test in matched_for_chip { - let command = crate::generate_build_command( - &package_path, - args.chip, - &target, - test, - action.clone(), - false, - args.toolchain.as_deref(), - args.timings, - run_test_extra_args, - )?; - artifact_meta.insert(command.artifact_name.clone(), test.clone()); - commands.push(command); - } - } - } - - if !unsupported_for_chip.is_empty() { - log::warn!( - "Skipping unsupported tests for '{}': {}", - args.chip, - unsupported_for_chip.join(", ") - ); - } - - if !unknown_selected.is_empty() { - bail!("Test not found: {}", unknown_selected.join(", ")) - } - } else { - for test in tests_for_chip { - let command = crate::generate_build_command( - &package_path, - args.chip, - &target, - test, - action.clone(), - false, - args.toolchain.as_deref(), - args.timings, - &[], - )?; - artifact_meta.insert(command.artifact_name.clone(), test.clone()); - commands.push(command); - } - } - - let mut harness_for_artifact = HashMap::::new(); - if is_radio_package { - for test in artifact_meta.values() { - if is_support_firmware(test) { - continue; - } - let Some(harness_name) = test.harness_firmware() else { - continue; - }; - - let Some(harness_meta) = all_tests.iter().find(|candidate| { - if !candidate.supports_chip(args.chip) { - return false; - } - - let harness_basename = harness_name.rsplit('/').next().unwrap_or(harness_name); - candidate.binary_name() == harness_name - || candidate.output_file_name() == harness_name - || candidate.binary_name() == harness_basename - || candidate.output_file_name() == harness_basename - }) else { - bail!( - "Missing harness firmware '{harness_name}' required by '{}'", - test.output_file_name() - ); - }; - - harness_for_artifact.insert(test.output_file_name(), harness_meta.clone()); - } - } - - // Ensure required harness firmware is built so the artifact is - // self-contained for `run elfs` on the HIL runner. Not needed on Run: - // `build_radio_harness` builds harnesses lazily per test. - if is_radio_package && matches!(action, CargoAction::Build(_)) { - use std::collections::HashSet; - - let mut queued: HashSet = artifact_meta - .values() - .map(firmware::Metadata::output_file_name) - .collect(); - - let mut harnesses_to_add: Vec = Vec::new(); - for harness in harness_for_artifact.values() { - if queued.insert(harness.output_file_name()) { - harnesses_to_add.push(harness.clone()); - } - } - - for harness in harnesses_to_add { - let command = crate::generate_build_command( - &package_path, - args.chip, - &target, - &harness, - action.clone(), - false, - args.toolchain.as_deref(), - args.timings, - &[], - )?; - artifact_meta.insert(command.artifact_name.clone(), harness); - commands.push(command); - } - } - - let mut failed = Vec::new(); - let built_commands = commands.build(false); - let built_artifacts = artifact_meta.keys().cloned().collect::>(); - - let mut built_harness = HashMap::::new(); - - for c in built_commands { - let repeat = if matches!(action, CargoAction::Run) { - args.repeat - } else { - 1 - }; - - let radio_meta = artifact_meta.get(&c.artifact_name); - - // Support firmware never runs as a DUT; it's used only as a pre-step - // for whichever DUT requests it via `HARNESS-FIRMWARE`. - if matches!(action, CargoAction::Run) && radio_meta.is_some_and(is_support_firmware) { - log::info!("Skipping support firmware '{}' as DUT", c.artifact_name); - continue; - } - - println!( - "Command: cargo {}", - c.command.join(" ").replace("---", "\n ---") - ); - - for i in 0..repeat { - if repeat != 1 { - log::info!("Run {}/{}", i + 1, repeat); - } - - if matches!(action, CargoAction::Run) - && let Some(harness_meta) = harness_for_artifact.get(&c.artifact_name) - { - let harness_path = match build_radio_harness( - workspace, - &package_path, - args.chip, - &target, - args.toolchain.as_deref(), - args.timings, - harness_meta, - &mut built_harness, - ) { - Ok(path) => path, - Err(e) => { - failed.push(c.artifact_name.clone()); - log::error!( - "Failed to build harness firmware '{}' for '{}': {e}", - harness_meta.output_file_name(), - c.artifact_name - ); - break; - } - }; - - let harness_spec = crate::radio_hil_runner::HarnessSpec { - binary_path: &harness_path, - target: &target, - }; - if let Err(e) = - crate::radio_hil_runner::run_radio_test(&c, Some(harness_spec), None) - { - failed.push(c.artifact_name.clone()); - log::error!("Radio test '{}' failed: {}", c.artifact_name, e); - break; - } - } else if c.run(false).is_err() { - failed.push(c.artifact_name.clone()); - } - } - } - - move_artifacts(args.chip, &action); - - if !failed.is_empty() { - bail!("Failed tests: {:#?}", failed); - } - - if is_radio_package && let CargoAction::Build(Some(out_dir)) = &action { - write_radio_elf_manifest( - out_dir, - args.chip, - &built_artifacts, - &artifact_meta, - &harness_for_artifact, - )?; - } - - Ok(()) -} - -const RADIO_ELF_MANIFEST_FILENAME: &str = "radio-elfs.json"; - -#[derive(Debug, Serialize)] -struct RadioElfManifestEntry { - artifact: String, - harness: Option, - support_firmware: bool, -} - -fn write_radio_elf_manifest( - out_dir: &Path, - chip: Chip, - built_artifacts: &[String], - artifact_meta: &HashMap, - harness_for_artifact: &HashMap, -) -> Result<()> { - let mut entries = Vec::new(); - for artifact in built_artifacts { - let Some(meta) = artifact_meta.get(artifact) else { - continue; - }; - entries.push(RadioElfManifestEntry { - artifact: artifact.clone(), - harness: harness_for_artifact - .get(artifact) - .map(firmware::Metadata::output_file_name), - support_firmware: is_support_firmware(meta), - }); - } - - if entries.is_empty() { - return Ok(()); - } - - let manifest_path = out_dir - .join(chip.to_string()) - .join(RADIO_ELF_MANIFEST_FILENAME); - let payload = serde_json::to_string_pretty(&entries)?; - std::fs::write(&manifest_path, payload) - .with_context(|| format!("Failed to write {}", manifest_path.display()))?; - Ok(()) -} - -/// Build the harness firmware required by a radio HIL test (if not already -/// built) and return the resulting ELF path. Results are cached in -/// `built_harness` so repeated tests sharing a harness only build it once. -fn build_radio_harness( - workspace: &Path, - package_path: &Path, - chip: Chip, - target: &str, - toolchain: Option<&str>, - timings: bool, - harness: &firmware::Metadata, - built_harness: &mut HashMap, -) -> Result { - let artifact_name = harness.output_file_name(); - if let Some(path) = built_harness.get(&artifact_name) { - return Ok(path.clone()); - } - - let builder = crate::generate_build_command( - package_path, - chip, - target, - harness, - CargoAction::Build(None), - false, - toolchain, - timings, - &[], - )?; - let built = CargoCommandBatcher::build_one_for_cargo(&builder); - log::info!( - "Building harness firmware: cargo {}", - built.command.join(" ") - ); - built - .run(false) - .with_context(|| format!("Failed to build harness firmware '{artifact_name}'"))?; - - let path = crate::radio_hil_runner::resolve_release_binary(workspace, target, &artifact_name); - if !path.exists() { - bail!( - "Harness firmware '{artifact_name}' built successfully but binary not found at {}", - path.display() - ); - } - - built_harness.insert(artifact_name, path.clone()); - Ok(path) -} - -fn resolve_radio_module_alias( - all_tests: &[firmware::Metadata], - chip: Chip, - selected: &str, -) -> Option { - let module_file = format!("{selected}.rs"); - let module_decl = format!("mod {selected};"); - - all_tests - .iter() - .find(|test| { - test.supports_chip(chip) - && test.harness_firmware().is_none() - && std::fs::read_to_string(test.example_path()).is_ok_and(|source| { - source.contains(&module_file) || source.contains(&module_decl) - }) - }) - .cloned() -} - -fn is_support_firmware(meta: &firmware::Metadata) -> bool { - meta.is_support_firmware() -} - -fn move_artifacts(chip: Chip, action: &CargoAction) { +pub(crate) fn move_artifacts(chip: Chip, action: &CargoAction) { if let CargoAction::Build(Some(out_dir)) = action { // Move binaries let from = out_dir.join("tmp"); diff --git a/xtask/src/commands/relcheck.rs b/xtask/src/commands/relcheck.rs index c3a96cd89af..c406a3c866d 100644 --- a/xtask/src/commands/relcheck.rs +++ b/xtask/src/commands/relcheck.rs @@ -1,55 +1,144 @@ use std::{ collections::HashMap, path::{Path, PathBuf}, + process::{Command, Stdio}, str::from_utf8, }; -use anyhow::{Result, bail}; -use clap::{Args, Subcommand}; +use anyhow::{Context, Result, bail, ensure}; +use clap::{Subcommand, ValueEnum as _}; use semver::{Comparator, Op, Version, VersionReq}; use strum::IntoEnumIterator; use toml_edit::Table; -use crate::{Package, cargo::CargoToml, windows_safe_path}; +use crate::{Package, cargo::CargoToml, commands::release::plan::Plan, windows_safe_path}; #[derive(Debug, Subcommand)] pub enum RelCheckCmds { /// Initialize the local registry Init, - /// Deinitialize the local registry Deinit, - - /// Update the local registry from the crates in this repository - Update(UpdateArgs), - - /// Remove the path-dependencies from examples and make sure the dependencies are available in - /// the local registry. + /// Package the release plan's crates into the local registry at their planned versions. + Update, + /// Rewrite `esp-*` path dependencies in examples and tests to registry versions, and point + /// compile-tests at the registry. ReplacePathDeps, /// Validate workspace esp-rom-sys dependency version policy. CheckRomSysPolicy, } -#[derive(Args, Debug, Clone)] -pub struct UpdateArgs { - #[arg(value_enum, default_values_t = Package::iter())] - packages: Vec, -} - pub fn run_rel_check(args: RelCheckCmds) -> Result<()> { ensure_cargo_local_registry()?; match args { RelCheckCmds::Init => init_rel_check()?, RelCheckCmds::Deinit => deinit_rel_check()?, - RelCheckCmds::Update(args) => update(args)?, - RelCheckCmds::ReplacePathDeps => scrap_path_deps()?, + RelCheckCmds::Update => update(&load_plan()?)?, + RelCheckCmds::ReplacePathDeps => scrap_path_deps(&load_plan()?)?, RelCheckCmds::CheckRomSysPolicy => check_rom_sys_policy(Path::new("."))?, } Ok(()) } +fn load_plan() -> Result { + Plan::from_path(Path::new("release_plan.jsonc")) +} + +/// In a GitHub `pull_request` run, write the release plan embedded in the PR +/// body to release_plan.jsonc. A no-op elsewhere: local runs use the file +/// `execute-plan` already wrote. +fn download_release_plan() -> Result<()> { + let Some(pr) = std::env::var("GITHUB_REF") + .ok() + .and_then(|r| pr_number_from_ref(&r)) + else { + return Ok(()); + }; + + let repo = std::env::var("GITHUB_REPOSITORY").unwrap_or_else(|_| crate::UPSTREAM_REPO.into()); + let output = Command::new("gh") + .args(["pr", "view", &pr.to_string()]) + .args(["--repo", &repo, "--json", "body", "-q", ".body"]) + .output() + .context("Failed to run `gh pr view`")?; + ensure!( + output.status.success(), + "`gh pr view {pr}` failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + + let body = String::from_utf8_lossy(&output.stdout); + let plan = extract_jsonc_block(&body) + .with_context(|| format!("PR #{pr} body has no jsonc release-plan block"))?; + std::fs::write("release_plan.jsonc", plan).context("Failed to write release_plan.jsonc") +} + +/// The PR number from a `refs/pull//merge` ref, if `git_ref` is one. +fn pr_number_from_ref(git_ref: &str) -> Option { + git_ref + .strip_prefix("refs/pull/")? + .split('/') + .next()? + .parse() + .ok() +} + +/// The contents of the first ```jsonc fenced block in `text`. +fn extract_jsonc_block(text: &str) -> Option { + let mut lines = text.lines().map(|l| l.trim_end_matches('\r')); + lines + .by_ref() + .find(|l| l.trim_start().starts_with("```jsonc"))?; + let block: Vec<&str> = lines.take_while(|l| l.trim() != "```").collect(); + (!block.is_empty()).then(|| block.join("\n")) +} + +/// The version an `esp-*` path dependency is rewritten to: the plan's version +/// when the crate is being released, otherwise the newest already in the +/// registry. A frozen crate must never resolve to a working-tree version. +fn choose_replacement_version( + krate: &Package, + plan: &Plan, + registry_versions: &[Version], +) -> Result { + if let Some(entry) = plan.packages.iter().find(|entry| &entry.package == krate) { + return Ok(entry.new_version.clone()); + } + + registry_versions.iter().max().cloned().ok_or_else(|| { + anyhow::anyhow!("{krate} is not in the plan and has no version in the local registry") + }) +} + +/// Ambient `CARGO*` variables stripped, so a nested cargo does not leak its +/// resolver configuration into the invoked one. +fn cargo_env() -> Vec<(String, String)> { + std::env::vars() + .filter(|(k, _)| !k.starts_with("CARGO")) + .collect() +} + +/// Run cargo with a clean environment, capturing stderr so a failure (a resolver +/// error included) is surfaced verbatim instead of being retried or swallowed. +fn run_cargo(cmd: &mut Command, what: &str) -> Result<()> { + let output = cmd + .env_clear() + .envs(cargo_env()) + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .output() + .with_context(|| format!("Failed to spawn cargo while {what}"))?; + + ensure!( + output.status.success(), + "cargo failed while {what}:\n{}", + String::from_utf8_lossy(&output.stderr) + ); + Ok(()) +} + fn toolchain() -> String { "esp".to_string() } @@ -120,172 +209,112 @@ fn deinit_rel_check() -> Result<()> { Ok(()) } +/// The shared local registry path, canonicalized and Windows-safe as +/// cargo-local-registry wants it. `target/local-registry` must already exist. +fn local_registry_path() -> Result { + Ok(windows_safe_path( + &PathBuf::from("target/local-registry").canonicalize()?, + )) +} + +/// Path to a toolchain's build-std `Cargo.lock`. +fn build_std_lock(toolchain: &str) -> Result { + Ok(toolchain_folder(toolchain)?.join("lib/rustlib/src/rust/library/Cargo.lock")) +} + +/// `cargo local-registry --no-delete --sync ` with a clean +/// environment (ambient `CARGO*` stripped so a parent cargo does not leak its +/// resolver config). `cwd` is set when `lock` is relative to a subproject. +fn sync_local_registry(lock: &Path, registry: &Path, cwd: Option<&Path>) -> Result<()> { + let mut cmd = Command::new("cargo"); + cmd.arg("local-registry") + .arg("--no-delete") + .arg("--sync") + .arg(lock) + .arg(registry) + .stdout(Stdio::null()) + .env_clear() + .envs(cargo_env()); + if let Some(cwd) = cwd { + cmd.current_dir(cwd); + } + log::info!("{cmd:?}"); + cmd.status()?; + Ok(()) +} + fn init_rel_check() -> Result<()> { - fn prepare_for_directory(project: &Path) -> Result<()> { + fn prepare_for_directory(project: &Path, registry: &Path) -> Result<()> { log::info!("Processing {}", project.display()); let _ = std::fs::remove_file(project.join("Cargo.lock")); // make sure we have the `Cargo.lock` file - let status = std::process::Command::new("cargo") + let status = Command::new("cargo") .arg(format!("+{}", toolchain())) .arg("metadata") .arg("--format-version=1") - .current_dir(&project) - .stdout(std::process::Stdio::null()) + .current_dir(project) + .stdout(Stdio::null()) .status()?; - if !status.success() { log::warn!("Failed"); } // add all dependencies referenced by the lock file - let mut cmd = std::process::Command::new("cargo"); - cmd.arg("local-registry"); - cmd.arg("--no-delete"); - cmd.arg("--sync"); - cmd.arg("Cargo.lock"); - cmd.arg(windows_safe_path( - &std::path::PathBuf::from("target/local-registry") - .canonicalize() - .unwrap(), - )); - cmd.stdout(std::process::Stdio::null()); - cmd.env_clear(); - cmd.envs( - std::env::vars() - .into_iter() - .filter(|(k, _)| !k.starts_with("CARGO")), - ); - cmd.current_dir(&project); - - log::info!("{:?}", cmd); - cmd.status()?; - Ok(()) + sync_local_registry(Path::new("Cargo.lock"), registry, Some(project)) } + download_release_plan()?; + // cleanup if std::fs::exists("target/local-registry")? { std::fs::remove_dir_all("target/local-registry")?; } std::fs::create_dir("target/local-registry")?; + let registry = local_registry_path()?; // prepare latest released versions - prepare_for_directory(Path::new("init-local-registry"))?; + prepare_for_directory(Path::new("init-local-registry"), ®istry)?; // prepare versions from compile-tests - might not be latest released for dir in std::fs::read_dir("compile-tests")? { - if let Ok(dir) = dir { - if dir.file_type()?.is_dir() { - prepare_for_directory(&dir.path())?; - } + let dir = dir?; + if dir.file_type()?.is_dir() { + prepare_for_directory(&dir.path(), ®istry)?; } } - // install dependencies needed for build-std - let mut cmd = std::process::Command::new("cargo"); - cmd.arg("local-registry"); - cmd.arg("--no-delete"); - cmd.arg("--sync"); - cmd.arg(format!( - "{}/lib/rustlib/src/rust/library/Cargo.lock", - toolchain_folder(&toolchain())?.display() - )); - cmd.arg("target/local-registry"); - cmd.stdout(std::process::Stdio::null()); - cmd.env_clear(); - cmd.envs( - std::env::vars() - .into_iter() - .filter(|(k, _)| !k.starts_with("CARGO")), - ); - - log::info!("{:?}", cmd); - cmd.status()?; - - // "for reasons" (e.g. running examples later via the "normal" xtask) also do it for other - // toolchains - let mut cmd = std::process::Command::new("cargo"); - cmd.arg("local-registry"); - cmd.arg("--no-delete"); - cmd.arg("--sync"); - cmd.arg(format!( - "{}/lib/rustlib/src/rust/library/Cargo.lock", - toolchain_folder("nightly")?.display() - )); - cmd.arg("target/local-registry"); - cmd.stdout(std::process::Stdio::null()); - cmd.env_clear(); - cmd.envs( - std::env::vars() - .into_iter() - .filter(|(k, _)| !k.starts_with("CARGO")), - ); - - log::info!("{:?}", cmd); - cmd.status()?; - - let mut cmd = std::process::Command::new("cargo"); - cmd.arg("local-registry"); - cmd.arg("--no-delete"); - cmd.arg("--sync"); - cmd.arg(format!( - "{}/lib/rustlib/src/rust/library/Cargo.lock", - toolchain_folder("stable")?.display() - )); - cmd.arg("target/local-registry"); - cmd.stdout(std::process::Stdio::null()); - cmd.env_clear(); - cmd.envs( - std::env::vars() - .into_iter() - .filter(|(k, _)| !k.starts_with("CARGO")), - ); - - log::info!("{:?}", cmd); - cmd.status()?; - - // and lastly do it for the xtask itself - let mut cmd = std::process::Command::new("cargo"); - cmd.arg("local-registry"); - cmd.arg("--no-delete"); - cmd.arg("--sync"); - cmd.arg("Cargo.lock"); - cmd.arg(windows_safe_path( - &std::path::PathBuf::from("target/local-registry") - .canonicalize() - .unwrap(), - )); - cmd.stdout(std::process::Stdio::null()); - cmd.env_clear(); - cmd.envs( - std::env::vars() - .into_iter() - .filter(|(k, _)| !k.starts_with("CARGO")), - ); + // Sync the build-std lock for every toolchain we build with: `esp` for the + // registry build itself, plus `nightly`/`stable` so examples run later via + // the normal xtask resolve against this same registry. + for toolchain in [toolchain().as_str(), "nightly", "stable"] { + sync_local_registry(&build_std_lock(toolchain)?, ®istry, None)?; + } - log::info!("{:?}", cmd); - cmd.status()?; + // and lastly the xtask itself + sync_local_registry(Path::new("Cargo.lock"), ®istry, None)?; Ok(()) } -fn update(args: UpdateArgs) -> Result<()> { +fn update(plan: &Plan) -> Result<()> { if !std::fs::exists("target/local-registry")? { bail!("Cannot update - run `init` first."); } let workspace = Path::new("."); - // Recursively collect dependencies. A bit inefficient, but we don't need to - // sort a lot. - let mut packages_to_release = args + // Only the plan's crates are packaged from the working tree; everything else + // is already in the registry from crates.io, so packaging it here would risk + // publishing unreleased content under a released version number. + let plan_versions = plan .packages .iter() - .filter(|p| p.is_published()) - .flat_map(|p| related_crates(workspace, *p)) - .collect::>(); + .map(|entry| (entry.package, entry.new_version.clone())) + .collect::>(); + let mut packages_to_release = plan_versions.keys().copied().collect::>(); packages_to_release.sort(); packages_to_release.dedup(); @@ -294,10 +323,18 @@ fn update(args: UpdateArgs) -> Result<()> { .map(|pkg| CargoToml::new(workspace, *pkg).map(|cargo_toml| (*pkg, cargo_toml))) .collect::>>()?; - // Determine package dependencies (package -> dependencies) + // Restrict the dependency graph to plan crates so each is packaged after + // the plan crates it depends on: their `.crate` files must already be in + // the registry to resolve. Dependencies outside the plan come from + // crates.io and are already present. let mut dep_graph = HashMap::new(); for (package, toml) in package_tomls.iter_mut() { - dep_graph.insert(*package, toml.repo_dependencies()); + let deps = toml + .repo_dependencies() + .into_iter() + .filter(|dep| plan_versions.contains_key(dep)) + .collect(); + dep_graph.insert(*package, deps); } // Topological sort the packages into a release order. Note that this is not a stable order, @@ -311,18 +348,32 @@ fn update(args: UpdateArgs) -> Result<()> { for package in sorted.iter() { log::info!("Package = {}", package); + let planned_version = plan_versions + .get(package) + .expect("topological sort only contains plan crates"); + let toml_ref = package.toml(); let Some(ref toml) = *toml_ref else { - continue; + bail!("Cannot package {package}: no Cargo.toml found"); }; let package_path = toml.package_path(); - let version = toml.version(); + let version_str = toml.version().to_string(); + let version = toml.package_version(); + + // The release branch working tree carries the bumped versions, so + // packaging the tree must yield exactly the planned version. A mismatch + // means the tree and the plan disagree; refuse rather than publish a + // wrong version into the registry. + ensure!( + &version == planned_version, + "Working-tree version of {package} is {version}, but the plan releases \ + {planned_version}. The release branch must carry the planned versions." + ); if std::fs::exists(format!( - "target/local-registry/{}-{}.crate", - package, version + "target/local-registry/{package}-{version_str}.crate" ))? { - log::warn!("Already exists as version {version}"); + log::warn!("Already exists as version {version_str}"); continue; } @@ -332,35 +383,19 @@ fn update(args: UpdateArgs) -> Result<()> { log::info!("Updating..."); // make sure we have a lock file - std::process::Command::new("cargo") - .arg("update") - .current_dir(&package_path) - .env_clear() - .envs( - std::env::vars() - .into_iter() - .filter(|(k, _)| !k.starts_with("CARGO")), - ) - .status()?; + let mut cmd = Command::new("cargo"); + cmd.arg("update").current_dir(&package_path); + run_cargo(&mut cmd, &format!("running `cargo update` for {package}"))?; // prepare all the deps we need - let mut cmd = std::process::Command::new("cargo"); - cmd.arg("local-registry"); - cmd.arg("--no-delete"); - cmd.arg("--sync"); - cmd.arg("Cargo.lock"); - cmd.arg("../target/local-registry"); - cmd.stdout(std::process::Stdio::null()); - cmd.env_clear(); - cmd.envs( - std::env::vars() - .into_iter() - .filter(|(k, _)| !k.starts_with("CARGO")), - ); - cmd.current_dir(&package_path); - - log::info!("{:?}", cmd); - cmd.status()?; + let mut cmd = Command::new("cargo"); + cmd.arg("local-registry") + .arg("--no-delete") + .arg("--sync") + .arg("Cargo.lock") + .arg("../target/local-registry") + .current_dir(&package_path); + run_cargo(&mut cmd, &format!("syncing dependencies for {package}"))?; std::fs::write( ".cargo/config.toml", @@ -385,34 +420,19 @@ fn update(args: UpdateArgs) -> Result<()> { .display() ), )?; - let res = std::process::Command::new("cargo") - .arg("package") + let mut cmd = Command::new("cargo"); + cmd.arg("package") .arg("--no-verify") .arg("--verbose") .arg("--allow-dirty") .arg("--index=http://crates.io") .arg("--target-dir=../target") - .current_dir(&package_path) - .env_clear() - .envs( - std::env::vars() - .into_iter() - .filter(|(k, _)| !k.starts_with("CARGO")), - ) - .status(); - - log::info!("{:?}", res); - - if !res?.success() { - // don't fail early if packaging fails - real problems will show up later - log::warn!( - "Failed to prepare package '{}' for local publishing - Skipping!", - package - ); - continue; - } - + .current_dir(&package_path); + // A plan crate that fails to package is a hard error. Restore the config + // before reacting so a failure does not leave the source block behind. + let packaged = run_cargo(&mut cmd, &format!("packaging {package}")); std::fs::write(".cargo/config.toml", &original_config)?; + packaged?; // copy the crate to our registry let toml = package.toml(); @@ -486,39 +506,30 @@ fn update(args: UpdateArgs) -> Result<()> { Ok(()) } -fn latest_version_of_crate(krate: &str) -> Result { - let matching = std::fs::read_dir("target/local-registry/")?.filter(|f| { - if let Ok(f) = f { - f.file_name().to_str().unwrap().starts_with(krate) - } else { - false - } - }); - +/// Every version of `krate` present as a `.crate` file in the local registry. +fn registry_versions_of_crate(krate: &str) -> Result> { let prefix = format!("{krate}-"); - let mut version = None; - for entry in matching { + let mut versions = Vec::new(); + for entry in std::fs::read_dir("target/local-registry/")? { let entry = entry?; let name = entry.file_name(); - let vstr = name - .to_str() - .unwrap() - .strip_prefix(&prefix) - .unwrap() - .strip_suffix(".crate") - .unwrap(); - if let Ok(v) = vstr.parse::() { - if version.is_none() || &v > version.as_ref().unwrap() { - version = Some(v); - } + let Some(name) = name.to_str() else { + continue; + }; + // `esp-hal-embassy-1.0.0.crate` also starts with `esp-hal-`; the version + // parse below rejects the leftover crate-name segment, so only exact + // matches survive. + let Some(rest) = name.strip_prefix(&prefix) else { + continue; + }; + let Some(vstr) = rest.strip_suffix(".crate") else { + continue; + }; + if let Ok(v) = vstr.parse::() { + versions.push(v); } } - - if let Some(v) = version { - Ok(v.to_string()) - } else { - Err(anyhow::anyhow!("`{krate}` not found")) - } + Ok(versions) } fn ensure_cargo_local_registry() -> Result<()> { @@ -552,7 +563,8 @@ fn revert_scrap_path_deps() -> Result<()> { crate::Package::Examples.to_string(), crate::Package::HilTest.to_string(), crate::Package::HilTestRadio.to_string(), - crate::Package::QaTest.to_string(), + crate::Package::QaTest.directory().to_string(), + crate::Package::CompileTests.directory().to_string(), ]; for pkg in pkgs { @@ -586,7 +598,7 @@ fn revert_scrap_path_deps() -> Result<()> { Ok(()) } -fn scrap_path_deps() -> Result<()> { +fn scrap_path_deps(plan: &Plan) -> Result<()> { if !std::fs::exists("target/local-registry")? { bail!("Cannot scrap path dependencies - run `init` first."); } @@ -595,7 +607,7 @@ fn scrap_path_deps() -> Result<()> { crate::Package::Examples.to_string(), crate::Package::HilTest.to_string(), crate::Package::HilTestRadio.to_string(), - crate::Package::QaTest.to_string(), + crate::Package::QaTest.directory().to_string(), ]; for pkg in pkgs { @@ -609,40 +621,32 @@ fn scrap_path_deps() -> Result<()> { for manifest_path in manifest_paths { // make sure we have a lock file std::fs::remove_file(manifest_path.join("Cargo.lock")).ok(); - let status = std::process::Command::new("cargo") - .arg(format!("+{}", toolchain())) + let mut cmd = Command::new("cargo"); + cmd.arg(format!("+{}", toolchain())) .arg("metadata") .arg("--format-version=1") - .current_dir(&manifest_path) - .stdout(std::process::Stdio::null()) - .status()?; - - if !status.success() { - log::warn!("Failed"); - } + .current_dir(&manifest_path); + run_cargo( + &mut cmd, + &format!("resolving metadata in {}", manifest_path.display()), + )?; // add dependencies to the local registry - let mut cmd = std::process::Command::new("cargo"); - cmd.arg("local-registry"); - cmd.arg("--no-delete"); - cmd.arg("--sync"); - cmd.arg("Cargo.lock"); - cmd.arg(windows_safe_path( - &std::path::PathBuf::from("target/local-registry") - .canonicalize() - .unwrap(), - )); - cmd.stdout(std::process::Stdio::null()); - cmd.env_clear(); - cmd.envs( - std::env::vars() - .into_iter() - .filter(|(k, _)| !k.starts_with("CARGO")), - ); - cmd.current_dir(&manifest_path); - - log::info!("{:?}", cmd); - cmd.status()?; + let mut cmd = Command::new("cargo"); + cmd.arg("local-registry") + .arg("--no-delete") + .arg("--sync") + .arg("Cargo.lock") + .arg(windows_safe_path( + &std::path::PathBuf::from("target/local-registry") + .canonicalize() + .unwrap(), + )) + .current_dir(&manifest_path); + run_cargo( + &mut cmd, + &format!("syncing dependencies in {}", manifest_path.display()), + )?; // rename files we are going to change std::fs::rename( @@ -666,13 +670,28 @@ fn scrap_path_deps() -> Result<()> { let krate = dep.0.get(); if krate.starts_with("esp-") { - let latest = latest_version_of_crate(krate)?; + let registry_versions = registry_versions_of_crate(krate)?; + // A crate that does not map to a `Package` cannot be in the + // plan, so it takes the newest registry version like any frozen + // crate. + let replacement = match Package::from_str(krate, true) { + Ok(pkg) => { + choose_replacement_version(&pkg, plan, ®istry_versions)? + } + Err(_) => { + registry_versions.into_iter().max().ok_or_else(|| { + anyhow::anyhow!( + "`{krate}` has no version in the local registry" + ) + })? + } + }; dep.1.as_table_like_mut().and_then(|table| { table.remove("path"); table.insert( "version", toml_edit::Item::Value(toml_edit::Value::String( - toml_edit::Formatted::new(latest), + toml_edit::Formatted::new(replacement.to_string()), )), ); Some(table) @@ -690,8 +709,20 @@ fn scrap_path_deps() -> Result<()> { if !config.contains("local-registry") { std::fs::write( manifest_path.join(".cargo/config.toml"), - format!( - r#"{} + with_local_registry_source(&config)?, + )?; + } + } + } + } + + redirect_compile_tests() +} + +/// `config` with crates.io replaced by the local registry. +fn with_local_registry_source(config: &str) -> Result { + Ok(format!( + r#"{} # {}{} [source.crates-io] @@ -701,20 +732,33 @@ replace-with = 'local-registry' [source.local-registry] local-registry = '{}' "#, - config, - "STOP", - "SHIP", - windows_safe_path( - &std::path::PathBuf::from("target/local-registry") - .canonicalize() - .unwrap() - ) - .display() - ), - )?; - } - } + config, + "STOP", + "SHIP", + local_registry_path()?.display() + )) +} + +/// Resolve every compile-test project against the local registry, or a plan +/// crate's unpublished version cannot resolve. Requirements stay untouched, +/// unlike `scrap_path_deps`: the frozen lines' pins are what is under test. +fn redirect_compile_tests() -> Result<()> { + let root = Path::new(crate::Package::CompileTests.directory()); + for project in crate::find_packages(root)? { + let config_path = project.join(".cargo/config.toml"); + let backup_path = project.join(".cargo/config.toml$"); + if std::fs::exists(&backup_path)? { + continue; } + + // `init` resolved these against crates.io; a stale lock would hide the + // plan's semver-compatible releases from the frozen lines. + std::fs::remove_file(project.join("Cargo.lock")).ok(); + + let config = std::fs::read_to_string(&config_path) + .with_context(|| format!("Failed to read {}", config_path.display()))?; + std::fs::rename(&config_path, &backup_path)?; + std::fs::write(&config_path, with_local_registry_source(&config)?)?; } Ok(()) @@ -722,13 +766,6 @@ local-registry = '{}' // --- -// some code duplicated from `plan.rs` - de-dup once we want to do this for real! -fn related_crates(workspace: &Path, package: Package) -> Vec { - related_crates_cb(package, &|p| { - CargoToml::new(workspace, p).unwrap().repo_dependencies() - }) -} - fn topological_sort(dep_graph: &HashMap>) -> Vec { let mut sorted = Vec::new(); let mut dep_graph = dep_graph.clone(); @@ -748,27 +785,6 @@ fn topological_sort(dep_graph: &HashMap>) -> Vec sorted } -/// Collects dependencies recursively, based on a callback that provides direct dependencies. -/// -/// This is an implementation detail of the `related_crates` function, separate for testing -/// purposes. -fn related_crates_cb( - package: Package, - direct_dependencies: &impl Fn(Package) -> Vec, -) -> Vec { - let mut packages = vec![package]; - - for dep in direct_dependencies(package) { - for dep in related_crates_cb(dep, direct_dependencies) { - if !packages.contains(&dep) { - packages.push(dep); - } - } - } - - packages -} - const EXPECTED: (u64, u64) = (0, 1); const EXACT_ALLOWLIST: [Package; 1] = [Package::EspRadio]; @@ -853,3 +869,48 @@ fn extract_exact(comps: &[Comparator]) -> Option { build: Default::default(), }) } + +#[cfg(all(test, feature = "rel-check"))] +mod tests { + use super::*; + + fn ver(s: &str) -> Version { + Version::parse(s).unwrap() + } + + fn sample_plan() -> Plan { + let json = r#"{ + "base": "main", + "slug": "abc123", + "packages": [ + { "package": "esp-metadata-generated", "semver_checked": false, "current_version": "0.5.1", "new_version": "0.6.0", "tag_name": "esp-metadata-generated-v0.6.0", "bump": { "base": "Minor", "pre": null } }, + { "package": "esp-hal", "semver_checked": true, "current_version": "1.2.0", "new_version": "1.3.0", "tag_name": "esp-hal-v1.3.0", "bump": { "base": "Minor", "pre": null } } + ] +}"#; + serde_json::from_str(json).unwrap() + } + + #[test] + fn plan_crate_uses_plan_version_over_registry() { + // The registry carries a newer version, but a plan crate resolves to its + // planned version. + let registry = [ver("0.6.5"), ver("0.5.1")]; + let chosen = + choose_replacement_version(&Package::EspMetadataGenerated, &sample_plan(), ®istry) + .unwrap(); + assert_eq!(chosen, ver("0.6.0")); + } + + #[test] + fn frozen_crate_uses_newest_registry_version() { + let registry = [ver("0.10.0"), ver("0.11.0"), ver("0.9.0")]; + let chosen = + choose_replacement_version(&Package::EspAlloc, &sample_plan(), ®istry).unwrap(); + assert_eq!(chosen, ver("0.11.0")); + } + + #[test] + fn frozen_crate_without_registry_versions_errors() { + assert!(choose_replacement_version(&Package::EspAlloc, &sample_plan(), &[]).is_err()); + } +} diff --git a/xtask/src/commands/release.rs b/xtask/src/commands/release.rs index 8a56ea67494..2fe2317de2f 100644 --- a/xtask/src/commands/release.rs +++ b/xtask/src/commands/release.rs @@ -2,20 +2,26 @@ use clap::Subcommand; #[cfg(feature = "release")] pub mod bump_msrv; +#[cfg(feature = "release")] pub mod bump_version; pub mod changelog_preview; #[cfg(feature = "release")] pub mod execute_plan; #[cfg(feature = "release")] +pub(crate) mod new_stable_api; +#[cfg(feature = "release")] pub mod plan; #[cfg(feature = "release")] pub mod post_release; pub mod publish; #[cfg(feature = "release")] pub mod publish_plan; +#[cfg(feature = "release")] +pub mod registry; pub mod semver_check; pub mod tag_releases; +#[cfg(feature = "release")] pub use bump_version::*; pub use changelog_preview::*; #[cfg(feature = "release")] @@ -39,8 +45,9 @@ pub const PLACEHOLDER: &str = "{{currentVersion}}"; #[derive(Debug, Subcommand)] pub enum Release { /// Create a release plan. This is the first step in the release process. - /// Accepts zero or more package names. If no package names are - /// specified, all packages are included. + /// The plan always covers every published package; use `--exclude` to leave + /// specific packages out (along with any dependency that becomes private to + /// the excluded set). /// /// The result of this command is a json file that can be customized to /// control what and how gets released. @@ -76,13 +83,14 @@ pub enum Release { /// - Check if the changelog can be finalized /// - Update the version in the changelog /// - Replaces `{{currentVersion}}` markers in source files and the migration guide. + #[cfg(feature = "release")] BumpVersion(BumpVersionArgs), /// Attempt to publish the specified package. Publish(PublishArgs), /// Generate git tags for all new package releases. TagReleases(TagReleasesArgs), - /// Update the MSRV (Badges in README.md, "rust-version" in Cargo.toml, the - /// toolchain used in CI) + /// Update the MSRV (Badges in README.md, "rust-version" in Cargo.toml). CI + /// derives its MSRV toolchain from esp-hal's "rust-version". #[cfg(feature = "release")] BumpMsrv(bump_msrv::BumpMsrvArgs), } diff --git a/xtask/src/commands/release/bump_msrv.rs b/xtask/src/commands/release/bump_msrv.rs index 03bf8367911..9ec97470fdf 100644 --- a/xtask/src/commands/release/bump_msrv.rs +++ b/xtask/src/commands/release/bump_msrv.rs @@ -29,8 +29,9 @@ pub struct BumpMsrvArgs { /// This will process /// - `Cargo.toml` for the packages (adjust (or add if not present) the "rust-version") /// - `README.md` for the packages if it exists (adjusts the MSRV badge) -/// - IF the esp-hal package was touched: .github/workflows/ci.yml (adapts the `MSRV: ""` -/// entry) +/// +/// CI needs no changes: `.github/actions/setup-toolchains` reads the MSRV from +/// esp-hal's "rust-version". /// /// Non-published packages are not touched. /// @@ -65,8 +66,6 @@ pub fn bump_msrv(workspace: &Path, args: BumpMsrvArgs) -> Result<()> { published }; - let adjust_ci = to_process.contains(&Package::EspHal); - // process packages let badge_re = Regex::new( r"(?https://img.shields.io/badge/MSRV-)(?[0123456789.]*)(?-)", @@ -122,21 +121,6 @@ pub fn bump_msrv(workspace: &Path, args: BumpMsrvArgs) -> Result<()> { } } - if adjust_ci { - // process ".github/workflows/ci.yml" - println!("Processing .github/workflows/ci.yml"); - let ci_yml_path = workspace.join(".github/workflows/ci.yml"); - - let ci_yml = std::fs::read_to_string(&ci_yml_path)?; - let ci_yml = Regex::new("(MSRV:.*\\\")([0123456789.]*)(\\\")")? - .replace(&ci_yml, |caps: &Captures| { - format!("{}{new_msrv}{}", &caps[1], &caps[3]) - }); - if !args.dry_run { - std::fs::write(ci_yml_path, ci_yml.as_bytes())?; - } - } - println!("\nPlease review the changes before committing."); Ok(()) } diff --git a/xtask/src/commands/release/bump_version.rs b/xtask/src/commands/release/bump_version.rs index 61bd440cc63..f3103ce41b1 100644 --- a/xtask/src/commands/release/bump_version.rs +++ b/xtask/src/commands/release/bump_version.rs @@ -16,7 +16,7 @@ use crate::{ Version, cargo::CargoToml, changelog::Changelog, - commands::PLACEHOLDER, + commands::{PLACEHOLDER, release::registry::RegistrySnapshot}, find_packages, }; @@ -103,10 +103,13 @@ pub fn bump_version(workspace: &Path, args: BumpVersionArgs) -> Result<()> { pre: args.pre, }; + // Even a manual bump must not land on a version crates.io already holds. + let registry = RegistrySnapshot::fetch(args.packages.iter().copied())?; + // Bump the version for each given package: for package in args.packages { let mut package = CargoToml::new(workspace, package)?; - update_package(&mut package, &bump, false, false)?; + update_package(&mut package, &bump, ®istry, false, false)?; } Ok(()) @@ -114,6 +117,8 @@ pub fn bump_version(workspace: &Path, args: BumpVersionArgs) -> Result<()> { /// Update the specified package by bumping its version, updating its changelog, /// +/// The bump steps over version numbers `registry` reports as taken. +/// /// `skip_dependent_rewrites` skips rewriting intra-workspace path-dep version /// requirements on sibling crates. Set this on backport patch releases: those /// requirements use `~X.Y.Z`, which already accepts the new patch (since @@ -122,12 +127,14 @@ pub fn bump_version(workspace: &Path, args: BumpVersionArgs) -> Result<()> { /// them anyway is pure churn. pub fn update_package( package: &mut CargoToml, - version: &VersionBump, + amount: &VersionBump, + registry: &RegistrySnapshot, dry_run: bool, skip_dependent_rewrites: bool, ) -> Result { check_crate_before_bumping(package)?; - let new_version = bump_crate_version(package, version, dry_run, skip_dependent_rewrites)?; + let new_version = + bump_crate_version(package, amount, registry, dry_run, skip_dependent_rewrites)?; finalize_changelog(package, &new_version, dry_run)?; finalize_placeholders(package, &new_version, dry_run)?; @@ -230,17 +237,20 @@ fn check_dependency_before_bumping(item: &Item) -> Result<()> { Ok(()) } -/// Bump the version of the specified package by the specified amount. +/// Bump the version of the specified package by the specified amount, stepping +/// over version numbers crates.io has already seen. fn bump_crate_version( bumped_package: &mut CargoToml, amount: &VersionBump, + registry: &RegistrySnapshot, dry_run: bool, skip_dependent_rewrites: bool, ) -> Result { let prev_version = bumped_package.package_version(); - let version = do_version_bump(&prev_version, amount) + let planned = do_version_bump(&prev_version, amount) .with_context(|| format!("Failed to bump version of {}", bumped_package.package))?; + let version = registry.next_free_version(bumped_package.package, &planned, amount)?; if dry_run { log::info!( @@ -301,6 +311,36 @@ fn bump_crate_version( } } + // compile-tests/hal tracks the current lines. Frozen ble_*/wifi_* stay on + // the minor they were snapshotted at, so they are not rewritten here. + let hal_manifest = bumped_package + .workspace + .join("compile-tests") + .join("hal") + .join("Cargo.toml"); + if hal_manifest.exists() { + let content = fs::read_to_string(&hal_manifest) + .with_context(|| format!("Could not read {}", hal_manifest.display()))?; + let mut toml = + CargoToml::from_str(&bumped_package.workspace, Package::CompileTests, &content) + .with_context(|| format!("Could not parse {}", hal_manifest.display()))?; + if toml.change_version_of_dependency(&package_name, &version) { + if dry_run { + log::info!( + " Dry run: would update {package_name} in compile-tests/hal: \ + ({prev_version} -> {version})" + ); + } else { + log::info!( + " Bumping {package_name} version for compile-tests/hal: \ + ({prev_version} -> {version})" + ); + fs::write(&hal_manifest, toml.manifest.to_string()) + .with_context(|| format!("Could not write {}", hal_manifest.display()))?; + } + } + } + Ok(version) } @@ -401,10 +441,7 @@ fn finalize_changelog( new_version: &semver::Version, dry_run: bool, ) -> Result<()> { - let changelog_path = bumped_package - .workspace - .join(bumped_package.package.to_string()) - .join("CHANGELOG.md"); + let changelog_path = bumped_package.package_path().join("CHANGELOG.md"); if !changelog_path.exists() { // No changelog exists for this package @@ -597,6 +634,71 @@ mod tests { } } + /// A reserved version has to change what gets written: both the manifest of + /// the bumped package and the requirement its dependents carry. + #[test] + fn a_reserved_version_changes_what_is_written() { + let workspace = tempfile::tempdir().unwrap(); + let manifest_of = |package: Package| { + workspace + .path() + .join(package.directory()) + .join("Cargo.toml") + }; + + // The dependent rewrite pass loads every non-standalone package and the + // example projects, so all of them have to exist on disk. + fs::create_dir(workspace.path().join("examples")).unwrap(); + for package in Package::iter().filter(|p| !p.contains_standalone_projects()) { + fs::create_dir_all(workspace.path().join(package.directory())).unwrap(); + fs::write( + manifest_of(package), + format!("[package]\nname = \"{package}\"\nversion = \"0.0.0\"\n"), + ) + .unwrap(); + } + + fs::write( + manifest_of(Package::EspSync), + "[package]\nname = \"esp-sync\"\nversion = \"0.1.1\"\n", + ) + .unwrap(); + fs::write( + manifest_of(Package::EspHal), + "[package]\nname = \"esp-hal\"\nversion = \"1.0.0\"\n\n\ + [dependencies]\nesp-sync = { version = \"0.1.1\", path = \"../esp-sync\" }\n", + ) + .unwrap(); + + // esp-rs/esp-hal#5385: the Minor bump lands on the yanked 0.2.0. + let registry = + RegistrySnapshot::from_taken([(Package::EspSync, vec!["0.2.0".parse().unwrap()])]); + + let mut manifest = CargoToml::new(workspace.path(), Package::EspSync).unwrap(); + let new_version = update_package( + &mut manifest, + &VersionBump::minor(), + ®istry, + false, + false, + ) + .unwrap(); + + assert_eq!(new_version.to_string(), "0.2.1"); + + let bumped = fs::read_to_string(manifest_of(Package::EspSync)).unwrap(); + assert!( + bumped.contains(r#"version = "0.2.1""#), + "esp-sync did not receive the stepped version:\n{bumped}" + ); + + let dependent = fs::read_to_string(manifest_of(Package::EspHal)).unwrap(); + assert!( + dependent.contains(r#"version = "0.2.1""#), + "esp-hal still requires the reserved version:\n{dependent}" + ); + } + #[test] fn test_rejected_dependencies() { let toml = r#" diff --git a/xtask/src/commands/release/changelog_preview.rs b/xtask/src/commands/release/changelog_preview.rs index 3a6b57b4bfd..34a406a9a69 100644 --- a/xtask/src/commands/release/changelog_preview.rs +++ b/xtask/src/commands/release/changelog_preview.rs @@ -131,15 +131,13 @@ pub(crate) fn collect_changelogs( let mut pr_changelogs: Vec = Vec::new(); let mut skipped = 0usize; + let mut parse_errors: Vec = Vec::new(); for pr in prs { match PrChangelog::parse(pr.number, &pr.body) { Ok(Some(cl)) => pr_changelogs.push(cl), Ok(None) => skipped += 1, - Err(e) => { - log::warn!("PR #{}: parse error — {e}", pr.number); - skipped += 1; - } + Err(e) => parse_errors.push(format!("PR #{}: {e}", pr.number)), } } @@ -147,6 +145,16 @@ pub(crate) fn collect_changelogs( log::info!("{skipped} PR(s) had no changelog entries and were skipped."); } + // A malformed PR description must stop the harvest: entries after the error are + // lost, and a release built from them would be incomplete. + if !parse_errors.is_empty() { + bail!( + "{} PR description(s) could not be parsed:\n{}", + parse_errors.len(), + parse_errors.join("\n") + ); + } + // Load each relevant crate's CHANGELOG.md, merge in the PR entries. // // keyed by crate name (e.g. "esp-hal") diff --git a/xtask/src/commands/release/execute_plan.rs b/xtask/src/commands/release/execute_plan.rs index 6840d088d12..871d257e37b 100644 --- a/xtask/src/commands/release/execute_plan.rs +++ b/xtask/src/commands/release/execute_plan.rs @@ -3,14 +3,24 @@ use std::{path::Path, process::Command}; use anyhow::{Context, Result, bail, ensure}; use clap::Args; use strum::IntoEnumIterator; -use toml_edit::{Item, Value}; use crate::{ cargo::CargoToml, commands::{ VersionBump, checker::generate_baseline, - release::plan::{PackagePlan, Plan}, + do_version_bump, + release::{ + plan::{ + PackagePlan, + Plan, + StaleDependency, + format_stale_dependency_warnings, + print_stale_dependency_warnings, + validate_plan, + }, + registry::RegistrySnapshot, + }, update_package, }, git::{current_branch, ensure_workspace_clean, get_remote_name_for}, @@ -30,7 +40,8 @@ pub struct ApplyPlanArgs { manual_pull_request: bool, } -/// Execute the release plan by making code changes, committing them to a new +/// Execute the release plan: bump versions, merge changelog entries, commit the +/// changes to a fresh release branch, and open (or update) the release PR. pub fn execute_plan(workspace: &Path, args: ApplyPlanArgs) -> Result<()> { ensure_workspace_clean(workspace) .with_context(|| format!("Workspace {workspace:?} is not clean!"))?; @@ -62,12 +73,15 @@ pub fn execute_plan(workspace: &Path, args: ApplyPlanArgs) -> Result<()> { ); } - // Preflight: load and validate every package up front, before touching any - // files, so a mismatched version or other plan error aborts without leaving - // the workspace half-edited. The parsed manifests are reused by the apply - // loop below, so each is read and validated exactly once. - let mut manifests = Vec::with_capacity(plan.packages.len()); - for step in plan.packages.iter() { + // Recompute each version and tag from `current_version` and `bump` before + // validation, so a hand-edited `bump` (not a stale `new_version`) decides + // what is released, and a drifted manifest aborts before any file changes. + // + // Do not reuse these manifests in the apply loop: bumping a package rewrites + // its workspace dependents on disk, so each must be re-read there or an + // earlier dependency bump would be silently reverted. + let mut bump_decisions = Vec::with_capacity(plan.packages.len()); + for step in plan.packages.iter_mut() { let package = CargoToml::new(workspace, step.package).with_context(|| { format!( "Couldn't create Cargo.toml in workspace {workspace:?} for {:?}", @@ -75,18 +89,24 @@ pub fn execute_plan(workspace: &Path, args: ApplyPlanArgs) -> Result<()> { ) })?; - match validate_package(&package, step)? { - Preflight::Bump => manifests.push(Some(package)), + match recompute_and_validate_package(&package, step)? { + Preflight::Bump => bump_decisions.push(true), Preflight::AlreadyReleased => { println!( "Package {} is already at version {}. Skipping.", step.package, step.new_version ); - manifests.push(None); + bump_decisions.push(false); } } } + // The plan is hand-edited between `plan` and here (packages get removed and + // bumps get tweaked), so run every planner gate against the recomputed + // versions before touching any files. + let warnings = validate_plan(workspace, &plan.packages)?; + print_stale_dependency_warnings(&warnings); + // Must run before the apply loop: `update_package` finalizes Unreleased into // the new version section, so fragments added after would land in the wrong // (new, empty) Unreleased. @@ -107,17 +127,30 @@ pub fn execute_plan(workspace: &Path, args: ApplyPlanArgs) -> Result<()> { println!("Dry run: would merge PR changelog entries into CHANGELOG.md / MIGRATING-*.md"); } - // Make code changes, reusing the manifests validated above. Packages that - // were already at their target version are stored as `None` and skipped. + // The bumps are re-derived here, so they are re-checked against the index + let registry = RegistrySnapshot::fetch(plan.packages.iter().map(|step| step.package))?; + + // Make code changes. Re-read each manifest from disk instead of reusing the + // preflight copies: earlier steps in this loop may have rewritten this + // package's dependency versions on disk, and saving a stale in-memory copy + // would revert them. Packages already at their target version are skipped. let skip_dependent_rewrites = plan.backport.is_some(); - for (step, manifest) in plan.packages.iter_mut().zip(manifests) { - let Some(mut package) = manifest else { + for (step, should_bump) in plan.packages.iter_mut().zip(bump_decisions) { + if !should_bump { continue; - }; + } + + let mut package = CargoToml::new(workspace, step.package).with_context(|| { + format!( + "Couldn't create Cargo.toml in workspace {workspace:?} for {:?}", + step.package + ) + })?; let new_version = update_package( &mut package, &step.bump, + ®istry, !args.no_dry_run, skip_dependent_rewrites, )?; @@ -168,12 +201,18 @@ pub fn execute_plan(workspace: &Path, args: ApplyPlanArgs) -> Result<()> { let branch_name = format!("release-branch-{}", plan.slug); let branch = make_git_changes(!args.no_dry_run, &branch_name, &commit_message(&plan))?; + // Report-only: include the compile-test chip coverage in the PR body. A read + // failure is logged and the section omitted rather than aborting the release. + let coverage_section = compile_test_coverage_section(workspace); + open_pull_request( &branch, !args.no_dry_run, args.manual_pull_request, &plan_source, &plan, + &warnings, + &coverage_section, ) .with_context(|| "Failed to open pull request")?; @@ -195,21 +234,39 @@ enum Preflight { AlreadyReleased, } -/// Validate a package against its plan entry without mutating anything. +/// Recompute a package's `new_version`/`tag_name` from its `bump`, validate it +/// against the manifest on disk, and update the plan entry in place. /// /// Run for every package before any changelog or version edits happen, so that -/// a bad plan aborts cleanly instead of leaving the workspace half-edited. The -/// same checks gate the actual bump, but live here only — the apply loop reuses -/// the [`Preflight`] result instead of repeating them. -fn validate_package(package: &CargoToml, step: &PackagePlan) -> Result { +/// a bad plan aborts cleanly instead of leaving the workspace half-edited, and +/// so the checks that follow see the version the `bump` actually produces rather +/// than a possibly-stale `new_version` field. +fn recompute_and_validate_package( + package: &CargoToml, + step: &mut PackagePlan, +) -> Result { let current = package.package_version(); + + let new_version = do_version_bump(&step.current_version, &step.bump).with_context(|| { + format!( + "Failed to compute the new version of {} from its bump", + step.package + ) + })?; + + // Re-run after the bump was already applied: the manifest already carries + // the recomputed target version. if current != step.current_version { - if current == step.new_version { + if current == new_version { + step.new_version = new_version; + step.tag_name = step.package.tag(&step.new_version); return Ok(Preflight::AlreadyReleased); } bail!( - "The version of package {} has changed in an unexpected way. Cannot continue.", - step.package + "The manifest version of {} is {current}, but the plan's current_version is {}. \ + Re-run `cargo xrelease plan`.", + step.package, + step.current_version ); } @@ -224,6 +281,8 @@ fn validate_package(package: &CargoToml, step: &PackagePlan) -> Result String { const UPSTREAM_REPO: &str = "esp-rs/esp-hal"; // `manual-changelog` exempts the PR from the direct-CHANGELOG-edit check (the release -// tooling writes the changelog wholesale). The `release:*` labels each gate an optional, -// heavy CI workflow; all are applied by default so every check runs, and a maintainer can -// remove individual ones to skip a check that isn't relevant to the packages being released. -const PR_LABELS: &[&str] = &[ - "manual-changelog", - "release:docs", - "release:registry:compile-test", - "release:registry:ci", -]; - -fn build_pr_body(plan: &Plan, release_plan_str: &str) -> String { +// tooling writes the changelog wholesale). `release:docs` gates the docs build. +// `merge-freeze-exempt` lets the PR through the merge queue during a release freeze; it is a +// no-op when no freeze is active. +// +// The registry compile-test runs on every release PR and the examples/tests step runs by +// default, skipped only by adding `release:registry:skip-ci` (see `pre-rel-check.yml`), so +// neither is applied here as an opt-in gate. +const PR_LABELS: &[&str] = &["manual-changelog", "release:docs", "merge-freeze-exempt"]; + +/// The compile-test chip coverage section for the PR body, or an empty string +/// when it cannot be computed. Report-only. +fn compile_test_coverage_section(workspace: &Path) -> String { + match crate::firmware::compile_test_coverage(workspace) { + Ok(coverage) => format!( + "\n### Compile-test chip coverage\n\n{}\n", + crate::firmware::format_compile_test_coverage(&coverage) + ), + Err(e) => { + log::warn!("Could not compute compile-test coverage: {e}"); + String::new() + } + } +} + +fn build_pr_body( + plan: &Plan, + release_plan_str: &str, + warnings: &[StaleDependency], + coverage_section: &str, +) -> String { let packages = format_package_list(plan); + let stale_section = if warnings.is_empty() { + String::new() + } else { + format!( + "\n### Stale-dependency warnings\n\nThese in-repo dependencies have commits since \ + their last release. The registry check decides whether this release needs them:\n\n{}\n", + format_stale_dependency_warnings(warnings).join("\n") + ) + }; + let mut body = format!( r#"This pull request prepares the following packages for release: {packages} - +{stale_section}{coverage_section}
Release plan (click to expand) @@ -425,8 +513,10 @@ fn open_pull_request( manual_pull_request: bool, release_plan_str: &str, release_plan: &Plan, + warnings: &[StaleDependency], + coverage_section: &str, ) -> Result<()> { - let body = build_pr_body(release_plan, release_plan_str); + let body = build_pr_body(release_plan, release_plan_str, warnings, coverage_section); if dry_run { println!("Dry run: would create/update the release PR with body:"); @@ -473,7 +563,11 @@ fn head_spec(upstream_url: &str, branch_name: &str) -> Result { } } -fn gh_stdin(args: &[&str], stdin_data: &str) -> Result { +/// Spawn `gh` with `args`, feed `stdin_data` to its stdin, and return the raw +/// output. A non-zero exit is *not* treated as an error here so callers can +/// inspect stderr (e.g. to detect "a pull request already exists"). Callers +/// that only care about success should use [`gh_stdin`]. +fn gh_run(args: &[&str], stdin_data: &str) -> Result { use std::io::Write; let mut child = Command::new("gh") @@ -491,9 +585,13 @@ fn gh_stdin(args: &[&str], stdin_data: &str) -> Result { .write_all(stdin_data.as_bytes()) .context("Failed to write stdin to gh")?; - let out = child + child .wait_with_output() - .with_context(|| format!("`gh {}` failed", args.join(" ")))?; + .with_context(|| format!("`gh {}` failed", args.join(" "))) +} + +fn gh_stdin(args: &[&str], stdin_data: &str) -> Result { + let out = gh_run(args, stdin_data)?; if !out.status.success() { bail!( "`gh {}` failed: {}", @@ -534,64 +632,100 @@ fn find_existing_pr(branch_name: &str) -> Result> { .and_then(|n| n.as_u64())) } -fn upsert_pull_request(branch: &Branch, plan: &Plan, body: &str) -> Result { - let title = release_subject(plan); - if let Some(num) = find_existing_pr(&branch.name)? { - log::info!("Updating existing release PR #{num}"); - let num_str = num.to_string(); - gh_stdin( - &[ - "pr", - "edit", - &num_str, - "--repo", - UPSTREAM_REPO, - "--title", - &title, - "--body-file", - "-", - ], - body, - )?; - Ok(num) - } else { - let head = head_spec(&branch.upstream, &branch.name)?; - log::info!("Creating release PR (head: {head}, base: {})", plan.base); - let mut args: Vec<&str> = vec![ +/// Extract the numeric PR id from any text containing a `.../pull/` URL. +/// +/// Works for both the URL `gh pr create` prints on success and the +/// "...already exists: " message it prints on failure. A `/pull/new/...` +/// URL (as produced by `git push`) has no number and yields `None`. +fn parse_pr_number(text: &str) -> Option { + let start = text.rfind("/pull/")? + "/pull/".len(); + let digits: String = text[start..] + .chars() + .take_while(|c| c.is_ascii_digit()) + .collect(); + digits.parse().ok() +} + +/// Update the title and body of an existing release PR, leaving labels and +/// reviewers untouched. +fn edit_release_pr(number: u64, title: &str, body: &str) -> Result<()> { + let number = number.to_string(); + gh_stdin( + &[ "pr", - "create", + "edit", + &number, "--repo", UPSTREAM_REPO, - "--base", - &plan.base, - "--head", - &head, "--title", - &title, - ]; - for l in PR_LABELS { - args.push("--label"); - args.push(l); - } - args.push("--body-file"); - args.push("-"); - let stdout = gh_stdin(&args, body)?; - // `gh pr create` prints the PR URL as the last line of stdout. - let url = stdout - .lines() - .rev() - .map(str::trim) - .find(|l| !l.is_empty()) - .unwrap_or(""); - let num = url - .rsplit('/') - .next() - .and_then(|s| s.parse::().ok()) - .with_context(|| { - format!("Failed to parse PR number from `gh pr create` output: {url}") - })?; - Ok(num) + title, + "--body-file", + "-", + ], + body, + )?; + Ok(()) +} + +fn upsert_pull_request(branch: &Branch, plan: &Plan, body: &str) -> Result { + let title = release_subject(plan); + + // Reuse an existing open release PR when we can find one, so re-running the + // release edits the same PR instead of opening (and re-labelling) another. + if let Some(num) = find_existing_pr(&branch.name)? { + log::info!("Updating existing release PR #{num}"); + edit_release_pr(num, &title, body)?; + return Ok(num); + } + + let head = head_spec(&branch.upstream, &branch.name)?; + log::info!("Creating release PR (head: {head}, base: {})", plan.base); + let mut args: Vec<&str> = vec![ + "pr", + "create", + "--repo", + UPSTREAM_REPO, + "--base", + &plan.base, + "--head", + &head, + "--title", + &title, + ]; + // Labels are applied only when the PR is first created. A maintainer may + // later remove one to skip its optional CI check, so the edit path above + // deliberately never re-applies them. + for l in PR_LABELS { + args.push("--label"); + args.push(l); + } + args.push("--body-file"); + args.push("-"); + + let out = gh_run(&args, body)?; + if out.status.success() { + let stdout = String::from_utf8_lossy(&out.stdout); + return parse_pr_number(&stdout).with_context(|| { + format!("Failed to parse PR number from `gh pr create` output: {stdout}") + }); } + + // GitHub's PR listing lags for a moment after the branch is pushed, so + // `find_existing_pr` can miss a PR that actually exists and we land here on + // a re-run. `gh pr create` then fails with "a pull request ... already + // exists: ". Recover by editing that PR instead of bailing: letting + // `gh pr create` run a second time is what re-applied every release label + // and re-requested reviews, showing up as duplicated PR timeline entries. + let stderr = String::from_utf8_lossy(&out.stderr); + if stderr.contains("already exists") + && let Some(num) = parse_pr_number(&stderr) + { + log::info!("Release PR #{num} already exists - updating it instead of opening a duplicate"); + edit_release_pr(num, &title, body)?; + return Ok(num); + } + + bail!("`gh pr create` failed: {stderr}"); } fn print_manual_instructions(branch: &Branch, plan: &Plan, body: &str) -> Result<()> { @@ -656,6 +790,29 @@ branch 'foo' set up to track 'origin/foo'. assert_eq!(url, "https://github.com/bugadani/esp-hal/pull/new/foo"); } + #[test] + fn parse_pr_number_from_create_and_already_exists() { + // `gh pr create` success: bare PR URL on stdout. + assert_eq!( + parse_pr_number("https://github.com/esp-rs/esp-hal/pull/1234\n"), + Some(1234) + ); + + // `gh pr create` failure when the PR already exists: the number must be + // recovered from the message so we can edit instead of duplicating. + let stderr = "a pull request for branch \"release-branch-t9telr\" into branch \"main\" \ + already exists:\nhttps://github.com/esp-rs/esp-hal/pull/6190\n"; + assert_eq!(parse_pr_number(stderr), Some(6190)); + + // A `/pull/new/` URL (from `git push`) carries no PR number. + assert_eq!( + parse_pr_number("https://github.com/esp-rs/esp-hal/pull/new/release-branch-x"), + None + ); + + assert_eq!(parse_pr_number("no pull url here"), None); + } + #[test] fn create_comparison_url() { let cases = [ diff --git a/xtask/src/commands/release/new_stable_api.rs b/xtask/src/commands/release/new_stable_api.rs new file mode 100644 index 00000000000..e0a5cb4d0c2 --- /dev/null +++ b/xtask/src/commands/release/new_stable_api.rs @@ -0,0 +1,109 @@ +use std::{ + collections::{BTreeMap, BTreeSet, HashSet}, + path::Path, +}; + +use anyhow::Context; +use public_api::{PublicApi, PublicItem, diff::PublicApiDiff}; +use serde::{Deserialize, Serialize}; + +use crate::{ + Package, + metadata::Chip, + semver_check::{baseline_gz, build_prepared_doc_json, decompress_gz}, +}; + +/// One `new_stable_api` entry. +#[derive(Debug, Clone, Deserialize, Serialize)] +pub struct NewStableItem { + pub item: String, + pub chips: BTreeSet, +} + +/// Public items stable in the working tree but not in the API baseline. +/// +/// Returns the items and the chips that have no baseline to compare against. +pub(crate) fn newly_stable( + workspace: &Path, + package: Package, + chips: &[Chip], +) -> anyhow::Result<(Vec, BTreeSet)> { + let package_path = crate::windows_safe_path(&workspace.join(package.directory())); + let mut newly_stable: BTreeMap> = BTreeMap::new(); + let mut unchecked_chips = BTreeSet::new(); + + for chip in chips + .iter() + .copied() + .filter(|chip| package.supports_chip(*chip)) + { + let Some(baseline_gz_path) = baseline_gz(workspace, package, chip)? else { + log::warn!("Not checking new stable API for {package} {chip}: no API baseline"); + unchecked_chips.insert(chip); + continue; + }; + let baseline = workspace + .join("target/semver-baseline-doc") + .join(package.to_string()) + .join(format!("{chip}.json")); + decompress_gz(&baseline_gz_path, &baseline)?; + let current = build_prepared_doc_json(package, &chip, &package_path)?; + + let diff = PublicApiDiff::between( + public_api_from_rustdoc(&baseline)?, + public_api_from_rustdoc(¤t)?, + ); + // A new enum would otherwise also list every variant. + let added_ids: HashSet<_> = diff.added.iter().map(PublicItem::id).collect(); + for item in &diff.added { + if !item + .parent_id() + .is_some_and(|parent| added_ids.contains(&parent)) + { + newly_stable + .entry(item.to_string()) + .or_default() + .insert(chip); + } + } + } + + let items = newly_stable + .into_iter() + .map(|(item, chips)| NewStableItem { item, chips }) + .collect(); + + Ok((items, unchecked_chips)) +} + +fn public_api_from_rustdoc(path: &Path) -> anyhow::Result { + public_api::Builder::from_rustdoc_json(path) + .omit_blanket_impls(true) + .omit_auto_trait_impls(true) + .omit_auto_derived_impls(true) + .build() + .with_context(|| format!("Failed to parse public API from {}", path.display())) +} + +#[cfg(test)] +mod tests { + use super::*; + + const CTS_CONFIG_ENUM: &str = "pub enum esp_hal::uart::CtsConfig"; + + #[test] + fn new_stable_item_serializes_item_and_chips_as_separate_keys() { + let entry = NewStableItem { + item: CTS_CONFIG_ENUM.to_string(), + chips: BTreeSet::from([Chip::Esp32s31, Chip::Esp32, Chip::Esp32c6]), + }; + + assert_eq!( + serde_json::to_value(&entry).unwrap(), + serde_json::json!({ + "item": CTS_CONFIG_ENUM, + "chips": ["esp32", "esp32c6", "esp32s31"], + }) + ); + } +} diff --git a/xtask/src/commands/release/plan.rs b/xtask/src/commands/release/plan.rs index c81efb21804..9ed857a1d7e 100644 --- a/xtask/src/commands/release/plan.rs +++ b/xtask/src/commands/release/plan.rs @@ -1,11 +1,16 @@ -use std::{collections::HashMap, io::Write, path::Path, process::Command}; +use std::{ + collections::{BTreeSet, HashMap, HashSet}, + io::Write, + path::Path, + process::Command, +}; use anyhow::{Context, Result, bail, ensure}; use cargo_semver_checks::ReleaseType; use clap::Args; +use semver::VersionReq; use serde::{Deserialize, Serialize}; use strum::IntoEnumIterator; -use toml_edit::{Item, Value}; use crate::{ Package, @@ -15,7 +20,12 @@ use crate::{ VersionBump, checker::min_package_update, do_version_bump, - release::changelog_preview, + release::{ + changelog_preview, + new_stable_api, + new_stable_api::NewStableItem, + registry::RegistrySnapshot, + }, }, git::{BackportInfo, current_branch, parse_backport_branch}, metadata::Chip, @@ -29,9 +39,15 @@ pub struct PlanArgs { #[arg(long)] allow_non_main: bool, - /// The packages to be released. - #[arg(value_enum, default_values_t = Package::iter())] - packages: Vec, + /// Packages to leave out of the release plan. + /// + /// The plan always starts from the full set of published packages; this only + /// removes the named packages, plus any dependency that becomes private to + /// the excluded set. If what remains is inconsistent (a frozen crate would + /// pull an incompatible version of a released crate), planning fails and + /// names the conflict. + #[arg(long, value_enum)] + exclude: Vec, } /// A package in the release plan. @@ -44,6 +60,14 @@ pub struct PackagePlan { pub tag_name: String, /// The version bump that will be applied to the package. pub bump: VersionBump, + /// Public items stable now but not in the API baseline. `None` if the + /// package is not semver-checked. `execute-plan` ignores it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub new_stable_api: Option>, + /// Chips with no API baseline, so an empty `new_stable_api` is not an + /// all-clear for them. + #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] + pub new_stable_api_unchecked_chips: BTreeSet, } /// A release plan is a list of packages and their version increments. @@ -127,13 +151,13 @@ pub fn plan(workspace: &Path, args: PlanArgs) -> Result<()> { println!("Backport branch detected: releasing only {}.", ctx.package); vec![ctx.package] } else { - // Recursively collect dependencies. A bit inefficient, but we don't - // need to sort a lot. - let mut pkgs = args - .packages - .iter() + // Always start from every published package plus their dependencies. + // Only `--exclude` narrows this: releasing an arbitrary subset would + // pull in dependencies while silently dropping the dependents that also + // need re-releasing. + let mut pkgs = Package::iter() .filter(|p| p.is_published()) - .flat_map(|p| related_crates(workspace, *p)) + .flat_map(|p| related_crates(workspace, p)) .collect::>(); pkgs.sort(); @@ -184,36 +208,45 @@ pub fn plan(workspace: &Path, args: PlanArgs) -> Result<()> { let mut update_amounts = vec![]; let all_chips = Chip::iter().collect::>(); + // Resolve the changed/unchanged status of every package up front so a + // missing release tag surfaces as an error here rather than being swallowed + // by the lazy callback below. + let mut changed_status = HashMap::new(); + for package in sorted.iter().copied() { + changed_status.insert( + package, + package_changed_since_last_release(workspace, package)?, + ); + } + let changed = collect_changed_packages( &sorted, // Read direct dependencies out of Cargo.toml &|p| CargoToml::new(workspace, p).unwrap().repo_dependencies(), - &|p| package_changed_since_last_release(workspace, p), + &|p| changed_status[&p], ); for package in sorted.iter().copied() { + let mut newly_stable = None; let amount = if changed[&package] { let mut amount = if package.is_semver_checked() { - min_package_update(workspace, package, &all_chips)? + newly_stable = Some(new_stable_api::newly_stable( + workspace, package, &all_chips, + )?); + // `min_package_update` only sees what the stable API requires: Major for breaking + // changes, Minor for deprecations and `#[must_use]`, Patch for everything else, + // including new API and unstable changes. Semver-checked crates cut patch releases + // from their backport branch, so `main` releases at least Minor. + match min_package_update(workspace, package, &all_chips)? { + ReleaseType::Patch => ReleaseType::Minor, + other => other, + } } else { - let forever_unstable = if let Some(metadata) = - package_tomls[&package].espressif_metadata() - && let Some(Item::Value(forever_unstable)) = metadata.get("forever-unstable") - { - // Special case: some packages are perma-unstable, meaning they won't ever have - // a stable release. For these packages, we always use a - // patch release. - if let Value::Boolean(forever_unstable) = forever_unstable { - *forever_unstable.value() - } else { - log::warn!( - "Invalid value for 'forever-unstable' in metadata - must be a boolean" - ); - true - } - } else { - false - }; + // Perma-unstable packages never get a stable release, so they always take a + // patch bump. + let forever_unstable = package_tomls[&package] + .espressif_metadata_bool("forever-unstable") + .unwrap_or(false); if forever_unstable { ReleaseType::Patch @@ -239,7 +272,7 @@ pub fn plan(workspace: &Path, args: PlanArgs) -> Result<()> { None }; - update_amounts.push((package, amount)); + update_amounts.push((package, amount, newly_stable)); } // Generate plan file. The plan should include, as an ordered list, the packages @@ -252,62 +285,83 @@ pub fn plan(workspace: &Path, args: PlanArgs) -> Result<()> { // after tweaks keeps targeting the same release branch. let slug = read_existing_slug(&plan_path)?.unwrap_or_else(generate_slug); - let plan = Plan { - base: current_branch, - slug, - backport: backport.clone(), - packages: update_amounts - .into_iter() - .filter_map(|(package, bump)| { - bump.map(|b| { - let current_version = package_tomls[&package].package_version(); - - let bump = if !current_version.pre.is_empty() { - // Package is already in a pre-release cycle — continue it - // on the same base. Hand-edit the plan to start a new - // cycle on a bumped base (e.g. `1.1.0-alpha.0` from - // `1.0.0`) by also setting `base`. - VersionBump { - base: None, - pre: Some( - current_version - .pre - .as_str() - .split('.') - .next() - .unwrap() - .to_string(), - ), - } - } else { - let base = match b { - ReleaseType::Major => Version::Major, - ReleaseType::Minor => Version::Minor, - ReleaseType::Patch => Version::Patch, - _ => unreachable!(), - }; - VersionBump { - base: Some(base), - pre: None, - } + let mut plan_packages = update_amounts + .into_iter() + .filter_map(|(package, bump, newly_stable)| { + bump.map(|b| { + let current_version = package_tomls[&package].package_version(); + + let bump = if !current_version.pre.is_empty() { + // Package is already in a pre-release cycle - continue it + // on the same base. Hand-edit the plan to start a new + // cycle on a bumped base (e.g. `1.1.0-alpha.0` from + // `1.0.0`) by also setting `base`. + VersionBump { + base: None, + pre: Some( + current_version + .pre + .as_str() + .split('.') + .next() + .unwrap() + .to_string(), + ), + } + } else { + let base = match b { + ReleaseType::Major => Version::Major, + ReleaseType::Minor => Version::Minor, + ReleaseType::Patch => Version::Patch, + _ => unreachable!(), }; + VersionBump { + base: Some(base), + pre: None, + } + }; - let new_version = do_version_bump(¤t_version, &bump).unwrap(); - let tag_name = package.tag(&new_version); + let new_version = do_version_bump(¤t_version, &bump).unwrap(); + let tag_name = package.tag(&new_version); + let (new_stable_api, unchecked_chips) = newly_stable.unzip(); - PackagePlan { - package, - semver_checked: package.is_semver_checked(), - current_version, - new_version, - tag_name, - bump, - } - }) + PackagePlan { + package, + semver_checked: package.is_semver_checked(), + current_version, + new_version, + tag_name, + bump, + new_stable_api, + new_stable_api_unchecked_chips: unchecked_chips.unwrap_or_default(), + } }) - .collect(), + }) + .collect::>(); + + // Drop any excluded packages (and dependencies that become private to them) + // before validating that what remains is a self-consistent release. + apply_exclusions(workspace, &mut plan_packages, &args.exclude)?; + + // Refuse a plan that is wrong on paper (published requirements, manifest + // drift) and surface stale-dependency warnings before writing the file. + let warnings = validate_plan(workspace, &plan_packages)?; + print_stale_dependency_warnings(&warnings); + + // Report which chips each compile-test project covers. Report-only: a gap here + // never blocks the plan (it surfaces at build time instead). + print_compile_test_coverage(workspace); + + let mut plan = Plan { + base: current_branch, + slug, + backport: backport.clone(), + packages: plan_packages, }; + let registry = RegistrySnapshot::fetch(plan.packages.iter().map(|step| step.package))?; + resolve_reserved_versions(&mut plan.packages, ®istry)?; + log::debug!("Writing release plan to {}", plan_path.display()); let mut plan_header = String::from( @@ -329,6 +383,9 @@ pub fn plan(workspace: &Path, args: PlanArgs) -> Result<()> { // release plan. The release plan will then be added to the release PR and will be used to // orchestrate the actual publishing process. // +// Version numbers crates.io already holds are skipped automatically: a yanked release keeps its +// number reserved forever. Change the bump to release something else. +// // For each package, this plan contains the version bump that will be applied. // A bump has two orthogonal fields — `base` (how much to bump // major.minor.patch) and `pre` (the pre-release identifier): @@ -379,6 +436,21 @@ pub fn plan(workspace: &Path, args: PlanArgs) -> Result<()> { Ok(()) } +/// Step every planned version crates.io already holds, keeping each tag name +/// pointing at the version it will actually be cut for. +fn resolve_reserved_versions( + plan_packages: &mut [PackagePlan], + registry: &RegistrySnapshot, +) -> Result<()> { + for step in plan_packages.iter_mut() { + step.new_version = + registry.next_free_version(step.package, &step.new_version, &step.bump)?; + step.tag_name = step.package.tag(&step.new_version); + } + + Ok(()) +} + fn collect_changed_packages( sorted: &[Package], direct_dependencies: &impl Fn(Package) -> Vec, @@ -440,32 +512,22 @@ pub fn ensure_main_branch(allow_non_main: bool) -> Result<(String, Option bool { - let toml = CargoToml::new(workspace, package).expect("Failed to load Cargo.toml"); +fn package_changed_since_last_release(workspace: &Path, package: Package) -> Result { + let toml = CargoToml::new(workspace, package)?; let last_version: semver::Version = toml.package_version(); - let last_tag = package.tag(&last_version); - let mut commits = commits_since_tag(workspace, &toml.package_path(), &last_tag); - - if commits == 0 { - // Try to look up the last tag in the git history and retry. - let last_tag = Command::new("git") - .args(["describe", "--tags", "--abbrev=0"]) - .current_dir(workspace) - .output() - .expect("Failed to get last tag"); - let last_tag = String::from_utf8_lossy(&last_tag.stdout); - let last_tag = last_tag.trim(); - - if !last_tag.is_empty() { - commits = commits_since_tag(workspace, &toml.package_path(), last_tag); - } - } + ensure!( + crate::git::ref_exists(workspace, &last_tag)?, + "Cannot determine whether {package} changed since its last release: the tag {last_tag} \ + does not exist. Every published package must be tagged at its current version." + ); + + let commits = commits_since_tag(workspace, &toml.package_path(), &last_tag); log::trace!("{package}: {commits} commits since last release"); - commits > 0 + Ok(commits > 0) } fn commits_since_tag(workspace: &Path, package_path: &Path, tag: &str) -> usize { @@ -512,6 +574,418 @@ fn related_crates(workspace: &Path, package: Package) -> Vec { }) } +/// Build a map from each published package to the published packages that +/// depend on it. `dev-dependencies` are excluded (see +/// [`CargoToml::repo_dependency_requirements`]). +fn build_dependents(workspace: &Path) -> Result>> { + let mut dependents: HashMap> = HashMap::new(); + for pkg in Package::iter().filter(|p| p.is_published() && !p.contains_standalone_projects()) { + let mut deps = CargoToml::new(workspace, pkg)? + .repo_dependency_requirements() + .into_iter() + .map(|(dep, _)| dep) + .collect::>(); + deps.sort(); + deps.dedup(); + for dep in deps { + dependents.entry(dep).or_default().push(pkg); + } + } + Ok(dependents) +} + +/// Remove the excluded packages from `plan_packages`, along with any package +/// that becomes private to the excluded set (every published dependent removed). +/// +/// Version consistency of what remains is left to [`validate_plan`], so +/// exclusions that stay compatible are allowed and only genuine +/// incompatibilities are rejected. +fn apply_exclusions( + workspace: &Path, + plan_packages: &mut Vec, + exclude: &[Package], +) -> Result<()> { + if exclude.is_empty() { + return Ok(()); + } + + let dependents = build_dependents(workspace)?; + let in_plan = plan_packages + .iter() + .map(|p| p.package) + .collect::>(); + + for pkg in exclude { + if !in_plan.contains(pkg) { + log::warn!("--exclude {pkg}: not part of the generated plan; ignoring."); + } + } + + let removed = compute_exclusion_removals(&dependents, &in_plan, exclude); + + // Report what was dropped so the removal is visible. + let explicit = exclude.iter().copied().collect::>(); + let mut dropped = removed.iter().copied().collect::>(); + dropped.sort(); + for pkg in &dropped { + if explicit.contains(pkg) { + println!("Excluding {pkg} from the release plan."); + } else { + println!("Dropping {pkg}: only depended on by excluded packages."); + } + } + + plan_packages.retain(|p| !removed.contains(&p.package)); + + Ok(()) +} + +/// Pure core of [`apply_exclusions`]: given the in-repo dependents map, the set +/// of packages currently in the plan, and the packages to exclude, return the +/// full set of packages to remove - the explicitly excluded ones plus any that +/// become private to the excluded set. +fn compute_exclusion_removals( + dependents: &HashMap>, + in_plan: &HashSet, + exclude: &[Package], +) -> HashSet { + let mut kept = in_plan.clone(); + let mut removed = HashSet::new(); + + // Remove the explicitly excluded packages. + for pkg in exclude { + if kept.remove(pkg) { + removed.insert(*pkg); + } + } + + // Iteratively drop packages whose every published dependent has been + // removed: with no remaining consumer among the released crates, releasing + // them is pointless. A top-level crate (no in-repo dependents at all) is + // kept. + loop { + let newly_private = kept + .iter() + .copied() + .filter(|p| { + let deps = dependents.get(p).map(Vec::as_slice).unwrap_or(&[]); + !deps.is_empty() && deps.iter().all(|q| !kept.contains(q)) + }) + .collect::>(); + + if newly_private.is_empty() { + break; + } + for p in newly_private { + kept.remove(&p); + removed.insert(p); + } + } + + removed +} + +/// A plan crate that depends on a frozen in-repo crate carrying commits since +/// its release tag. Whether those commits are actually needed is decided by the +/// registry check, so this is surfaced as a warning, not an error. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct StaleDependency { + /// The plan crate doing the depending. + pub package: Package, + /// The frozen in-repo dependency with unreleased commits. + pub dependency: Package, + /// The frozen dependency's release tag. + pub tag: String, + /// Number of commits touching the dependency's directory since its tag. + pub commits: usize, +} + +/// Newest non-pre-release `{package}-v*` tag on `tree_version`'s major.minor +/// line. Backport patches (1.2.2 vs tree 1.2.0) are what users resolve; the +/// working-tree version's own tag can lag that line. +fn newest_patch_tag( + package: Package, + tree_version: &semver::Version, + tags: &[String], +) -> Option { + let prefix = format!("{package}-v"); + let mut best: Option = None; + for tag in tags { + let Some(ver) = tag + .strip_prefix(&prefix) + .and_then(|s| semver::Version::parse(s).ok()) + else { + continue; + }; + if !ver.pre.is_empty() { + continue; + } + if ver.major != tree_version.major || ver.minor != tree_version.minor { + continue; + } + if best.as_ref().is_none_or(|b| ver > *b) { + best = Some(ver); + } + } + best.map(|v| package.tag(&v)) +} + +/// Run every planner gate against a finalized set of plan packages, refusing a +/// plan that is wrong on paper and returning the non-blocking stale-dependency +/// warnings. +/// +/// A frozen crate (published, not in the plan, not a standalone-project +/// collection) is read from its tags, never the working tree, which +/// `bump_crate_version` rewrites for every workspace crate. Its requirements +/// come from the newest patch on its line, which is what users resolve; drift is +/// measured against the tag of the working-tree version, since a backport +/// branch's manifest changes are not unreleased work on this branch. +pub fn validate_plan(workspace: &Path, packages: &[PackagePlan]) -> Result> { + let in_plan = packages.iter().map(|p| p.package).collect::>(); + let releasing = packages + .iter() + .map(|p| (p.package, p.new_version.clone())) + .collect::>(); + + let mut frozen_reqs: HashMap> = HashMap::new(); + let mut drift_errors = Vec::new(); + for pkg in Package::iter().filter(|p| p.is_published() && !p.contains_standalone_projects()) { + if in_plan.contains(&pkg) { + continue; + } + + let mut tree = CargoToml::new(workspace, pkg)?; + let tree_version = tree.package_version(); + let tree_tag = pkg.tag(&tree_version); + ensure!( + crate::git::ref_exists(workspace, &tree_tag)?, + "Cannot validate the release: frozen package {pkg} has no release tag {tree_tag}." + ); + let tags = crate::git::list_tags(workspace, &format!("{pkg}-v*"))?; + let resolved_tag = + newest_patch_tag(pkg, &tree_version, &tags).unwrap_or_else(|| tree_tag.clone()); + + let mut at_resolved = CargoToml::at_ref(workspace, pkg, &resolved_tag)?; + frozen_reqs.insert(pkg, at_resolved.repo_dependency_requirements()); + + let mut at_tree_tag = CargoToml::at_ref(workspace, pkg, &tree_tag)?; + let tree_deps = tree.dependency_requirements(); + let tag_deps = at_tree_tag.dependency_requirements(); + if tree_deps != tag_deps { + drift_errors.push(format_manifest_drift(pkg, &tree_tag, &tree_deps, &tag_deps)); + } + } + + let violations = release_closure_violations(&frozen_reqs, &releasing); + ensure!( + violations.is_empty(), + "The release plan is refused: the following frozen crates' published manifests reject a \ + planned version. Add the named crate(s) to the plan so their requirements are raised, \ + or remove the crate(s) they conflict with.\n{}", + violations.join("\n") + ); + + ensure!( + drift_errors.is_empty(), + "The release plan is refused: the following frozen crates' working-tree manifests differ \ + from their release tags. A frozen crate must match what was published; add each listed \ + crate to the plan so the change is released.\n\n{}", + drift_errors.join("\n\n") + ); + + // Non-blocking: a plan crate depending on a frozen in-repo crate with + // commits since its tag. The registry check decides if they are needed. + let mut deps_of: HashMap> = HashMap::new(); + for step in packages { + let mut toml = CargoToml::new(workspace, step.package)?; + let deps = toml + .repo_dependency_requirements() + .into_iter() + .map(|(dep, _)| dep) + .filter(|dep| !in_plan.contains(dep) && dep.is_published()) + .collect::>(); + deps_of.insert(step.package, deps); + } + + let mut to_check = deps_of.values().flatten().copied().collect::>(); + to_check.sort(); + to_check.dedup(); + + let mut stale: HashMap = HashMap::new(); + for dep in to_check { + let dep_toml = CargoToml::new(workspace, dep)?; + let dep_tag = dep.tag(&dep_toml.package_version()); + ensure!( + crate::git::ref_exists(workspace, &dep_tag)?, + "Cannot check {dep} for staleness: its release tag {dep_tag} does not exist." + ); + let commits = commits_since_tag(workspace, &dep_toml.package_path(), &dep_tag); + if commits > 0 { + stale.insert(dep, (commits, dep_tag)); + } + } + + let plan_crates = packages.iter().map(|p| p.package).collect::>(); + Ok(stale_dependency_warnings(&plan_crates, &deps_of, &stale)) +} + +/// Pure core of the stale-dependency warning: pair each plan crate with its +/// dependencies that carry commits since their release. `deps_of` holds each +/// plan crate's out-of-plan published dependencies; `stale` maps a dependency +/// with unreleased commits to its `(commit count, tag)`. +fn stale_dependency_warnings( + plan_crates: &[Package], + deps_of: &HashMap>, + stale: &HashMap, +) -> Vec { + let mut warnings = Vec::new(); + for &package in plan_crates { + let mut deps = deps_of.get(&package).cloned().unwrap_or_default(); + deps.sort(); + deps.dedup(); + for dep in deps { + if let Some((commits, tag)) = stale.get(&dep) { + warnings.push(StaleDependency { + package, + dependency: dep, + tag: tag.clone(), + commits: *commits, + }); + } + } + } + warnings +} + +/// Pure core of the upward closure walk: for every frozen crate (mapped to its +/// published requirements) each requirement on a plan crate must accept that +/// crate's planned version. Returns the sorted list of violations; empty means +/// consistent. +fn release_closure_violations( + frozen_reqs: &HashMap>, + releasing: &HashMap, +) -> Vec { + let mut violations = Vec::new(); + for (frozen, reqs) in frozen_reqs { + for (dep, req) in reqs { + let Some(new_version) = releasing.get(dep) else { + continue; + }; + let accepted = VersionReq::parse(req) + .map(|r| r.matches(new_version)) + .unwrap_or(false); + if !accepted { + violations.push(format!( + " - {frozen} (frozen) requires {dep} \"{req}\" in its published manifest, \ + which does not accept the planned {dep} {new_version}" + )); + } + } + } + + violations.sort(); + violations.dedup(); + violations +} + +/// Render a manifest-drift error for one frozen crate: the requirements that +/// differ between its working tree and its release tag. +fn format_manifest_drift( + pkg: Package, + tag: &str, + tree_deps: &[(String, String)], + tag_deps: &[(String, String)], +) -> String { + let tree_map = tree_deps.iter().cloned().collect::>(); + let tag_map = tag_deps.iter().cloned().collect::>(); + + let mut names = tree_map + .keys() + .chain(tag_map.keys()) + .cloned() + .collect::>(); + names.sort(); + names.dedup(); + + let mut lines = vec![format!("{pkg} (frozen at {tag}) has drifted:")]; + for name in names { + match (tag_map.get(&name), tree_map.get(&name)) { + (Some(published), Some(tree)) if published != tree => { + lines.push(format!( + " - {name}: {published:?} (tag) -> {tree:?} (working tree)" + )); + } + (Some(published), None) => { + lines.push(format!( + " - {name}: {published:?} (tag) removed in working tree" + )); + } + (None, Some(tree)) => { + lines.push(format!(" - {name}: added in working tree as {tree:?}")); + } + _ => {} + } + } + lines.join("\n") +} + +/// Print the compile-test chip coverage table. Report-only; a failure to read +/// it is logged and swallowed so it can never block a plan. +fn print_compile_test_coverage(workspace: &Path) { + match crate::firmware::compile_test_coverage(workspace) { + Ok(coverage) => { + println!("\nCompile-test chip coverage:"); + println!( + "{}", + crate::firmware::format_compile_test_coverage(&coverage) + ); + } + Err(e) => log::warn!("Could not compute compile-test coverage: {e}"), + } +} + +/// Print stale-dependency warnings to stdout, grouped by plan crate. +pub fn print_stale_dependency_warnings(warnings: &[StaleDependency]) { + if warnings.is_empty() { + return; + } + println!("\nStale-dependency warnings:"); + for line in format_stale_dependency_warnings(warnings) { + println!("{line}"); + } + println!( + "These dependencies have commits since their last release. The registry check decides \ + whether the release needs them." + ); +} + +/// Format stale-dependency warnings as lines grouped under each plan crate, for +/// both the plan output and the PR body. +pub fn format_stale_dependency_warnings(warnings: &[StaleDependency]) -> Vec { + let mut by_package: HashMap> = HashMap::new(); + for w in warnings { + by_package.entry(w.package).or_default().push(w); + } + + let mut packages = by_package.keys().copied().collect::>(); + packages.sort(); + + let mut lines = Vec::new(); + for package in packages { + lines.push(format!("- {package}:")); + let mut deps = by_package.remove(&package).unwrap(); + deps.sort_by_key(|w| w.dependency); + for w in deps { + let plural = if w.commits == 1 { "commit" } else { "commits" }; + lines.push(format!( + " - {} has {} {plural} since {}", + w.dependency, w.commits, w.tag + )); + } + } + lines +} + /// Merge PR changelog and migration guide entries from recently-merged PRs /// directly into each package's `CHANGELOG.md` and `MIGRATING-*.md` files. /// @@ -543,17 +1017,14 @@ pub(super) fn generate_changelog_draft(workspace: &Path, plan: &Plan) -> Vec r, - Err(e) => { - log::warn!( - "Could not collect changelog entries (is `gh` installed and authenticated?): {e}" - ); - return vec![]; - } - }; + let (changelogs, migrations) = + match changelog_preview::collect_changelogs(workspace, &since_ref, 500, &plan.base) { + Ok(r) => r, + Err(e) => { + log::warn!("Could not collect changelog entries: {e}"); + return vec![]; + } + }; let mut modified: Vec = Vec::new(); @@ -757,4 +1228,452 @@ mod tests { &[Package::EspHal, Package::EspRadio, Package::EspRtos], ); } + + fn ver(s: &str) -> semver::Version { + semver::Version::parse(s).unwrap() + } + + /// A forward dependency graph (with version requirements) modelled on the + /// real xtensa/Wi-Fi chain. Dev-dependencies are excluded, matching the + /// real graph (notably esp-radio's dev-dependency on esp-rtos, which must + /// NOT make esp-rtos look private to esp-radio): + /// ```text + /// esp-radio -> esp-hal, esp-phy, esp-radio-rtos-driver, esp-alloc + /// esp-rtos -> esp-hal, esp-radio-rtos-driver, esp-alloc + /// esp-hal -> esp-sync, xtensa-lx + /// esp-sync -> xtensa-lx + /// esp-phy -> esp-sync + /// ``` + fn xtensa_deps_of() -> HashMap> { + HashMap::from([ + ( + Package::EspRadio, + vec![ + (Package::EspHal, "~1.2.0-rc.0".to_string()), + (Package::EspPhy, "0.2.0".to_string()), + (Package::EspRadioRtosDriver, "0.3.0".to_string()), + (Package::EspAlloc, "0.10.0".to_string()), + ], + ), + ( + Package::EspRtos, + vec![ + (Package::EspHal, "~1.2.0-rc.0".to_string()), + (Package::EspRadioRtosDriver, "0.3.0".to_string()), + (Package::EspAlloc, "0.10.0".to_string()), + ], + ), + ( + Package::EspHal, + vec![ + (Package::EspSync, "0.3.0".to_string()), + (Package::XtensaLx, "0.13.0".to_string()), + ], + ), + ( + Package::EspSync, + vec![(Package::XtensaLx, "0.13.0".to_string())], + ), + ( + Package::EspPhy, + vec![(Package::EspSync, "0.3.0".to_string())], + ), + (Package::EspRadioRtosDriver, vec![]), + (Package::EspAlloc, vec![]), + (Package::XtensaLx, vec![]), + ]) + } + + /// Inverse of [`xtensa_deps_of`]: each crate to its in-repo dependents. + fn xtensa_dependents() -> HashMap> { + HashMap::from([ + (Package::EspHal, vec![Package::EspRadio, Package::EspRtos]), + (Package::EspPhy, vec![Package::EspRadio]), + ( + Package::EspRadioRtosDriver, + vec![Package::EspRadio, Package::EspRtos], + ), + (Package::EspAlloc, vec![Package::EspRadio, Package::EspRtos]), + (Package::EspSync, vec![Package::EspHal, Package::EspPhy]), + (Package::XtensaLx, vec![Package::EspHal, Package::EspSync]), + ]) + } + + fn full_release_set() -> HashSet { + [ + Package::EspRadio, + Package::EspRtos, + Package::EspHal, + Package::EspSync, + Package::EspPhy, + Package::EspRadioRtosDriver, + Package::EspAlloc, + Package::XtensaLx, + ] + .into_iter() + .collect() + } + + /// A plan entry for [`resolve_reserved_versions`], which reads only + /// `package`, `new_version` and `bump`. + fn planned(package: Package, new_version: &str, bump: VersionBump) -> PackagePlan { + let new_version = ver(new_version); + + PackagePlan { + package, + semver_checked: false, + current_version: new_version.clone(), + tag_name: package.tag(&new_version), + new_version, + bump, + new_stable_api: None, + new_stable_api_unchecked_chips: BTreeSet::new(), + } + } + + #[test] + fn a_reservation_moves_one_entry_and_leaves_the_rest() { + // esp-rs/esp-hal#5385: esp-sync 0.2.0 is yanked, so the plan cannot use + // it, and the tag has to follow the version it is cut for. + let mut plan = vec![ + planned(Package::EspSync, "0.2.0", VersionBump::minor()), + planned(Package::EspHal, "1.2.0", VersionBump::minor()), + ]; + let registry = RegistrySnapshot::from_taken([(Package::EspSync, vec![ver("0.2.0")])]); + + resolve_reserved_versions(&mut plan, ®istry).unwrap(); + + assert_eq!(plan[0].new_version, ver("0.2.1")); + assert_eq!(plan[0].tag_name, "esp-sync-v0.2.1"); + assert_eq!(plan[1].new_version, ver("1.2.0")); + assert_eq!(plan[1].tag_name, "esp-hal-v1.2.0"); + } + + /// Keep only the requirements of crates that are frozen (not in the + /// release), mirroring how [`validate_plan`] reads the upward walk's input + /// from the tags of crates left out of the plan. + fn frozen_reqs_from( + deps_of: &HashMap>, + releasing: &HashMap, + ) -> HashMap> { + deps_of + .iter() + .filter(|(pkg, _)| !releasing.contains_key(pkg)) + .map(|(pkg, reqs)| (*pkg, reqs.clone())) + .collect() + } + + #[test] + fn closure_full_release_is_consistent() { + // Everything is released, so nothing is frozen and no published + // requirement can reject a planned version. + let releasing = HashMap::from([ + (Package::EspRadio, ver("1.0.0-beta.1")), + (Package::EspRtos, ver("0.4.0")), + (Package::EspHal, ver("1.2.0-rc.1")), + (Package::EspSync, ver("0.4.0")), + (Package::EspPhy, ver("0.3.0")), + (Package::EspRadioRtosDriver, ver("0.4.0")), + (Package::EspAlloc, ver("0.11.0")), + (Package::XtensaLx, ver("0.14.0")), + ]); + let frozen = frozen_reqs_from(&xtensa_deps_of(), &releasing); + assert!(release_closure_violations(&frozen, &releasing).is_empty()); + } + + #[test] + fn closure_freezing_radio_while_bumping_its_deps_is_rejected() { + // Drop esp-radio (and its private esp-phy) but bump the crates it + // depends on. The frozen esp-radio's published manifest still requires + // the old esp-alloc / esp-radio-rtos-driver, so the upward walk refuses. + let releasing = HashMap::from([ + (Package::EspRtos, ver("0.4.0")), + (Package::EspHal, ver("1.2.0-rc.1")), + (Package::EspSync, ver("0.4.0")), + (Package::EspRadioRtosDriver, ver("0.4.0")), + (Package::EspAlloc, ver("0.11.0")), + (Package::XtensaLx, ver("0.14.0")), + ]); + let frozen = frozen_reqs_from(&xtensa_deps_of(), &releasing); + let violations = release_closure_violations(&frozen, &releasing); + assert!( + violations + .iter() + .any(|v| v.contains("esp-radio") && v.contains("esp-alloc")), + "expected an esp-radio/esp-alloc violation, got: {violations:?}" + ); + } + + #[test] + fn closure_frozen_esp_hal_with_bumped_xtensa_is_rejected() { + // Bump xtensa-lx (breaking) but freeze esp-hal: esp-hal's published + // manifest requires xtensa-lx 0.13, which rejects the planned 0.14. + let releasing = HashMap::from([ + (Package::XtensaLx, ver("0.14.0")), + (Package::EspSync, ver("0.4.0")), + (Package::EspRtos, ver("0.4.0")), + ]); + let frozen = frozen_reqs_from(&xtensa_deps_of(), &releasing); + let violations = release_closure_violations(&frozen, &releasing); + assert!( + violations + .iter() + .any(|v| v.contains("esp-hal") && v.contains("xtensa-lx")), + "expected an esp-hal/xtensa-lx violation, got: {violations:?}" + ); + } + + #[test] + fn exclusion_radio_prunes_only_phy() { + // Excluding esp-radio drops its genuinely-private esp-phy, but keeps + // esp-rtos, esp-alloc and esp-radio-rtos-driver: those are used beyond + // esp-radio (and esp-radio's dev-dependency on esp-rtos is not counted). + let removed = compute_exclusion_removals( + &xtensa_dependents(), + &full_release_set(), + &[Package::EspRadio], + ); + assert_eq!( + removed, + [Package::EspRadio, Package::EspPhy] + .into_iter() + .collect::>() + ); + } + + #[test] + fn exclusion_esp_hal_removes_only_esp_hal() { + // esp-hal keeps dependents that stay in the plan, so nothing is + // auto-pruned. Whether freezing esp-hal is *safe* is left to the + // closure check, not decided here. + let removed = compute_exclusion_removals( + &xtensa_dependents(), + &full_release_set(), + &[Package::EspHal], + ); + assert_eq!( + removed, + [Package::EspHal].into_iter().collect::>() + ); + } + + #[test] + fn closure_releasing_radio_over_frozen_lower_stack_is_ok() { + // Release esp-radio while freezing esp-phy and the whole lower stack: + // none of the frozen crates' deps are bumped, so no published + // requirement is violated. + let releasing = HashMap::from([ + (Package::EspRadio, ver("1.0.0-beta.1")), + (Package::EspRtos, ver("0.4.0")), + (Package::EspRadioRtosDriver, ver("0.4.0")), + (Package::EspAlloc, ver("0.11.0")), + ]); + let frozen = frozen_reqs_from(&xtensa_deps_of(), &releasing); + assert!(release_closure_violations(&frozen, &releasing).is_empty()); + } + + #[test] + fn closure_freezing_esp_phy_while_bumping_esp_sync_is_rejected() { + // Bump esp-sync but freeze esp-phy: esp-phy's published manifest still + // requires esp-sync 0.3, which rejects the planned 0.4. + let releasing = HashMap::from([ + (Package::EspRadio, ver("1.0.0-beta.1")), + (Package::EspSync, ver("0.4.0")), + ]); + let frozen = frozen_reqs_from(&xtensa_deps_of(), &releasing); + let violations = release_closure_violations(&frozen, &releasing); + assert!( + violations + .iter() + .any(|v| v.contains("esp-phy") && v.contains("esp-sync")), + "expected an esp-phy/esp-sync violation, got: {violations:?}" + ); + } + + /// The #6341 graph: frozen esp-hal and esp-config require + /// esp-metadata-generated ^0.5 in their published manifests. + fn emg_deps_of() -> HashMap> { + HashMap::from([ + ( + Package::EspHal, + vec![(Package::EspMetadataGenerated, "0.5".to_string())], + ), + ( + Package::EspConfig, + vec![(Package::EspMetadataGenerated, "0.5".to_string())], + ), + ]) + } + + #[test] + fn releasing_emg_alone_is_refused_by_frozen_dependents() { + // #6341: bumping esp-metadata-generated to 0.6.0 while esp-hal and + // esp-config stay frozen at ^0.5 must be refused, since their published + // manifests reject 0.6.0. + let releasing = HashMap::from([(Package::EspMetadataGenerated, ver("0.6.0"))]); + let frozen = frozen_reqs_from(&emg_deps_of(), &releasing); + let violations = release_closure_violations(&frozen, &releasing); + assert!( + violations + .iter() + .any(|v| v.contains("esp-hal") && v.contains("esp-metadata-generated")), + "expected an esp-hal/esp-metadata-generated violation, got: {violations:?}" + ); + assert!( + violations + .iter() + .any(|v| v.contains("esp-config") && v.contains("esp-metadata-generated")), + "expected an esp-config/esp-metadata-generated violation, got: {violations:?}" + ); + } + + #[test] + fn releasing_emg_with_its_dependents_is_accepted() { + // Adding esp-hal and esp-config to the plan unfreezes them, so nothing + // constrains esp-metadata-generated. + let releasing = HashMap::from([ + (Package::EspMetadataGenerated, ver("0.6.0")), + (Package::EspConfig, ver("0.9.0")), + (Package::EspHal, ver("1.3.0")), + ]); + let frozen = frozen_reqs_from(&emg_deps_of(), &releasing); + assert!(release_closure_violations(&frozen, &releasing).is_empty()); + } + + #[test] + fn edited_bump_changes_the_version_the_check_sees() { + // A frozen esp-hal requiring esp-metadata-generated ^0.5. Editing the + // bump from minor to patch changes the planned version the closure walk + // evaluates, flipping the outcome. + let frozen = HashMap::from([( + Package::EspHal, + vec![(Package::EspMetadataGenerated, "0.5".to_string())], + )]); + let current = ver("0.5.1"); + + let minor = do_version_bump(¤t, &VersionBump::minor()).unwrap(); + assert_eq!(minor, ver("0.6.0")); + let releasing = HashMap::from([(Package::EspMetadataGenerated, minor)]); + assert!( + !release_closure_violations(&frozen, &releasing).is_empty(), + "a minor bump to 0.6.0 must be rejected by ^0.5" + ); + + let patch = do_version_bump(¤t, &VersionBump::patch()).unwrap(); + assert_eq!(patch, ver("0.5.2")); + let releasing = HashMap::from([(Package::EspMetadataGenerated, patch)]); + assert!( + release_closure_violations(&frozen, &releasing).is_empty(), + "a patch bump to 0.5.2 must be accepted by ^0.5" + ); + } + + #[test] + fn newest_patch_tag_picks_backport_ahead_of_tree() { + // Tree is 1.2.0 (last main release); users resolve 1.2.2 from the + // backport branch. Pre-releases and other minors must not win. + let tags = [ + "esp-hal-v1.1.9".to_string(), + "esp-hal-v1.2.0".to_string(), + "esp-hal-v1.2.0-rc.0".to_string(), + "esp-hal-v1.2.1".to_string(), + "esp-hal-v1.2.2".to_string(), + "esp-hal-v1.3.0".to_string(), + ]; + assert_eq!( + newest_patch_tag(Package::EspHal, &ver("1.2.0"), &tags).as_deref(), + Some("esp-hal-v1.2.2") + ); + } + + #[test] + fn newest_patch_tag_falls_back_when_line_has_no_tags() { + let tags = [ + "esp-hal-v1.1.9".to_string(), + "esp-config-v0.5.1".to_string(), + ]; + assert_eq!( + newest_patch_tag(Package::EspHal, &ver("1.2.0"), &tags), + None + ); + } + + #[test] + fn manifest_drift_lists_only_changed_requirements() { + // Published tag required emg ^0.5 and an unchanged external dep; the + // working tree drifted emg to ^0.6. + let tag = vec![ + ("embassy-time".to_string(), "0.5".to_string()), + ("esp-metadata-generated".to_string(), "0.5".to_string()), + ]; + let tree = vec![ + ("embassy-time".to_string(), "0.5".to_string()), + ("esp-metadata-generated".to_string(), "0.6".to_string()), + ]; + let msg = format_manifest_drift(Package::EspHal, "esp-hal-v1.2.1", &tree, &tag); + assert!(msg.contains("esp-metadata-generated"), "got: {msg}"); + assert!(msg.contains("0.5") && msg.contains("0.6"), "got: {msg}"); + assert!( + !msg.contains("embassy-time"), + "unchanged deps must not be listed, got: {msg}" + ); + } + + #[test] + fn stale_dependency_warns_for_frozen_dep_with_commits() { + // #6334 (esp-radio beta.1): esp-radio is released while + // esp-metadata-generated stays frozen with commits since its tag (the + // S31 Wi-Fi metadata), so the planner warns. esp-hal has no new commits, + // so it is not flagged. + let deps_of = HashMap::from([( + Package::EspRadio, + vec![Package::EspMetadataGenerated, Package::EspHal], + )]); + let stale = HashMap::from([( + Package::EspMetadataGenerated, + (3usize, "esp-metadata-generated-v0.5.1".to_string()), + )]); + + let warnings = stale_dependency_warnings(&[Package::EspRadio], &deps_of, &stale); + assert_eq!(warnings.len(), 1); + assert_eq!(warnings[0].package, Package::EspRadio); + assert_eq!(warnings[0].dependency, Package::EspMetadataGenerated); + assert_eq!(warnings[0].commits, 3); + assert_eq!(warnings[0].tag, "esp-metadata-generated-v0.5.1"); + } + + #[test] + fn stale_dependency_warnings_group_by_package() { + // #6334 (esp-radio beta.1): esp-radio is released against a frozen + // esp-metadata-generated 0.5.1 that has commits since its tag (the S31 + // Wi-Fi metadata), so the planner warns rather than refusing. + let warnings = vec![ + StaleDependency { + package: Package::EspRadio, + dependency: Package::EspMetadataGenerated, + tag: "esp-metadata-generated-v0.5.1".to_string(), + commits: 3, + }, + StaleDependency { + package: Package::EspRadio, + dependency: Package::EspHal, + tag: "esp-hal-v1.2.1".to_string(), + commits: 1, + }, + ]; + let lines = format_stale_dependency_warnings(&warnings); + assert_eq!(lines[0], "- esp-radio:"); + assert!( + lines + .iter() + .any(|l| l.contains("esp-hal") && l.contains("1 commit since")), + "got: {lines:?}" + ); + assert!( + lines + .iter() + .any(|l| l.contains("esp-metadata-generated") && l.contains("3 commits since")), + "got: {lines:?}" + ); + } } diff --git a/xtask/src/commands/release/post_release.rs b/xtask/src/commands/release/post_release.rs index 376901eff76..b3bbd82c2b8 100644 --- a/xtask/src/commands/release/post_release.rs +++ b/xtask/src/commands/release/post_release.rs @@ -50,7 +50,7 @@ pub fn post_release(workspace: &std::path::Path, args: PostReleaseArgs) -> Resul } // Get the package's directory path - let package_path = workspace.join(package.to_string()); + let package_path = workspace.join(package.directory()); let cargo_toml_path = package_path.join("Cargo.toml"); // Read and parse Cargo.toml diff --git a/xtask/src/commands/release/publish.rs b/xtask/src/commands/release/publish.rs index 8fe2bea390a..5d7815176a6 100644 --- a/xtask/src/commands/release/publish.rs +++ b/xtask/src/commands/release/publish.rs @@ -19,8 +19,7 @@ pub struct PublishArgs { /// Publish a package to crates.io. pub fn publish(workspace: &Path, args: PublishArgs) -> Result<()> { - let package_name = args.package.to_string(); - let package_path = windows_safe_path(&workspace.join(&package_name)); + let package_path = windows_safe_path(&workspace.join(args.package.directory())); ensure!( args.package.is_published(), diff --git a/xtask/src/commands/release/registry.rs b/xtask/src/commands/release/registry.rs new file mode 100644 index 00000000000..555294fb3bf --- /dev/null +++ b/xtask/src/commands/release/registry.rs @@ -0,0 +1,316 @@ +//! Queries crates.io for version numbers that are already spoken for. + +use std::{collections::HashMap, time::Duration}; + +use anyhow::{Context, Result, bail}; +use tame_index::{ + IndexKrate, + IndexLocation, + IndexUrl, + SparseIndex, + external::reqwest::blocking::ClientBuilder, + index::{FileLock, RemoteSparseIndex}, +}; + +use crate::{ + Package, + commands::{VersionBump, do_version_bump}, +}; + +/// Pull the version numbers out of one index entry. +fn versions_of(krate: &IndexKrate) -> Vec { + krate + .versions + .iter() + .filter_map(|v| match v.version.parse::() { + Ok(parsed) => Some(parsed), + Err(e) => { + // Pre-semver crates exist in the index. They cannot collide + // with anything we generate, so drop them rather than fail. + log::debug!("Ignoring unparseable index version {:?}: {e}", v.version); + None + } + }) + .collect() +} + +/// What crates.io already holds for a set of packages, fetched in one go. +#[derive(Debug, Default)] +pub struct RegistrySnapshot { + /// Per package: every version the index knows, yanked ones included. + taken: HashMap>, +} + +impl RegistrySnapshot { + /// Look up every package in one batch. + pub fn fetch(packages: impl IntoIterator) -> Result { + let by_name = packages + .into_iter() + .map(|p| (p.to_string(), p)) + .collect::>(); + + if by_name.is_empty() { + return Ok(Self::default()); + } + + let index = SparseIndex::new(IndexLocation::new(IndexUrl::CratesIoSparse)) + .context("Failed to open the crates.io sparse index")?; + + let client = ClientBuilder::new() + // Fail a stalled request instead of hanging the release. + .timeout(Duration::from_secs(15)) + .build() + .context("Failed to build an HTTP client for the crates.io index")?; + + let remote = RemoteSparseIndex::new(index, client); + + // A crate that was never published comes back as `Ok(None)`, so only + // transport and parse failures are retried. + crate::retry_on_failure("The crates.io index query", || { + let results = remote.krates( + by_name.keys().cloned().collect(), + false, + &FileLock::unlocked(), + ); + + let mut taken = HashMap::with_capacity(by_name.len()); + for (name, result) in results { + let krate = result + .with_context(|| format!("Failed to query the crates.io index for {name}"))?; + + match krate { + Some(krate) => { + taken.insert(by_name[&name], versions_of(&krate)); + } + None => log::debug!("{name} has never been published to crates.io"), + } + } + + Ok(Self { taken }) + }) + } + + /// Whether crates.io has seen this exact number. Yanked releases stay in + /// the index and keep their number reserved forever. + fn is_taken(&self, package: Package, version: &semver::Version) -> bool { + self.taken + .get(&package) + .is_some_and(|versions| versions.contains(version)) + } + + /// Move `planned` on by one step if crates.io already holds it. Two + /// collisions in a row are left to a reviewer. + pub fn next_free_version( + &self, + package: Package, + planned: &semver::Version, + bump: &VersionBump, + ) -> Result { + if !self.is_taken(package, planned) { + return Ok(planned.clone()); + } + + let step = match bump.pre { + Some(ref pre) => VersionBump::pre(pre.clone()), + None => VersionBump::patch(), + }; + let next = do_version_bump(planned, &step)?; + + if self.is_taken(package, &next) { + bail!( + "crates.io already holds both {package} {planned} and {next}. Change the bump \ + of {package} in the release plan to pick a version." + ); + } + + log::warn!("crates.io already holds {package} {planned}, moving the release to {next}."); + + Ok(next) + } +} + +#[cfg(test)] +impl RegistrySnapshot { + /// Build a snapshot without touching the network. + pub(crate) fn from_taken( + taken: impl IntoIterator)>, + ) -> Self { + Self { + taken: taken.into_iter().collect(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Version; + + /// A snapshot holding the given versions for [`Package::EspSync`]. + fn snapshot(versions: &[&str]) -> RegistrySnapshot { + let taken = versions.iter().map(|v| v.parse().unwrap()).collect(); + + RegistrySnapshot { + taken: HashMap::from([(Package::EspSync, taken)]), + } + } + + /// A snapshot parsed out of raw crates.io index data: newline-delimited + /// JSON, one object per published version. Only the fields the parser + /// requires are filled in. This is the only way to express the yanked flag, + /// which the index carries but [`RegistrySnapshot`] deliberately drops. + fn index_snapshot(versions: &[(&str, bool)]) -> RegistrySnapshot { + let cksum = "0".repeat(64); + let raw = versions + .iter() + .map(|(version, yanked)| { + format!( + r#"{{"name":"esp-sync","vers":"{version}","deps":[],"cksum":"{cksum}","features":{{}},"yanked":{yanked}}}"# + ) + }) + .collect::>() + .join("\n"); + + let krate = IndexKrate::from_slice(raw.as_bytes()).unwrap(); + + RegistrySnapshot { + taken: HashMap::from([(Package::EspSync, versions_of(&krate))]), + } + } + + #[track_caller] + fn assert_free(planned: &str, bump: VersionBump, snapshot: &RegistrySnapshot, expected: &str) { + let planned = planned.parse().unwrap(); + let free = snapshot + .next_free_version(Package::EspSync, &planned, &bump) + .expect("expected a free version"); + assert_eq!(free.to_string(), expected); + } + + #[track_caller] + fn assert_no_free_version(planned: &str, bump: VersionBump, snapshot: &RegistrySnapshot) { + let planned = planned.parse().unwrap(); + let error = snapshot + .next_free_version(Package::EspSync, &planned, &bump) + .expect_err("expected no free version"); + assert!( + error.to_string().contains("already holds both"), + "unexpected error: {error}" + ); + } + + #[test] + fn free_version_is_left_alone() { + assert_free( + "0.2.1", + VersionBump::minor(), + &snapshot(&["0.2.0"]), + "0.2.1", + ); + assert_free( + "0.2.0", + VersionBump::minor(), + &RegistrySnapshot::default(), + "0.2.0", + ); + } + + #[test] + fn taken_version_is_skipped() { + // esp-rs/esp-hal#5385: esp-sync 0.1.1 + Minor lands on the yanked 0.2.0. + assert_free( + "0.2.0", + VersionBump::minor(), + &snapshot(&["0.1.0", "0.1.1", "0.2.0"]), + "0.2.1", + ); + } + + #[test] + fn consecutive_taken_versions_are_left_to_a_reviewer() { + assert_no_free_version( + "0.2.0", + VersionBump::minor(), + &snapshot(&["0.2.0", "0.2.1"]), + ); + assert_no_free_version( + "1.1.0-beta.3", + VersionBump::pre("beta"), + &snapshot(&["1.1.0-beta.3", "1.1.0-beta.4"]), + ); + } + + #[test] + fn pre_release_steps_the_counter() { + assert_free( + "1.1.0-beta.3", + VersionBump::pre("beta"), + &snapshot(&["1.1.0-beta.3"]), + "1.1.0-beta.4", + ); + // Starting a fresh cycle on a bumped base steps the counter too. + assert_free( + "1.1.0-alpha.0", + VersionBump::base_and_pre(Version::Minor, "alpha"), + &snapshot(&["1.1.0-alpha.0"]), + "1.1.0-alpha.1", + ); + } + + #[test] + fn other_packages_are_unaffected_by_a_reservation() { + // Reservations are per crate; esp-hal must not inherit esp-sync's. + let snapshot = snapshot(&["0.2.0"]); + let planned = "0.2.0".parse().unwrap(); + + let free = snapshot + .next_free_version(Package::EspHal, &planned, &VersionBump::minor()) + .unwrap(); + + assert_eq!(free.to_string(), "0.2.0"); + } + + #[test] + fn yanked_version_from_index_data_is_taken() { + // The esp-sync index as it stood when esp-rs/esp-hal#5385 was filed, + // plus a pre-semver entry of the kind the real index still carries. + assert_free( + "0.2.0", + VersionBump::minor(), + &index_snapshot(&[ + ("0.1", false), + ("0.1.0", false), + ("0.2.0", true), + ("0.1.1", false), + ]), + "0.2.1", + ); + } + + #[test] + fn live_release_is_stepped_over() { + // A number held by a resolvable release is as unavailable as a yanked + // one. Stepping over it lets `plan` recover from a partially completed + // release instead of forcing the plan to be unpicked by hand. + assert_free( + "0.2.0", + VersionBump::minor(), + &index_snapshot(&[("0.2.0", false)]), + "0.2.1", + ); + } + + /// The only coverage of [`RegistrySnapshot::fetch`], so it queries the real + /// index. Both assertions are stable: crates.io never frees a published + /// number, yanked or not. + #[test] + fn live_index_reports_the_yanked_esp_sync_release() { + let snapshot = RegistrySnapshot::fetch([Package::EspSync]).unwrap(); + + // cargo cannot resolve 0.2.0 at all, but the number stays reserved. + assert!(snapshot.is_taken(Package::EspSync, &"0.2.0".parse().unwrap())); + // A number nobody will ever publish, so the fetch is not reporting + // everything as taken. + assert!(!snapshot.is_taken(Package::EspSync, &"99.0.0".parse().unwrap())); + } +} diff --git a/xtask/src/commands/release/semver_check.rs b/xtask/src/commands/release/semver_check.rs index df810940dec..47890b2b762 100644 --- a/xtask/src/commands/release/semver_check.rs +++ b/xtask/src/commands/release/semver_check.rs @@ -20,16 +20,16 @@ pub struct SemverCheckArgs { #[command(subcommand)] pub command: SemverCheckCmd, - /// Package(s) to target. - #[arg(long, value_enum, value_delimiter = ',', default_values_t = vec![Package::EspHal, Package::EspRomSys, Package::EspRadio])] + /// Package(s) to target. Omitted means every semver-checked package. + #[arg(long, alias = "package", value_enum, value_delimiter = ',')] pub packages: Vec, /// Default packages that are not supposed to run, used in CI. #[arg(long, value_enum, value_delimiter = ' ')] pub exclude_packages: Vec, - /// Chip(s) to target. - #[arg(long, value_enum, value_delimiter = ',', default_values_t = Chip::iter())] + /// Chip(s) to target. Omitted means every chip. + #[arg(long, alias = "chip", value_enum, value_delimiter = ',', default_values_t = Chip::iter())] pub chips: Vec, } @@ -46,17 +46,27 @@ pub fn semver_checks(workspace: &Path, args: SemverCheckArgs) -> anyhow::Result< } #[cfg(feature = "semver-checks")] - match args.command { - SemverCheckCmd::GenerateBaseline => { - checker::generate_baseline(&workspace, args.packages, args.chips) + { + let packages = if args.packages.is_empty() { + Package::iter() + .filter(|p| p.is_semver_checked() || p.has_semver_config()) + .collect() + } else { + args.packages + }; + + match args.command { + SemverCheckCmd::GenerateBaseline => { + checker::generate_baseline(&workspace, packages, args.chips) + } + SemverCheckCmd::Check => checker::check_for_breaking_changes( + &workspace, + packages, + args.exclude_packages, + args.chips, + ), + SemverCheckCmd::DownloadBaselines => checker::download_baselines(&workspace, packages), } - SemverCheckCmd::Check => checker::check_for_breaking_changes( - &workspace, - args.packages, - args.exclude_packages, - args.chips, - ), - SemverCheckCmd::DownloadBaselines => checker::download_baselines(&workspace, args.packages), } } @@ -67,7 +77,6 @@ pub mod checker { fs, io::Write, path::{Path, PathBuf}, - str::FromStr, }; use anyhow::Context; @@ -76,7 +85,7 @@ pub mod checker { use crate::{ Package, metadata::Chip, - semver_check::{build_doc_json, minimum_update}, + semver_check::{baseline_stem, build_prepared_doc_json, minimum_update}, }; /// Generate the API baselines for the specified packages and chips. @@ -94,24 +103,14 @@ pub mod checker { continue; } log::info!("Chip = {}", chip.to_string()); - let package_name = package.to_string(); - let package_path = crate::windows_safe_path(&workspace.join(&package_name)); + let package_path = crate::windows_safe_path(&workspace.join(package.directory())); - package.prepare_semver_check(&package_path, chip)?; + let current_path = build_prepared_doc_json(package, chip, &package_path)?; - let current_path = build_doc_json(package, chip, &package_path)?; - - let dest_path = workspace.join("esp-rom-sys/src/generated_rom_symbols.rs"); - package.clean_semver_check(&dest_path)?; - - let file_name = if package.chip_features_matter() { - chip.to_string() - } else { - "api".to_string() - }; - - let to_path = PathBuf::from(&package_path) - .join(format!("api-baseline/{}.json.gz", file_name)); + let to_path = PathBuf::from(&package_path).join(format!( + "api-baseline/{}.json.gz", + baseline_stem(package, *chip) + )); fs::create_dir_all(to_path.parent().unwrap())?; log::debug!("Compress into {current_path:?}"); @@ -213,17 +212,17 @@ pub mod checker { #[derive(Debug)] enum BaselineSource { - Artifact(String), // GitHub Actions artifact name + ReleaseAsset(String), // GitHub release asset name } - /// Download API baselines from GitHub Actions artifacts for the specified packages. + /// Download API baselines from the `api-baselines` GitHub release for the specified packages. /// Fails with helpful error message if baselines are not available. pub fn download_baselines(workspace: &Path, packages: Vec) -> anyhow::Result<()> { for package in packages { log::info!("Downloading API baselines for {package}"); let package_name = package.to_string(); - let package_path = crate::windows_safe_path(&workspace.join(&package_name)); + let package_path = crate::windows_safe_path(&workspace.join(package.directory())); let baseline_dir = package_path.join("api-baseline"); // Remove existing baselines @@ -231,24 +230,23 @@ pub mod checker { std::fs::remove_dir_all(&baseline_dir)?; } - // Try to download from GitHub Actions artifacts - // Note: Artifacts have a 90-day retention limit for public repositories - let artifact_name = format!("api-baselines-{}", package_name); + // Try to download from the `api-baselines` GitHub release + let asset_name = format!("api-baselines-{}", package_name); - let baseline_sources = vec![BaselineSource::Artifact(artifact_name)]; + let baseline_sources = vec![BaselineSource::ReleaseAsset(asset_name)]; let mut downloaded = false; for baseline_source in baseline_sources { match &baseline_source { - BaselineSource::Artifact(artifact_name) => { + BaselineSource::ReleaseAsset(asset_name) => { log::info!( - "Attempting to download from GitHub Actions artifact: {artifact_name}" + "Attempting to download from GitHub release asset: {asset_name}" ); let repo = std::env::var("GITHUB_REPOSITORY") .unwrap_or_else(|_| "esp-rs/esp-hal".to_string()); - if try_download_from_artifact(&package_path, artifact_name, &repo)? { + if try_download_from_release(&package_path, asset_name, &repo)? { log::info!( - "Successfully downloaded baselines from artifact {artifact_name}" + "Successfully downloaded baselines from release asset {asset_name}" ); downloaded = true; break; @@ -258,7 +256,9 @@ pub mod checker { } if !downloaded { - return Err(anyhow::anyhow!("No API baselines found for {package}!")); + return Err(anyhow::anyhow!( + "No API baselines found for {package}! A run of `API Baseline Generation` restores the baselines." + )); } // Verify that baselines were extracted correctly @@ -297,10 +297,10 @@ pub mod checker { Ok(()) } - /// Try to download baselines from a GitHub Actions artifact - fn try_download_from_artifact( + /// Try to download baselines from the `api-baselines` GitHub release + fn try_download_from_release( package_path: &PathBuf, - artifact_name: &str, + asset_name: &str, repo: &str, ) -> anyhow::Result { use std::{io::Cursor, process::Command}; @@ -310,119 +310,44 @@ pub mod checker { // Check if GitHub CLI is available let gh_check = Command::new("gh").arg("--version").output(); if gh_check.is_err() { - log::error!("GitHub CLI (gh) not available, skipping artifact download"); + log::error!("GitHub CLI (gh) not available, skipping release asset download"); return Ok(false); } - // Query repository artifacts via GitHub API and download the one matching `artifact_name` - log::info!("Attempting to download artifact: {artifact_name} from {repo}"); + // Download the baseline ZIP from the `api-baselines` GitHub release + log::info!("Attempting to download release asset: {asset_name} from {repo}"); - // List artifacts for the repository, filtered by name - let list_output = Command::new("gh") + let download = Command::new("gh") .args([ - "api", - "-H", - "Accept: application/vnd.github+json", - "-H", - "X-GitHub-Api-Version: 2022-11-28", - &format!("/repos/{}/actions/artifacts?name={}", repo, artifact_name), + "release", + "download", + "api-baselines", + "--repo", + repo, + "--pattern", + &format!("{asset_name}.zip"), + "--output", + "-", ]) .output(); - let artifacts: Vec = match list_output { - Ok(result) if result.status.success() => { - let body = String::from_utf8_lossy(&result.stdout); - log::debug!("Artifacts list response: {}", body); - if let Ok(json) = serde_json::from_str::(&body) { - match json.get("artifacts").and_then(|a| a.as_array()) { - Some(arr) => arr.clone(), - None => vec![], - } - } else { - vec![] - } - } - Ok(result) => { - let stderr = String::from_utf8_lossy(&result.stderr); - log::debug!("Failed to list artifacts. stderr: {}", stderr); - vec![] - } + let result = match download { + Ok(result) => result, Err(e) => { - log::debug!("Error invoking gh api to list artifacts: {}", e); - vec![] - } - }; - - if artifacts.is_empty() { - log::debug!("No artifacts found for name {}", artifact_name); - return Ok(false); - } - - // Find the latest, non-expired artifact - let latest_artifact = artifacts - .iter() - .filter(|artifact| { - let name_matches = artifact - .get("name") - .and_then(|v| v.as_str()) - .map(|n| n == artifact_name) - .unwrap_or(false); - - let expired = artifact - .get("expired") - .and_then(|v| v.as_bool()) - .unwrap_or(false); - - name_matches && !expired - }) - .max_by_key(|artifact| { - artifact - .get("created_at") - .and_then(|v| v.as_str()) - .map(|s| jiff::Timestamp::from_str(s).expect("Invalid timestamp")) - }); - - let Some(artifact) = latest_artifact else { - log::debug!( - "No valid (non-expired) artifacts found for {}", - artifact_name - ); - return Ok(false); - }; - - let id = match artifact.get("id").and_then(|v| v.as_u64()) { - Some(id) => id.to_string(), - None => { - log::debug!("Artifact missing ID field"); + log::error!( + "Error invoking gh release download for {}: {}", + asset_name, + e + ); return Ok(false); } }; - log::debug!("Downloading artifact id {} (name: {})", id, artifact_name); - - // Download the artifact ZIP (API returns a redirect to the ZIP) - let download = Command::new("gh") - .args([ - "api", - "-H", - "Accept: application/vnd.github+json", - "-H", - "X-GitHub-Api-Version: 2022-11-28", - &format!("/repos/{}/actions/artifacts/{}/zip", repo, id), - ]) - .output(); - - let Ok(result) = download else { - log::debug!("Error invoking gh api to download artifact id {}", id); - return Ok(false); - }; - if !result.status.success() { let stderr = String::from_utf8_lossy(&result.stderr); - log::debug!( - "Failed to download artifact id {} (name: {}). stderr: {}", - id, - artifact_name, + log::error!( + "Failed to download release asset {}.zip. stderr: {}", + asset_name, stderr ); return Ok(false); @@ -434,7 +359,7 @@ pub mod checker { let mut archive = match ZipArchive::new(Cursor::new(&result.stdout)) { Ok(arc) => arc, Err(e) => { - log::debug!("Failed to open ZIP archive for artifact id {}: {}", id, e); + log::error!("Failed to open ZIP archive for {}: {}", asset_name, e); return Ok(false); } }; @@ -488,7 +413,7 @@ pub mod checker { } } - // Check if artifact produced any baselines + // Check if release asset produced any baselines if let Ok(entries) = std::fs::read_dir(&baseline_dir) { if entries.flatten().any(|e| { let p = e.path(); @@ -501,7 +426,7 @@ pub mod checker { return Ok(true); } } - log::debug!("No downloadable artifacts found for {}", artifact_name); + log::error!("No baselines found in release asset {}", asset_name); Ok(false) } } diff --git a/xtask/src/commands/run.rs b/xtask/src/commands/run.rs index 02c0ef993fc..f652e92b293 100644 --- a/xtask/src/commands/run.rs +++ b/xtask/src/commands/run.rs @@ -1,47 +1,51 @@ use std::{ - collections::HashMap, + collections::{HashMap, HashSet}, fs, path::{Path, PathBuf}, process::Command, }; -use anyhow::{Context as _, Result, bail}; -use clap::{Args, Subcommand}; +use anyhow::{Context as _, Result, anyhow, bail}; +use clap::Args; use serde::Deserialize; +use strum::IntoEnumIterator as _; -use super::{DocTestArgs, ExamplesArgs, TestsArgs}; +use super::tests::SKIPPED_SELECTORS_FILENAME; use crate::{ Package, cargo::{CargoAction, CargoArgsBuilder}, firmware::{self, Metadata}, metadata::Chip, radio_hil_runner::run_radio_test_elf, + resolve::{ResolveInput, resolve}, }; // ---------------------------------------------------------------------------- -// Subcommands - -#[derive(Debug, Subcommand)] -pub enum Run { - /// Run doctests for specified chip and package. - DocTests(DocTestArgs), - /// Run all ELFs in a folder. - Elfs(RunElfsArgs), - /// Run the given example for the specified chip. - Example(ExamplesArgs), - /// Run all applicable tests or the specified test for a specified chip. - Tests(TestsArgs), -} +// Command Arguments -// ---------------------------------------------------------------------------- -// Subcommand Arguments +/// Arguments common to commands which act on doctests. +#[cfg_attr( + feature = "mcp", + xtask_mcp_macros::mcp_tool( + description = "Run doc tests for the specified chip and packages", + command = "doc-tests" + ) +)] +#[derive(Debug, Args)] +pub struct DocTestArgs { + /// Chip and/or package, in any order. Doc tests run on one chip, so the chip is required. + pub tokens: Vec, + /// Package(s) where we wish to run doc tests. Accepts the same names the tokens do. + #[arg(long, alias = "package", value_enum, value_delimiter = ',')] + pub packages: Vec, +} /// Arguments for running ELFs. #[cfg_attr( feature = "mcp", xtask_mcp_macros::mcp_tool( description = "Run all ELFs in a folder using probe-rs. Use --filter binary or binary::test_name to select which ELFs/tests run.", - command = "run elfs" + command = "elfs" ) )] #[derive(Debug, Args)] @@ -63,9 +67,24 @@ pub struct RunElfsArgs { /// Run doc tests for the specified package and chip. pub fn run_doc_tests(workspace: &Path, args: DocTestArgs) -> Result<()> { + let mut input = ResolveInput::from_tokens(args.tokens); + input.packages = args.packages; + let resolution = resolve(input); + if !resolution.names.is_empty() { + bail!("Unknown argument: {}", resolution.names.join(", ")); + } + let [chip] = resolution.chips[..] else { + bail!("Name exactly one chip to run doc tests for"); + }; + let packages = if resolution.packages.is_empty() { + Package::iter().collect() + } else { + resolution.packages + }; + let mut success = true; - for package in args.packages { - success &= run_doc_tests_for_package(workspace, package, args.chip)?; + for package in packages { + success &= run_doc_tests_for_package(workspace, package, chip)?; } anyhow::ensure!(success, "One or more doc tests failed"); Ok(()) @@ -92,8 +111,7 @@ pub fn run_doc_tests_for_package(workspace: &Path, package: Package, chip: Chip) return Ok(true); }; - let package_name = package.to_string(); - let package_path = crate::windows_safe_path(&workspace.join(&package_name)); + let package_path = crate::windows_safe_path(&workspace.join(package.directory())); if package.has_chip_features() { doc_config.features.push(chip.to_string()); @@ -150,10 +168,10 @@ pub fn run_elfs(args: RunElfsArgs) -> Result<()> { if !path.is_file() { continue; } - if path - .file_name() - .is_some_and(|name| name == std::ffi::OsStr::new(RADIO_ELF_MANIFEST_FILENAME)) - { + if path.file_name().is_some_and(|name| { + name == std::ffi::OsStr::new(RADIO_ELF_MANIFEST_FILENAME) + || name == std::ffi::OsStr::new(SKIPPED_SELECTORS_FILENAME) + }) { continue; } @@ -301,12 +319,26 @@ pub fn run_elfs(args: RunElfsArgs) -> Result<()> { .filter(|(_, matched)| !**matched) .map(|(filter, _)| filter.raw.as_str()) .collect::>(); + let skipped_selectors = load_skipped_selectors(&args.path)?; + let (skipped, unmatched): (Vec<_>, Vec<_>) = unmatched.into_iter().partition(|raw| { + let raw = raw.to_lowercase(); + skipped_selectors + .iter() + .any(|name| name.to_lowercase().contains(&raw)) + }); if !unmatched.is_empty() { bail!( "ELF selector did not match any artifact: {}", unmatched.join(", ") ); } + if !skipped.is_empty() { + log::warn!( + "Skipping selectors without a test for '{}': {}", + args.chip, + skipped.join(", ") + ); + } if !failed.is_empty() { bail!("Failed tests: {:?}", failed); @@ -341,7 +373,10 @@ fn parse_elf_filters(raw_filters: &[String]) -> Result> { None => (raw, None), }; - let binary = binary.trim().to_lowercase(); + let mut binary = binary.trim().to_lowercase(); + if let Some(stem) = binary.strip_suffix(".rs") { + binary = stem.to_string(); + } if binary.is_empty() { bail!("Empty binary filter in ELF selector '{raw}' is not allowed"); } @@ -403,6 +438,18 @@ fn load_radio_test_manifest(path: &Path) -> Result Result> { + let skipped_path = path.join(SKIPPED_SELECTORS_FILENAME); + if !skipped_path.exists() { + return Ok(HashSet::new()); + } + + let content = fs::read_to_string(&skipped_path) + .with_context(|| format!("Failed to read {}", skipped_path.display()))?; + serde_json::from_str(&content) + .with_context(|| format!("Failed to parse {}", skipped_path.display())) +} + fn resolve_harness_binary_path(elfs: &[(String, PathBuf)], harness_name: &str) -> Option { if let Some((_, path)) = elfs.iter().find(|(name, _)| name == harness_name) { return Some(path.clone()); @@ -416,15 +463,17 @@ fn resolve_harness_binary_path(elfs: &[(String, PathBuf)], harness_name: &str) - /// Run the specified examples for the given chip. pub fn run_examples( - args: ExamplesArgs, + package: Package, + chip: Chip, + debug: bool, + toolchain: Option<&str>, + timings: bool, examples: Vec, package_path: &Path, ) -> Result<()> { let mut examples = examples; - // At this point, chip can never be `None`, so we can safely unwrap it. - let chip = args.chip.unwrap(); - let target = args.package.as_package().target_triple(&chip)?; + let target = package.target_triple(&chip)?; examples.sort_by_key(|ex| ex.tag()); @@ -437,7 +486,7 @@ pub fn run_examples( log::info!("Running example '{}'", example.output_file_name()); if interactive { - if let Some(description) = example.description() { + if let Some(description) = example.description_for(&target) { log::info!( "\n\n{}\n\nPress ENTER to run example, `s` to skip", description.trim() @@ -467,9 +516,9 @@ pub fn run_examples( &target, &example, CargoAction::Run, - args.debug, - args.toolchain.as_deref(), - args.timings, + debug, + toolchain, + timings, &[], ); @@ -481,7 +530,16 @@ pub fn run_examples( let key = console.read_key(); match key { - Ok(console::Key::Char('r')) => break, + Ok(console::Key::Char('r')) => { + // A retry looks again, so a board swapped in meanwhile is the one + // to run on. Another chip is for the caller to start over for. + if let Some(connected) = crate::detect::rescan_with_espflash()? + && connected != chip + { + return Err(anyhow!(connected)); + } + break; + } Ok(console::Key::Char('s')) => { skip = true; break; diff --git a/xtask/src/commands/tests.rs b/xtask/src/commands/tests.rs new file mode 100644 index 00000000000..0b02e94fac3 --- /dev/null +++ b/xtask/src/commands/tests.rs @@ -0,0 +1,455 @@ +use std::{ + collections::HashMap, + path::{Path, PathBuf}, +}; + +use anyhow::{Context, Result, bail}; +use serde::Serialize; + +use super::move_artifacts; +use crate::{ + Package, + cargo::{CargoAction, CargoCommandBatcher}, + firmware, + metadata::Chip, +}; + +/// Execute the given action on the specified HIL tests. +pub fn tests( + workspace: &Path, + package: Package, + chip: Chip, + test: Option<&[String]>, + action: CargoAction, + repeat: usize, + toolchain: Option<&str>, + timings: bool, +) -> Result<()> { + if !matches!(package, Package::HilTest | Package::HilTestRadio) { + bail!("Unknown test package: {package}. Use 'hil-test' or 'hil-test-radio'"); + } + + let package_path = crate::windows_safe_path(&workspace.join(package.directory())); + let is_radio_package = package == Package::HilTestRadio; + + // Determine the appropriate build target for the given package and chip: + let target = package.target_triple(&chip)?; + + // Load all test metadata first so we can differentiate between: + // - unknown test selectors (typos) + // - valid tests that are unsupported for the selected chip. + let mut all_tests = crate::firmware::load_package(workspace, package)?; + all_tests.sort_by_key(|a| a.binary_name()); + let tests_for_chip = all_tests + .iter() + .filter(|example| example.supports_chip(chip)) + .collect::>(); + + // Radio tests reuse the normal HIL flow; the only difference is a pre-step + // that builds and flashes the support firmware on a secondary probe. + if let CargoAction::Build(Some(out_dir)) = &action { + // Make sure the tmp directory has no garbage for us. + let tmp_dir = out_dir.join("tmp"); + _ = std::fs::remove_dir_all(&tmp_dir); + std::fs::create_dir_all(&tmp_dir).unwrap(); + } + + let mut commands = CargoCommandBatcher::new(); + let mut artifact_meta = HashMap::::new(); + let mut unsupported_for_chip: Vec = Vec::new(); + // Execute the specified action: + // If user sets some specific test(s) + if let Some(test_arg) = test { + let trimmed: Vec<&str> = test_arg.iter().map(|s| s.trim()).collect(); + + // Reject `--test ""` / `--test " "` + if trimmed.iter().all(|s| s.is_empty()) { + bail!("Empty test selector is not allowed."); + } + + let mut unknown_selected: Vec = Vec::new(); + + for selected in trimmed.into_iter().filter(|s| !s.is_empty()) { + let (test_arg, filter) = match selected.split_once("::") { + Some((test, filter)) => (Some(test), Some(filter)), + None => (Some(selected), None), + }; + + let run_test_extra_args = if is_radio_package && action == CargoAction::Run { + &[] + } else { + (action == CargoAction::Run) + .then(|| filter.as_ref().map(std::slice::from_ref)) + .flatten() + .unwrap_or(&[]) + }; + + let matched: Vec<_> = all_tests.iter().filter(|t| t.matches(test_arg)).collect(); + + if matched.is_empty() { + if is_radio_package + && let Some(radio_meta) = resolve_radio_module_alias(&all_tests, chip, selected) + { + let command = crate::generate_build_command( + &package_path, + chip, + &target, + &radio_meta, + action.clone(), + false, + toolchain, + timings, + &[], + )?; + artifact_meta.insert(command.artifact_name.clone(), radio_meta); + commands.push(command); + continue; + } + unknown_selected.push(selected.to_string()); + } else { + let matched_for_chip: Vec<_> = matched + .into_iter() + .filter(|t| t.supports_chip(chip)) + .collect(); + + if matched_for_chip.is_empty() { + unsupported_for_chip.push(selected.to_string()); + continue; + } + + for test in matched_for_chip { + let command = crate::generate_build_command( + &package_path, + chip, + &target, + test, + action.clone(), + false, + toolchain, + timings, + run_test_extra_args, + )?; + artifact_meta.insert(command.artifact_name.clone(), test.clone()); + commands.push(command); + } + } + } + + if !unsupported_for_chip.is_empty() { + log::warn!( + "Skipping unsupported tests for '{}': {}", + chip, + unsupported_for_chip.join(", ") + ); + } + + if !unknown_selected.is_empty() { + bail!("Test not found: {}", unknown_selected.join(", ")) + } + } else { + for test in tests_for_chip { + let command = crate::generate_build_command( + &package_path, + chip, + &target, + test, + action.clone(), + false, + toolchain, + timings, + &[], + )?; + artifact_meta.insert(command.artifact_name.clone(), test.clone()); + commands.push(command); + } + } + + let mut harness_for_artifact = HashMap::::new(); + if is_radio_package { + for test in artifact_meta.values() { + if is_support_firmware(test) { + continue; + } + let Some(harness_name) = test.harness_firmware() else { + continue; + }; + + let Some(harness_meta) = all_tests.iter().find(|candidate| { + if !candidate.supports_chip(chip) { + return false; + } + + let harness_basename = harness_name.rsplit('/').next().unwrap_or(harness_name); + candidate.binary_name() == harness_name + || candidate.output_file_name() == harness_name + || candidate.binary_name() == harness_basename + || candidate.output_file_name() == harness_basename + }) else { + bail!( + "Missing harness firmware '{harness_name}' required by '{}'", + test.output_file_name() + ); + }; + + harness_for_artifact.insert(test.output_file_name(), harness_meta.clone()); + } + } + + // Ensure required harness firmware is built so the artifact is + // self-contained for `elfs` on the HIL runner. Not needed on Run: + // `build_radio_harness` builds harnesses lazily per test. + if is_radio_package && matches!(action, CargoAction::Build(_)) { + use std::collections::HashSet; + + let mut queued: HashSet = artifact_meta + .values() + .map(firmware::Metadata::output_file_name) + .collect(); + + let mut harnesses_to_add: Vec = Vec::new(); + for harness in harness_for_artifact.values() { + if queued.insert(harness.output_file_name()) { + harnesses_to_add.push(harness.clone()); + } + } + + for harness in harnesses_to_add { + let command = crate::generate_build_command( + &package_path, + chip, + &target, + &harness, + action.clone(), + false, + toolchain, + timings, + &[], + )?; + artifact_meta.insert(command.artifact_name.clone(), harness); + commands.push(command); + } + } + + let mut failed = Vec::new(); + let built_commands = commands.build(false); + let built_artifacts = artifact_meta.keys().cloned().collect::>(); + + let mut built_harness = HashMap::::new(); + + for c in built_commands { + let repeat = if matches!(action, CargoAction::Run) { + repeat + } else { + 1 + }; + + let radio_meta = artifact_meta.get(&c.artifact_name); + + // Support firmware never runs as a DUT; it's used only as a pre-step + // for whichever DUT requests it via `HARNESS-FIRMWARE`. + if matches!(action, CargoAction::Run) && radio_meta.is_some_and(is_support_firmware) { + log::info!("Skipping support firmware '{}' as DUT", c.artifact_name); + continue; + } + + println!( + "Command: cargo {}", + c.command.join(" ").replace("---", "\n ---") + ); + + for i in 0..repeat { + if repeat != 1 { + log::info!("Run {}/{}", i + 1, repeat); + } + + if matches!(action, CargoAction::Run) + && let Some(harness_meta) = harness_for_artifact.get(&c.artifact_name) + { + let harness_path = match build_radio_harness( + workspace, + &package_path, + chip, + &target, + toolchain, + timings, + harness_meta, + &mut built_harness, + ) { + Ok(path) => path, + Err(e) => { + failed.push(c.artifact_name.clone()); + log::error!( + "Failed to build harness firmware '{}' for '{}': {e}", + harness_meta.output_file_name(), + c.artifact_name + ); + break; + } + }; + + let harness_spec = crate::radio_hil_runner::HarnessSpec { + binary_path: &harness_path, + target: &target, + }; + if let Err(e) = + crate::radio_hil_runner::run_radio_test(&c, Some(harness_spec), None) + { + failed.push(c.artifact_name.clone()); + log::error!("Radio test '{}' failed: {}", c.artifact_name, e); + break; + } + } else if c.run(false).is_err() { + failed.push(c.artifact_name.clone()); + } + } + } + + move_artifacts(chip, &action); + + if !failed.is_empty() { + bail!("Failed tests: {:#?}", failed); + } + + if is_radio_package && let CargoAction::Build(Some(out_dir)) = &action { + write_radio_elf_manifest( + out_dir, + chip, + &built_artifacts, + &artifact_meta, + &harness_for_artifact, + )?; + } + + if let CargoAction::Build(Some(out_dir)) = &action + && !unsupported_for_chip.is_empty() + && !built_artifacts.is_empty() + { + let path = out_dir + .join(chip.to_string()) + .join(SKIPPED_SELECTORS_FILENAME); + std::fs::write(&path, serde_json::to_string(&unsupported_for_chip)?) + .with_context(|| format!("Failed to write {}", path.display()))?; + } + + Ok(()) +} + +/// Lists the selectors that `elfs` may leave unmatched, because they have no test for the chip. +pub(crate) const SKIPPED_SELECTORS_FILENAME: &str = "skipped-selectors.json"; + +const RADIO_ELF_MANIFEST_FILENAME: &str = "radio-elfs.json"; + +#[derive(Debug, Serialize)] +struct RadioElfManifestEntry { + artifact: String, + harness: Option, + support_firmware: bool, +} + +fn write_radio_elf_manifest( + out_dir: &Path, + chip: Chip, + built_artifacts: &[String], + artifact_meta: &HashMap, + harness_for_artifact: &HashMap, +) -> Result<()> { + let mut entries = Vec::new(); + for artifact in built_artifacts { + let Some(meta) = artifact_meta.get(artifact) else { + continue; + }; + entries.push(RadioElfManifestEntry { + artifact: artifact.clone(), + harness: harness_for_artifact + .get(artifact) + .map(firmware::Metadata::output_file_name), + support_firmware: is_support_firmware(meta), + }); + } + + if entries.is_empty() { + return Ok(()); + } + + let manifest_path = out_dir + .join(chip.to_string()) + .join(RADIO_ELF_MANIFEST_FILENAME); + let payload = serde_json::to_string_pretty(&entries)?; + std::fs::write(&manifest_path, payload) + .with_context(|| format!("Failed to write {}", manifest_path.display()))?; + Ok(()) +} + +/// Build the harness firmware required by a radio HIL test (if not already +/// built) and return the resulting ELF path. Results are cached in +/// `built_harness` so repeated tests sharing a harness only build it once. +fn build_radio_harness( + workspace: &Path, + package_path: &Path, + chip: Chip, + target: &str, + toolchain: Option<&str>, + timings: bool, + harness: &firmware::Metadata, + built_harness: &mut HashMap, +) -> Result { + let artifact_name = harness.output_file_name(); + if let Some(path) = built_harness.get(&artifact_name) { + return Ok(path.clone()); + } + + let builder = crate::generate_build_command( + package_path, + chip, + target, + harness, + CargoAction::Build(None), + false, + toolchain, + timings, + &[], + )?; + let built = CargoCommandBatcher::build_one_for_cargo(&builder); + log::info!( + "Building harness firmware: cargo {}", + built.command.join(" ") + ); + built + .run(false) + .with_context(|| format!("Failed to build harness firmware '{artifact_name}'"))?; + + let path = crate::radio_hil_runner::resolve_release_binary(workspace, target, &artifact_name); + if !path.exists() { + bail!( + "Harness firmware '{artifact_name}' built successfully but binary not found at {}", + path.display() + ); + } + + built_harness.insert(artifact_name, path.clone()); + Ok(path) +} + +fn resolve_radio_module_alias( + all_tests: &[firmware::Metadata], + chip: Chip, + selected: &str, +) -> Option { + let module_file = format!("{selected}.rs"); + let module_decl = format!("mod {selected};"); + + all_tests + .iter() + .find(|test| { + test.supports_chip(chip) + && test.harness_firmware().is_none() + && std::fs::read_to_string(test.example_path()).is_ok_and(|source| { + source.contains(&module_file) || source.contains(&module_decl) + }) + }) + .cloned() +} + +fn is_support_firmware(meta: &firmware::Metadata) -> bool { + meta.is_support_firmware() +} diff --git a/xtask/src/detect.rs b/xtask/src/detect.rs new file mode 100644 index 00000000000..ad7fcfb3c2f --- /dev/null +++ b/xtask/src/detect.rs @@ -0,0 +1,344 @@ +//! Chip inference from a connected device. +//! +//! When the chip is omitted, `run` uses [`with_espflash`] and `test` uses [`with_probe_rs`], so +//! that detection picks the port or probe the command is about to drive. +//! +//! Detection shells out to tools already on `PATH`, this crate does not link them. With several +//! devices attached, a terminal gets a prompt and everything else gets an error. + +use std::{fmt, io::IsTerminal, process::Command, str::FromStr, time::Duration}; + +use anyhow::Result; +use inquire::Select; +use serde::Deserialize; + +use crate::metadata::Chip; + +const SHORT_TIMEOUT: Duration = Duration::from_secs(10); +const ESPFLASH_TIMEOUT: Duration = Duration::from_secs(20); + +/// Infer the chip via `espflash`, used by `run` because it resets the board anyway. +pub fn with_espflash() -> Result> { + pick_connected(detect_via_espflash()) +} + +/// Infer the chip via `probe-rs`, used by `test` because it runs through the probe anyway. +pub fn with_probe_rs() -> Result> { + pick_connected(detect_via_probe_rs()) +} + +/// Infer the chip via `espflash` again, for a retry. +/// +/// Looks at every port instead of the one in `ESPFLASH_PORT`, because a board comes back on a port +/// of its own, the same cable names it differently over UART than over USB-JTAG. +pub fn rescan_with_espflash() -> Result> { + pick_connected(identify(espflash_ports())) +} + +fn pick_connected(devices: Vec) -> Result> { + let device = match devices.len() { + 0 => return Ok(None), + 1 => devices.into_iter().next().unwrap(), + _ => match pick_device(devices)? { + Some(device) => device, + None => return Ok(None), + }, + }; + export_connection(&device); + log::info!("Using connected chip {device}"); + Ok(Some(device.chip)) +} + +/// `Ok(None)` when there is nobody to ask. Cancelling the prompt is an answer of its own, and stops +/// the command rather than leaving it to guess. +fn pick_device(devices: Vec) -> Result> { + let summary = devices + .iter() + .map(|device| device.to_string()) + .collect::>() + .join(", "); + if !std::io::stdin().is_terminal() { + log::info!( + "Multiple ESP devices connected ({summary}). Pass the chip name, or run from a terminal to pick one." + ); + return Ok(None); + } + Ok(Some( + Select::new("Select the connected chip:", devices).prompt()?, + )) +} + +/// Tells the tools which device to use, through the env vars they read for it. A retry can find the +/// board on a new port, so whatever is in there is replaced. +fn export_connection(device: &ConnectedDevice) { + let (key, value) = match &device.via { + Connection::Serial(port) => ("ESPFLASH_PORT", port), + Connection::Probe { selector, .. } => ("PROBE_RS_PROBE", selector), + }; + unsafe { std::env::set_var(key, value) }; +} + +#[derive(Debug, Clone, PartialEq, Eq)] +struct ConnectedDevice { + chip: Chip, + via: Connection, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +enum Connection { + Serial(String), + Probe { selector: String, name: String }, +} + +impl fmt::Display for ConnectedDevice { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match &self.via { + Connection::Serial(port) => write!(f, "{} on {port}", self.chip), + Connection::Probe { name, selector } if selector.is_empty() => { + write!(f, "{} via {name}", self.chip) + } + Connection::Probe { name, selector } => { + write!(f, "{} via {name} ({selector})", self.chip) + } + } + } +} + +fn detect_via_probe_rs() -> Vec { + if let Ok(selector) = std::env::var("PROBE_RS_PROBE") + && !selector.is_empty() + { + return probe_rs_mi_info(Some(&selector), "probe") + .into_iter() + .collect(); + } + + let probes = probe_rs_list(); + if probes.is_empty() { + return probe_rs_mi_info(None, "probe").into_iter().collect(); + } + + probes + .into_iter() + .filter_map(|probe| probe_rs_mi_info(Some(&probe.selector), &probe.name)) + .collect() +} + +struct ProbeRef { + name: String, + selector: String, +} + +fn probe_rs_list() -> Vec { + let Some(output) = run_cli("probe-rs", &["list"], SHORT_TIMEOUT) else { + return Vec::new(); + }; + if !output.status.success() { + log::debug!( + "probe-rs list failed: {}", + String::from_utf8_lossy(&output.stderr).trim() + ); + return Vec::new(); + } + parse_probe_list(&String::from_utf8_lossy(&output.stdout)) +} + +fn probe_rs_mi_info(probe: Option<&str>, name: &str) -> Option { + let mut args = vec!["mi", "info", "--non-interactive"]; + if let Some(probe) = probe { + args.extend_from_slice(&["--probe", probe]); + } + let output = run_cli("probe-rs", &args, SHORT_TIMEOUT)?; + if !output.status.success() { + log::debug!( + "probe-rs mi info failed: {}", + String::from_utf8_lossy(&output.stderr).trim() + ); + return None; + } + let chip = chip_from_mi_info(&String::from_utf8_lossy(&output.stdout))?; + Some(ConnectedDevice { + chip, + via: Connection::Probe { + selector: probe.unwrap_or_default().to_string(), + name: name.to_string(), + }, + }) +} + +fn detect_via_espflash() -> Vec { + let ports = match std::env::var("ESPFLASH_PORT") { + Ok(port) if !port.is_empty() => vec![port], + _ => espflash_ports(), + }; + identify(ports) +} + +fn identify(ports: Vec) -> Vec { + if ports.len() > 1 { + log::info!("Identifying {} connected serial devices…", ports.len()); + } + ports + .into_iter() + .filter_map(|port| { + let chip = espflash_board_info(&port)?; + Some(ConnectedDevice { + chip, + via: Connection::Serial(port), + }) + }) + .collect() +} + +fn espflash_board_info(port: &str) -> Option { + let output = run_cli( + "espflash", + &[ + "board-info", + "--non-interactive", + "--skip-update-check", + "-p", + port, + ], + ESPFLASH_TIMEOUT, + )?; + if !output.status.success() { + log::debug!( + "espflash board-info {port} failed: {}", + String::from_utf8_lossy(&output.stderr).trim() + ); + return None; + } + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + chip_from_board_info(&stdout).or_else(|| chip_from_board_info(&stderr)) +} + +fn espflash_ports() -> Vec { + let Some(output) = run_cli( + "espflash", + &["list-ports", "--name-only", "--skip-update-check"], + SHORT_TIMEOUT, + ) else { + return Vec::new(); + }; + if !output.status.success() { + log::debug!( + "espflash list-ports failed: {}", + String::from_utf8_lossy(&output.stderr).trim() + ); + return Vec::new(); + } + let mut ports = Vec::new(); + for line in String::from_utf8_lossy(&output.stdout).lines() { + let line = line.trim(); + if line.is_empty() { + continue; + } + // `/dev/cu.foo` and `/dev/tty.foo` are the same UART on macOS, prefer `cu`. + let port = match line.strip_prefix("/dev/tty.") { + Some(rest) => format!("/dev/cu.{rest}"), + None => line.to_string(), + }; + if !ports.contains(&port) { + ports.push(port); + } + } + ports +} + +fn run_cli(program: &str, args: &[&str], timeout: Duration) -> Option { + let mut command = Command::new(program); + command.args(args); + match crate::run_command_with_output_timeout(command, program, timeout) { + Ok(output) => Some(output), + Err(err) => { + log::debug!("{err:#}"); + None + } + } +} + +#[derive(Debug, Deserialize)] +struct MiInfo { + chip: String, +} + +fn chip_from_mi_info(stdout: &str) -> Option { + let info: MiInfo = serde_json::from_str(stdout.trim()).ok()?; + chip_from_tool_name(&info.chip) +} + +fn chip_from_board_info(text: &str) -> Option { + for line in text.lines() { + let Some(rest) = line.trim().strip_prefix("Chip type:") else { + continue; + }; + let name = rest.trim().split_whitespace().next()?; + return chip_from_tool_name(name); + } + None +} + +fn chip_from_tool_name(name: &str) -> Option { + let mut normalized = name.trim().to_ascii_lowercase(); + if let Some(stripped) = normalized.strip_suffix("_lp") { + normalized = stripped.to_string(); + } + normalized.retain(|c| c != '-'); + Chip::from_str(&normalized).ok() +} + +fn parse_probe_list(stdout: &str) -> Vec { + stdout.lines().filter_map(parse_probe_list_line).collect() +} + +fn parse_probe_list_line(line: &str) -> Option { + let rest = line.trim().strip_prefix('[')?; + let (_index, rest) = rest.split_once(']')?; + let rest = rest.strip_prefix(':')?.trim(); + + // `ESP JTAG -- 303a:1001:30:ED:A0:E4:19:20 (EspJtag)` + if let Some((name, rest)) = rest.split_once(" -- ") { + let selector = rest + .rsplit_once(" (") + .map(|(selector, _)| selector) + .unwrap_or(rest) + .trim() + .to_string(); + if selector.is_empty() { + return None; + } + return Some(ProbeRef { + name: name.trim().to_string(), + selector, + }); + } + + // Older: `ESP JTAG (VID: 303a, PID: 1001, Serial: …, EspJtag)` + let (name, paren) = rest.rsplit_once(" (")?; + let paren = paren.strip_suffix(')')?; + + let mut vid = None; + let mut pid = None; + let mut serial = None; + for part in paren.split(", ") { + if let Some(value) = part.strip_prefix("VID: ") { + vid = Some(value); + } else if let Some(value) = part.strip_prefix("PID: ") { + pid = Some(value); + } else if let Some(value) = part.strip_prefix("Serial: ") { + serial = Some(value); + } + } + let vid = vid?; + let pid = pid?; + let selector = match serial { + Some(serial) if !serial.is_empty() => format!("{vid}:{pid}:{serial}"), + _ => format!("{vid}:{pid}"), + }; + Some(ProbeRef { + name: name.to_string(), + selector, + }) +} diff --git a/xtask/src/documentation.rs b/xtask/src/documentation.rs index da84e20624e..dcc2f7641ee 100644 --- a/xtask/src/documentation.rs +++ b/xtask/src/documentation.rs @@ -1,5 +1,5 @@ use std::{ - fs::{self, create_dir_all}, + fs::{self, FileTimes, create_dir_all}, io::Write, path::{Path, PathBuf}, }; @@ -91,10 +91,21 @@ pub fn build_documentation( // Some packages have chip features, but they have no effect on the public API; // in this case, there's no point building it multiple times, so just build one // copy of the docs. Otherwise, use the provided chip arguments: - match package { - _ if package.chip_features_matter() => chips.to_vec(), - Package::XtensaLxRt => vec![Chip::Esp32s3], - _ => vec![Chip::Esp32c6], + if package.chip_features_matter() { + chips.to_vec() + } else { + let chip = chips + .iter() + .copied() + .find(|c| *c == Chip::Esp32c6 && package.validate_package_chip(c).is_ok()) + .or_else(|| { + chips + .iter() + .copied() + .find(|c| package.validate_package_chip(c).is_ok()) + }) + .unwrap_or(Chip::Esp32c6); + vec![chip] } } else { log::debug!("Package '{package}' does not have chip features, ignoring argument"); @@ -289,11 +300,26 @@ fn highest_eligible_version(manifest: &Manifest) -> Option { } /// Relative URL from `latest/index.html` to this package's versioned docs root. -fn latest_redirect_base(package: &Package, version: &semver::Version) -> String { +/// +/// nginx rewrites `/latest/` deep links to `/latest/?path=`, and the +/// redirect page merges that `path` onto this base, so the base must always be the +/// version root: `` already starts with the chip directory for packages with +/// device-specific docs, or with the crate directory otherwise. +fn latest_redirect_base(version: &semver::Version) -> String { + format!("../{}/", version) +} + +/// Path (relative to the versioned docs root) used when `/latest/` is requested +/// without a deep-link remainder. +/// +/// Packages with device-specific docs generate an index page at their version +/// root, so no fallback path is needed. Other packages have no such index (the +/// version root 404s/403s), so point at the crate's rustdoc index instead. +fn latest_redirect_fallback(package: &Package) -> String { if package.chip_features_matter() { - format!("../{}/", version) + String::new() } else { - format!("../{}/{}/", version, package.to_string().replace('-', "_")) + format!("{}/index.html", package.to_string().replace('-', "_")) } } @@ -303,12 +329,14 @@ fn latest_redirect_html( package: &Package, version: &semver::Version, ) -> Result { - let base = latest_redirect_base(package, version); + let base = latest_redirect_base(version); + let fallback = latest_redirect_fallback(package); let resources_path = workspace.join("resources"); render_template(&resources_path, "latest_redirect.html.somni", { let mut env = Env::new(); - env.value("base", base.as_str()); + env.value("base", base.as_str()) + .value("fallback", fallback.as_str()); env }) } @@ -320,8 +348,7 @@ fn cargo_doc( channel: Option<&str>, base_url: Option<&str>, ) -> Result { - let package_name = package.to_string(); - let package_path = crate::windows_safe_path(&workspace.join(&package_name)); + let package_path = crate::windows_safe_path(&workspace.join(package.directory())); // Process Cargo.toml for documentation let pre_process_res = pre_process_cargo_toml(chip, &package_path); @@ -331,11 +358,11 @@ fn cargo_doc( cargo_doc_without_pre_processing(workspace, package, chip, channel, base_url); // Restore the original Cargo.toml - restore_cargo_toml(package_path)?; + restore_cargo_toml(&package_path)?; cargo_doc_res } else { // Restore the original Cargo.toml - restore_cargo_toml(package_path)?; + restore_cargo_toml(&package_path)?; Err(pre_process_res.err().unwrap()) } } @@ -348,7 +375,7 @@ fn cargo_doc_without_pre_processing( base_url: Option<&str>, ) -> Result { let package_name = package.to_string(); - let package_path = crate::windows_safe_path(&workspace.join(&package_name)); + let package_path = crate::windows_safe_path(&workspace.join(package.directory())); // build documentation using the pre-processed Cargo.toml if let Some(chip) = chip { @@ -374,33 +401,63 @@ fn cargo_doc_without_pre_processing( None }; - // cleaning the docs isn't strictly necessary but otherwise rustdoc will pick up - // any docs which were built previously resulting in inconsistency regarding how esp-* - // inter-crate links are rendered - // - // however a real problem is that this could pick up e.g. esp-hal docs for the wrong target chip - // (rustdoc doesn't know about our chip features, it just knows about target triples!) - // - // this was never an issue when building via the GitHub workflow because of the way the job is - // setup but better safe than sorry - // - // ideally we could just use `cargo clean --doc` but for `+esp` this turned out to be not - // working as intended let mut docs_target = if let Ok(target_path) = std::env::var("CARGO_TARGET_DIR") { PathBuf::from(target_path) } else { - workspace.join(package.to_string()).join("target") + workspace.join(package.directory()).join("target") }; if let Some(ref target) = target { docs_target = docs_target.join(&target); }; docs_target = docs_target.join("doc"); - if docs_target.exists() { - log::info!("Removing directory {:?}", docs_target); - fs::remove_dir_all(&docs_target) - .with_context(|| format!("Unable to remove {:?}", docs_target))?; + // One rustdoc output directory is shared by every package and chip on the same target + // triple, and rustdoc does not know about our chip features. Park the previous build's + // directory under `.xtask-doc-cache/` and restore the one for this package and chip + // if we have built it before, so Cargo can skip rustdoc when nothing changed. + let build_id_path = docs_target.with_file_name(".xtask-doc-build-id"); + let cache_dir = docs_target.with_file_name(".xtask-doc-cache"); + let build_id = match chip { + Some(chip) => format!("{package}-{chip}"), + None => package.to_string(), + }; + + let prev_id = fs::read_to_string(&build_id_path) + .ok() + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty() && !s.contains(['/', '\\', ' '])); + + if docs_target.exists() && prev_id.as_deref() != Some(build_id.as_str()) { + if let Some(prev_id) = prev_id { + let parked = cache_dir.join(prev_id); + if parked.exists() { + fs::remove_dir_all(&parked) + .with_context(|| format!("Unable to remove {:?}", parked))?; + } + fs::create_dir_all(&cache_dir) + .with_context(|| format!("Unable to create {:?}", cache_dir))?; + fs::rename(&docs_target, &parked) + .with_context(|| format!("Unable to park {:?} to {:?}", docs_target, parked))?; + } else { + log::info!("Removing directory {:?}", docs_target); + fs::remove_dir_all(&docs_target) + .with_context(|| format!("Unable to remove {:?}", docs_target))?; + } + } + + if !docs_target.exists() { + let parked = cache_dir.join(&build_id); + if parked.exists() { + fs::rename(&parked, &docs_target) + .with_context(|| format!("Unable to restore {:?} to {:?}", parked, docs_target))?; + } + } + + if let Some(parent) = build_id_path.parent() { + fs::create_dir_all(parent).with_context(|| format!("Unable to create {:?}", parent))?; } + fs::write(&build_id_path, &build_id) + .with_context(|| format!("Failed to write {}", build_id_path.display()))?; let mut features = vec![]; let doc_config = if let Some(chip) = &chip { @@ -492,34 +549,19 @@ fn cargo_doc_without_pre_processing( } } builder.add_env_var("RUSTDOCFLAGS", &rustdocflags); - // Special case: `esp-storage` requires the optimization level to be 2 or 3: - if package == Package::EspStorage { - builder.add_env_var("CARGO_PROFILE_DEBUG_OPT_LEVEL", "3"); - } let command = CargoCommandBatcher::build_one_for_cargo(&builder); log::debug!("{command:#?}"); crate::cargo::run_with_env(&command.command, &package_path, command.env_vars, false) .with_context(|| format!("Failed to run `cargo doc` for {}", package_name))?; - // Build up the path at which the built documentation can be found: - let mut docs_path = if let Ok(target_path) = std::env::var("CARGO_TARGET_DIR") { - PathBuf::from(target_path) - } else { - workspace.join(package.to_string()).join("target") - }; - - if let Some(ref target) = target { - docs_path = docs_path.join(target); - } - docs_path = docs_path.join("doc"); - - Ok(crate::windows_safe_path(&docs_path)) + Ok(crate::windows_safe_path(&docs_target)) } /// Pre-process the Cargo.toml file /// -/// This will keep the original as "Cargo.toml_original" +/// This will keep the original as "Cargo.toml_original", unless there is nothing to +/// pre-process, in which case the file is left untouched. /// /// This will check for `#DOC_IF ` lines - evaluating the condition to false will turn /// any documenting comments into non-documenting comments until a `#DOC_ENDIF` line is encountered. @@ -527,26 +569,13 @@ fn cargo_doc_without_pre_processing( /// The only currently supported function for expressions is `has()` /// e.g. `has("psram")` fn pre_process_cargo_toml(chip: Option, package_path: &Path) -> Result<(), anyhow::Error> { - let cargo_toml = std::fs::read_to_string(windows_safe_path(&package_path.join("Cargo.toml"))) - .with_context(|| { - format!( - "Failed to read {}", - package_path.join("Cargo.toml").display() - ) - })?; + restore_cargo_toml(package_path)?; - std::fs::rename( - windows_safe_path(&package_path.join("Cargo.toml")), - windows_safe_path(&package_path.join("Cargo.toml_original")), - ) - .with_context(|| { - format!( - "Failed to rename {}", - package_path.join("Cargo.toml").display() - ) - })?; + let manifest_path = windows_safe_path(&package_path.join("Cargo.toml")); + let original_path = windows_safe_path(&package_path.join("Cargo.toml_original")); - let cargo_toml = cargo_toml.lines(); + let cargo_toml = std::fs::read_to_string(&manifest_path) + .with_context(|| format!("Failed to read {}", manifest_path.display()))?; let chip_cfg = chip.as_ref().map(|chip| Config::for_chip(chip)); let mut processed_cargo_toml = Vec::new(); @@ -560,7 +589,7 @@ fn pre_process_cargo_toml(chip: Option, package_path: &Path) -> Result<(), }); let mut hide = false; - for line in cargo_toml { + for line in cargo_toml.lines() { let mut line = line.to_string(); if line.starts_with("#DOC_ENDIF") { @@ -588,22 +617,35 @@ fn pre_process_cargo_toml(chip: Option, package_path: &Path) -> Result<(), processed_cargo_toml.push(line); } - std::fs::write( - windows_safe_path(&package_path.join("Cargo.toml")), - processed_cargo_toml.join("\n"), - ) - .with_context(|| { - format!( - "Failed to write pre-processed {}", - package_path.join("Cargo.toml").display() - ) - })?; + let mut processed_cargo_toml = processed_cargo_toml.join("\n"); + if cargo_toml.ends_with('\n') { + processed_cargo_toml.push('\n'); + } + + // Rewriting the manifest would make cargo rebuild the crate, so leave it alone when + // there is nothing to pre-process. + if processed_cargo_toml == cargo_toml { + return Ok(()); + } + + std::fs::rename(&manifest_path, &original_path) + .with_context(|| format!("Failed to rename {}", manifest_path.display()))?; + + std::fs::write(&manifest_path, processed_cargo_toml) + .with_context(|| format!("Failed to write pre-processed {}", manifest_path.display()))?; + + // Keep the original mtime so Cargo does not treat the temporary manifest as newly modified. + let mtime = fs::metadata(&original_path)?.modified()?; + fs::File::options() + .write(true) + .open(&manifest_path)? + .set_times(FileTimes::new().set_modified(mtime))?; Ok(()) } /// Restore the original Cargo.toml file -fn restore_cargo_toml(package_path: PathBuf) -> Result<(), anyhow::Error> { +fn restore_cargo_toml(package_path: &Path) -> Result<(), anyhow::Error> { if std::fs::exists(windows_safe_path(&package_path.join("Cargo.toml_original")))? { if std::fs::exists(windows_safe_path(&package_path.join("Cargo.toml")))? { std::fs::remove_file(windows_safe_path(&package_path.join("Cargo.toml")))?; @@ -767,12 +809,7 @@ pub fn build_documentation_index( let meta = generate_documentation_meta_for_package(*package, &chips, &version_label)?; // Render the template to HTML and write it out to the desired path: - let html = render_template(&resources_path, "package_index.html.somni", { - let mut env = Env::new(); - env.value("package", package.to_string().replace('-', "_")) - .value("metadata", Iter(meta)); - env - })?; + let html = render_package_index(&resources_path, *package, meta)?; let path = version_path.join("index.html"); fs::write(&path, html).context("Failed to write index.html")?; log::info!("Created {}", path.display()); @@ -812,6 +849,26 @@ pub fn build_documentation_index( Ok(()) } +fn render_package_index( + resources_path: &Path, + package: Package, + meta: Vec, +) -> Result { + let peripheral_support = if package == Package::EspHal { + crate::metadata::peripheral_support_html() + } else { + "" + }; + + render_template(resources_path, "package_index.html.somni", { + let mut env = Env::new(); + env.value("package", package.to_string().replace('-', "_")) + .value("metadata", Iter(meta)) + .value("peripheral_support", peripheral_support); + env + }) +} + fn generate_documentation_meta_for_package( package: Package, chips: &[Chip], @@ -1003,7 +1060,7 @@ fn render_template(resources: &Path, template: &str, env: Env) -> Result #[cfg(test)] mod tests { - use std::path::Path; + use std::{fs, path::Path}; use somni_expr::somni_struct; use somni_template::{Env, Iter, TemplateTypes}; @@ -1015,8 +1072,11 @@ mod tests { highest_eligible_version, is_eligible_docs_version, latest_redirect_base, + latest_redirect_fallback, latest_redirect_html, + pre_process_cargo_toml, render_template, + restore_cargo_toml, should_write_latest_redirect, }; @@ -1036,6 +1096,46 @@ mod tests { manifest } + #[test] + fn processed_manifest_preserves_original_mtime() { + let temp = tempfile::tempdir().unwrap(); + let package_path = temp.path().join("package"); + fs::create_dir(&package_path).unwrap(); + + let original = "#DOC_IF has(\"wifi_driver_supported\")\n## Wi-Fi\n#DOC_ENDIF\n"; + fs::write(package_path.join("Cargo.toml"), original).unwrap(); + let original_mtime = fs::metadata(package_path.join("Cargo.toml")) + .unwrap() + .modified() + .unwrap(); + + // Simulate an interrupted run on a Wi-Fi chip followed by a non-Wi-Fi chip without an + // explicit restore in between. + pre_process_cargo_toml(Some(crate::Chip::Esp32c6), &package_path).unwrap(); + assert_eq!( + fs::read_to_string(package_path.join("Cargo.toml")).unwrap(), + "## Wi-Fi\n" + ); + + pre_process_cargo_toml(Some(crate::Chip::Esp32h2), &package_path).unwrap(); + let processed_mtime = fs::metadata(package_path.join("Cargo.toml")) + .unwrap() + .modified() + .unwrap(); + + assert_eq!(original_mtime, processed_mtime); + assert_eq!( + fs::read_to_string(package_path.join("Cargo.toml")).unwrap(), + "# Wi-Fi\n" + ); + + restore_cargo_toml(&package_path).unwrap(); + assert_eq!( + fs::read_to_string(package_path.join("Cargo.toml")).unwrap(), + original + ); + } + #[test] fn eligible_docs_version_rule() { assert!(is_eligible_docs_version(&version("0.5.0"))); @@ -1145,28 +1245,46 @@ mod tests { #[test] fn latest_redirect_base_paths() { let v = semver::Version::parse("2.1.0").unwrap(); + // The base is always the version root; deep-link remainders appended by + // the redirect page already include the chip or crate directory. + assert_eq!(latest_redirect_base(&v), "../2.1.0/"); + } + + #[test] + fn latest_redirect_fallback_paths() { + // Packages with device-specific docs generate an index at the version root. + assert_eq!(latest_redirect_fallback(&crate::Package::EspHal), ""); + // Other packages have no version-root index; land on the crate's index. assert_eq!( - latest_redirect_base(&crate::Package::EspHal, &v), - "../2.1.0/" - ); - assert_eq!( - latest_redirect_base(&crate::Package::EspAlloc, &v), - "../2.1.0/esp_alloc/" + latest_redirect_fallback(&crate::Package::EspAlloc), + "esp_alloc/index.html" ); } /// Small integration check for the redirect template. #[test] - fn latest_redirect_html_matches_latest_redirect_base() { + fn latest_redirect_html_matches_base_and_fallback() { let ws = workspace(); let ver = semver::Version::parse("1.0.0").unwrap(); - let pkg = crate::Package::EspHal; - let html = latest_redirect_html(ws, &pkg, &ver).unwrap(); - let base = latest_redirect_base(&pkg, &ver); - - assert!(html.contains(&format!("var base = \"{base}\""))); - assert!(html.contains(&format!("content=\"0; url={base}\""))); + for (pkg, fallback) in [ + (crate::Package::EspHal, ""), + (crate::Package::EspAlloc, "esp_alloc/index.html"), + ] { + let html = latest_redirect_html(ws, &pkg, &ver).unwrap(); + let base = latest_redirect_base(&ver); + + assert!(html.contains(&format!("var base = \"{base}\""))); + assert!(html.contains(&format!("var fallback = \"{fallback}\""))); + assert!(html.contains(&format!("content=\"0; url={base}{fallback}\""))); + + // URL fragments (`#method.foo`) never reach nginx, but browsers + // re-attach them to the 301 target, so the redirect page must carry + // `location.hash` over to the final destination explicitly. + assert!(html.contains("var hash = location.hash;")); + assert!(html.contains("location.replace(base + pathFromQuery + hash)")); + assert!(html.contains("location.replace(base + fallback + hash)")); + } } /// The version select box is embedded in a page full of braces, so make sure the @@ -1208,13 +1326,8 @@ mod tests { ) .unwrap(); - let html = render_template(&ws.join("resources"), "package_index.html.somni", { - let mut env = Env::new(); - env.value("package", "esp_hal") - .value("metadata", Iter(meta)); - env - }) - .unwrap(); + let html = super::render_package_index(&ws.join("resources"), crate::Package::EspHal, meta) + .unwrap(); assert!( html.contains("esp_hal Documentation"), @@ -1232,6 +1345,10 @@ mod tests { html.contains("1.0.0"), "{html}" ); + assert!( + html.contains(r#"
"#), + "{html}" + ); } #[test] @@ -1243,15 +1360,10 @@ mod tests { ) .unwrap(); - let html = render_template( + let html = super::render_package_index( &workspace().join("resources"), - "package_index.html.somni", - { - let mut env = Env::new(); - env.value("package", "esp_hal") - .value("metadata", Iter(meta)); - env - }, + crate::Package::EspHal, + meta, ) .unwrap(); @@ -1261,6 +1373,25 @@ mod tests { ); } + #[test] + fn package_index_omits_peripheral_matrix_for_other_packages() { + let meta = generate_documentation_meta_for_package( + crate::Package::EspRadio, + &[crate::Chip::Esp32c6], + "main", + ) + .unwrap(); + + let html = super::render_package_index( + &workspace().join("resources"), + crate::Package::EspRadio, + meta, + ) + .unwrap(); + + assert!(!html.contains(r#"id="peripheral-support""#), "{html}"); + } + #[test] fn index_renders_a_row_per_package() { // `generate_documentation_meta_for_index` resolves manifests relative to the current @@ -1301,6 +1432,10 @@ mod tests { "{html}" ); assert!(html.contains("esp-hal"), "{html}"); + assert!( + html.contains(r#"Peripheral Support Matrix"#), + "{html}" + ); } #[test] diff --git a/xtask/src/firmware.rs b/xtask/src/firmware.rs index c42dfa40449..0536d647fe2 100644 --- a/xtask/src/firmware.rs +++ b/xtask/src/firmware.rs @@ -1,5 +1,5 @@ use std::{ - collections::HashMap, + collections::{BTreeSet, HashMap}, fs, path::{Path, PathBuf}, }; @@ -8,8 +8,9 @@ use anyhow::{Context, Result, bail}; use clap::ValueEnum; use serde::Deserialize; use strum::IntoEnumIterator as _; +use toml_edit::DocumentMut; -use crate::{ScriptContext, metadata::Chip, windows_safe_path}; +use crate::{Package, ScriptContext, metadata::Chip, windows_safe_path}; /// A single, configured example (or test). #[derive(Debug, Clone)] @@ -94,6 +95,16 @@ impl Metadata { self.description.clone() } + /// Optional description of the example, with `{CHIP}` and `{TARGET}` + /// placeholders replaced for a run on the given target triple. + pub fn description_for(&self, target: &str) -> Option { + self.description.as_deref().map(|description| { + description + .replace("{CHIP}", self.chip.as_ref()) + .replace("{TARGET}", target) + }) + } + /// Optional support firmware binary to run on a second target. pub fn harness_firmware(&self) -> Option<&str> { self.harness_firmware.as_deref() @@ -110,15 +121,52 @@ impl Metadata { return false; }; - filter == self.binary_name() || filter == self.output_file_name() + self.matches_name(filter) } - /// Check if the example matches the given name (case insensitive). + /// Returns this example's path relative to `package_root` for matching. + /// + /// Drops a `.rs` suffix and a `src/bin/` prefix, so nested projects become + /// `ota/update` and bins stay `sleep_timer`. + pub fn lookup_name(&self, package_root: &Path) -> String { + let path = self.example_path(); + let relative = path.strip_prefix(package_root).unwrap_or(path); + let mut name = relative.to_string_lossy().replace('\\', "/"); + if let Some(stripped) = name.strip_suffix(".rs") { + name = stripped.to_string(); + } + if let Some(stripped) = name.strip_prefix("src/bin/") { + name = stripped.to_string(); + } + name + } + + /// Checks if the example matches the given name (case insensitive). + /// + /// Accepts the binary name, the output file name, and a relative path + /// (`ota/update`, `examples/ota/update`). pub fn matches_name(&self, name: &str) -> bool { - name.to_lowercase() == self.binary_name() || name.to_lowercase() == self.output_file_name() + let name = normalize_source_name(name); + if name.is_empty() { + return false; + } + if name == self.binary_name().to_lowercase() + || name == self.output_file_name().to_lowercase() + { + return true; + } + let path = normalize_source_name(&self.example_path().to_string_lossy()); + path.ends_with(&format!("/{name}")) } } +fn normalize_source_name(name: &str) -> String { + name.trim() + .trim_end_matches(".rs") + .replace('\\', "/") + .to_lowercase() +} + /// A single configuration of an example, as parsed from metadata lines. #[derive(Debug, Default, Clone)] pub struct Configuration { @@ -169,6 +217,10 @@ struct MetaLine { /// /// - `//% METADATA_KEY: value` or /// - `//% METADATA_KEY(config_name_1, config_name_2, ...): value`. +/// +/// `ENV-IF(expr)` and `FEATURES-IF(expr)` overlay env or features on existing +/// configurations. `expr` is a `CHIP_FILTER` expression; unlike `ENV(name)` it does not +/// create a new configuration binary. fn parse_meta_line(line: &str) -> anyhow::Result { let Some((key, value)) = line.trim_start_matches("//%").split_once(':') else { bail!("Metadata line is missing ':': {}", line); @@ -199,17 +251,10 @@ fn parse_meta_line(line: &str) -> anyhow::Result { /// Returns the chips selected by a `CHIP_FILTER` expression (a boolean expression over /// cfg symbols, key-value cfg symbols, and chip names, e.g. `cfg_symbol && !esp32`, /// `esp32c6 || esp32h2`, or `interrupt_controller != "clic"`). -fn parse_chips(expr: &str) -> anyhow::Result> { - let script_ctx = ScriptContext::new(); - +fn parse_chips(expr: &str) -> Result> { let mut chips = Vec::new(); for chip in Chip::iter() { - let mut ctx = script_ctx.for_chip(chip); - - let selected = ctx.evaluate(expr).map_err(|err| { - anyhow::anyhow!("{err:?}").context("Failed to evaluate chip expression") - })?; - if selected { + if chip_matches(chip, expr)? { chips.push(chip); } } @@ -244,6 +289,8 @@ pub fn load(path: &Path) -> Result> { }; let mut configurations = HashMap::::new(); + let mut env_overlays: Vec<(Vec, String, String)> = Vec::new(); + let mut feature_overlays: Vec<(Vec, Vec)> = Vec::new(); // Unless specified, an example is assumed to be valid for all chips. for (line_no, line) in text @@ -272,32 +319,39 @@ pub fn load(path: &Path) -> Result> { } // Cargo features to enable for the current configuration. "FEATURES" => { - let mut values = meta_line - .value - .split_ascii_whitespace() - .map(ToString::to_string) - .collect::>(); - - // Sort the features so they are in a deterministic order: - values.sort(); - + let values = parse_feature_list(&meta_line.value); relevant_metadata.apply(|meta| meta.features.extend_from_slice(&values)); } + // Same language as CHIP_FILTER. Adds these features on matching chips. + "FEATURES-IF" => { + if meta_line.config_names.is_empty() { + bail!("FEATURES-IF needs a chip expression in parentheses"); + } + feature_overlays.push(( + parse_chips(&meta_line.config_names.join(" || "))?, + parse_feature_list(&meta_line.value), + )); + } // esp-config env vars, one per line "ENV" => { - let (env_var, value) = meta_line - .value - .split_once('=') - .with_context(|| "CONFIG metadata must be in the form 'CONFIG=VALUE'")?; - - let env_var = env_var.trim(); - let value = value.trim(); - + let (env_var, value) = parse_env_assignment(&meta_line.value)?; relevant_metadata.apply(|meta| { - meta.esp_config - .insert(env_var.to_string(), value.to_string()); + meta.esp_config.insert(env_var.clone(), value.clone()); }); } + // Same language as CHIP_FILTER. Adds or replaces that one variable on + // matching chips, does not create a configuration. + "ENV-IF" => { + if meta_line.config_names.is_empty() { + bail!("ENV-IF needs a chip expression in parentheses"); + } + let (env_var, value) = parse_env_assignment(&meta_line.value)?; + env_overlays.push(( + parse_chips(&meta_line.config_names.join(" || "))?, + env_var, + value, + )); + } // Tags by which the user can filter examples. "TAG" => { relevant_metadata.apply(|meta| meta.tag = Some(meta_line.value.to_string())); @@ -360,6 +414,22 @@ pub fn load(path: &Path) -> Result> { configuration.features.sort(); for chip in configuration.chips.as_deref().unwrap_or(&[]) { + let mut features = configuration.features.clone(); + for (chips, extra) in &feature_overlays { + if chips.contains(chip) { + features.extend(extra.iter().cloned()); + } + } + features.sort(); + features.dedup(); + + let mut env_vars = configuration.esp_config.clone(); + for (chips, key, value) in &env_overlays { + if chips.contains(chip) { + env_vars.insert(key.clone(), value.clone()); + } + } + examples.push(Metadata { // File properties example_path: path.clone(), @@ -368,11 +438,11 @@ pub fn load(path: &Path) -> Result> { // Configuration chip: *chip, configuration_name: configuration.name.clone(), - features: configuration.features.clone(), + features, tag: configuration.tag.clone(), harness_firmware: configuration.harness_firmware.clone(), support_firmware: configuration.support_firmware.unwrap_or(false), - env_vars: configuration.esp_config.clone(), + env_vars, cargo_config: configuration.cargo_config.clone(), }) } @@ -385,11 +455,6 @@ pub fn load(path: &Path) -> Result> { Ok(examples) } -#[derive(Debug, Deserialize)] -struct CargoToml { - features: HashMap>, -} - /// Parse the chip set from `//% CHIP_FILTER:` annotations in a source file. /// Returns `None` if the annotation is not present. fn parse_chips_from_annotation( @@ -419,6 +484,15 @@ fn parse_chips_from_annotation( } /// Load all examples by finding all packages in the given path, and parsing their metadata. +/// +/// Two shapes coexist under `examples/` and `compile-tests/`: +/// +/// - A project with no per-chip `[features]` table: chips come from its `//% CHIP_FILTER` +/// annotation (every chip when absent), and xtask forwards `/` to each chip-aware +/// dependency. This is how compile-tests work. +/// - A self-contained project (e.g. `examples/async/embassy_ethernet`), each buildable on its own +/// and meant to be copied elsewhere as a starting point, declares one `[features]` key per +/// supported chip; that is its chip set, narrowed by an optional `//% CHIP_FILTER`. pub fn load_cargo_toml(examples_path: &Path) -> Result> { let mut examples = Vec::new(); @@ -437,40 +511,61 @@ pub fn load_cargo_toml(examples_path: &Path) -> Result> { let text = fs::read_to_string(&main_rs_path)?; let description = parse_description(&text); - let toml = fs::read_to_string(&cargo_toml_path)?; - let toml: CargoToml = toml_edit::de::from_str(&toml)?; + let toml_str = fs::read_to_string(&cargo_toml_path)?; + let doc = toml_str + .parse::() + .with_context(|| format!("Failed to parse {}", cargo_toml_path.display()))?; - let cargo_chips: Vec = toml - .features - .keys() - .filter_map(|k| Chip::from_str(k, true).ok()) - .collect(); - - let chips_from_annotations = parse_chips_from_annotation(&text).with_context(|| { + let annotation_chips = parse_chips_from_annotation(&text).with_context(|| { format!("Failed to parse annotations in {}", main_rs_path.display()) })?; + let feature_chips = feature_table_chips(&doc); - // If the annotation requires chips that are not declared in Cargo.toml, bail. - if let Some(ref required) = chips_from_annotations { - let missing = required - .iter() - .filter(|c| !cargo_chips.contains(c)) - .collect::>(); - if !missing.is_empty() { - anyhow::bail!( - "{}: chips {missing:?} are required by the annotation but missing from Cargo.toml", - package_path.display() - ); + if feature_chips.is_empty() { + let deps = chip_aware_deps(&doc); + for chip in selected_chips(&annotation_chips) { + let features = deps.iter().map(|dep| format!("{dep}/{chip}")).collect(); + examples.push(Metadata { + example_path: package_path.clone(), + chip, + configuration_name: String::new(), + features, + tag: None, + description: description.clone(), + harness_firmware: None, + support_firmware: false, + env_vars: HashMap::new(), + cargo_config: Vec::new(), + }); } + continue; } - let chips = cargo_chips.into_iter().filter(|c| { - chips_from_annotations - .as_ref() - .is_none_or(|set| set.contains(c)) - }); + // A `[features]` chip table, narrowed by an optional `//% CHIP_FILTER`. Without an + // annotation the project must list every chip, otherwise a newly added chip silently + // drops out of its coverage. + let missing: Vec = Chip::iter() + .filter(|chip| match &annotation_chips { + Some(annotated) => annotated.contains(chip), + None => true, + }) + .filter(|chip| !feature_chips.contains(chip)) + .collect(); + if !missing.is_empty() { + bail!( + "{}: chips {missing:?} are missing from Cargo.toml. Add them, or narrow the set \ + with a `//% CHIP_FILTER:` annotation.", + package_path.display() + ); + } - for chip in chips { + for chip in feature_chips { + if annotation_chips + .as_ref() + .is_some_and(|set| !set.contains(&chip)) + { + continue; + } examples.push(Metadata { example_path: package_path.clone(), chip, @@ -489,6 +584,414 @@ pub fn load_cargo_toml(examples_path: &Path) -> Result> { Ok(examples) } +/// Chips selected by a `//% CHIP_FILTER` annotation, or every chip when absent. +fn selected_chips(annotation: &Option>) -> Vec { + match annotation { + Some(set) => Chip::iter().filter(|c| set.contains(c)).collect(), + None => Chip::iter().collect(), + } +} + +/// Whether the standalone project at `dir` declares a per-chip `[features]` +/// table. Compile-tests do not (their chip rides on forwarded `/` +/// features), so the bare chip feature must not be enabled for them. +pub(crate) fn project_has_chip_feature_table(dir: &Path) -> bool { + std::fs::read_to_string(dir.join("Cargo.toml")) + .ok() + .and_then(|s| s.parse::().ok()) + .is_some_and(|doc| !feature_table_chips(&doc).is_empty()) +} + +/// The chips named by a project's `[features]` keys. +fn feature_table_chips(doc: &DocumentMut) -> Vec { + doc.get("features") + .and_then(|f| f.as_table()) + .map(|table| { + table + .iter() + .filter_map(|(key, _)| Chip::from_str(key, true).ok()) + .collect() + }) + .unwrap_or_default() +} + +/// The `esp-*` dependencies that declare chip features; xtask forwards each as +/// `/` for the selected chips. Chip-agnostic deps (esp-alloc) and +/// third-party crates are left out. +fn chip_aware_deps(doc: &DocumentMut) -> Vec { + let Some(table) = doc.get("dependencies").and_then(|d| d.as_table()) else { + return Vec::new(); + }; + let mut deps = Vec::new(); + for (name, item) in table.iter() { + let real = item.get("package").and_then(|p| p.as_str()).unwrap_or(name); + if let Ok(pkg) = Package::from_str(real, true) + && pkg.has_chip_features() + && !deps.contains(&pkg) + { + deps.push(pkg); + } + } + deps.sort(); + deps +} + +/// Whether `expr` holds for `chip`, evaluated against the chip's device metadata. +fn chip_matches(chip: Chip, expr: &str) -> Result { + let script_ctx = ScriptContext::new(); + let mut ctx = script_ctx.for_chip(chip); + ctx.evaluate(expr) +} + +/// The chips each compile-test project selects (from its `//% CHIP_FILTER`), +/// keyed by project directory name. Report-only helper for the plan and PR body. +pub fn compile_test_coverage(workspace: &Path) -> Result)>> { + let root = windows_safe_path(&workspace.join(Package::CompileTests.directory())); + let mut packages = crate::find_packages(&root)?; + packages.sort(); + + let mut coverage = Vec::new(); + for package_path in packages { + let main_rs_path = package_path.join("src").join("main.rs"); + if !main_rs_path.exists() { + continue; + } + let text = fs::read_to_string(&main_rs_path)?; + let chips = selected_chips(&parse_chips_from_annotation(&text)?); + let name = package_path + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + coverage.push((name, chips)); + } + + coverage.sort_by(|a, b| a.0.cmp(&b.0)); + Ok(coverage) +} + +/// Render [`compile_test_coverage`] as one `- project: chip, chip` line each. +pub fn format_compile_test_coverage(coverage: &[(String, Vec)]) -> String { + coverage + .iter() + .map(|(project, chips)| { + let chips = if chips.is_empty() { + "(no chips)".to_string() + } else { + chips + .iter() + .map(ToString::to_string) + .collect::>() + .join(", ") + }; + format!("- {project}: {chips}") + }) + .collect::>() + .join("\n") +} + +/// The feature names declared for `version` in a crates.io sparse-index body +/// (newline-delimited JSON). Merges `features` and `features2`, since cargo +/// splits weak/`dep:` syntax into the latter but the names are equally valid. +pub fn features_for_version( + index_body: &str, + version: &semver::Version, +) -> Result> { + #[derive(Deserialize)] + struct IndexEntry { + vers: String, + #[serde(default)] + features: HashMap>, + #[serde(default)] + features2: Option>>, + } + + for line in index_body.lines() { + let line = line.trim(); + if line.is_empty() { + continue; + } + let entry: IndexEntry = serde_json::from_str(line) + .with_context(|| format!("Failed to parse crates.io index line: {line}"))?; + // Compare parsed versions so build metadata on one side doesn't cause a miss. + let Ok(entry_version) = semver::Version::parse(&entry.vers) else { + continue; + }; + if entry_version == *version { + let mut names: BTreeSet = entry.features.into_keys().collect(); + if let Some(features2) = entry.features2 { + names.extend(features2.into_keys()); + } + return Ok(names); + } + } + + bail!("version {version} was not found in the crates.io index response"); +} + +/// The highest non-yanked published version satisfying `req`, from a sparse-index body. +fn max_version_matching( + index_body: &str, + req: &semver::VersionReq, +) -> Result> { + #[derive(Deserialize)] + struct VersionEntry { + vers: String, + #[serde(default)] + yanked: bool, + } + + let mut best: Option = None; + for line in index_body.lines() { + let line = line.trim(); + if line.is_empty() { + continue; + } + let entry: VersionEntry = serde_json::from_str(line) + .with_context(|| format!("Failed to parse crates.io index line: {line}"))?; + if entry.yanked { + continue; + } + let Ok(version) = semver::Version::parse(&entry.vers) else { + continue; + }; + if req.matches(&version) && best.as_ref().is_none_or(|b| version > *b) { + best = Some(version); + } + } + + Ok(best) +} + +/// The crates.io sparse-index URL for a crate, following the registry's prefix layout. +fn sparse_index_url(crate_name: &str) -> String { + let name = crate_name.to_lowercase(); + let prefix = match name.len() { + 1 => "1".to_string(), + 2 => "2".to_string(), + 3 => format!("3/{}", &name[0..1]), + _ => format!("{}/{}", &name[0..2], &name[2..4]), + }; + format!("https://index.crates.io/{prefix}/{name}") +} + +/// Fetch a crate's sparse-index document via `curl`, or `None` when curl or the +/// network is unavailable. curl avoids a dependency for one best-effort check. +fn fetch_sparse_index(crate_name: &str) -> Option { + let url = sparse_index_url(crate_name); + let output = std::process::Command::new("curl") + .args(["-sSf", &url]) + .output() + .ok()?; + if !output.status.success() { + return None; + } + String::from_utf8(output.stdout).ok() +} + +/// Whether a compile-test project can build a chip at the versions that resolve. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ChipCoverage { + Builds, + /// A dependency's resolving line predates the chip. `released` is set when + /// another dependency ships the chip from the working tree, i.e. this + /// release publishes the chip and the project cannot test it. + Skipped { + released: bool, + }, +} + +/// Where a chip-dep's `` feature comes from at the version that resolves. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum DepChipSupport { + WorkingTree, + Published, + Missing, +} + +/// Whether every `chip-deps` crate of the compile-test project at `project_path` +/// declares the `` cargo feature at the version that will resolve. +/// +/// A frozen dependency line that predates the chip skips this project for the +/// chip instead of hitting a `/` feature cargo cannot find. A crate +/// this release publishes that lacks the feature is a hard error (see +/// [`chip_dep_declares_feature`]). +pub fn compile_test_project_supports_chip( + workspace: &Path, + project_path: &Path, + chip: Chip, +) -> Result { + let cargo_toml_path = project_path.join("Cargo.toml"); + let toml_str = fs::read_to_string(&cargo_toml_path)?; + let doc = toml_str + .parse::() + .with_context(|| format!("Failed to parse {}", cargo_toml_path.display()))?; + + let mut index_cache: HashMap> = HashMap::new(); + let mut support = Vec::new(); + for dep in chip_aware_deps(&doc) { + let dep = dep.to_string(); + let found = + chip_dep_declares_feature(workspace, project_path, &doc, &dep, chip, &mut index_cache)?; + if found == DepChipSupport::Missing { + log::info!( + "Skipping compile-test {} for {chip}: dependency `{dep}` does not support it at \ + the version that resolves", + project_path.display() + ); + } + support.push(found); + } + + Ok(coverage(&support)) +} + +fn coverage(support: &[DepChipSupport]) -> ChipCoverage { + if !support.contains(&DepChipSupport::Missing) { + return ChipCoverage::Builds; + } + ChipCoverage::Skipped { + released: support.contains(&DepChipSupport::WorkingTree), + } +} + +fn chip_dep_declares_feature( + workspace: &Path, + project: &Path, + doc: &DocumentMut, + dep: &str, + chip: Chip, + index_cache: &mut HashMap>, +) -> Result { + let chip_feature = chip.to_string(); + + let Some(req_str) = dependency_requirement(doc, dep) else { + bail!( + "{}: `{dep}` is a compile-test chip-dep but has no [dependencies] entry", + project.display() + ); + }; + let req = semver::VersionReq::parse(&req_str).with_context(|| { + format!( + "{}: invalid version requirement `{req_str}` for {dep}", + project.display() + ) + })?; + + let tree = if let Ok(package) = Package::from_str(dep, true) + && let Ok(toml) = crate::cargo::CargoToml::new(workspace, package) + { + Some(( + toml.package_version(), + manifest_declares_feature(&toml.manifest, &chip_feature), + )) + } else { + None + }; + + let index_body = index_cache + .entry(dep.to_string()) + .or_insert_with(|| fetch_sparse_index(dep)); + let max_published = match index_body.as_deref() { + Some(body) => max_version_matching(body, &req)?, + None => None, + }; + + // Trust the tree only when cargo will resolve that version (it is newer + // than, or the only match for, the requirement). A published tree version + // older than the index max is crates.io's crate, whose features can lag. + if let Some((tree_version, has_feature)) = &tree + && tree_is_resolving_version(tree_version, &req, max_published.as_ref()) + { + if *has_feature { + return Ok(DepChipSupport::WorkingTree); + } + bail!( + "{}: crate `{dep}` {tree_version} (working tree) does not declare the \ + `{chip_feature}` feature required for {chip}. A chip was added to the metadata \ + without a matching feature in {dep}.", + project.display() + ); + } + + // Frozen line: read the published index. A missing feature means this line + // predates the chip, so the project does not cover it - skip, do not error. + let Some(index_body) = index_body.as_deref() else { + log::warn!( + "Cannot verify `{dep}` ({chip}) against the crates.io index (offline?); attempting the build" + ); + return Ok(DepChipSupport::Published); + }; + + let Some(resolved) = max_published else { + log::warn!("No published `{dep}` satisfies `{req_str}`; attempting the build"); + return Ok(DepChipSupport::Published); + }; + + let features = features_for_version(index_body, &resolved)?; + Ok(if features.contains(&chip_feature) { + DepChipSupport::Published + } else { + DepChipSupport::Missing + }) +} + +/// Whether the working-tree crate is the version cargo will resolve. +/// +/// A published tree version that is older than the index max must not win: +/// cargo picks the published crate, whose feature table can lag the tree. +fn tree_is_resolving_version( + tree_version: &semver::Version, + req: &semver::VersionReq, + max_published: Option<&semver::Version>, +) -> bool { + req.matches(tree_version) && max_published.is_none_or(|published| tree_version > published) +} + +/// The version requirement string for `dep` in a manifest's `[dependencies]`, +/// whether written as `dep = "x"`, `dep = { version = "x" }`, or a table. +fn dependency_requirement(doc: &DocumentMut, dep: &str) -> Option { + let item = doc.get("dependencies")?.get(dep)?; + item.as_str() + .or_else(|| item.get("version").and_then(|v| v.as_str())) + .map(String::from) +} + +fn manifest_declares_feature(manifest: &DocumentMut, feature: &str) -> bool { + manifest + .get("features") + .and_then(|f| f.as_table()) + .is_some_and(|table| table.contains_key(feature)) +} + +/// Load every example or test the given package owns. +/// +/// Packages keep their firmware in one of three shapes: a directory of standalone projects, a +/// `src/bin` directory, or an `examples` directory. +pub fn load_package(workspace: &Path, package: Package) -> Result> { + let root = windows_safe_path(&workspace.join(package.directory())); + if package.contains_standalone_projects() { + return load_cargo_toml(&root); + } + + let src_bin = root.join("src").join("bin"); + let bins = if src_bin.is_dir() { + src_bin + } else { + root.join("examples") + }; + + let mut firmware = load(&bins)?; + // hil-test-radio keeps the tests and their harness firmware in subdirectories. + for nested in ["tests", "support"] { + let dir = bins.join(nested); + if dir.exists() { + firmware.extend(load(&dir)?); + } + } + + Ok(firmware) +} + /// Find the metadata entry for an artifact/test name. pub fn find_test_by_name<'a>(tests: &'a [Metadata], name: &str) -> Option<&'a Metadata> { tests.iter().find(|test| { @@ -498,6 +1001,22 @@ pub fn find_test_by_name<'a>(tests: &'a [Metadata], name: &str) -> Option<&'a Me }) } +fn parse_env_assignment(value: &str) -> Result<(String, String)> { + let (env_var, value) = value + .split_once('=') + .with_context(|| "CONFIG metadata must be in the form 'CONFIG=VALUE'")?; + Ok((env_var.trim().to_string(), value.trim().to_string())) +} + +fn parse_feature_list(value: &str) -> Vec { + let mut values = value + .split_ascii_whitespace() + .map(ToString::to_string) + .collect::>(); + values.sort(); + values +} + fn parse_bool(value: &str) -> Result { match value.trim().to_ascii_lowercase().as_str() { "true" => Ok(true), @@ -521,3 +1040,264 @@ fn parse_description(text: &str) -> Option { description } + +#[cfg(test)] +mod tests { + use super::*; + + fn chips(expr: &str) -> Vec { + parse_chips(expr).expect("expression should evaluate") + } + + #[test] + fn wifi_predicate_selects_wifi_chips() { + let selected = chips("wifi_driver_supported"); + // The wifi compile-test must cover both incident chips: esp32s31 (#6334, + // beta.1 shipped against emg lacking its Wi-Fi metadata) and esp32c5 + // (Wi-Fi 6 metadata not exercised). esp32h2 and esp32p4 have no Wi-Fi. + assert!(selected.contains(&Chip::Esp32s31)); + assert!(selected.contains(&Chip::Esp32c5)); + assert!(!selected.contains(&Chip::Esp32h2)); + assert!(!selected.contains(&Chip::Esp32p4)); + } + + #[test] + fn bt_predicate_selects_bt_chips() { + let selected = chips("bt_driver_supported"); + // esp32h2 has a Bluetooth driver but no Wi-Fi one, and esp32s31 gained a + // BLE driver (#6332). Radio-less chips (esp32s2, esp32p4) are excluded. + assert!(selected.contains(&Chip::Esp32h2)); + assert!(selected.contains(&Chip::Esp32s31)); + assert!(!selected.contains(&Chip::Esp32s2)); + assert!(!selected.contains(&Chip::Esp32p4)); + } + + #[test] + fn hal_predicate_selects_every_chip() { + // `true` is the `hal` project's predicate: it must cover esp32p4, which + // nothing else selects, so no chip is left without a compile-test. + let selected = chips("true"); + assert!(selected.contains(&Chip::Esp32p4)); + assert_eq!(selected.len(), Chip::iter().count()); + } + + #[test] + fn false_predicate_selects_no_chip() { + // A predicate no chip satisfies yields an empty set; the build path turns + // this into a hard zero-coverage error. + assert!(chips("false").is_empty()); + } + + #[test] + fn description_for_substitutes_chip_and_target() { + let example = Metadata { + example_path: PathBuf::from("ota/update"), + chip: Chip::Esp32c6, + configuration_name: String::new(), + features: Vec::new(), + tag: None, + description: Some( + "espflash save-image --chip={CHIP} target/{TARGET}/release/ota_update \ + target/ota_image" + .to_string(), + ), + harness_firmware: None, + support_firmware: false, + env_vars: HashMap::new(), + cargo_config: Vec::new(), + }; + + let description = example + .description_for("riscv32imac-esp-unknown-elf") + .unwrap(); + assert_eq!( + description, + "espflash save-image --chip=esp32c6 \ + target/riscv32imac-esp-unknown-elf/release/ota_update target/ota_image" + ); + } + + #[test] + fn chip_aware_deps_are_the_esp_crates_with_chip_features() { + // esp-hal and esp-alloc both declare per-chip features and are forwarded; + // embassy-executor is third-party (not a workspace crate) and is left out. + let doc = r#" + [dependencies] + esp-hal = "1.1.0" + esp-alloc = "0.10.0" + embassy-executor = "0.10.0" + "# + .parse::() + .unwrap(); + + let deps = chip_aware_deps(&doc); + assert!(deps.contains(&Package::EspHal)); + assert!(deps.contains(&Package::EspAlloc)); + assert_eq!(deps.len(), 2); + } + + #[test] + fn feature_table_chips_reads_only_chip_keys() { + let doc = r#" + [features] + default = [] + esp32 = [] + esp32c6 = [] + "# + .parse::() + .unwrap(); + + let chips = feature_table_chips(&doc); + assert!(chips.contains(&Chip::Esp32)); + assert!(chips.contains(&Chip::Esp32c6)); + assert_eq!(chips.len(), 2); + } + + #[test] + fn features_for_version_reports_declared_feature_names() { + // Two versions of the same crate; only 0.18.0 declares `esp32c6`. + let body = concat!( + r#"{"name":"esp-radio","vers":"0.17.0","deps":[],"features":{"wifi":[],"esp32":[]},"cksum":"a","yanked":false}"#, + "\n", + r#"{"name":"esp-radio","vers":"0.18.0","deps":[],"features":{"wifi":[]},"features2":{"esp32c6":[]},"cksum":"b","yanked":false}"#, + "\n", + ); + + let older = features_for_version(body, &semver::Version::parse("0.17.0").unwrap()).unwrap(); + assert!(!older.contains("esp32c6")); + + // The resolved (max satisfying) version and its merged feature set. + let req = semver::VersionReq::parse("^0.18.0").unwrap(); + let resolved = max_version_matching(body, &req).unwrap().unwrap(); + assert_eq!(resolved, semver::Version::parse("0.18.0").unwrap()); + let features = features_for_version(body, &resolved).unwrap(); + assert!(features.contains("esp32c6")); + assert!(features.contains("wifi")); + } + + #[test] + fn features_for_version_flags_missing_chip_feature() { + // The mechanism behind #6334 (beta.1) and new-chip coverage: the + // published version that resolves lacks the required chip feature, so the + // feature check can skip an old dependency line for that chip instead of + // failing the build. + let body = concat!( + r#"{"name":"dep","vers":"1.0.0","deps":[],"features":{"esp32":[]},"cksum":"a","yanked":false}"#, + "\n", + r#"{"name":"dep","vers":"1.1.0","deps":[],"features":{"esp32":[]},"cksum":"b","yanked":false}"#, + "\n", + ); + let req = semver::VersionReq::parse("^1.0").unwrap(); + let resolved = max_version_matching(body, &req).unwrap().unwrap(); + assert_eq!(resolved, semver::Version::parse("1.1.0").unwrap()); + let features = features_for_version(body, &resolved).unwrap(); + assert!(!features.contains("esp32s31")); + } + + #[test] + fn real_compile_tests_cover_every_chip() { + // Exercises the real projects end to end: derives each one's chip set + // from its `//% CHIP_FILTER` against the live metadata, and asserts every + // chip is covered so no release chip is silently untested. + let workspace = crate::repo_root_for_tests(); + let coverage = compile_test_coverage(&workspace).expect("coverage should compute"); + + for chip in Chip::iter() { + assert!( + coverage.iter().any(|(_, chips)| chips.contains(&chip)), + "chip {chip} is not covered by any compile-test project" + ); + } + + // `hal` is the catch-all, and esp32p4 relies on it exclusively. + let hal = coverage + .iter() + .find(|(name, _)| name == "hal") + .expect("hal project present"); + assert_eq!(hal.1.len(), Chip::iter().count()); + + let p4_projects = coverage + .iter() + .filter(|(_, chips)| chips.contains(&Chip::Esp32p4)) + .map(|(name, _)| name.as_str()) + .collect::>(); + assert_eq!(p4_projects, ["hal"]); + } + + #[test] + fn coverage_builds_when_every_dep_has_the_chip() { + use DepChipSupport::*; + assert_eq!(coverage(&[WorkingTree, Published]), ChipCoverage::Builds); + } + + #[test] + fn coverage_flags_a_released_chip_a_published_dep_lacks() { + // esp-hal ships the chip from the tree, esp-backtrace resolves a line without it. + use DepChipSupport::*; + assert_eq!( + coverage(&[WorkingTree, Missing]), + ChipCoverage::Skipped { released: true } + ); + } + + #[test] + fn coverage_skips_a_chip_nothing_in_the_build_ships() { + // Partial release without the chip's crates: every dep is a published line. + use DepChipSupport::*; + assert_eq!( + coverage(&[Published, Missing, Missing]), + ChipCoverage::Skipped { released: false } + ); + } + + #[test] + fn tree_is_resolving_when_newer_than_published() { + let req = semver::VersionReq::parse("1.2").unwrap(); + let tree = semver::Version::parse("1.3.0").unwrap(); + let published = semver::Version::parse("1.2.2").unwrap(); + assert!(tree_is_resolving_version(&tree, &req, Some(&published))); + } + + #[test] + fn tree_is_not_resolving_when_published_is_ahead() { + // Tree 1.2.0 with unreleased chip features; cargo resolves crates.io 1.2.2. + let req = semver::VersionReq::parse("1.2").unwrap(); + let tree = semver::Version::parse("1.2.0").unwrap(); + let published = semver::Version::parse("1.2.2").unwrap(); + assert!(!tree_is_resolving_version(&tree, &req, Some(&published))); + } + + #[test] + fn tree_is_not_resolving_when_equal_to_published() { + let req = semver::VersionReq::parse("1.2").unwrap(); + let tree = semver::Version::parse("1.2.2").unwrap(); + let published = semver::Version::parse("1.2.2").unwrap(); + assert!(!tree_is_resolving_version(&tree, &req, Some(&published))); + } + + #[test] + fn tree_is_resolving_when_nothing_is_published() { + let req = semver::VersionReq::parse("1.3").unwrap(); + let tree = semver::Version::parse("1.3.0").unwrap(); + assert!(tree_is_resolving_version(&tree, &req, None)); + } + + #[test] + fn frozen_line_tree_does_not_match_req() { + let req = semver::VersionReq::parse("~1.1.0").unwrap(); + let tree = semver::Version::parse("1.2.0").unwrap(); + let published = semver::Version::parse("1.1.1").unwrap(); + assert!(!tree_is_resolving_version(&tree, &req, Some(&published))); + } + + #[test] + fn sparse_index_url_follows_registry_prefix_layout() { + assert_eq!(sparse_index_url("a"), "https://index.crates.io/1/a"); + assert_eq!(sparse_index_url("bc"), "https://index.crates.io/2/bc"); + assert_eq!(sparse_index_url("abc"), "https://index.crates.io/3/a/abc"); + assert_eq!( + sparse_index_url("esp-hal"), + "https://index.crates.io/es/p-/esp-hal" + ); + } +} diff --git a/xtask/src/git.rs b/xtask/src/git.rs index a5cf1763d90..1482d9352d2 100644 --- a/xtask/src/git.rs +++ b/xtask/src/git.rs @@ -70,6 +70,66 @@ pub fn current_branch() -> Result { Ok(String::from_utf8_lossy(&status.stdout).trim().to_string()) } +/// Local tags matching `pattern` (`git tag -l `). +#[cfg(feature = "release")] +pub fn list_tags(workspace: &std::path::Path, pattern: &str) -> Result> { + let output = Command::new("git") + .args(["tag", "-l", pattern]) + .current_dir(workspace) + .output() + .context("Failed to list git tags")?; + + anyhow::ensure!( + output.status.success(), + "`git tag -l {pattern}` failed: {}", + String::from_utf8_lossy(&output.stderr).trim() + ); + + Ok(String::from_utf8_lossy(&output.stdout) + .lines() + .map(|l| l.trim().to_string()) + .filter(|l| !l.is_empty()) + .collect()) +} + +/// Whether `git_ref` (a tag, branch or commit) exists in the repository. +pub fn ref_exists(workspace: &std::path::Path, git_ref: &str) -> Result { + let status = Command::new("git") + .args(["rev-parse", "--verify", "--quiet"]) + .arg(format!("{git_ref}^{{commit}}")) + .current_dir(workspace) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .status() + .context("Failed to check whether a git ref exists")?; + + Ok(status.success()) +} + +/// Read `repo_relative_path` as it existed at `git_ref` via `git show`. The path +/// must use `/` separators, as git addresses tree entries that way on every OS. +pub fn show_file_at_ref( + workspace: &std::path::Path, + git_ref: &str, + repo_relative_path: &str, +) -> Result { + let spec = format!("{git_ref}:{repo_relative_path}"); + let output = Command::new("git") + .arg("show") + .arg(&spec) + .current_dir(workspace) + .output() + .with_context(|| format!("Failed to run `git show {spec}`"))?; + + anyhow::ensure!( + output.status.success(), + "`git show {spec}` failed: {}", + String::from_utf8_lossy(&output.stderr).trim() + ); + + Ok(String::from_utf8_lossy(&output.stdout).to_string()) +} + #[cfg(feature = "release")] /// Ensure that the git workspace is clean (no uncommitted changes). pub fn ensure_workspace_clean(workspace: &std::path::Path) -> Result<()> { diff --git a/xtask/src/lib.rs b/xtask/src/lib.rs index 27e76740252..9b1760ec52b 100644 --- a/xtask/src/lib.rs +++ b/xtask/src/lib.rs @@ -2,10 +2,12 @@ use std::{ collections::HashMap, fs, path::{Path, PathBuf}, - time::Duration, + process::{Command, Stdio}, + thread, + time::{Duration, Instant}, }; -use anyhow::{Context, Result, anyhow}; +use anyhow::{Context, Result, anyhow, bail}; use cargo::CargoAction; use parking_lot::{MappedMutexGuard, Mutex, MutexGuard}; use pretty_yaml::{config::FormatOptions, format_text}; @@ -22,11 +24,13 @@ use crate::{ pub mod cargo; pub mod changelog; pub mod commands; +pub mod detect; pub mod documentation; pub mod firmware; pub mod git; pub mod metadata; pub mod pr_changelog; +pub mod resolve; /// GitHub repository used for all `gh` CLI calls. pub const UPSTREAM_REPO: &str = "esp-rs/esp-hal"; @@ -64,55 +68,17 @@ pub struct CheckConfig { pub env: HashMap, } -#[derive( - Debug, - Clone, - Copy, - PartialEq, - Eq, - PartialOrd, - Ord, - Hash, - clap::ValueEnum, - strum::Display, - strum::EnumIter, - strum::AsRefStr, - serde::Deserialize, - serde::Serialize, -)] -#[serde(rename_all = "kebab-case")] -#[strum(serialize_all = "kebab-case")] -/// Represents the packages in the `esp-hal` workspace. -pub enum Package { - EspAlloc, - EspBacktrace, - EspBootloaderEspIdf, - EspConfig, - EspHal, - EspHalProcmacros, - EspRomSys, - EspLpHal, - EspMetadata, - EspMetadataGenerated, - EspPhy, - EspPrintln, - EspRiscvRt, - EspStorage, - EspSync, - EspRadio, - EspRadioRtosDriver, - EspRtos, - Examples, - HilTest, - HilTestRadio, - QaTest, - XtensaLx, - XtensaLxRt, - XtensaLxRtProcMacros, - - CompileTests, +/// One `host-test-configs` case from `[package.metadata.espressif]`. +#[derive(Debug, Clone, Default)] +pub struct HostTestConfig { + pub features: Vec, + pub cargo_args: Vec, + pub test_args: Vec, + pub miri: bool, } +include!(concat!(env!("OUT_DIR"), "/packages.rs")); + // Returns the root directory of the esp-hal repository. fn repo_root() -> PathBuf { let cwd = std::env::current_dir().unwrap(); @@ -176,24 +142,18 @@ impl Package { /// Does the package have inline assembly? pub fn has_inline_assembly(&self, workspace: &Path) -> bool { - // feature(asm_experimental_arch) is enabled in all crates that use Xtensa - // assembly, which covers crates that use assembly AND are used for both - // architectures (e.g. esp-backtrace). - // But RISC-V doesn't need this feature, so we can either scrape the crate - // source, or check in a list of packages. - if matches!(self, Package::EspRiscvRt | Package::EspLpHal) { - return true; - } - - let lib_rs_path = workspace.join(self.to_string()).join("src").join("lib.rs"); - let Ok(source) = std::fs::read_to_string(&lib_rs_path) else { - return false; - }; - - source - .lines() - .filter(|line| line.starts_with("#![")) - .any(|line| line.contains("asm_experimental_arch")) + let src_path = workspace.join(self.directory()).join("src"); + walkdir::WalkDir::new(src_path) + .into_iter() + .filter_map(Result::ok) + .filter(|e| e.path().extension().is_some_and(|ext| ext == "rs")) + .any(|entry| { + std::fs::read_to_string(entry.path()).is_ok_and(|src| { + src.contains("asm_experimental_arch") + || src.contains("asm!(") + || src.contains("asm!{") + }) + }) } /// Is the package compatible with the given chip? @@ -217,7 +177,7 @@ impl Package { /// Does the package have a migration guide? pub fn has_migration_guide(&self, workspace: &Path) -> bool { - let package_path = workspace.join(self.to_string()); + let package_path = workspace.join(self.directory()); // Check if the package directory exists let Ok(entries) = std::fs::read_dir(&package_path) else { @@ -239,21 +199,32 @@ impl Package { /// Does the package have any host tests? /// - /// Returns true when `src/**/*.rs` contains `#[test]`. Packages that return - /// true must also have a match arm in [`run_host_tests`]; see `xtask/README.md` - /// ("Host tests"). + /// Returns true when `host-test-configs` is configured in `[package.metadata.espressif]` + /// or when `src/**/*.rs` contains `#[test]`. Packages that return + /// true must configure `host-test-configs` in `[package.metadata.espressif]`; + /// see `xtask/README.md` ("Host tests"). pub fn has_host_tests(&self, workspace: &Path) -> bool { - if *self == Package::HilTest || *self == Package::HilTestRadio { + if self.contains_standalone_projects() { + return false; + } + if !self.host_test_config_rules().is_empty() { + return true; + } + // Test suites (`hil-test`, `hil-test-radio`) use `#[test]` with `embedded-test` + // rather than host `cargo test`. + let package_dir = workspace.join(self.directory()); + if package_dir.join("src").join("bin").is_dir() && !self.is_published() { return false; } - let package_path = workspace.join(self.to_string()).join("src"); + let package_path = package_dir.join("src"); walkdir::WalkDir::new(package_path) .into_iter() .filter_map(Result::ok) .filter(|e| e.path().extension().is_some_and(|ext| ext == "rs")) .any(|entry| { - std::fs::read_to_string(entry.path()).is_ok_and(|src| src.contains("#[test]")) + std::fs::read_to_string(entry.path()) + .is_ok_and(|src| src.lines().any(|line| line.trim().starts_with("#[test]"))) }) } @@ -273,11 +244,6 @@ impl Package { .unwrap_or(false) } - /// Is this "package" a directory of standalone projects rather than a single crate? - pub fn contains_standalone_projects(&self) -> bool { - matches!(self, Package::Examples | Package::CompileTests) - } - /// Should documentation be built for the package, and should the package be /// published? pub fn is_published(&self) -> bool { @@ -291,11 +257,25 @@ impl Package { /// Build on host pub fn build_on_host(&self, features: &[String]) -> bool { - match self { - Self::EspConfig | Self::EspMetadata => true, - Self::EspMetadataGenerated if features.iter().any(|f| f == "build-script") => true, - _ => false, + if !self.needs_build_std() { + return true; } + + let toml = self.toml(); + let Some(ref toml) = *toml else { + return false; + }; + let Some(metadata) = toml.espressif_metadata() else { + return false; + }; + let Some(Item::Value(Value::Array(host_features))) = metadata.get("host-features") else { + return false; + }; + + host_features.iter().any(|hf| { + hf.as_str() + .is_some_and(|hf| features.iter().any(|f| f == hf)) + }) } fn parse_required_features(table: &InlineTable) -> Vec { @@ -435,10 +415,6 @@ impl Package { // TODO: perhaps we should use the docs.rs metadata for doc features for packages that have no // chip-specific features. pub fn doc_config_rules(&self, config: &Config) -> Option { - if *self == Self::Examples { - return None; - } - let config = self.single_config_rule_from_metadata(config, "doc-config"); log::debug!("Doc config for package '{}': {:?}", self, config); @@ -512,6 +488,64 @@ impl Package { cases } + /// Host test configurations to run for this package via `cargo xtask host-tests`. + pub fn host_test_config_rules(&self) -> Vec { + let toml = self.toml(); + let Some(ref toml) = *toml else { + return Vec::new(); + }; + + let mut cases = Vec::new(); + if let Some(metadata) = toml.espressif_metadata() + && let Some(config_meta) = metadata.get("host-test-configs") + { + let Item::Value(Value::Array(tables)) = config_meta else { + panic!( + "'host-test-configs' must be an array of tables. {:?}", + config_meta + ); + }; + + for table in tables { + let Value::InlineTable(table) = table else { + panic!("'host-test-configs' items must be inline tables."); + }; + + let features = Self::parse_required_features(table); + + let parse_str_array = |key: &str| -> Vec { + let Some(val) = table.get(key) else { + return Vec::new(); + }; + let Value::Array(arr) = val else { + panic!("'{key}' must be an array."); + }; + arr.iter() + .map(|v| { + v.as_str() + .unwrap_or_else(|| panic!("'{key}' items must be strings.")) + .to_owned() + }) + .collect() + }; + + let cargo_args = parse_str_array("cargo-args"); + let test_args = parse_str_array("test-args"); + let miri = table.get("miri").and_then(|v| v.as_bool()).unwrap_or(false); + + cases.push(HostTestConfig { + features, + cargo_args, + test_args, + miri, + }); + } + } + + log::debug!("Host test configs for package '{}': {:?}", self, cases); + cases + } + fn toml(&self) -> MappedMutexGuard<'_, Option> { let tomls = TOML.lock(); @@ -596,8 +630,8 @@ impl Package { format!("{self}-v{version}") } - #[cfg(feature = "release")] - fn is_semver_checked(&self) -> bool { + #[cfg(feature = "semver-checks")] + pub(crate) fn is_semver_checked(&self) -> bool { let toml = self.toml(); let Some(ref toml) = *toml else { // No Cargo.toml in the package, must be the examples @@ -608,13 +642,24 @@ impl Package { } #[cfg(feature = "semver-checks")] - pub(crate) fn clean_semver_check(&self, dest_path: &Path) -> anyhow::Result<()> { - if self == &Package::EspRomSys && dest_path.exists() { - fs::remove_file(dest_path) + pub(crate) fn has_semver_config(&self) -> bool { + let toml = self.toml(); + let Some(ref toml) = *toml else { + return false; + }; + toml.espressif_metadata() + .is_some_and(|m| m.contains_key("semver-config")) + } + + #[cfg(feature = "semver-checks")] + pub(crate) fn clean_semver_check(&self, package_path: &Path) -> anyhow::Result<()> { + let dest_path = package_path.join("src/generated_rom_symbols.rs"); + if dest_path.exists() { + fs::remove_file(&dest_path) .context("Failed to remove existing generated_rom_symbols.rs")?; // Create new file with placeholder content - fs::write(dest_path, "// Do not delete - placeholder for fmt!\n") + fs::write(&dest_path, "// Do not delete - placeholder for fmt!\n") .context("Failed to create new generated_rom_symbols.rs placeholder")?; } @@ -627,9 +672,9 @@ impl Package { package_path: &Path, chip: &Chip, ) -> anyhow::Result<()> { - if self == &Package::EspRomSys { + if package_path.join("src/generated_rom_symbols.rs").exists() { log::info!("Generating ROM symbol markers for chip: {}", chip); - crate::commands::generate_rom_symbols::generate_rom_symbols(&package_path, chip)?; + crate::commands::generate_rom_symbols::generate_rom_symbols(package_path, chip)?; } Ok(()) } @@ -707,14 +752,24 @@ pub fn generate_build_command( if !features.is_empty() { log::info!(" Features: {}", features.join(", ")); } - features.push(chip.to_string()); - let cwd = if package_path.ends_with("examples") || package_path.ends_with("compile-tests") { + // A standalone project is a directory with its own manifest, anything else is a source file + // inside the package. + let standalone_project = package.extension().is_none(); + + let cwd = if standalone_project { package_path.join(package).to_path_buf() } else { package_path.to_path_buf() }; + // Host-package and self-contained builds enable the bare chip feature; + // metadata-driven compile-tests have no per-chip `[features]` table and carry + // the chip through forwarded `/` features, so it must not be added. + if !standalone_project || firmware::project_has_chip_feature_table(&cwd) { + features.push(chip.to_string()); + } + let mut builder = CargoArgsBuilder::new(app.output_file_name()) .manifest_path(cwd.join("Cargo.toml")) .config_path(cwd.join(".cargo").join("config.toml")) @@ -730,7 +785,7 @@ pub fn generate_build_command( let bin_arg = if package.starts_with("src/bin") { Some(format!("--bin={}", app.binary_name())) - } else if !package_path.ends_with("examples") && !package_path.ends_with("compile-tests") { + } else if !standalone_project { Some(format!("--example={}", app.binary_name())) } else { None @@ -821,28 +876,6 @@ pub fn copy_dir_all(src: impl AsRef, dst: impl AsRef) -> Result<()> Ok(()) } -/// Return a (sorted) list of paths to each valid Cargo package in the -/// workspace. -pub fn package_paths(workspace: &Path) -> Result> { - let mut paths = Vec::new(); - for entry in fs::read_dir(workspace).context("Failed to read {workspace}")? { - let entry = entry?; - if entry.file_type()?.is_dir() && entry.path().join("Cargo.toml").exists() { - paths.push(entry.path()); - } - } - - paths.sort(); - - log::debug!( - "Found {} packages in workspace '{}':", - paths.len(), - workspace.display() - ); - - Ok(paths) -} - /// Parse the version from the specified package's Cargo manifest. pub fn package_version(_workspace: &Path, package: Package) -> Result { let toml = package.toml(); @@ -865,7 +898,7 @@ pub fn format_package( format_rules: Option<&Path>, ) -> Result<()> { log::info!("Formatting package: {}", package); - let package_path = workspace.join(package.as_ref()); + let package_path = workspace.join(package.directory()); let paths = if package.contains_standalone_projects() { crate::find_packages(&package_path)? @@ -884,100 +917,41 @@ pub fn format_package( /// Run the host tests for the specified package. /// /// Called by `cargo xtask host-tests` for every package where [`Package::has_host_tests`] -/// is true. **When adding `#[test]` functions to a package, add a match arm here** -/// with the correct `cargo test` flags/features. See `xtask/README.md` ("Host tests"). +/// is true. Driven by `host-test-configs` in `[package.metadata.espressif]`. +/// See `xtask/README.md` ("Host tests"). pub fn run_host_tests(workspace: &Path, package: Package) -> Result<()> { log::info!("Running host tests for package: {}", package); - let package_path = workspace.join(package.as_ref()); - - let cmd = CargoArgsBuilder::default(); - - match package { - Package::EspConfig => cargo::run( - &cmd.clone() - .subcommand("test") - .features(&["build".into(), "tui".into()]) - .build(), - &package_path, - ), - - Package::EspBootloaderEspIdf => cargo::run( - &cmd.clone() - .subcommand("test") - .arg("--lib") - .arg("--tests") - .features(&["std".into(), "embedded-storage".into()]) - .arg("--") - .arg("--test-threads=1") - .build(), - &package_path, - ), - - Package::EspStorage => { - cargo::run( - &cmd.clone() - .subcommand("test") - .features(&["emulation".into()]) - .arg("--") - .arg("--test-threads=1") - .build(), - &package_path, - )?; - - cargo::run( - &cmd.clone() - .subcommand("test") - .features(&["emulation".into(), "bytewise-read".into()]) - .arg("--") - .arg("--test-threads=1") - .build(), - &package_path, - )?; + let package_path = workspace.join(package.directory()); - log::info!("Running miri host tests for package: {}", package); + let configs = package.host_test_config_rules(); + if configs.is_empty() { + return Err(anyhow!( + "Instructions for host testing were not provided in Cargo.toml (`host-test-configs`) for: '{}'", + package, + )); + } - cargo::run( - &cmd.clone() - .toolchain("nightly") - .subcommand("miri") - .subcommand("test") - .features(&["emulation".into()]) - .arg("--") - .arg("--test-threads=1") - .build(), - &package_path, - )?; - - cargo::run( - &cmd.clone() - .toolchain("nightly") - .subcommand("miri") - .subcommand("test") - .features(&["emulation".into(), "bytewise-read".into()]) - .arg("--") - .arg("--test-threads=1") - .build(), - &package_path, - ) + for config in configs { + let mut cmd = CargoArgsBuilder::default(); + if config.miri { + log::info!("Running miri host tests for package: {}", package); + cmd = cmd.toolchain("nightly").subcommand("miri"); } - Package::EspHalProcmacros => cargo::run( - &cmd.clone() - .subcommand("test") - .features(&[ - "has-lp-core".into(), - "is-lp-core".into(), - "rtc-slow".into(), - "rtc-fast".into(), - ]) - .build(), - &package_path, - ), - Package::EspMetadata => cargo::run(&cmd.clone().subcommand("test").build(), &package_path), - _ => Err(anyhow!( - "Instructions for host testing were not provided for: '{}'", - package, - )), + cmd = cmd.subcommand("test"); + for arg in &config.cargo_args { + cmd = cmd.arg(arg); + } + cmd = cmd.features(&config.features); + if !config.test_args.is_empty() { + cmd = cmd.arg("--"); + for arg in &config.test_args { + cmd = cmd.arg(arg); + } + } + cargo::run(&cmd.build(), &package_path)?; } + + Ok(()) } /// How many times an operation that writes source files is attempted before @@ -989,7 +963,10 @@ const WRITE_ATTEMPTS: usize = 5; /// Writing files can transiently fail if another process (an editor, a virus /// scanner, ...) holds a lock on them, so give the lock a chance to disappear /// before propagating the error. -fn retry_on_failure(what: &str, mut operation: impl FnMut() -> Result) -> Result { +pub(crate) fn retry_on_failure( + what: &str, + mut operation: impl FnMut() -> Result, +) -> Result { for attempt in 1..=WRITE_ATTEMPTS { match operation() { Ok(value) => return Ok(value), @@ -1184,18 +1161,171 @@ pub(crate) fn repo_root_for_tests() -> PathBuf { .to_path_buf() } +/// Spawn `command`, capture stdout/stderr, kill it if it exceeds `timeout`. +pub(crate) fn run_command_with_output_timeout( + mut command: Command, + name: &str, + timeout: Duration, +) -> Result { + let mut child = command + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .map_err(|e| anyhow!("Failed to spawn {name}: {e}"))?; + let start = Instant::now(); + + loop { + if child.try_wait()?.is_some() { + return child + .wait_with_output() + .map_err(|e| anyhow!("Failed to collect {name} output: {e}")); + } + + if start.elapsed() > timeout { + let _ = child.kill(); + let _ = child.wait(); + bail!("{name} timed out after {}s", timeout.as_secs()); + } + + thread::sleep(Duration::from_millis(100)); + } +} + #[cfg(test)] mod tests { + use std::collections::{BTreeMap, BTreeSet}; + use strum::IntoEnumIterator; use super::*; + fn split_chip_suffix(name: &str) -> Option<(&str, String)> { + // `esp32` is a suffix of `esp32c5`, so the longest match is the right one. + let chip = Chip::iter() + .map(|chip| chip.to_string()) + .filter(|chip| name.ends_with(chip.as_str())) + .max_by_key(String::len)?; + + Some((&name[..name.len() - chip.len()], chip)) + } + + /// Chips that the manifest declares a dependency for, grouped by shared prefix. + fn declared_chip_dependencies(toml: &mut CargoToml) -> BTreeMap> { + let mut declared = BTreeMap::>::new(); + + toml.visit_dependencies(|_, _, table| { + for (name, _) in table.iter() { + if let Some((prefix, chip)) = split_chip_suffix(name) { + declared.entry(prefix.to_owned()).or_default().insert(chip); + } + } + }); + + declared + } + + /// Chips that each feature forwards to, keyed by feature, prefix and forwarded feature. + fn forwarded_chip_features( + toml: &CargoToml, + ) -> BTreeMap<(String, String, String), BTreeSet> { + let mut forwarded = BTreeMap::<_, BTreeSet<_>>::new(); + + let Some(Item::Table(features)) = toml.manifest.get("features") else { + return forwarded; + }; + + for (feature, entries) in features.iter() { + let Item::Value(Value::Array(entries)) = entries else { + continue; + }; + + for entry in entries { + let Some((dependency, forwarded_feature)) = + entry.as_str().and_then(|entry| entry.split_once('/')) + else { + continue; + }; + + let dependency = dependency.strip_suffix('?').unwrap_or(dependency); + let Some((prefix, chip)) = split_chip_suffix(dependency) else { + continue; + }; + + forwarded + .entry(( + feature.to_owned(), + prefix.to_owned(), + forwarded_feature.to_owned(), + )) + .or_default() + .insert(chip); + } + } + + forwarded + } + + /// Whether the per-chip dependency of `chip` should receive `forwarded_feature`. + fn chip_expects_feature(chip: &str, forwarded_feature: &str) -> bool { + let symbol = format!("{}_driver_supported", forwarded_feature.replace('-', "_")); + if !Chip::all_symbols().contains(&symbol) { + return true; + } + + let chip = chip + .parse::() + .unwrap_or_else(|_| panic!("unknown chip `{chip}`")); + + Config::for_chip(&chip).symbols.contains(&symbol) + } + + #[test] + fn chip_coverage_dependency_features_are_forwarded() { + let mut problems = Vec::new(); + + for package in Package::iter() { + let mut toml = package.toml(); + let Some(toml) = toml.as_mut() else { + continue; + }; + + let declared = declared_chip_dependencies(toml); + + for ((feature, prefix, forwarded_feature), chips) in forwarded_chip_features(toml) { + let Some(declared) = declared.get(&prefix) else { + continue; + }; + + let missing = declared + .difference(&chips) + .filter(|chip| chip_expects_feature(chip, &forwarded_feature)) + .collect::>(); + if !missing.is_empty() { + problems.push(format!( + "{package}: feature `{feature}` forwards `{prefix}?/{forwarded_feature}`, but not for {missing:?}" + )); + } + } + } + + assert!(problems.is_empty(), "{}", problems.join("\n")); + } + + #[test] + fn chip_coverage_dependency_feature_support() { + assert!(chip_expects_feature("esp32", "wifi")); + assert!(!chip_expects_feature("esp32h2", "wifi")); + assert!(chip_expects_feature("esp32h2", "bt")); + assert!(!chip_expects_feature("esp32s2", "bt")); + assert!(chip_expects_feature("esp32s2", "defmt")); + } + #[test] fn packages_are_either_crates_or_collections_of_standalone_projects() { let workspace = repo_root_for_tests(); for package in Package::iter() { - let package_path = workspace.join(package.to_string()); + let package_path = workspace.join(package.directory()); assert!( package_path.is_dir(), "package '{package}' has no directory at {}", @@ -1211,6 +1341,50 @@ mod tests { package.contains_standalone_projects(), ); } + + assert_eq!(Package::QaTest.to_string(), "qa-test"); + assert_eq!(Package::QaTest.directory(), "examples/qa"); + } + + #[test] + fn chip_coverage_standalone_projects_declare_required_chips() { + let workspace = repo_root_for_tests(); + + for package in Package::iter().filter(Package::contains_standalone_projects) { + crate::firmware::load_package(&workspace, package) + .unwrap_or_else(|err| panic!("failed to load '{package}': {err}")); + } + } + + #[test] + fn chip_coverage_missing_chip_is_an_error_for_feature_table_projects() { + let omitted = Chip::Esp32c61; + + // A project with a `[features]` chip table and no CHIP_FILTER must list every chip, + // otherwise a newly added chip silently drops out of its coverage. + let with_table = tempfile::TempDir::new().unwrap(); + let project = with_table.path().join("with-features"); + fs::create_dir_all(project.join("src")).unwrap(); + let mut features = String::from("[features]\n"); + for chip in Chip::iter() { + if chip != omitted { + features.push_str(&format!("{chip} = []\n")); + } + } + fs::write(project.join("Cargo.toml"), features).unwrap(); + fs::write(project.join("src").join("main.rs"), "fn main() {}\n").unwrap(); + + let err = crate::firmware::load_cargo_toml(with_table.path()).unwrap_err(); + assert!(format!("{err:#}").contains(&format!("{omitted:?}"))); + + // A project without a `[features]` table (compile-tests shape) is exempt: its chips ride + // on CHIP_FILTER and forwarded `/` features, not a per-chip table. + let without_table = tempfile::TempDir::new().unwrap(); + let project = without_table.path().join("without-features"); + fs::create_dir_all(project.join("src")).unwrap(); + fs::write(project.join("Cargo.toml"), "[dependencies]\n").unwrap(); + fs::write(project.join("src").join("main.rs"), "fn main() {}\n").unwrap(); + crate::firmware::load_cargo_toml(without_table.path()).unwrap(); } #[test] @@ -1218,7 +1392,7 @@ mod tests { let workspace = repo_root_for_tests(); for package in Package::iter().filter(Package::contains_standalone_projects) { - let projects = find_packages(&workspace.join(package.to_string())) + let projects = find_packages(&workspace.join(package.directory())) .unwrap_or_else(|err| panic!("could not enumerate projects of '{package}': {err}")); assert!( diff --git a/xtask/src/main.rs b/xtask/src/main.rs index f79945dfbae..e5d8a7ffe45 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -1,20 +1,11 @@ -use std::{ - path::{Path, PathBuf}, - process::Command, - time::Instant, -}; - -use anyhow::{Context, Result, bail}; +use anyhow::{Context, Result}; use clap::{Args, Parser}; use esp_devtool as xtask; -use object::{Object, ObjectSymbol, SymbolKind, read::archive::ArchiveFile}; -use rustc_demangle::try_demangle; use strum::IntoEnumIterator; use xtask::{ Package, - cargo::{CargoAction, CargoArgsBuilder, CargoCommandBatcher}, - commands::*, - metadata::{Chip, Config}, + commands::{dispatch::Verb, *}, + metadata::Chip, }; // ---------------------------------------------------------------------------- @@ -22,12 +13,25 @@ use xtask::{ #[derive(Debug, Parser)] enum Cli { - /// Build-related subcommands - #[clap(subcommand)] - Build(Build), - /// Run-related subcommands - #[clap(subcommand)] - Run(Run), + /// Build examples or HIL tests. + Build(DispatchArgs), + /// Run an example or qa binary. + Run(DispatchArgs), + /// Check crates, or try-build examples and tests. + #[clap(alias = "check-packages")] + Check(DispatchArgs), + /// Run HIL tests. + Test(DispatchArgs), + /// Build rustdoc for the specified packages and chips. + #[clap(alias = "docs", alias = "doc")] + Documentation(BuildDocumentationArgs), + /// Build the documentation index. + #[cfg(feature = "deploy-docs")] + DocumentationIndex(BuildDocumentationIndexArgs), + /// Run rustdoc tests for the specified chip. + DocTests(DocTestArgs), + /// Run prebuilt ELFs with probe-rs. + Elfs(RunElfsArgs), /// Release-related subcommands #[clap(subcommand)] Release(Release), @@ -35,13 +39,12 @@ enum Cli { /// Perform (parts of) the checks done in CI Ci(CiArgs), /// Format all packages in the workspace with rustfmt - #[clap(alias = "format-packages")] + #[clap(name = "fmt", alias = "fmt-packages", alias = "format-packages")] FmtPackages(FmtPackagesArgs), /// Run cargo clean Clean(CleanArgs), - /// Check all packages in the workspace with cargo check - CheckPackages(CheckPackagesArgs), /// Lint all packages in the workspace with clippy + #[clap(name = "lint", alias = "lint-packages")] LintPackages(LintPackagesArgs), /// Semver Checks SemverCheck(SemverCheckArgs), @@ -53,12 +56,12 @@ enum Cli { CheckPrChangelog(CheckPrChangelogArgs), /// Run host-tests in the workspace with `cargo test` HostTests(HostTestsArgs), - /// Check global symbols in the compiled `.rlib` of the specified packages for the specified - /// chips. - CheckGlobalSymbols(CheckPackagesArgs), - #[cfg(feature = "report")] - /// Generate reports from CI data. - GenerateReport(generate_report::ReportArgs), + /// Check global symbols in the compiled `.rlib` of esp-hal for the given chips. + CheckGlobalSymbols { + /// Chip(s) to check. Omitted means every chip. + #[arg(value_enum, value_delimiter = ',', default_values_t = Chip::iter())] + chips: Vec, + }, /// Tasks for checking compile tests with a local registry. #[cfg(feature = "rel-check")] #[clap(subcommand)] @@ -81,7 +84,7 @@ struct CheckPrChangelogArgs { #[derive(Debug, Args)] struct CheckChangelogArgs { /// Package(s) to tag. - #[arg(long, value_enum, value_delimiter = ',', default_values_t = Package::iter())] + #[arg(long, alias = "package", value_enum, value_delimiter = ',', default_values_t = Package::iter())] packages: Vec, /// Re-generate the changelog with consistent formatting. @@ -119,31 +122,28 @@ fn main() -> Result<()> { } match Cli::parse() { - // Build-related subcommands: - Cli::Build(build) => match build { - Build::Documentation(args) => build_documentation(&workspace, args), - #[cfg(feature = "deploy-docs")] - Build::DocumentationIndex(args) => build_documentation_index(&workspace, args), - Build::Examples(args) => examples(&workspace, args, CargoAction::Build(None)), - Build::Package(args) => build_package(&workspace, args), - Build::Tests(args) => tests( - &workspace, - args, - CargoAction::Build(Some(target_path.join("tests"))), - ), - }, - - // Run-related subcommands: - Cli::Run(run) => match run { - Run::DocTests(args) => run_doc_tests(&workspace, args), - Run::Elfs(args) => run_elfs(args), - Run::Example(args) => examples(&workspace, args, CargoAction::Run), - Run::Tests(args) => tests(&workspace, args, CargoAction::Run), - }, + Cli::Build(args) => dispatch::dispatch(&workspace, Verb::Build, args, |args| { + check_packages(&workspace, args) + }), + Cli::Run(args) => dispatch::dispatch(&workspace, Verb::Run, args, |args| { + check_packages(&workspace, args) + }), + Cli::Check(args) => dispatch::dispatch(&workspace, Verb::Check, args, |args| { + check_packages(&workspace, args) + }), + Cli::Test(args) => dispatch::dispatch(&workspace, Verb::Test, args, |args| { + check_packages(&workspace, args) + }), + Cli::Documentation(args) => build_documentation(&workspace, args), + #[cfg(feature = "deploy-docs")] + Cli::DocumentationIndex(args) => build_documentation_index(&workspace, args), + Cli::DocTests(args) => run_doc_tests(&workspace, args), + Cli::Elfs(args) => run_elfs(args), // Release-related subcommands: Cli::Release(release) => match release { Release::ChangelogPreview(args) => changelog_preview(&workspace, args), + #[cfg(feature = "release")] Release::BumpVersion(args) => bump_version(&workspace, args), Release::TagReleases(args) => tag_releases(&workspace, args), Release::Publish(args) => publish(&workspace, args), @@ -162,15 +162,12 @@ fn main() -> Result<()> { Cli::Ci(args) => run_ci_checks(&workspace, args), Cli::FmtPackages(args) => fmt_packages(&workspace, args), Cli::Clean(args) => clean(&workspace, args), - Cli::CheckPackages(args) => check_packages(&workspace, args), Cli::LintPackages(args) => lint_packages(&workspace, args), Cli::SemverCheck(args) => semver_checks(&workspace, args), Cli::CheckChangelog(args) => check_changelog(&workspace, &args.packages, args.normalize), Cli::CheckPrChangelog(args) => check_pr_changelog(&workspace, args.pr), Cli::HostTests(args) => host_tests(&workspace, args), - Cli::CheckGlobalSymbols(args) => check_global_symbols(&args.chips), - #[cfg(feature = "report")] - Cli::GenerateReport(args) => generate_report::generate_report(&workspace, args), + Cli::CheckGlobalSymbols { chips } => check_global_symbols(&chips), #[cfg(feature = "rel-check")] Cli::RelCheck(relcheck) => relcheck::run_rel_check(relcheck), @@ -181,750 +178,3 @@ fn main() -> Result<()> { .block_on(xtask::commands::mcp::run_mcp_server()), } } - -// ---------------------------------------------------------------------------- -// Subcommands - -fn fmt_packages(workspace: &Path, args: FmtPackagesArgs) -> Result<()> { - let mut packages = args.packages; - packages.sort(); - - for package in packages { - xtask::format_package(workspace, package, args.check, None)?; - } - - // Keep formatting "helper" crates that are intentionally not in - // the Package enum. - for package_path in ["xtask", "xtask-mcp-macros"] { - log::info!("Formatting package: {}", package_path); - xtask::format_package_path(workspace, &workspace.join(package_path), args.check, None)?; - } - - // format ymls in .github/ - xtask::format_yml(args.check, "./.github")?; - - Ok(()) -} - -fn clean(workspace: &Path, args: CleanArgs) -> Result<()> { - let mut packages = args.packages; - packages.sort(); - - for package in packages { - let path = workspace.join(package.to_string()); - for dir in walkdir::WalkDir::new(path) { - if let Ok(dir) = dir - && let path = dir.path() - && path.join("Cargo.toml").exists() - { - log::info!("Cleaning folder: {}", path.display()); - let cargo_args = CargoArgsBuilder::default() - .subcommand("clean") - .arg("--target-dir") - .arg(path.join("target").display().to_string()) - .build(); - - xtask::cargo::run(&cargo_args, path).with_context(|| { - format!( - "Failed to run `cargo run` with {cargo_args:?} in {}", - path.display() - ) - })?; - } - } - } - - Ok(()) -} - -fn check_packages(workspace: &Path, args: CheckPackagesArgs) -> Result<()> { - log::debug!("Checking packages: {:?}", args.packages); - let mut packages = args.packages; - packages.sort(); - - let mut commands = CargoCommandBatcher::new(); - - for package in packages.iter().filter(|p| p.is_published()) { - // Unfortunately each package has its own unique requirements for - // building, so we need to handle each individually (though there - // is *some* overlap) - for chip in &args.chips { - log::debug!(" for chip: {}", chip); - let device = Config::for_chip(chip); - - if let Err(e) = package.validate_package_chip(chip) { - log::warn!("{e}. Skipping"); - continue; - } - - for mut check_config in package.check_config_rules(device) { - if package.has_chip_features() { - check_config.features.push(device.name.clone()); - } - - commands.push(build_check_package_command( - workspace, - *package, - chip, - &["--no-default-features"], - &check_config, - args.toolchain.as_deref(), - )?); - } - } - } - - for c in commands.build(false) { - println!( - "Command: cargo {}", - c.command.join(" ").replace("---", "\n ---") - ); - c.run(false)?; - } - - Ok(()) -} - -fn build_check_package_command( - workspace: &Path, - package: Package, - chip: &Chip, - args: &[&str], - check_config: &xtask::CheckConfig, - mut toolchain: Option<&str>, -) -> Result { - log::info!( - "Checking package: {} ({}, features: {:?}, env: {:?})", - package, - chip, - check_config.features, - check_config.env - ); - - let path = workspace.join(package.to_string()); - let features = &check_config.features; - - let mut builder = CargoArgsBuilder::default() - .subcommand("check") - .manifest_path(path.join("Cargo.toml")); - - if !package.build_on_host(features) { - if chip.is_xtensa() { - // In case the user doesn't specify a toolchain, make sure we use +esp - toolchain.get_or_insert("esp"); - } - builder = builder.target(package.target_triple(chip)?); - } - - if let Some(toolchain) = toolchain { - if !package.build_on_host(features) && toolchain.starts_with("esp") { - builder = builder.config("-Zbuild-std=core,alloc"); - } - builder = builder.toolchain(toolchain); - } - - builder = builder.args(args); - - if !features.is_empty() { - builder = builder.arg(format!("--features={}", features.join(","))); - } - - for (key, value) in &check_config.env { - builder.add_env_var(key, value); - } - // TODO: these should come from the outside - builder.add_env_var("CI", "1"); - builder.add_env_var("DEFMT_LOG", "trace"); - builder.add_env_var("ESP_LOG", "trace"); - - Ok(builder) -} - -fn lint_packages(workspace: &Path, args: LintPackagesArgs) -> Result<()> { - log::debug!("Linting packages: {:?}", args.packages); - let mut packages = args.packages; - packages.sort(); - - for package in packages.iter().filter(|p| p.is_published()) { - // Unfortunately each package has its own unique requirements for - // building, so we need to handle each individually (though there - // is *some* overlap) - for chip in &args.chips { - log::debug!(" for chip: {}", chip); - let device = Config::for_chip(chip); - - if let Err(e) = package.validate_package_chip(chip) { - log::warn!("{e}. Skipping"); - continue; - } - - for mut check_config in package.lint_config_rules(device) { - if package.has_chip_features() { - check_config.features.push(device.name.clone()); - } - - lint_package( - workspace, - *package, - chip, - &["--no-default-features"], - &check_config, - args.fix, - args.toolchain.as_deref(), - )?; - } - } - } - - Ok(()) -} - -fn lint_package( - workspace: &Path, - package: Package, - chip: &Chip, - args: &[&str], - check_config: &xtask::CheckConfig, - fix: bool, - mut toolchain: Option<&str>, -) -> Result<()> { - log::info!( - "Linting package: {} ({}, features: {:?}, env: {:?})", - package, - chip, - check_config.features, - check_config.env - ); - - let path = workspace.join(package.to_string()); - let features = &check_config.features; - - let mut builder = CargoArgsBuilder::default() - .subcommand("clippy") - .manifest_path(path.join("Cargo.toml")); - - if !package.build_on_host(features) { - if chip.is_xtensa() { - // In case the user doesn't specify a toolchain, make sure we use +esp - toolchain.get_or_insert("esp"); - } - builder = builder.target(package.target_triple(chip)?); - } - - if let Some(toolchain) = toolchain { - if !package.build_on_host(features) && toolchain.starts_with("esp") { - builder = builder.config("-Zbuild-std=core,alloc"); - } - builder = builder.toolchain(toolchain); - } - - for arg in args { - builder = builder.arg(arg.to_string()); - } - - if !features.is_empty() { - builder = builder.arg(format!("--features={}", features.join(","))); - } - - let mut builder = if fix { - builder.arg("--fix").arg("--lib").arg("--allow-dirty") - } else { - builder.arg("--").arg("-D").arg("warnings").arg("--no-deps") - }; - - for (key, value) in &check_config.env { - builder.add_env_var(key, value); - } - builder.add_env_var("CI", "1"); - builder.add_env_var("DEFMT_LOG", "trace"); - - let command = CargoCommandBatcher::build_one_for_cargo(&builder); - xtask::cargo::run_with_env(&command.command, &path, command.env_vars, false) - .with_context(|| format!("Failed to run `cargo clippy` in {}", path.display()))?; - - Ok(()) -} - -struct Runner { - failed: Vec<&'static str>, - started_at: Instant, - skip_steps: Vec, - run_steps: Vec, - steps_executed: usize, -} - -impl Runner { - fn new(options: &CiArgs) -> Self { - Self { - failed: Vec::new(), - started_at: Instant::now(), - skip_steps: { - let mut skip = vec![]; - if options.no_lint { - skip.push(String::from("lint")); - } - if options.no_docs { - skip.push(String::from("docs")); - skip.push(String::from("doc-tests")); - } - if options.no_check_crates { - skip.push(String::from("check")); - } - skip - }, - run_steps: options.steps.clone(), - steps_executed: 0, - } - } - - fn run(&mut self, id: &str, group: &'static str, op: impl FnOnce() -> Result<()>) { - if self.skip_steps.iter().any(|s| s == id) { - log::debug!("{group} skipped by user request"); - return; - } - if !self.run_steps.is_empty() && !self.run_steps.iter().any(|s| s == id) { - log::debug!("{group} skipped by user request"); - return; - } - - self.steps_executed += 1; - - // Output grouped logs - // https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-commands#grouping-log-lines - println!("::group::{group}"); - if let Err(e) = op() { - log::error!("{group} failed: {e:?}"); - self.failed.push(group); - } else { - log::debug!("{group} succeeded"); - } - println!("::endgroup::"); - } - - fn finish(self) -> Result<()> { - fn write_summary(message: &str) { - if let Some(summary_file) = std::env::var_os("GITHUB_STEP_SUMMARY") { - std::fs::write(summary_file, message).unwrap(); - } - } - - let expected_to_run = self - .run_steps - .iter() - .filter(|s| !self.skip_steps.contains(s)) - .cloned() - .collect::>(); - if self.steps_executed == 0 && !expected_to_run.is_empty() { - bail!( - "The following steps were requested but not executed: {}. Perhaps they contain typos?", - expected_to_run.join(", ") - ); - } - - log::info!("CI checks completed in {:?}", self.started_at.elapsed()); - - if !self.failed.is_empty() { - let mut summary = String::new(); - summary.push_str("# Summary of failed CI checks\n"); - for failed_check in self.failed { - summary.push_str(&format!("* {failed_check}\n")); - } - println!("{summary}"); - write_summary(&summary); - bail!("CI checks failed"); - } - - Ok(()) - } -} - -fn run_ci_checks(workspace: &Path, args: CiArgs) -> Result<()> { - log::info!("Running CI checks for chip: {}", args.chip); - println!("::add-matcher::.github/rust-matchers.json"); - - let run_locally = !std::env::var("CI").is_ok(); - - let mut runner = Runner::new(&args); - - if !run_locally && args.steps.is_empty() { - runner.skip_steps.push(String::from("tests")); - } - - unsafe { - std::env::set_var("CI", "true"); - } - - runner.run("check", "Check crates", || { - check_packages( - workspace, - CheckPackagesArgs { - packages: Package::iter().collect(), - chips: vec![args.chip], - toolchain: args.toolchain.clone(), - }, - ) - }); - - runner.run("lint", "Lint", || { - lint_packages( - workspace, - LintPackagesArgs { - packages: Package::iter().collect(), - chips: vec![args.chip], - fix: false, - toolchain: args.toolchain.clone(), - }, - ) - }); - - runner.run("doc-tests", "Run Doc Test", || { - run_doc_tests( - workspace, - DocTestArgs { - packages: Package::iter().collect(), - chip: args.chip, - }, - ) - }); - - runner.run("docs", "Build Docs", || { - build_documentation( - workspace, - BuildDocumentationArgs { - packages: vec![Package::EspHal, Package::EspRadio, Package::EspRtos], - chips: vec![args.chip], - ..Default::default() - }, - ) - }); - - // for chips with esp-lp-hal: Build all supported examples for the low-power - // core first - if args.chip.has_lp_core() { - // Build prerequisite examples (esp-lp-hal) - // `examples` copies the examples to a folder with the chip name as the last - // path element then we copy it to the place where the HP core example - // expects it - runner.run("lp-examples", "Build LP-HAL Examples", || { - // The LP examples aren't really that demanding, but they need to be at a certain place. - // Instead of trying to figure out where the results are, let's just make sure the - // target folder is set up as expected. - let original_target_dir = std::env::var("CARGO_TARGET_DIR"); - - unsafe { - std::env::set_var( - "CARGO_TARGET_DIR", - workspace.join("esp-lp-hal").join("target"), - ); - } - let result = examples( - workspace, - ExamplesArgs { - package: ExamplesPackage::EspLpHal, - chip: Some(args.chip), - example: Some("all".to_string()), - debug: false, - toolchain: args.toolchain.clone(), - timings: false, - }, - CargoAction::Build(None), - ); - - // Still need to rename examples to remove the fingerprint off of their names: - let dir = workspace - .join("esp-lp-hal") - .join("target") - .join(Package::EspLpHal.target_triple(&args.chip)?) - .join("release") - .join("examples"); - let examples = dir - .read_dir() - .with_context(|| format!("Failed to read examples directory: {}", dir.display()))?; - for example in examples { - let example = example.context("Failed to read example")?; - let example_path = example.path(); - if example - .file_type() - .with_context(|| { - format!( - "Failed to get file type for example: {}", - example_path.display() - ) - })? - .is_file() - && example_path.extension().is_none() - { - let example_name = example.file_name().to_string_lossy().to_string(); - let Some((without_fingerprint, fingerprint)) = example_name.rsplit_once('-') - else { - // Skip non-fingerprinted files to avoid self-copying - // artifacts (for example "blinky" -> "blinky"). - continue; - }; - // Cargo fingerprints are hexadecimal, so only rewrite files - // that actually look like fingerprinted artifacts. - if !fingerprint.chars().all(|c| c.is_ascii_hexdigit()) { - continue; - } - - let dst = dir.join(without_fingerprint); - - if dst.exists() { - std::fs::remove_file(&dst).with_context(|| { - format!( - "Failed to remove destination file {} before copying", - dst.display() - ) - })?; - } - - log::debug!("Copying {} to {}", example_path.display(), dst.display()); - - // Copy so we don't trigger a rebuild unnecessarily by deleting the original - std::fs::copy(&example_path, &dst).with_context(|| { - format!( - "Failed to copy example: {} to {}", - example_path.display(), - dst.display() - ) - })?; - // Check that the destination file matches the source file - let dst_contents = std::fs::read(&dst).with_context(|| { - format!("Failed to read destination file: {}", dst.display()) - })?; - let src_contents = std::fs::read(&example_path).with_context(|| { - format!("Failed to read source file: {}", example_path.display()) - })?; - if dst_contents != src_contents { - return Err(anyhow::anyhow!( - "Destination file {} does not match source file {}", - dst.display(), - example_path.display() - )); - } - } - } - - // Restore the original target directory - unsafe { - if let Ok(target) = original_target_dir { - std::env::set_var("CARGO_TARGET_DIR", target); - } else { - std::env::remove_var("CARGO_TARGET_DIR"); - } - } - - result - }); - - // Check documentation. Reuse the "docs" ID, as the docs build should include all applicable - // packages. - runner.run("docs", "Build LP-HAL docs", || { - build_documentation( - workspace, - BuildDocumentationArgs { - packages: vec![Package::EspLpHal], - chips: vec![args.chip], - ..Default::default() - }, - ) - }); - } - - runner.run("examples", "Build examples", || { - // The `ota_example` expects a file named `target/ota_image` - it doesn't - // care about the contents however - std::fs::create_dir_all("./target") - .with_context(|| "Failed to create `./target`".to_string())?; - std::fs::write("./target/ota_image", "DUMMY").with_context(|| { - "Failed to create a dummy file required by ota example!".to_string() - })?; - - examples( - workspace, - ExamplesArgs { - package: ExamplesPackage::Examples, - chip: Some(args.chip), - example: Some("all".to_string()), - debug: true, - toolchain: args.toolchain.clone(), - timings: false, - }, - CargoAction::Build(None), - ) - }); - - runner.run("qa-test", "Build qa-test", || { - examples( - workspace, - ExamplesArgs { - package: ExamplesPackage::QaTest, - chip: Some(args.chip), - example: Some("all".to_string()), - debug: true, - toolchain: args.toolchain.clone(), - timings: false, - }, - CargoAction::Build(None), - ) - }); - - // Try-build tests - runner.run("tests", "Build tests", || { - let target_path = workspace.join("target"); - - tests( - workspace, - TestsArgs { - chip: args.chip, - repeat: 1, - test: None, - toolchain: None, - timings: false, - package: "hil-test".to_string(), - }, - CargoAction::Build(Some(target_path.join("tests"))), - )?; - - tests( - workspace, - TestsArgs { - chip: args.chip, - repeat: 1, - test: None, - toolchain: None, - timings: false, - package: "hil-test-radio".to_string(), - }, - CargoAction::Build(Some(target_path.join("tests"))), - ) - }); - - runner.finish() -} - -fn host_tests(workspace: &Path, args: HostTestsArgs) -> Result<()> { - let mut packages = args.packages; - packages.sort(); - - for package in packages { - log::debug!("Running host-tests for package: {}", package); - if package.has_host_tests(workspace) { - xtask::run_host_tests(workspace, package)?; - } - } - - Ok(()) -} - -/// Build the given package for the given chip and return its `.rlib path` with `esp` toolchain. -fn build_rlib(package: &str, chip: &str, target: &str) -> Result { - let workspace = std::env::current_dir().with_context(|| "Failed to get the current dir!")?; - Command::new("cargo") - .args([ - "+esp", - "build", - "--no-default-features", - "--features", - chip, - "--target", - target, - "-Zbuild-std=core", - ]) - .current_dir(workspace.join(package)) - .status() - .context("Failed to run cargo build")?; - - let lib_name = format!("lib{}.rlib", package.replace('-', "_")); - let rlib_path = Path::new("target") - .join(target) - .join("debug") - .join(&lib_name); - - if !rlib_path.exists() { - anyhow::bail!("Expected rlib not found: {}", rlib_path.display()); - } - - Ok(rlib_path) -} - -/// Check global symbols in the compiled rlib of the specified packages for the -/// specified chips. Reports any unmangled global symbols that may pollute the -/// global namespace. -fn check_global_symbols(chips: &[Chip]) -> Result<()> { - let mut total_problematic = vec![]; - - let package = Package::EspHal; // Only esp-hal for now - - for chip in chips { - let target = package.target_triple(chip)?; - - let rlib_path = match build_rlib(package.as_ref(), chip.as_ref(), &target) { - Ok(path) => path, - Err(e) => { - println!( - "Failed to build/find rlib for {} on {}: {}", - package, chip, e - ); - continue; - } - }; - - log::info!("Checking global symbols for {} on {}:\n", package, chip); - - let data = std::fs::read(&rlib_path) - .with_context(|| format!("Failed to read {}!", rlib_path.display()))?; - let archive = ArchiveFile::parse(data.as_slice()) - .with_context(|| "Failed to create archive!".to_string())?; - - let mut problematic_symbols: Vec<(String, SymbolKind, usize)> = Vec::new(); - - for member in archive.members().flatten() { - let obj = object::File::parse( - member - .data(data.as_slice()) - .with_context(|| "Failed to parse archive!")?, - )?; - - for symbol in obj.symbols().filter(|s| s.is_global() && s.is_definition()) { - if let Ok(name) = symbol.name() - && try_demangle(name).is_err() - { - let section = symbol.section_index().map(|i| i.0).unwrap_or(0); - problematic_symbols.push((name.to_string(), symbol.kind(), section)); - } - } - } - - if problematic_symbols.is_empty() { - println!("All global symbols are properly mangled Rust symbols\n"); - } else { - println!( - "Found {} potentially problematic global symbols:", - problematic_symbols.len(), - ); - - for (name, kind, _) in &problematic_symbols { - println!("{:?} {}", kind, name); - } - - total_problematic.extend( - problematic_symbols - .into_iter() - .map(|(name, kind, _)| (chip, name, kind)), - ); - } - } - - if !total_problematic.is_empty() { - for (chip, name, kind) in total_problematic.iter() { - println!("{}: {} ({:?})", chip, name, kind); - } - Err(anyhow::anyhow!( - "Found {count} unmangled global symbols across all packages/chips", - count = total_problematic.len() - )) - } else { - Ok(()) - } -} diff --git a/xtask/src/metadata.rs b/xtask/src/metadata.rs index c77ce6ab852..a30d3d74d74 100644 --- a/xtask/src/metadata.rs +++ b/xtask/src/metadata.rs @@ -18,7 +18,7 @@ use anyhow::{Context, Result, bail}; use strum::IntoEnumIterator; /// Cache layout this devtool understands. Must match `esp-metadata`. -const CACHE_VERSION: u32 = 1; +const CACHE_VERSION: u32 = 2; /// Supported devices. #[derive( @@ -44,24 +44,36 @@ pub enum Chip { /// ESP32 Esp32, /// ESP32-C2, ESP8684 + #[value(alias = "c2")] Esp32c2, /// ESP32-C3, ESP8685 + #[value(alias = "c3")] Esp32c3, /// ESP32-C5 + #[value(alias = "c5")] Esp32c5, /// ESP32-C6 + #[value(alias = "c6")] Esp32c6, /// ESP32-C61 + #[value(alias = "c61")] Esp32c61, /// ESP32-H2 + #[value(alias = "h2")] Esp32h2, + /// ESP32-H4 + Esp32h4, /// ESP32-P4 (chip revision v3.x / eco5 only) + #[value(alias = "p4")] Esp32p4, /// ESP32-S2 + #[value(alias = "s2")] Esp32s2, /// ESP32-S3 + #[value(alias = "s3")] Esp32s3, /// ESP32-S31 + #[value(alias = "s31")] Esp32s31, } @@ -104,6 +116,11 @@ impl Chip { } } +/// Pre-rendered HTML peripheral support matrix for the `esp-hal` documentation index. +pub fn peripheral_support_html() -> &'static str { + &cache().peripheral_support_html +} + /// The configuration symbols of a single device. #[derive(Debug, Default, Clone)] pub struct Config { @@ -143,6 +160,7 @@ struct Cache { hash: String, symbols: Vec, kv_symbols: Vec, + peripheral_support_html: String, chips: BTreeMap, } diff --git a/xtask/src/pr_changelog.rs b/xtask/src/pr_changelog.rs index 82aef460822..39ce9693918 100644 --- a/xtask/src/pr_changelog.rs +++ b/xtask/src/pr_changelog.rs @@ -176,6 +176,23 @@ fn parse_section_heading(heading: &str) -> Option<(String, Option)> { } } +/// Is `title` the title of a block that holds sections (`# Changelog`, `# Migration guide`)? +fn is_block_title(title: &str) -> bool { + title.eq_ignore_ascii_case("Changelog") || title.eq_ignore_ascii_case("Migration guide") +} + +/// Error message for an H1 heading inside a block that is not a block title. +/// +/// Such a heading ends the block, so the sections after it would be dropped +/// without notice. `# esp-hal/I2S driver` in place of `## esp-hal/I2S driver` is +/// a typical cause. +fn unexpected_h1(title: &str) -> String { + format!( + "Invalid H1 heading `# {title}`. Section headings must be H2: `## crate` or \ + `## crate/area` in `# Changelog`, `## crate/area` in `# Migration guide`." + ) +} + /// Find or create a `PrSection` for the given crate/area pair. fn get_or_insert_section<'a>( sections: &'a mut Vec, @@ -222,8 +239,11 @@ fn parse_changelog_subsection(text: &str, sections: &mut Vec) -> Resu for line in non_comment_lines(after) { let line = line.trim(); - if line.starts_with("# ") { - break; + if let Some(h1) = line.strip_prefix("# ") { + if is_block_title(h1) { + break; + } + bail!("{}", unexpected_h1(h1)); } else if let Some(h2) = line.strip_prefix("## ") { match parse_section_heading(h2) { Some((crate_name, area)) => current = Some((crate_name, area)), @@ -296,8 +316,11 @@ fn parse_migration_guide_block(body: &str, sections: &mut Vec) -> Res let mut current_lines: Vec<&str> = Vec::new(); for line in non_comment_lines(after) { - if line.starts_with("# ") { - break; + if let Some(h1) = line.strip_prefix("# ") { + if is_block_title(h1) { + break; + } + bail!("{}", unexpected_h1(h1)); } else if let Some(h2) = line.strip_prefix("## ") { flush_migration(sections, ¤t, ¤t_lines); current_lines.clear(); @@ -567,7 +590,10 @@ fn validate_changelog_subsection(after: &str, errors: &mut Vec) { for line in non_comment_lines(after) { let line = line.trim(); - if line.starts_with("# ") { + if let Some(h1) = line.strip_prefix("# ") { + if !is_block_title(h1) { + errors.push(unexpected_h1(h1)); + } break; } else if let Some(h2) = line.strip_prefix("## ") { section_exempted = false; @@ -635,7 +661,10 @@ pub fn validate(body: &str) -> Vec { let mut awaiting_h3 = false; for line in non_comment_lines(after) { - if line.starts_with("# ") { + if let Some(h1) = line.strip_prefix("# ") { + if !is_block_title(h1) { + errors.push(unexpected_h1(h1)); + } break; } else if let Some(h2) = line.strip_prefix("## ") { in_section = false; @@ -942,6 +971,67 @@ Replace all uses of `OldType` with `NewType`. assert_eq!(parse_section_heading(" / Some area"), None); } + /// A section heading written as `# crate/area` instead of `## crate/area` ends + /// the block, which drops every section after it. Both the parser and the + /// validator must report it. + #[test] + fn rejects_h1_section_heading() { + let body = "\ +# Migration guide + +# esp-hal/I2S driver + +### I2S DMA now uses the DmaBuffer API + +I2S no longer uses manually passed DMA descriptors. +"; + let err = PrChangelog::parse(5603, body).unwrap_err().to_string(); + assert!( + err.contains("Invalid H1 heading"), + "unexpected error: {err}" + ); + assert!( + err.contains("# esp-hal/I2S driver"), + "unexpected error: {err}" + ); + + let errors = validate(body); + assert!( + errors.iter().any(|e| e.contains("Invalid H1 heading")), + "unexpected errors: {errors:?}" + ); + } + + /// The other block title is the only H1 that may follow a block. + #[test] + fn migration_guide_ends_at_changelog_heading() { + let body = "\ +# Migration guide + +## esp-hal/SPI + +### Title + +Keep this. + +# Changelog + +## esp-hal + +- Added: Must not be part of the migration guide. +"; + let cl = PrChangelog::parse(1, body).unwrap().unwrap(); + let guide = cl + .sections + .iter() + .find_map(|s| s.migration_guide.as_deref()) + .unwrap(); + assert!(guide.contains("Keep this.")); + assert!(!guide.contains("Must not be part")); + let errors = validate(body); + assert!(errors.is_empty(), "unexpected errors: {errors:?}"); + } + /// A PR that only has a `# Migration guide` section for a crate must NOT be /// treated as having a changelog entry for that crate. The `changelog` field /// of the resulting `PrSection` must be empty so that coverage checks diff --git a/xtask/src/radio_hil_runner.rs b/xtask/src/radio_hil_runner.rs index c8b739f0ddc..f9eab61a659 100644 --- a/xtask/src/radio_hil_runner.rs +++ b/xtask/src/radio_hil_runner.rs @@ -88,7 +88,7 @@ pub fn run_radio_test( /// Run a radio HIL test directly from prebuilt ELFs. /// -/// Used by `run elfs`, where there is no `cargo run` command to delegate to. +/// Used by `elfs`, where there is no `cargo run` command to delegate to. pub fn run_radio_test_elf( dut_binary_path: &Path, harness_binary_path: Option<&Path>, @@ -346,7 +346,8 @@ fn detect_probes(probes: Option) -> Result> { let mut command = Command::new("probe-rs"); command.args(["list"]); - let output = run_command_with_output_timeout(command, "probe-rs list", PROBE_LIST_TIMEOUT)?; + let output = + crate::run_command_with_output_timeout(command, "probe-rs list", PROBE_LIST_TIMEOUT)?; if !output.status.success() { let stderr = String::from_utf8_lossy(&output.stderr); bail!("Failed to run `probe-rs list`: {}", stderr.trim()); @@ -372,32 +373,3 @@ fn detect_probes(probes: Option) -> Result> { Ok(discovered) } - -fn run_command_with_output_timeout( - mut command: Command, - name: &str, - timeout: Duration, -) -> Result { - let mut child = command - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .spawn() - .map_err(|e| anyhow!("Failed to spawn {name}: {e}"))?; - let start = Instant::now(); - - loop { - if child.try_wait()?.is_some() { - return child - .wait_with_output() - .map_err(|e| anyhow!("Failed to collect {name} output: {e}")); - } - - if start.elapsed() > timeout { - let _ = child.kill(); - let _ = child.wait(); - bail!("{name} timed out after {}s", timeout.as_secs()); - } - - thread::sleep(Duration::from_millis(100)); - } -} diff --git a/xtask/src/resolve.rs b/xtask/src/resolve.rs new file mode 100644 index 00000000000..fc31b03424b --- /dev/null +++ b/xtask/src/resolve.rs @@ -0,0 +1,84 @@ +//! Free-form token resolution for `build` / `run` / `check` / `test`. +//! +//! Tokens after those verbs can be a chip, a crate, an example or test name, or +//! a package alias (`example`, `tests`, `qa`), in any order. Wired via +//! [`crate::commands::dispatch`]. + +use clap::ValueEnum as _; + +use crate::{Package, metadata::Chip}; + +/// Tokens and any chips/packages already known (e.g. from flags). +#[derive(Debug, Clone, Default)] +pub struct ResolveInput { + pub tokens: Vec, + pub chips: Vec, + pub packages: Vec, +} + +impl ResolveInput { + pub fn from_tokens(tokens: impl IntoIterator>) -> Self { + Self { + tokens: tokens.into_iter().map(Into::into).collect(), + ..Self::default() + } + } +} + +/// Classified tokens. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Resolution { + pub chips: Vec, + pub packages: Vec, + pub names: Vec, +} + +/// Classify `input.tokens`. Does not look up examples on disk. +pub fn resolve(mut input: ResolveInput) -> Resolution { + let mut chips = input.chips; + let mut packages = input.packages; + let mut names = Vec::new(); + + for token in input.tokens.drain(..) { + if let Some(chip) = chip_from_token(&token) { + if !chips.contains(&chip) { + chips.push(chip); + } + } else if let Ok(package) = Package::from_str(token.trim(), true) { + if !packages.contains(&package) { + packages.push(package); + } + } else { + names.push(token); + } + } + + Resolution { + chips, + packages, + names, + } +} + +/// `esp32-c6`, `ESP32C6` and `c6` name the same chip as `esp32c6`. +fn chip_from_token(token: &str) -> Option { + let mut normalized = token.trim().to_owned(); + normalized.retain(|c| c != '-'); + Chip::from_str(&normalized, true).ok() +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn package_aliases_and_names_both_work() { + let packages = resolve(ResolveInput::from_tokens(["qa", "hil-test-radio"])).packages; + assert_eq!(packages, vec![Package::QaTest, Package::HilTestRadio]); + } + + #[test] + fn everything_else_is_a_name() { + let names = resolve(ResolveInput::from_tokens(["sleep_timer"])).names; + assert_eq!(names, vec!["sleep_timer"]); + } +} diff --git a/xtask/src/semver_check.rs b/xtask/src/semver_check.rs index 08021960b68..9c220677653 100644 --- a/xtask/src/semver_check.rs +++ b/xtask/src/semver_check.rs @@ -14,8 +14,9 @@ use crate::{ metadata::{Chip, Config}, }; -/// Return the minimum required bump for the next release. -/// Even if nothing changed this will be [ReleaseType::Patch] +/// Return the minimum bump the stable API requires for the next release. +/// +/// Additions are not detected, so new API and unchanged API both return [ReleaseType::Patch]. pub fn minimum_update( workspace: &Path, package: Package, @@ -23,41 +24,21 @@ pub fn minimum_update( ) -> Result { log::info!("Package = {}, Chip = {}", package, chip); - let package_name = package.to_string(); - let package_path = crate::windows_safe_path(&workspace.join(&package_name)); + let package_path = crate::windows_safe_path(&workspace.join(package.directory())); - package.prepare_semver_check(&package_path, &chip)?; + let current_path = build_prepared_doc_json(package, &chip, &package_path)?; - let current_path = build_doc_json(package, &chip, &package_path)?; - - let dest_path = workspace.join("esp-rom-sys/src/generated_rom_symbols.rs"); - package.clean_semver_check(&dest_path)?; - - let file_name = if package.chip_features_matter() { - chip.to_string() - } else { - "api".to_string() - }; - - let baseline_path_gz = - PathBuf::from(&package_path).join(format!("api-baseline/{}.json.gz", file_name)); - if !baseline_path_gz.exists() { - download_baselines(&workspace, vec![package])?; - } - if package.chip_features_matter() && !baseline_path_gz.exists() { + let Some(baseline_path_gz) = baseline_gz(workspace, package, chip)? else { log::warn!( "No baseline found for package '{}', chip '{}' — skipping semver check for this chip", package, chip ); return Ok(ReleaseType::Patch); - } + }; let baseline_path = temp_file::TempFile::new().with_context(|| format!("Failed to create a TempFile!"))?; - let buffer = Vec::new(); - let mut decoder = flate2::write::GzDecoder::new(buffer); - decoder.write_all(&(fs::read(&baseline_path_gz)?))?; - fs::write(baseline_path.path(), decoder.finish()?)?; + decompress_gz(&baseline_path_gz, baseline_path.path())?; let mut semver_check = Check::new(Rustdoc::from_path(current_path)); semver_check.set_baseline(Rustdoc::from_path(baseline_path.path())); @@ -80,13 +61,74 @@ pub fn minimum_update( Ok(min_required_update) } +/// `{chip}` when chip features change the API, otherwise `api`. +pub(crate) fn baseline_stem(package: Package, chip: Chip) -> String { + if package.chip_features_matter() { + chip.to_string() + } else { + "api".to_string() + } +} + +/// Gzipped semver baseline for `package`/`chip`, downloading the package's +/// baselines if they are absent. `None` when chip features matter and that +/// chip has no baseline. +pub(crate) fn baseline_gz( + workspace: &Path, + package: Package, + chip: Chip, +) -> Result, Error> { + let package_path = crate::windows_safe_path(&workspace.join(package.directory())); + let baseline_path_gz = package_path.join(format!( + "api-baseline/{}.json.gz", + baseline_stem(package, chip) + )); + if !baseline_path_gz.exists() { + download_baselines(workspace, vec![package])?; + } + if package.chip_features_matter() && !baseline_path_gz.exists() { + return Ok(None); + } + Ok(Some(baseline_path_gz)) +} + +pub(crate) fn decompress_gz(src: &Path, dest: &Path) -> Result<(), Error> { + if let Some(parent) = dest.parent() { + fs::create_dir_all(parent)?; + } + let mut decoder = flate2::write::GzDecoder::new(Vec::new()); + decoder.write_all(&fs::read(src)?)?; + fs::write(dest, decoder.finish()?)?; + Ok(()) +} + +/// `prepare_semver_check`, build rustdoc JSON, then `clean_semver_check`, which +/// runs even when the build fails. +pub(crate) fn build_prepared_doc_json( + package: Package, + chip: &Chip, + package_path: &PathBuf, +) -> Result { + package.prepare_semver_check(package_path, chip)?; + let result = build_doc_json(package, chip, package_path); + if let Err(cleanup) = package.clean_semver_check(package_path) { + // A build failure is what the caller can act on, so it is not replaced. + if result.is_err() { + log::warn!("Failed to clean up after building the doc JSON: {cleanup:#}"); + } else { + return Err(cleanup); + } + } + result +} + +/// Build the rustdoc JSON of `package` for `chip`. pub(crate) fn build_doc_json( package: Package, chip: &Chip, package_path: &PathBuf, ) -> Result { let target_dir = std::env::var("CARGO_TARGET_DIR"); - let target_path = if let Ok(target) = target_dir { PathBuf::from(target) } else { diff --git a/xtensa-lx-rt/src/exception/asm.rs b/xtensa-lx-rt/src/exception/asm.rs index 731b26ad673..6677c717c2d 100644 --- a/xtensa-lx-rt/src/exception/asm.rs +++ b/xtensa-lx-rt/src/exception/asm.rs @@ -115,7 +115,7 @@ global_asm!( // context. // // - If the WOE bit is not enabled (for example, in code written for - // the CALL0 ABI), this becomes a silent noop and operates compatbily. + // the CALL0 ABI), this becomes a silent noop and operates compatibly. // // - Hilariously it's ACTUALLY FASTER than the HAL routine. And not // just a little bit, it's MUCH faster. With a mostly full register diff --git a/xtensa-lx-rt/src/lib.rs b/xtensa-lx-rt/src/lib.rs index 9347f06c898..0f3d1eda1f3 100644 --- a/xtensa-lx-rt/src/lib.rs +++ b/xtensa-lx-rt/src/lib.rs @@ -75,7 +75,9 @@ global_asm!( main = sym main, ); -global_asm!( +// `Reset` must be a single item: rustc does not emit separate `global_asm!` items in source +// order. +cfg_global_asm!( " // _xtensa_lx_rt_zero_fill // @@ -159,18 +161,9 @@ Reset: .Linit_data_done: memw // Make sure all writes are completed before proceeding. At this point, all static variables have been initialized. -" -); - -// According to 4.4.7.2 of the xtensa isa, ccount and compare are undefined on -// reset, set all values to zero to disable. ("timer interrupts are cleared by writing CCOMPARE[i]") -#[cfg(any( - XCHAL_HAVE_TIMER0, - XCHAL_HAVE_TIMER1, - XCHAL_HAVE_TIMER2, - XCHAL_HAVE_TIMER3 -))] -cfg_global_asm!( +", + // According to 4.4.7.2 of the xtensa isa, ccount and compare are undefined on + // reset, set all values to zero to disable. ("timer interrupts are cleared by writing CCOMPARE[i]") #[cfg(XCHAL_HAVE_TIMER0)] "wsr.ccompare0 a0", #[cfg(XCHAL_HAVE_TIMER1)] @@ -179,10 +172,13 @@ cfg_global_asm!( "wsr.ccompare2 a0", #[cfg(XCHAL_HAVE_TIMER3)] "wsr.ccompare3 a0", + #[cfg(any( + XCHAL_HAVE_TIMER0, + XCHAL_HAVE_TIMER1, + XCHAL_HAVE_TIMER2, + XCHAL_HAVE_TIMER3 + ))] "isync", -); - -global_asm!( " l32r a2, sym_init_start // vector table address wsr.vecbase a2